From 8a25ebdb95bccf8d744256f666ddbe2a9731e962 Mon Sep 17 00:00:00 2001 From: Marvin Date: Mon, 26 Oct 2026 20:55:12 +0100 Subject: [PATCH] Custom routing metric for links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A link's routing metric could only be one of four presets (Prefer, Normal, Avoid, Backup only). Links now also get a Custom option, closer to how real networks tune IGP metrics: - Multiplier mode scales the distance cost, (km + 60) × 0.1 to 100. - Cost mode sets an exact cost, 1 to 65535 like an OSPF metric. The preset buttons stay plain. Picking Custom explains how a link's cost is worked out and lists what each preset comes to on that link. Choosing Custom starts from the current preset and switching modes keeps the effective cost, so nothing moves until the player changes the value. Like the presets, it applies to every link between the two cities. The cost formula lives in one helper, linkW(), used by compute() and the traceroute paths. Custom links store mk/mv, which sanitize() repairs and clamps; old saves load unchanged. The link panel skips its daily re-render while the number field has focus, and Enter applies the value. Tests cover routing equivalence with the presets, rerouting by cost, mode switching, input clamping, saves, and the panel at desktop and phone width. French, Italian and Portuguese for the new strings. Perf on the big network: no change beyond noise, routing identical to main. --- CHANGELOG.md | 2 + site/i18n/fr.js | 11 ++++- site/i18n/it.js | 11 ++++- site/i18n/pt.js | 11 ++++- site/index.html | 34 +++++++++++---- tests/game.test.js | 102 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 161 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 648e743..fe661d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. + ## [1.31.0] — 2026-10-26 - Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen. diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 1b4c2ba..0bb9742 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1604,7 +1604,6 @@ "Going to customers in":"Vers les clients de", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Plus gros contributeur : {egress} à {city}. Passe-le en « Secours seul », donne aux clients une sortie plus proche (peering, cache, transit local) ou augmente la métrique de ce lien.", "Routing metric":"Métrique de routage", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. S’applique à tous les liens entre ces deux villes.", "Behind the Great Firewall":"Derrière le Grand Pare-feu", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Chine continentale joue selon ses propres règles. {list} et d’autres services étrangers y sont bloqués, donc les utilisateurs atteignent surtout des réseaux chinois. Le trafic qui passe la frontière perd environ {pct} en filtrage et congestion, sauf s’il emprunte une route premium : du transit CN-Too ou un circuit transfrontalier premium (tous deux vendus uniquement à Hong Kong), ou un PNI avec un réseau chinois. Le revenu par utilisateur est plus faible ici.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Les réseaux étrangers ont besoin d’une coentreprise locale et d’une licence d’opérateur pour construire ici.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"via un courtier en capacité", "List it with a capacity broker they keep 10%":"La confier à un courtier en capacité il garde 10 %", "Nothing spare to sell on this fiber right now.":"Rien à vendre sur cette fibre pour l’instant.", +"Custom":"Perso", +"Multiplier":"Multiplicateur", +"Cost":"Coût", +"Set":"Appliquer", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Coût sur ce lien : {w}. Autorisé : de {lo} à {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. Choisis Perso pour fixer ton propre multiplicateur ou coût. S’applique à tous les liens entre ces deux villes.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Le coût d’un lien, c’est sa longueur en km plus 60, fois un multiplicateur. Le trafic prend le chemin au coût total le plus bas.", +"Presets on this link: {list}.":"Préréglages sur ce lien : {list}.", +"Cost: the exact number, whatever the distance.":"Coût : le nombre exact, quelle que soit la distance.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicateur : il multiplie le coût de la distance, donc un lien plus long coûte toujours plus.", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 6bf8565..fdc589d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1603,7 +1603,6 @@ "Going to customers in":"Diretto ai clienti a", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Fonte principale: {egress} a {city}. Impostala su “Solo backup”, dai ai clienti un’uscita più vicina (peering, una cache, transit locale) o alza la metrica di questo link.", "Routing metric":"Metrica di routing", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Vale per tutti i link tra queste due città.", "Behind the Great Firewall":"Dietro il Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Cina continentale gioca con regole tutte sue. {list} e altri servizi stranieri qui sono bloccati, quindi gli utenti raggiungono soprattutto reti cinesi. Il traffico che attraversa il confine perde circa il {pct} tra filtri e congestione, a meno che non viaggi su una rotta premium: transit CN-Too o un circuito transfrontaliero premium (entrambi venduti solo a Hong Kong), oppure un PNI con una rete cinese. Qui i ricavi per utente sono più bassi.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Per costruire infrastrutture qui, le reti straniere hanno bisogno di una joint venture locale e di una licenza operativa.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"tramite un broker di capacità", "List it with a capacity broker they keep 10%":"Mettila in vendita con un broker di capacità trattiene il 10%", "Nothing spare to sell on this fiber right now.":"Per ora non c’è niente da vendere su questa fibra.", +"Custom":"Personalizzata", +"Multiplier":"Moltiplicatore", +"Cost":"Costo", +"Set":"Imposta", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Costo su questo link: {w}. Ammessi: da {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Scegli Personalizzata per impostare il tuo moltiplicatore o costo. Vale per tutti i link tra queste due città.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Il costo di un link è la sua lunghezza in km più 60, per un moltiplicatore. Il traffico prende il percorso col costo totale più basso.", +"Presets on this link: {list}.":"Preset su questo link: {list}.", +"Cost: the exact number, whatever the distance.":"Costo: il numero esatto, a prescindere dalla distanza.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Moltiplicatore: scala il costo della distanza, così un link più lungo costa comunque di più.", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9c443f5..9f4950d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1602,7 +1602,6 @@ "Going to customers in":"Indo para clientes em", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Maior fonte: {egress} em {city}. Coloque em “Só backup”, dê aos clientes uma saída mais próxima (peering, um cache, transit local) ou aumente a métrica deste link.", "Routing metric":"Métrica de roteamento", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Vale para todos os links entre essas duas cidades.", "Behind the Great Firewall":"Atrás do Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"A China continental joga com regras próprias. {list} e outros serviços estrangeiros são bloqueados aqui, então os usuários acessam principalmente redes chinesas. O tráfego que cruza a fronteira perde cerca de {pct} com filtragem e congestionamento, a menos que vá por uma rota premium: transit CN-Too ou um circuito transfronteiriço premium (ambos vendidos só em Hong Kong), ou um PNI com uma rede chinesa. A receita por usuário aqui é menor.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Redes estrangeiras precisam de uma joint venture local e de uma licença de operação para construir infraestrutura aqui.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"por um corretor de capacidade", "List it with a capacity broker they keep 10%":"Anunciar com um corretor de capacidade ele fica com 10%", "Nothing spare to sell on this fiber right now.":"Nada sobrando para vender nesta fibra por enquanto.", +"Custom":"Personalizada", +"Multiplier":"Multiplicador", +"Cost":"Custo", +"Set":"Aplicar", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Custo neste link: {w}. Permitido: de {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Escolha Personalizada para definir seu próprio multiplicador ou custo. Vale para todos os links entre essas duas cidades.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"O custo de um link é seu comprimento em km mais 60, vezes um multiplicador. O tráfego segue o caminho de menor custo total.", +"Presets on this link: {list}.":"Predefinições neste link: {list}.", +"Cost: the exact number, whatever the distance.":"Custo: o número exato, seja qual for a distância.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicador: multiplica o custo da distância, então um link mais longo continua custando mais.", }; diff --git a/site/index.html b/site/index.html index 9334e32..a125165 100644 --- a/site/index.html +++ b/site/index.html @@ -315,6 +315,7 @@ label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-t input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)} .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .network-name input.t{flex:1 1 240px;width:auto;min-width:0} +.metric-in{display:flex;gap:6px;align-items:center;margin-top:6px}.metric-in input.t{flex:1 1 120px;width:auto;min-width:0;font-size:16px;padding:4px 10px} .plug{display:flex;gap:12px;align-items:center;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;margin:10px 0 4px;background:var(--soft);box-shadow:0 3px 0 var(--ink);color:var(--ink);text-decoration:none} .plug:hover{background:#FFF6D6}.plug .pi{font-size:30px;line-height:1}.plug b{font-family:var(--display);font-size:16px}.plug .meta{display:block;margin-top:2px}.plug .go{margin-left:auto;font-weight:900;white-space:nowrap} .starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} @@ -719,6 +720,10 @@ const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}]; const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}]; const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1)); const MET={prefer:{l:tr('Prefer'),f:0.5},normal:{l:tr('Normal'),f:1},avoid:{l:tr('Avoid'),f:4},backup:{l:tr('Backup only'),f:60}}; +// Custom metrics: a multiplier on the distance cost (f) or an absolute IGP cost (w), capped like an OSPF metric. +const MET_LIM={f:[0.1,100],w:[1,65535]}; +const clampM=(k,v)=>{const [lo,hi]=MET_LIM[k];v=Math.min(hi,Math.max(lo,v));return k==='w'?Math.round(v):Math.round(v*100)/100;}; +const linkW=l=>l.metric==='custom'?(l.mk==='w'?l.mv:(l.km+60)*l.mv):(l.km+60)*MET[l.metric||'normal'].f; const PREF={high:tr('Prefer'),normal:tr('Normal'),low:tr('Backup only')}; const edgeKey=l=>l.aString(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x'; function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={}; - for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} + for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=linkW(l);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};} function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[]; @@ -1924,7 +1929,7 @@ function compute(){ const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; 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.ae.w,wLat=e=>e.lat+0.05; @@ -2202,7 +2207,7 @@ function sanitize(s){ for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); - s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric==='custom'){if(l.mk!=='w')l.mk='f';l.mv=clampM(l.mk,num(l.mv,l.mk==='w'?l.km+60:1));}else{if(l.metric&&!own(MET,l.metric))l.metric='normal';delete l.mk;delete l.mv;}return l;}); const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t)); s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); @@ -3039,7 +3044,13 @@ const ACT={ upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('Fabric port in {city} is full.',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();}, cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();}, setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=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();}, + setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return; + // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. + for(const x of pairLinks(l.a,l.b)){if(v==='custom'){if(x.metric!=='custom'){x.mk='f';x.mv=MET[x.metric||'normal'].f;}}else{delete x.mk;delete x.mv;}x.metric=v;}sfx('click');after();}, + metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l||l.metric!=='custom')return; + for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'&&x.mk!==k){const w=linkW(x);x.mk=k;x.mv=clampM(k,k==='w'?w:w/(x.km+60));}sfx('click');after();}, + metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||l.metric!=='custom'||!t)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} + t.blur();for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'){x.mk=l.mk;x.mv=clampM(l.mk,v);}sfx('click');after();}, 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();}, listMore:({k})=>{if(k!=='conn'&&k!=='cust')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;renderDash();}, @@ -3373,6 +3384,8 @@ function renderPanel(){checkLayer(); const P=$('panel'); if(!S||!UI.sel){P.hidden=true;return;} P.hidden=false; + // Don't wipe a half-typed custom metric on the daily re-render. + const fe=document.activeElement;if(fe&&fe.id==='metIn'&&UI.sel.type!=='city'&&fe.dataset.id===UI.sel.id)return; 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;morph($('panelBody'),html); const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st; @@ -3563,8 +3576,15 @@ function trafficSection(l){ if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr("Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.",{egress:esc(d.lab),city:CITY[d.city].name})}

`;} return h+``; } -function metricSection(l){const cur=l.metric||'normal'; - return `

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}
`;} +function metricSection(l){const cur=l.metric||'normal',base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; + let h=`

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('Custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; + if(cur==='custom'){const k=l.mk,[lo,hi]=MET_LIM[k],md=m=>k===m?'pink sm':'ghost sm'; + const pre=Object.keys(MET).map(m=>`${MET[m].l} ×${MET[m].f} = ${Math.round(base*MET[m].f)}`).join(', '); + h+=`

${tr('A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.')} ${tr('Presets on this link: {list}.',{list:pre})}

+
${btn(tr('Multiplier'),'metricMode',{id:l.id,k:'f'},md('f'))}${btn(tr('Cost'),'metricMode',{id:l.id,k:'w'},md('w'))}
+
${btn(tr('Set'),'metricSet',{id:l.id},'pink sm')}
+

${k==='w'?tr('Cost: the exact number, whatever the distance.'):tr('Multiplier: scales the distance cost, so a longer link still costs more.')} ${tr('Cost on this link: {w}. Allowed: {lo} to {hi}.',{w:Math.round(linkW(l)),lo:k==='w'?lo:'×'+lo,hi:k==='w'?hi:'×'+hi})}

`;} + return h+'
';} function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; let h=`

${tr('Behind the Great Firewall')}

${tr('Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}

`; if(st==='none')h+=`

${tr('Foreign networks need a local joint venture and an operating license to build infrastructure here.')}

${btn(tr('Apply for a license {price} + {mo}/mo · ~45 days',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false}); -addEventListener('keydown',e=>{if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); +addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); /* ---------- click delegation ---------- */ let pressing=false; diff --git a/tests/game.test.js b/tests/game.test.js index 6bbdadc..1502f83 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -405,3 +405,105 @@ test('#117 several scrubbing centers: nearest first, spill to the next, and far assert.equal(ev("S.scrubs.some(x=>x.city==='lon')"), false); assert.deepEqual(errors, []); }); + +// Custom routing metrics: a fra–ams–par triangle where the direct fra–par link is normally shortest. +const triangle = (ev) => { + ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev("for(const c of ['ams','par'])ACT.buildPop({city:c});const L=(a,b)=>{UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();};L('fra','ams');L('ams','par');L('fra','par');compute()"); + ev("window.FP=S.links.find(l=>(l.a==='fra'&&l.b==='par')||(l.a==='par'&&l.b==='fra')).id;window.hops=()=>JSON.stringify(trPaths('fra').path('par').map(h=>h.l.id))"); +}; + +test('a custom multiplier routes exactly like the matching preset', () => { + const { ev, errors } = load(); + triangle(ev); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")]), 'direct link wins by default'); + ev("ACT.setMetric({id:FP,v:'avoid'})"); + const avoid = ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"); + ev("ACT.setMetric({id:FP,v:'custom'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'custom'); + assert.equal(l.mk, 'f'); + assert.equal(l.mv, 4, 'custom starts from the preset it replaces'); + assert.equal(ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"), avoid); + ev("ACT.setMetric({id:FP,v:'normal'})"); + assert.equal(ev("'mk' in S.links.find(l=>l.id===FP)||'mv' in S.links.find(l=>l.id===FP)"), false, 'presets drop the custom fields'); + assert.deepEqual(errors, []); +}); + +test('an absolute custom cost steers the path, and switching modes keeps the cost', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.mk, 'w'); + assert.equal(l.mv, Math.round(l.km + 60), 'switching to cost keeps the effective metric'); + ev("ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'a huge cost sends traffic round via Amsterdam'); + ev("renderAll();$('metIn').value='1';ACT.metricSet({id:FP})"); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")])); + ev("ACT.metricMode({id:FP,k:'f'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1, 'converted back to a multiplier, clamped to the minimum'); + assert.deepEqual(errors, []); +}); + +test('custom metric input is validated and clamped', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.selLink({id:FP});renderAll()"); + ev("$('metIn').value='';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 1, 'empty input changes nothing'); + ev("renderAll();$('metIn').value='9999';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 100); + ev("renderAll();$('metIn').value='0';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1); + ev("ACT.metricMode({id:FP,k:'x'});ACT.setMetric({id:FP,v:'bogus'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).metric"), 'custom'); + assert.deepEqual(errors, []); +}); + +test('custom metrics survive a save, and broken ones are repaired', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});S.links.find(l=>l.id===FP).mv=777;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + let l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'w', 777]); + ev("Object.assign(S.links.find(l=>l.id===FP),{mk:'zz',mv:'lots'});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'f', 1]); + ev("Object.assign(S.links.find(l=>l.id===FP),{metric:'custom',mk:'w',mv:1e9});S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + // An old save: preset metric, no custom fields at all. + ev("const x=S.links.find(l=>l.id===FP);x.metric='avoid';delete x.mk;delete x.mv;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'avoid'); + assert.ok(!('mk' in l) && !('mv' in l)); + assert.equal(JSON.parse(ev("hops()")).length, 2, 'the old save still routes, avoiding the direct link'); + assert.deepEqual(errors, []); +}); + +test('preset buttons stay plain, and Custom explains the numbers, also on phones', () => { + const { ev, dom, errors } = load(); + triangle(ev); + for (const w of [1280, 390]) { + ev(`window.innerWidth=${w};ACT.setMetric({id:FP,v:'normal'});ACT.selLink({id:FP});renderAll()`); + const doc = dom.window.document; + const btns = [...doc.querySelectorAll('#panel [data-act="setMetric"]')]; + assert.equal(btns.length, 5); + const km = ev("S.links.find(l=>l.id===FP).km"); + assert.deepEqual(btns.map(b => b.textContent), ['Prefer', 'Normal', 'Avoid', 'Backup only', 'Custom']); + assert.equal(doc.getElementById('metIn'), null); + assert.doesNotMatch(doc.getElementById('panel').textContent, /times a multiplier/); + ev("ACT.setMetric({id:FP,v:'custom'})"); + assert.ok(doc.getElementById('metIn'), `custom editor at ${w}px`); + assert.ok(doc.querySelector('#panel [data-act="metricMode"]')); + const txt = doc.getElementById('panel').textContent; + assert.match(txt, /times a multiplier/); + assert.match(txt, new RegExp(`Normal ×1 = ${Math.round(km + 60)}, Avoid ×4 = ${Math.round((km + 60) * 4)}`)); + assert.match(txt, /Multiplier: scales the distance cost/); + assert.match(txt, /Cost on this link/); + ev("ACT.metricMode({id:FP,k:'w'})"); + assert.match(doc.getElementById('panel').textContent, /Cost: the exact number/); + } + assert.deepEqual(errors, []); +});