Merge #89: make big networks fast (routing, panels and map drawing)
This commit is contained in:
commit
4a6af1a348
6 changed files with 510 additions and 144 deletions
|
|
@ -9,6 +9,9 @@ All notable changes to this project are documented here. The project follows
|
||||||
- Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable.
|
- Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable.
|
||||||
- Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model.
|
- Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model.
|
||||||
- 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.
|
- 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. The connection and customer lists in the NOC dashboard show 100 rows at a time, with a button for more. While the game is paused or animations are off, the map is only redrawn when something on it changes, which saves a lot of battery on phones. On a phone, the map also rests while the NOC dashboard fills the screen, so scrolling it stays smooth.
|
||||||
|
- The game no longer gets slower after a long pause. The money that floats up from your cities on payday kept piling up off-screen instead of fading, hundreds of them on a big network.
|
||||||
|
|
||||||
## [1.28.0] — 2026-10-25
|
## [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.
|
- 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.
|
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.
|
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.
|
Served share per city (`sfOf`) drives eyeball revenue and customer mood.
|
||||||
|
|
||||||
## Actions and rendering
|
## 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
|
- `renderLeft()` draws the left tabs (deals, NOC, customers…), `renderPanel()` the
|
||||||
selection panel (city, link, network). On phones these become bottom sheets
|
selection panel (city, link, network). On phones these become bottom sheets
|
||||||
controlled by `renderTabbar()`.
|
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
|
- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses
|
||||||
a simplified style; parallel waves are grouped by `linkGroups()`.
|
a simplified style; parallel waves are grouped by `linkGroups()`.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
"homepage": "https://seriesoftub.es/",
|
"homepage": "https://seriesoftub.es/",
|
||||||
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
|
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
|
||||||
"scripts": {
|
"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",
|
"build": "bash scripts/build.sh",
|
||||||
"i18n:check": "node scripts/i18n-check.js",
|
"i18n:check": "node scripts/i18n-check.js",
|
||||||
"serve": "npm run build && npx --yes serve@14.2.4 _site"
|
"serve": "npm run build && npx --yes serve@14.2.4 _site"
|
||||||
|
|
|
||||||
|
|
@ -2430,4 +2430,8 @@
|
||||||
"Needs routers with {pn} ports or bigger at both ends ({city}).":"Servono router con porte da {pn} o più grandi a entrambe le estremità ({city}).",
|
"Needs routers with {pn} ports or bigger at both ends ({city}).":"Servono router con porte da {pn} o più grandi a entrambe le estremità ({city}).",
|
||||||
"Prices include {p} back for the old routers on eBuy.":"I prezzi includono {p} recuperati vendendo i vecchi router su eBuy.",
|
"Prices include {p} back for the old routers on eBuy.":"I prezzi includono {p} recuperati vendendo i vecchi router su eBuy.",
|
||||||
"New routers went in today. The next swap can wait until tomorrow.":"I nuovi router sono stati montati oggi. Il prossimo cambio può aspettare domani.",
|
"New routers went in today. The next swap can wait until tomorrow.":"I nuovi router sono stati montati oggi. Il prossimo cambio può aspettare domani.",
|
||||||
|
"+{n} more connection":"+{n} altra connessione",
|
||||||
|
"+{n} more connections":"+{n} altre connessioni",
|
||||||
|
"+{n} more customer":"+{n} altro cliente",
|
||||||
|
"+{n} more customers":"+{n} altri clienti",
|
||||||
};
|
};
|
||||||
|
|
|
||||||
420
site/index.html
420
site/index.html
|
|
@ -734,7 +734,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;
|
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)}):'';}
|
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 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 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 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);
|
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);
|
||||||
|
|
@ -871,7 +872,7 @@ const CITIES=[
|
||||||
// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat.
|
// 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]};
|
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];}}
|
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=[
|
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":"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]]]]},
|
{"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]]]]},
|
||||||
|
|
@ -1164,7 +1165,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:'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:'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.')});
|
{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);}
|
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);}
|
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.
|
// After Glitch leaves Korea, Seoul viewers watch half as much of it and the rest moves to everyone else.
|
||||||
|
|
@ -1666,14 +1669,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)});}
|
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 ================= */
|
/* ================= SIMULATION ================= */
|
||||||
// Binary-heap Dijkstra over an adjacency map {city:[[neighbour,edge],...]}. wf(edge) gives the weight,
|
// Binary-heap Dijkstra over city indices: adj[i] lists [neighbour, edge]. wf(edge) gives the weight, skip(v,edge) can
|
||||||
// skip(v,edge) can rule edges out, and the search stops early once `stop` is settled.
|
// rule edges out, and the search stops early once `stop` is settled. D is the distance to each city (Infinity: no
|
||||||
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;}}
|
// path) and P the edge it was reached by. The heap lives in two typed arrays, and equal distances always settle in the
|
||||||
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;}
|
// same order, so routes do not flip between runs.
|
||||||
function dijkstra(adj,src,wf,skip,stop){const dist={[src]:0},prev={},done=new Set(),h=[[0,src]];
|
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);
|
||||||
while(h.length){const [d,u]=hpop(h);if(done.has(u)||d>dist[u])continue;done.add(u);if(u===stop)break;
|
let cap=64,hd=new Float64Array(cap),hu=new Int32Array(cap),m=0;
|
||||||
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]);}}}
|
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;}
|
||||||
return {dist,prev};}
|
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 ----------
|
/* ---------- 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
|
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. */
|
save can't run code. One rule per line, # for comments. */
|
||||||
|
|
@ -1719,39 +1730,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};
|
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=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};}
|
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(){
|
function compute(){
|
||||||
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp);
|
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
|
||||||
const remote=remoteCities(),adj={}; pops.concat(remote).forEach(p=>adj[p]=[]);
|
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
|
||||||
const edges={},TRX=teRules();
|
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
|
||||||
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];
|
const edges={},TRX=teRules(),live=[];let NE=0;
|
||||||
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));}
|
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];
|
||||||
const SP={};
|
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));}
|
||||||
const wW=e=>e.w;for(const s of pops)SP[s]=dijkstra(adj,s,wW);
|
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by.
|
||||||
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;};
|
// 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 dijk=(s0,mode)=>dijkstra(adj,s0,mode==='fast'?e=>e.lat+0.05:e=>e.w*(1+10*prevU(e)));
|
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 E=[], ev=S.ev;
|
||||||
const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
|
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;
|
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;
|
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)});}
|
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: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 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: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});}
|
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).
|
// 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=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);}}
|
{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 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 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)){
|
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
|
// 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.
|
// 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;
|
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;
|
if(!popUp(c))continue;
|
||||||
// A shaped attack: `rtbh` is the player pulling the plug on the victim IP (junk gone, customer dark too);
|
// 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
|
// `edge` is the crude RouteScript `blackhole ddos` filter (junk gone, 10% of real traffic with it). Flowspec
|
||||||
|
|
@ -1768,95 +1795,143 @@ function compute(){
|
||||||
dd=atk.gbps*mult;
|
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);}}
|
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;
|
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;
|
if(edge)R2.teBlack+=atk.gbps*0.15+d*0.1;if(rtbh)R2.teBlack+=atk.gbps+d;
|
||||||
R2.cityBlocked=R2.cityBlocked||{};
|
R2.cityBlocked=R2.cityBlocked||{};
|
||||||
const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr;
|
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;
|
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)){flows.push({c,n:n.id,rem:a*0.85,cache:true});flows.push({c,n:n.id,rem:a*0.15});}
|
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 flows.push({c,n:n.id,rem:a});}
|
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={};
|
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
|
/* 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
|
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. */
|
unless today's is clearly better. */
|
||||||
const l2Routes=(A,B,b)=>{const m=b.route||'normal';
|
const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id);
|
||||||
if(m!=='scenic')return [{...l2walk(m==='fast'?dijk(A,'fast'):SP[A],A,B),share:1}];
|
// disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer.
|
||||||
const ek='l2:'+b.id,own=e=>(R.ef&&R.ef[e.id]&&R.ef[e.id].eg[ek])||0;
|
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 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 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 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 s1=dijkstra(adj,Ai,wf,null,Bi);if(s1.D[Bi]===Infinity)return [{...walkI(SPP[A],Ai,Bi),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 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,A,wf,(v,e)=>used.has(e.id),B);
|
const s2=dijkstra(adj,Ai,wf,(v,e)=>used.has(e.id),Bi);
|
||||||
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}];}
|
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;
|
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;}
|
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;
|
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.
|
// 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;
|
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;
|
for(const [A,B] of pairs){let amt=0;
|
||||||
if(popUp(A)&&popUp(B)&&SP[A]&&SP[A].dist[B]!==undefined){
|
if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][CIDX[B]]<Infinity){
|
||||||
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'};
|
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;
|
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 {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 n of ns)if(nres[n]!==undefined){nres[n]-=a;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+a;}
|
for(const i of ni)if(HAS[i])nodeTake(i,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 l of path){l.res-=a;l.ld+=a;carry(l,ek,NN+1,CIDX[B],a);}}}
|
||||||
else noPath=true;
|
else noPath=true;
|
||||||
minF=Math.min(minF,amt/b.bw);tot+=amt;}
|
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);}
|
R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;
|
||||||
const TE=!!(S.te&&S.te.on),TR=teRules();R2.teMoved=0;const teCache={},SPILL=TR&&TR.spill?TR.spill:1;
|
// Same answer as diversePaths(), which would rebuild today's live links for every customer.
|
||||||
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};};
|
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 altPath=(src,dst,base)=>{const key=src+'>'+dst,c0=teCache[key];
|
const TE=!!(S.te&&S.te.on),TR=teRules();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1;
|
||||||
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 altPath=(src,dst,base)=>{const key=src*NC+dst,c0=teCache.get(key);
|
||||||
const {dist,prev}=dijkstra(adj,src,wW,(v,e)=>res[e.id]<=1e-3||(nres[v]!==undefined&&nres[v]<=1e-3),dst);
|
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;
|
||||||
if(dist[dst]===undefined||dist[dst]>2*base+60){teCache[key]=false;return null;}
|
const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst);
|
||||||
const P=spPath({prev},src,dst);teCache[key]=P;return P;};
|
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 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 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];
|
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){
|
for(const rank of RANKS){
|
||||||
const Er=TR?E:E.filter(e=>base(e)===rank);if(!Er.length)continue;const sorted={};
|
if(TR?!E.length:!E.some(e=>base(e)===rank))continue;
|
||||||
for(const f of flows){
|
for(f of flows){
|
||||||
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
|
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
|
||||||
const sp=SP[f.c];
|
const lst=byRank[f.n][rank];if(!lst)continue;
|
||||||
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]));
|
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
|
||||||
const cands=srt.filter(e=>e.used<e.cap&&e.ok(f.n)&&(!TR||eff(e,f.n)===rank));
|
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
|
||||||
// Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over
|
exits gives. Exits only fill up once tried, so the usable ones stay the same until then. Nearly every flow
|
||||||
// them by free capacity (like several transits in one city), then top up in order if one fills.
|
fits in its first group: find that one with a scan (nothing is visited yet), and sort only what is left
|
||||||
// Push up to `want` along one path to exit e; returns what fitted.
|
when it does not fit. Most often the group is the POP's own exits: with no preferred exit on the list
|
||||||
const push=(e,P,want,keep=0)=>{const path=P.path,ns=P.ns;let amt=want;
|
and no other city at distance 0, the usable ones here are exactly the first group, already in order. */
|
||||||
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]);
|
G.length=0;
|
||||||
if(amt<=1e-6)return 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);}
|
||||||
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
|
if(!G.length){
|
||||||
const ek=e.k+':'+e.id;R2.egDesc[ek]={lab:e.lab,city:e.city,k:e.k};
|
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;}}
|
||||||
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;}
|
if(bh>1)continue;
|
||||||
e.used+=amt;f.rem-=amt;
|
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(!f.junk){let ok=amt;const fc=cnCity(f.c),ec=cnCity(e.city),nc=!!NET[f.n].cn;
|
if(G.length>1)G.sort(byDist);}
|
||||||
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);}
|
sendGroup(G);
|
||||||
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;}
|
if(f.rem<=1e-6)continue;
|
||||||
return amt;
|
const rest=lst.filter(usable).sort(byDist);
|
||||||
};
|
for(let i=0;i<rest.length&&f.rem>1e-6;){
|
||||||
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
|
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++;
|
||||||
// with free capacity, as long as they are no more than twice as long.
|
sendGroup(rest.slice(i,j));i=j;
|
||||||
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);}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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;
|
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;}
|
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
|
// money
|
||||||
|
|
@ -2711,19 +2786,20 @@ const ACT={
|
||||||
setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();},
|
setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();},
|
||||||
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},
|
goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();},
|
||||||
custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();},
|
custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();},
|
||||||
custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';renderDash();},
|
listMore:({k})=>{if(k!=='conn'&&k!=='cust')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;renderDash();},
|
||||||
custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';renderDash();},
|
custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';listReset('cust');renderDash();},
|
||||||
custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();},
|
custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';listReset('cust');renderDash();},
|
||||||
custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};UI.dtab='cust';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
|
custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;listReset('cust');if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();},
|
||||||
|
custOpen:({sad}={})=>{if(!S)return;UI.kf=sad?{f:'sad'}:{};listReset('cust');UI.dtab='cust';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
|
||||||
goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});},
|
goConn:({city,k})=>{if(!isCity(city)||!own(CONN_K,k))return;$('dash').hidden=true;ACT.goEgress({city,k});},
|
||||||
connF:({f,v})=>{const F=UI.cf=UI.cf||{};if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();},
|
connF:({f,v})=>{const F=UI.cf=UI.cf||{};listReset('conn');if(f==='all'){UI.cf={};}else if(f==='k'){F.k=own(CONN_K,v)?v:'';}renderDash();},
|
||||||
connCity:({v})=>{UI.cf=UI.cf||{};UI.cf.city=isCity(v)?v:'';renderDash();},
|
connCity:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.city=isCity(v)?v:'';renderDash();},
|
||||||
connNet:({v})=>{UI.cf=UI.cf||{};UI.cf.net=NET[v]?v:'';renderDash();},
|
connNet:({v})=>{UI.cf=UI.cf||{};listReset('conn');UI.cf.net=NET[v]?v:'';renderDash();},
|
||||||
connSort:({k})=>{if(!['k','city','name','use','mo'].includes(k))return;if(UI.connSort===k)UI.connDir=-(UI.connDir||1);else{UI.connSort=k;UI.connDir=k==='use'||k==='mo'?-1:1;}renderDash();},
|
connSort:({k})=>{if(!['k','city','name','use','mo'].includes(k))return;listReset('conn');if(UI.connSort===k)UI.connDir=-(UI.connDir||1);else{UI.connSort=k;UI.connDir=k==='use'||k==='mo'?-1:1;}renderDash();},
|
||||||
connFor:({net})=>{if(!NET[net])return;UI.cf={net};ACT.connOpen();},
|
connFor:({net})=>{if(!NET[net])return;UI.cf={net};ACT.connOpen();},
|
||||||
connCancel:({k,id})=>{const r=conns().find(x=>x.k===k&&x.id===id);if(!r||r.mine)return;const key='cc:'+k+':'+id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null;
|
connCancel:({k,id})=>{const r=conns().find(x=>x.k===k&&x.id===id);if(!r||r.mine)return;const key='cc:'+k+':'+id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null;
|
||||||
if(k==='t')ACT.cancelTransit({id,ok:1});else if(k==='p')ACT.cancelPni({id,ok:1});else if(k==='ix')ACT.cancelIx({city:id,ok:1});else if(k==='c')ACT.rmCache({id});else{const [city,prov]=id.split('|');ACT.rmNni({city,prov});}renderDash();},
|
if(k==='t')ACT.cancelTransit({id,ok:1});else if(k==='p')ACT.cancelPni({id,ok:1});else if(k==='ix')ACT.cancelIx({city:id,ok:1});else if(k==='c')ACT.rmCache({id});else{const [city,prov]=id.split('|');ACT.rmNni({city,prov});}renderDash();},
|
||||||
connOpen:()=>{if(!S)return;UI.dtab='conn';const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
|
connOpen:()=>{if(!S)return;UI.dtab='conn';listReset('conn');const d=$('dash');d.hidden=false;renderDash();d.scrollTop=0;},
|
||||||
applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast(tr('<b>Application filed.</b><br>Your local partner says about 45 days. Probably.'),'goal');after();},
|
applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast(tr('<b>Application filed.</b><br>Your local partner says about 45 days. Probably.'),'goal');after();},
|
||||||
togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.premium=!t.premium;sfx('click');after();},
|
togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.premium=!t.premium;sfx('click');after();},
|
||||||
buildScrub:({city,tier})=>{if(S.scrubAt)return;const T=SCRUB_TIERS[tier||0];if((lvl()||1)<T.lvl){toast(tr('<b>{tier} scrubbing unlocks at customer level {lv}.</b>',{tier:T.n,lv:T.lvl}),'bad');sfx('err');return;}if(!spend(T.cost))return;S.scrubAt=city;S.scrubTier=tier||0;S.scrubMode='always';toast(tr('<b>{tier} scrubbing center online in {city}.</b><br>Attacks up to {g} are cleaned, and you can sell DDoS protection.',{tier:T.n,city:CITY[city].name,g:fmtG(T.g)}),'good');after();},
|
buildScrub:({city,tier})=>{if(S.scrubAt)return;const T=SCRUB_TIERS[tier||0];if((lvl()||1)<T.lvl){toast(tr('<b>{tier} scrubbing unlocks at customer level {lv}.</b>',{tier:T.n,lv:T.lvl}),'bad');sfx('err');return;}if(!spend(T.cost))return;S.scrubAt=city;S.scrubTier=tier||0;S.scrubMode='always';toast(tr('<b>{tier} scrubbing center online in {city}.</b><br>Attacks up to {g} are cleaned, and you can sell DDoS protection.',{tier:T.n,city:CITY[city].name,g:fmtG(T.g)}),'good');after();},
|
||||||
|
|
@ -2885,6 +2961,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 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 logo=n=>`<span class="logo" style="--c:${n.col}">${initials(n)}</span>`;
|
||||||
const barCls=u=>u>=0.9?'bad':u>=0.65?'warn':'';
|
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 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;}
|
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;}
|
||||||
|
|
||||||
|
|
@ -3002,20 +3097,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>`;
|
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{
|
}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>`;
|
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 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 tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>Object.keys(S.ixp).some(c=>ixSessions(c).has(n.id))).length;
|
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;
|
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>`;
|
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();
|
function renderPanel(){checkLayer();
|
||||||
const P=$('panel');
|
const P=$('panel');
|
||||||
if(!S||!UI.sel){P.hidden=true;return;}
|
if(!S||!UI.sel){P.hidden=true;return;}
|
||||||
P.hidden=false;
|
P.hidden=false;
|
||||||
const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0;
|
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;
|
const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st;
|
||||||
}
|
}
|
||||||
function cityPanel(c){
|
function cityPanel(c){
|
||||||
|
|
@ -3312,6 +3407,10 @@ function bizWhy(b){const T=BIZ_T[b.type],out=[];if(T.event&&!eventLive(b))return
|
||||||
const moodCls=m=>m<30?'bad':m<60?'warn':'';
|
const moodCls=m=>m<30?'bad':m<60?'warn':'';
|
||||||
const custStats=()=>{const bz=S.biz.filter(b=>!BIZ_T[b.type].event),mo=bz.reduce((a,b)=>a+bizMo(b),0);
|
const custStats=()=>{const bz=S.biz.filter(b=>!BIZ_T[b.type].event),mo=bz.reduce((a,b)=>a+bizMo(b),0);
|
||||||
return {n:bz.length,unhappy:bz.filter(b=>b.mood<60).length,furious:bz.filter(b=>b.mood<30).length,avg:bz.length?(mo>0?bz.reduce((a,b)=>a+b.mood*bizMo(b),0)/mo:bz.reduce((a,b)=>a+b.mood,0)/bz.length):100,risk:bz.filter(b=>b.mood<60).reduce((a,b)=>a+bizMo(b),0)};};
|
return {n:bz.length,unhappy:bz.filter(b=>b.mood<60).length,furious:bz.filter(b=>b.mood<30).length,avg:bz.length?(mo>0?bz.reduce((a,b)=>a+b.mood*bizMo(b),0)/mo:bz.reduce((a,b)=>a+b.mood,0)/bz.length):100,risk:bz.filter(b=>b.mood<60).reduce((a,b)=>a+bizMo(b),0)};};
|
||||||
|
// Long lists show their first rows and grow on request: a thousand rows of buttons take the browser a long time to
|
||||||
|
// lay out again every day, worst of all on a phone. Filters, sorting and totals still cover every row.
|
||||||
|
const LIST_PAGE=100,listN=k=>(UI.listN&&UI.listN[k])||LIST_PAGE,listReset=k=>{if(UI.listN)delete UI.listN[k];};
|
||||||
|
const listMore=(k,n,lab)=>n>listN(k)?`<div class="btns" style="margin-top:6px">${btn(lab(Math.min(LIST_PAGE,n-listN(k))),'listMore',{k},'ghost sm')}</div>`:'';
|
||||||
function custSection(){const F=UI.kf||{};let h=`<div class="panel2" id="custSec" style="margin-top:12px"><h3>${tr('Customers')}</h3>`;
|
function custSection(){const F=UI.kf||{};let h=`<div class="panel2" id="custSec" style="margin-top:12px"><h3>${tr('Customers')}</h3>`;
|
||||||
if(!S.biz.length)return h+`<p class="empty">${tr('No customers yet. Offers show up in the Deals tab.')}</p></div>`;
|
if(!S.biz.length)return h+`<p class="empty">${tr('No customers yet. Offers show up in the Deals tab.')}</p></div>`;
|
||||||
const st=custStats();
|
const st=custStats();
|
||||||
|
|
@ -3327,8 +3426,8 @@ function custSection(){const F=UI.kf||{};let h=`<div class="panel2" id="custSec"
|
||||||
const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' <span style="color:var(--eye)">▲</span>':' <span style="color:var(--bad)">▼</span>';
|
const trend=b=>b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' <span style="color:var(--eye)">▲</span>':' <span style="color:var(--bad)">▼</span>';
|
||||||
const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]];
|
const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]];
|
||||||
h+=`<div class="seg" style="margin-bottom:4px">${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
|
h+=`<div class="seg" style="margin-bottom:4px">${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
|
||||||
h+=rows.map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)} <span class="meta">${esc(BIZ_T[b.type].l)}</span></div><div class="meta">${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}</div>${why.length?`<div class="why">${why.map(esc).join(' · ')}</div>`:''}<div class="bar ${moodCls(b.mood)}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}</div></div>${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}</div>`;}).join('');
|
h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `<div class="row"><div class="grow"><div class="nm">${esc(b.name)} <span class="meta">${esc(BIZ_T[b.type].l)}</span></div><div class="meta">${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}</div>${why.length?`<div class="why">${why.map(esc).join(' · ')}</div>`:''}<div class="bar ${moodCls(b.mood)}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}</div></div>${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}</div>`;}).join('');
|
||||||
return h+`</div>`;}
|
return h+listMore('cust',rows.length,n=>trn('+{n} more customer','+{n} more customers',n))+`</div>`;}
|
||||||
/* ---------- connections overview (#31, #33, #38) ----------
|
/* ---------- connections overview (#31, #33, #38) ----------
|
||||||
Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and
|
Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and
|
||||||
network, with a jump to the POP that holds it. The Networks tab shows the same per network. */
|
network, with a jump to the POP that holds it. The Networks tab shows the same per network. */
|
||||||
|
|
@ -3374,19 +3473,23 @@ function connSection(){const all=conns(),F=UI.cf||{};
|
||||||
const tc=rows.reduce((a,r)=>a+r.cap,0),tu=rows.reduce((a,r)=>a+r.use,0),tm=rows.reduce((a,r)=>a+r.mo,0);
|
const tc=rows.reduce((a,r)=>a+r.cap,0),tu=rows.reduce((a,r)=>a+r.use,0),tm=rows.reduce((a,r)=>a+r.mo,0);
|
||||||
if(isPhone()){const st=(r)=>r.down?` <span class="tag restrictive">${tr('DOWN')}</span>`:r.low?` <span class="tag st">${tr('backup')}</span>`:'';
|
if(isPhone()){const st=(r)=>r.down?` <span class="tag restrictive">${tr('DOWN')}</span>`:r.low?` <span class="tag st">${tr('backup')}</span>`:'';
|
||||||
h+=`<div class="seg" style="margin-bottom:4px">${[['k',tr('Type')],['city',tr('Where')],['use',tr('In use')],['mo',tr('Per month')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'connSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
|
h+=`<div class="seg" style="margin-bottom:4px">${[['k',tr('Type')],['city',tr('Where')],['use',tr('In use')],['mo',tr('Per month')]].map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'connSort',{k},sk===k?'pink sm':'ghost sm')).join('')}</div>`;
|
||||||
h+=rows.map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<div class="row"${r.down?' style="opacity:.55"':''}>${N?logo(N):`<span class="logo" style="--c:${CONN_COL[r.k]}">${r.k==='nni'?'NNI':'IX'}</span>`}<div class="grow"><div class="nm">${esc(r.name)} <span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span>${st(r)}</div><div class="meta">${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('{price}/mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}</div><div class="kv"><span>${tr('In use')}</span><b>${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>${r.mine?'':`<div class="btns">${connUp(r)}${connX(r)}</div>`}</div>${btn(tr('Open'),'goConn',{city:r.city,k:r.k},'ghost sm')}</div>`;}).join('');
|
h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<div class="row"${r.down?' style="opacity:.55"':''}>${N?logo(N):`<span class="logo" style="--c:${CONN_COL[r.k]}">${r.k==='nni'?'NNI':'IX'}</span>`}<div class="grow"><div class="nm">${esc(r.name)} <span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span>${st(r)}</div><div class="meta">${esc(CITY[r.city].name)} · ${esc(r.port)} · ${tr('{price}/mo',{price:fmt$(r.mo)})}${r.note?' · '+esc(r.note):''}</div><div class="kv"><span>${tr('In use')}</span><b>${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>${r.mine?'':`<div class="btns">${connUp(r)}${connX(r)}</div>`}</div>${btn(tr('Open'),'goConn',{city:r.city,k:r.k},'ghost sm')}</div>`;}).join('');
|
||||||
return h+`<div class="kv" style="margin-top:6px"><span><b>${trn('{n} connection','{n} connections',rows.length)}</b></span><b>${fmtG(tu)} / ${fmtCap(Math.round(tc))} · ${tr('{price}/mo',{price:fmt$(tm)})}</b></div></div>`;}
|
return h+listMore('conn',rows.length,n=>trn('+{n} more connection','+{n} more connections',n))+`<div class="kv" style="margin-top:6px"><span><b>${trn('{n} connection','{n} connections',rows.length)}</b></span><b>${fmtG(tu)} / ${fmtCap(Math.round(tc))} · ${tr('{price}/mo',{price:fmt$(tm)})}</b></div></div>`;}
|
||||||
const th=(k,l,c)=>`<th class="${c||''}">${k?`<button class="thb" data-act="connSort" data-args="${esc(JSON.stringify({k}))}">${l}${sk===k?(dir>0?' ▲':' ▼'):''}</button>`:l}</th>`;
|
const th=(k,l,c)=>`<th class="${c||''}">${k?`<button class="thb" data-act="connSort" data-args="${esc(JSON.stringify({k}))}">${l}${sk===k?(dir>0?' ▲':' ▼'):''}</button>`:l}</th>`;
|
||||||
h+=`<div class="tscroll"><table class="tbl"><thead><tr>${th('k',tr('Type'))}${th('city',tr('Where'))}${th('name',tr('With'))}${th('',tr('Port'))}${th('use',tr('In use'),'r')}${th('mo',tr('Per month'),'r')}<th></th></tr></thead><tbody>`;
|
h+=`<div class="tscroll"><table class="tbl"><thead><tr>${th('k',tr('Type'))}${th('city',tr('Where'))}${th('name',tr('With'))}${th('',tr('Port'))}${th('use',tr('In use'),'r')}${th('mo',tr('Per month'),'r')}<th></th></tr></thead><tbody>`;
|
||||||
h+=rows.map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<tr${r.down?' style="opacity:.55"':''}><td><span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span></td><td>${esc(CITY[r.city].name)}</td><td><span style="display:inline-flex;align-items:center;gap:6px">${N?logo(N):''}<span><b>${esc(r.name)}</b>${r.note?`<br><span class="meta">${esc(r.note)}</span>`:''}</span></span></td><td>${esc(r.port)}${r.down?` <span class="tag restrictive">${tr('DOWN')}</span>`:r.low?` <span class="tag st">${tr('backup')}</span>`:''}</td><td class="r">${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}<div class="bar ${barCls(u)}" style="margin-top:3px"><i style="width:${Math.min(100,u*100)}%"></i></div></td><td class="r">${fmt$(r.mo)}</td><td><div style="display:flex;flex-wrap:wrap;gap:6px;min-width:220px">${btn(tr('Open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connX(r)}</div></td></tr>`;}).join('');
|
h+=rows.slice(0,listN('conn')).map(r=>{const u=r.cap?r.use/r.cap:0,N=r.net&&NET[r.net];return `<tr${r.down?' style="opacity:.55"':''}><td><span class="tag" style="background:${CONN_COL[r.k]}">${tr(CONN_K[r.k])}</span></td><td>${esc(CITY[r.city].name)}</td><td><span style="display:inline-flex;align-items:center;gap:6px">${N?logo(N):''}<span><b>${esc(r.name)}</b>${r.note?`<br><span class="meta">${esc(r.note)}</span>`:''}</span></span></td><td>${esc(r.port)}${r.down?` <span class="tag restrictive">${tr('DOWN')}</span>`:r.low?` <span class="tag st">${tr('backup')}</span>`:''}</td><td class="r">${fmtG(r.use)} / ${fmtCap(Math.round(r.cap))}<div class="bar ${barCls(u)}" style="margin-top:3px"><i style="width:${Math.min(100,u*100)}%"></i></div></td><td class="r">${fmt$(r.mo)}</td><td><div style="display:flex;flex-wrap:wrap;gap:6px;min-width:220px">${btn(tr('Open'),'goConn',{city:r.city,k:r.k},'ghost sm')}${connUp(r)}${connX(r)}</div></td></tr>`;}).join('');
|
||||||
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>`;
|
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>${listMore('conn',rows.length,n=>trn('+{n} more connection','+{n} more connections',n))}</div>`;
|
||||||
return h;}
|
return h;}
|
||||||
// Where you connect to one network, as buttons that jump to the POP (Networks tab).
|
// Where you connect to one network, as buttons that jump to the POP (Networks tab).
|
||||||
function netWhere(n){const ch=[];
|
// Where you connect to each network, as [label, city, kind]: transit, PNIs, IX sessions, then caches. Built for all
|
||||||
for(const t of S.transit)if(t.net===n.id)ch.push([tr('Transit'),t.city,'t']);
|
// networks at once, so the network list works out each IX port's sessions a single time, not once per network.
|
||||||
for(const x of S.pni)if(x.net===n.id)ch.push(['PNI',x.city,'p']);
|
function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||(B[k][id]=[])).push(x);
|
||||||
for(const c in S.ixp)if(ixSessions(c).has(n.id))ch.push([ixName(c),ixCity(c),'ix']);
|
for(const t of S.transit)add('t',t.net,[tr('Transit'),t.city,'t']);
|
||||||
for(const c of new Set(S.caches.filter(x=>x.net===n.id).map(x=>x.city)))ch.push([tr('Cache'),c,'c']);
|
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;
|
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>`;}
|
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'];
|
const DTABS=['overview','cust','conn','traffic','infra','lease'];
|
||||||
|
|
@ -3456,7 +3559,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('')}
|
<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>`;
|
<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(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 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))}):'';
|
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))}):'';
|
||||||
|
|
@ -3719,7 +3822,9 @@ while(WAVES.length<220){const x=R1()*W,y=R1()*H;if(!onLand(x,y)&&!onLand(x+12,y)
|
||||||
while(HILLS.length<130){const x=R1()*W,y=R1()*H;if(onLand(x,y)&&!CITIES.some(c=>Math.hypot(c.x-x,c.y-y)<40))HILLS.push([x,y,6+R1()*10,R1()]);}
|
while(HILLS.length<130){const x=R1()*W,y=R1()*H;if(onLand(x,y)&&!CITIES.some(c=>Math.hypot(c.x-x,c.y-y)<40))HILLS.push([x,y,6+R1()*10,R1()]);}
|
||||||
const CLOUDS=Array.from({length:7},(_,i)=>({x:R1()*W,y:60+R1()*(H-120),s:.7+R1()*.6,v:3+R1()*4}));
|
const CLOUDS=Array.from({length:7},(_,i)=>({x:R1()*W,y:60+R1()*(H-120),s:.7+R1()*.6,v:3+R1()*4}));
|
||||||
const FLOATS=[];
|
const FLOATS=[];
|
||||||
function floater(x,y,text,col){if(!animOn())return;FLOATS.push({x,y,text,col,t:performance.now()});}
|
// Stamped with the map's animation clock, which stops while paused: on the real clock, every floater born after a
|
||||||
|
// pause lingered off-screen for as long as the pause had lasted, and paydays piled up hundreds of them.
|
||||||
|
function floater(x,y,text,col){if(!animOn()||UI.mapHid)return;FLOATS.push({x,y,text,col,t:animT});}
|
||||||
// Static markup: data-i18n text and every aria-label/title go through the dictionary once at boot.
|
// Static markup: data-i18n text and every aria-label/title go through the dictionary once at boot.
|
||||||
function i18nDom(){if(LANG==='en')return;for(const el of document.querySelectorAll('[data-i18n]'))el.textContent=tr(el.textContent);
|
function i18nDom(){if(LANG==='en')return;for(const el of document.querySelectorAll('[data-i18n]'))el.textContent=tr(el.textContent);
|
||||||
for(const a of ['aria-label','title'])for(const el of document.querySelectorAll('['+a+']'))el.setAttribute(a,tr(el.getAttribute(a)));}
|
for(const a of ['aria-label','title'])for(const el of document.querySelectorAll('['+a+']'))el.setAttribute(a,tr(el.getAttribute(a)));}
|
||||||
|
|
@ -3755,17 +3860,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
|
/* 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. */
|
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);
|
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).
|
// 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;}
|
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();
|
const GEO=new Map();
|
||||||
/* Parallel waves on the same cable (or in the same trench) draw as one line with a combined label (#19). */
|
/* 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).
|
// 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 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 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 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;}}}
|
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
|
// 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.
|
// none, a gentle curve. Its shape must not depend on how many waves already run between the two cities.
|
||||||
|
|
@ -3779,6 +3887,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=[];
|
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;}
|
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];}
|
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);}
|
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
|
// `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.
|
// them (#49), so they are drawn here every frame instead.
|
||||||
|
|
@ -3833,27 +3944,31 @@ function draw(now){
|
||||||
// cable systems
|
// cable systems
|
||||||
drawCables(ks);
|
drawCables(ks);
|
||||||
// links
|
// 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;
|
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 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){
|
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;
|
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';
|
ctx.lineCap='round';ctx.lineJoin='round';
|
||||||
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
|
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='#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([]);
|
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([]);}
|
// Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again.
|
||||||
const at=t=>polyAt(sp,gm.cum,t);
|
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;
|
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;
|
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 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;
|
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);}
|
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(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
|
// drag preview
|
||||||
|
|
@ -3883,6 +3998,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;}}
|
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});}
|
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;}
|
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);
|
for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly);
|
||||||
// floaters
|
// 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;}
|
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;}
|
||||||
|
|
@ -3935,8 +4053,9 @@ function drawBackhoe(x,y,now,sub){
|
||||||
}
|
}
|
||||||
ctx.restore();
|
ctx.restore();
|
||||||
}
|
}
|
||||||
const LBLW={};
|
// Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow.
|
||||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];});}catch(e){}
|
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();FRAME.length=0;});}catch(e){}
|
||||||
function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
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);
|
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';
|
ctx.save();ctx.translate(sx,sy);ctx.strokeStyle='#1E2640';
|
||||||
|
|
@ -3948,15 +4067,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();}
|
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();
|
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();}
|
}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(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(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.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();
|
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?'#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);}
|
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){
|
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 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 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);
|
const k=sc*(hov?1.15:1);
|
||||||
|
|
@ -3992,14 +4111,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();
|
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);}
|
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;}}
|
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));
|
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=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);}
|
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=S.inc.some(i=>i.ref===C.id&&i.type!=='leak');
|
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);}
|
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();
|
ctx.restore();
|
||||||
// label
|
// label
|
||||||
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
|
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?'#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);
|
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
|
||||||
}
|
}
|
||||||
|
|
@ -4007,7 +4126,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride){
|
||||||
|
|
||||||
/* ---------- hit tests & input ---------- */
|
/* ---------- 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 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);}
|
function wrapCam(){cam.x=((cam.x%W)+W)%W;cam.y=clamp(cam.y,0,H);}
|
||||||
const ptrs=new Map();
|
const ptrs=new Map();
|
||||||
cv.addEventListener('pointerdown',e=>{audioInit();cv.setPointerCapture(e.pointerId);ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
cv.addEventListener('pointerdown',e=>{audioInit();cv.setPointerCapture(e.pointerId);ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||||||
|
|
@ -4066,11 +4185,26 @@ function frame(now){
|
||||||
const dt=Math.min(250,now-last);last=now;
|
const dt=Math.min(250,now-last);last=now;
|
||||||
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
|
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
|
||||||
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
|
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
|
||||||
|
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
|
||||||
|
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
|
||||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
|
if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
|
||||||
if(n){UI.ticking=true;renderHUD();UI.ticking=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}}
|
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}
|
||||||
if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||||
try{draw(animOn()?animT:0);}catch(e){tickErr(e);}
|
const t=animOn()?animT:0;
|
||||||
|
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
|
||||||
}
|
}
|
||||||
|
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
|
||||||
|
under it is work nobody sees, so it waits until the map shows again (and no payday money piles up meanwhile). */
|
||||||
|
function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c.parentNode.hidden)continue;
|
||||||
|
const r=c.getBoundingClientRect();if(r.top<=1&&r.left<=1&&r.right>=innerWidth-1&&r.bottom>=innerHeight-1)return true;}return false;}
|
||||||
|
/* Paused, or with animations off, the map only changes when you move it, point at something or the network changes.
|
||||||
|
Until then the last frame is still right, so it is not drawn again (phones keep cool). It is redrawn at least once
|
||||||
|
a second anyway, and every frame while the land picture is still catching up with a zoom. */
|
||||||
|
const FRAME=[];
|
||||||
|
function mapStill(t,now){const sl=UI.sel,dr=UI.drag;
|
||||||
|
const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length];
|
||||||
|
let same=v.length===FRAME.length;for(let i=0;i<v.length;i++)if(FRAME[i]!==v[i]){same=false;FRAME[i]=v[i];}
|
||||||
|
return same&&now-(UI.drawnAt||0)<1000&&!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z));}
|
||||||
function tickErr(e){console.error('[tubes] tick failed',e);if(UI.tickErr)return;UI.tickErr=true;track('tick_error',true);
|
function tickErr(e){console.error('[tubes] tick failed',e);if(UI.tickErr)return;UI.tickErr=true;track('tick_error',true);
|
||||||
toast(tr('<b>Something in the NOC glitched.</b><br>The game kept going. If things look odd, export your save and open an issue on GitHub.'),'bad');}
|
toast(tr('<b>Something in the NOC glitched.</b><br>The game kept going. If things look odd, export your save and open an issue on GitHub.'),'bad');}
|
||||||
function boot(data){
|
function boot(data){
|
||||||
|
|
|
||||||
219
tests/speed.test.js
Normal file
219
tests/speed.test.js
Normal file
|
|
@ -0,0 +1,219 @@
|
||||||
|
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, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('long lists in the NOC dashboard show 100 rows at a time and grow on request', () => {
|
||||||
|
const { ev, errors } = load();
|
||||||
|
bigNet(ev);
|
||||||
|
// well over a hundred PNIs and customers
|
||||||
|
ev("const cs=Object.keys(S.pops);let i=0;for(const n of NETS)for(const c of cs.slice(0,2))S.pni.push({id:'tp'+(i++),city:c,net:n.id,tier:0,n:1,site:'a',sacrif:false});");
|
||||||
|
ev("for(let j=0;j<150;j++)S.biz.push({id:'tb'+j,city:'fra',city2:null,name:'Test '+j,type:'dia',bw:1,rate:100,mood:50+j%40,since:0,reqs:[],pm:50});compute()");
|
||||||
|
const total = ev('conns().length');
|
||||||
|
assert.ok(total > 200);
|
||||||
|
ev("UI.dtab='conn';ACT.connOpen()");
|
||||||
|
const rows = () => ev("document.querySelectorAll('#dashCard tbody tr').length");
|
||||||
|
assert.equal(rows(), 100);
|
||||||
|
assert.match(ev("document.querySelector('#dashCard [data-act=\"listMore\"]').textContent"), /\+100 more connections/);
|
||||||
|
assert.match(ev("document.getElementById('dashCard').textContent"), new RegExp(`${total} connections`), 'totals still count every connection');
|
||||||
|
ev("document.querySelector('#dashCard [data-act=\"listMore\"]').click()");
|
||||||
|
assert.equal(rows(), 200);
|
||||||
|
ev("ACT.connSort({k:'mo'})");
|
||||||
|
assert.equal(rows(), 100, 'a new sort starts short again');
|
||||||
|
// customers
|
||||||
|
ev("ACT.custOpen()");
|
||||||
|
const custRows = () => ev("document.querySelectorAll('#custSec .row').length");
|
||||||
|
assert.equal(custRows(), 100);
|
||||||
|
const left = ev('S.biz.length') - 100;
|
||||||
|
assert.ok(ev("document.querySelector('#custSec [data-act=\"listMore\"]').textContent").startsWith(`+${Math.min(100, left)} more customer`));
|
||||||
|
ev("ACT.listMore({k:'cust'});ACT.listMore({k:'cust'});ACT.listMore({k:'nope'})");
|
||||||
|
assert.equal(custRows(), Math.min(300, ev('S.biz.length')));
|
||||||
|
// phones get the same cap
|
||||||
|
ev("window.innerWidth=390;UI.dtab='conn';ACT.connOpen()");
|
||||||
|
assert.equal(ev("document.querySelectorAll('#connSec .row').length"), 100);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the map is only redrawn when something on it can have changed', () => {
|
||||||
|
const { ev, errors } = load();
|
||||||
|
bigNet(ev);
|
||||||
|
ev("closeModal();UI.anim='on';UI.speed=0;last=100000;worldLayer(cam.z)");
|
||||||
|
let T = 100000;
|
||||||
|
const frame = (code = '', dt = 16) => { if (code) ev(code); const a = ev('ctx.calls.n'); T += dt; ev(`frame(${T})`); return ev('ctx.calls.n') - a; };
|
||||||
|
frame(); frame();
|
||||||
|
assert.equal(frame(), 0, 'paused and untouched: nothing is drawn');
|
||||||
|
assert.ok(frame('cam.x+=5') > 0, 'moving the map redraws it');
|
||||||
|
assert.equal(frame(), 0);
|
||||||
|
assert.ok(frame("UI.hover='ams'") > 0, 'pointing at a city redraws');
|
||||||
|
assert.ok(frame("UI.sel={type:'city',id:'fra'}") > 0, 'selecting redraws');
|
||||||
|
assert.ok(frame('dayTick()') > 0, 'a new day redraws');
|
||||||
|
assert.equal(frame(), 0);
|
||||||
|
assert.ok(frame('', 1100) > 0, 'and once a second anyway');
|
||||||
|
assert.ok(frame('WL.key=null') > 0, 'the land picture catching up after a zoom or resize redraws');
|
||||||
|
ev('UI.speed=1');
|
||||||
|
assert.ok(frame() > 0 && frame() > 0, 'with the clock running every frame moves');
|
||||||
|
ev("ACT.animSet({v:'off'})");
|
||||||
|
frame(); frame();
|
||||||
|
assert.equal(frame(), 0, 'with animations off the running map stands still between days');
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('after a day the open panels catch up on the next frame, even when every frame has a day', () => {
|
||||||
|
const { ev, errors } = load();
|
||||||
|
bigNet(ev);
|
||||||
|
ev("closeModal();selectCity('fra');window.__rp=0;const rp0=renderPanel;renderPanel=function(){__rp++;return rp0.apply(this,arguments);}");
|
||||||
|
ev('UI.speed=1;acc=DAY_MS;last=0;frame(16)');
|
||||||
|
const day = ev('S.day');
|
||||||
|
assert.equal(ev('__rp'), 0, 'the frame with the day leaves the panels for later');
|
||||||
|
ev('frame(32)');
|
||||||
|
assert.equal(ev('__rp'), 1, 'the next frame updates them');
|
||||||
|
assert.equal(ev('S.day'), day);
|
||||||
|
// a day on every frame: the panels still follow, one frame behind
|
||||||
|
for (let i = 0; i < 3; i++) ev(`acc=DAY_MS;frame(${48 + 16 * i})`);
|
||||||
|
assert.equal(ev('__rp'), 3, 'each frame shows the day before it');
|
||||||
|
ev('frame(96)');
|
||||||
|
assert.equal(ev('__rp'), 4);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('payday money floaters fade after a long pause instead of piling up', () => {
|
||||||
|
const { ev, errors } = load();
|
||||||
|
bigNet(ev);
|
||||||
|
// a fake clock, so a ten-minute pause takes no time; no auto-pause in the middle
|
||||||
|
ev("closeModal();ACT.animSet({v:'on'});setPref('pauseFurious',false);setPref('pauseIncident',false);window.__clk=5000;performance.now=()=>__clk;last=__clk;UI.speed=1");
|
||||||
|
const run = (ms) => { for (let t = 0; t < ms; t += 16) ev('__clk+=16;frame(__clk)'); };
|
||||||
|
run(2000);
|
||||||
|
assert.equal(ev('FLOATS.length'), 0, 'floaters from building the network have faded');
|
||||||
|
ev('UI.speed=0;__clk+=600000;frame(__clk)');
|
||||||
|
ev('while(S.day%30!==29)dayTick();UI.speed=1;acc=DAY_MS');
|
||||||
|
run(16);
|
||||||
|
assert.equal(ev('S.day%30'), 0);
|
||||||
|
assert.ok(ev('FLOATS.length') > 0, 'payday shows the money');
|
||||||
|
run(2000);
|
||||||
|
assert.equal(ev('FLOATS.length'), 0, 'and it fades within two seconds of play');
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the map is not drawn while the dashboard covers the whole screen', () => {
|
||||||
|
const { ev, errors } = load();
|
||||||
|
bigNet(ev);
|
||||||
|
ev("closeModal();ACT.animSet({v:'on'});setPref('pauseFurious',false);setPref('pauseIncident',false);window.__clk=5000;performance.now=()=>__clk;last=__clk;UI.speed=1");
|
||||||
|
const frame = () => { const a = ev('ctx.calls.n'); ev('__clk+=16;frame(__clk)'); return ev('ctx.calls.n') - a; };
|
||||||
|
// jsdom has no layout, so the card says where it is: on a phone, scrolled down, it fills the screen
|
||||||
|
const at = (top) => ev(`$('dashCard').getBoundingClientRect=()=>({top:${top},left:0,right:innerWidth,bottom:innerHeight+900})`);
|
||||||
|
for (let t = 0; t < 2000; t += 16) frame();
|
||||||
|
assert.equal(ev('FLOATS.length'), 0, 'floaters from building the network have faded');
|
||||||
|
assert.ok(frame() > 0, 'the running map is drawn every frame');
|
||||||
|
ev('ACT.connOpen()'); at(-40);
|
||||||
|
assert.equal(frame(), 0, 'nothing is drawn under the dashboard');
|
||||||
|
ev('while(S.day%30!==29)dayTick();acc=DAY_MS');
|
||||||
|
for (let i = 0; i < 100; i++) assert.equal(frame(), 0);
|
||||||
|
assert.equal(ev('S.day%30'), 0, 'the game kept running');
|
||||||
|
assert.equal(ev('FLOATS.length'), 0, 'and payday money does not pile up out of sight');
|
||||||
|
at(6);
|
||||||
|
assert.ok(frame() > 0, 'back at the top, the strip of map above the card is drawn again');
|
||||||
|
at(-40); frame();
|
||||||
|
ev("$('dashCard').getBoundingClientRect=()=>({top:60,left:120,right:900,bottom:700})");
|
||||||
|
assert.ok(frame() > 0, 'a dashboard with the map around it (desktop) does not stop it');
|
||||||
|
at(-40); frame();
|
||||||
|
ev('ACT.dashClose()');
|
||||||
|
assert.ok(frame() > 0, 'closing the dashboard draws the map again');
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue