From 647e302f1c6278c88998de2cd03baa176d339e17 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 6 Nov 2026 18:26:24 +0000 Subject: [PATCH 1/8] The intern upgrades optical transport A new standing order, Upgrade optical transport. On fiber that is full and runs above a level, it moves the line system up one size (the Upgrade click), or trades the smallest lit channels for the biggest optic that fits, one at a time (setChCount; the old optics go to spares). With a line system chosen, every fiber below it is moved up, both steps in one night if need be, cold or not. A line system swap is a day without the fiber, so only where another live path joins its cities, no customer rides it, and routing the network without it serves as much as today (one compute, measured against today's routing). One fiber is tested and swapped a night, and a fiber that failed is left alone for a week (not saved), so the order costs at most one routing more, and only on a night with a fiber to try. --- CHANGELOG.md | 1 + site/i18n/de.js | 7 ++ site/i18n/es.js | 7 ++ site/i18n/fr.js | 7 ++ site/i18n/it.js | 7 ++ site/i18n/pt.js | 7 ++ src/game/60-features/95-standing-orders.js | 48 +++++++- src/i18n/en.js | 7 ++ tests/intern-optical-upgrade.test.js | 121 +++++++++++++++++++++ 9 files changed, 210 insertions(+), 2 deletions(-) create mode 100644 tests/intern-optical-upgrade.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fb4ce3..382ce54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. ## [3.0.0] — 2026-11-06 diff --git a/site/i18n/de.js b/site/i18n/de.js index 4374a2f..36c6582 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3226,6 +3226,8 @@ "ops.l_decom":{"one":"hat eine kleine Wave auf {where} zurückgegeben","other":"hat {n} kleine Waves zurückgegeben ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"hat einen Kanal auf {where} aufgeschaltet","other":"hat {n} Kanäle aufgeschaltet ({where})"}, +"ops.l_optswap":{"one":"hat eine Optik auf {where} gegen eine größere getauscht","other":"hat {n} Optiken gegen größere getauscht ({where})"}, +"ops.l_optup":{"one":"hat das Line System auf {where} ausgebaut","other":"hat {n} Line Systems ausgebaut ({where})"}, "ops.l_paid":"Kosten: {cost} einmalig, {mo}/Monat.", "ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"}, "ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"}, @@ -3258,6 +3260,8 @@ "ops.o_ix_d":"Jede Woche: den Route Servern beitreten und jedes willige Mitglied an jedem deiner Exchange-Ports fragen.", "ops.o_optics":"Mehr Dark Fiber beleuchten", "ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.", +"ops.o_optup":"Optischen Transport ausbauen", +"ops.o_optup_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Wähl ein Line System, und jede Faser mit einem kleineren wird darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht.", "ops.o_pni":"PNI mit den Großen", "ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.", "ops.o_ports":"Peering-Reserve halten", @@ -3278,6 +3282,8 @@ "ops.p_paid":"Paid Peering", "ops.p_pick":"Optiken", "ops.p_prov":"Anbieter", +"ops.p_swap":"Größere Optiken", +"ops.p_sys":"Line System", "ops.p_tier":"Größe", "ops.p_x":"Reserve", "ops.paused":"Pausiert", @@ -3292,6 +3298,7 @@ "ops.shift_report":"{name}s Woche", "ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung", "ops.standing_orders":"Daueraufträge", +"ops.sys_next":"Das nächste, wenn voll", "ops.template":"Neuer POP aus der Vorlage", "ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.", "ops.tpl_bb":"Breitband", diff --git a/site/i18n/es.js b/site/i18n/es.js index 40ce8a0..d447ada 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3224,6 +3224,8 @@ "ops.l_decom":{"one":"devolvió una wave pequeña en {where}","other":"devolvió {n} waves pequeñas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"encendió un canal en {where}","other":"encendió {n} canales ({where})"}, +"ops.l_optswap":{"one":"cambió una óptica por una más grande en {where}","other":"cambió {n} ópticas por otras más grandes ({where})"}, +"ops.l_optup":{"one":"mejoró el sistema de línea en {where}","other":"mejoró {n} sistemas de línea ({where})"}, "ops.l_paid":"Coste: {cost} de entrada, {mo}/mes.", "ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"}, "ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"}, @@ -3256,6 +3258,8 @@ "ops.o_ix_d":"Cada semana: unirse a los route servers y pedir peering a cada miembro dispuesto en cada uno de tus puertos de exchange.", "ops.o_optics":"Encender más fibra", "ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.", +"ops.o_optup":"Mejorar el transporte óptico", +"ops.o_optup_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Elige un sistema de línea y cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche.", "ops.o_pni":"PNI con los grandes", "ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.", "ops.o_ports":"Margen en puertos de peering", @@ -3276,6 +3280,8 @@ "ops.p_paid":"Peering de pago", "ops.p_pick":"Ópticas", "ops.p_prov":"Proveedor", +"ops.p_swap":"Ópticas más grandes", +"ops.p_sys":"Sistema de línea", "ops.p_tier":"Tamaño", "ops.p_x":"Margen", "ops.paused":"En pausa", @@ -3290,6 +3296,7 @@ "ops.shift_report":"La semana de {name}", "ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura", "ops.standing_orders":"Órdenes permanentes", +"ops.sys_next":"El siguiente, si está lleno", "ops.template":"POP nuevo desde plantilla", "ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.", "ops.tpl_bb":"Banda ancha", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 07a75e6..908b461 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3224,6 +3224,8 @@ "ops.l_decom":{"one":"a rendu une petite wave sur {where}","other":"a rendu {n} petites waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"a allumé un canal sur {where}","other":"a allumé {n} canaux ({where})"}, +"ops.l_optswap":{"one":"a remplacé une optique par une plus grande sur {where}","other":"a remplacé {n} optiques par de plus grandes ({where})"}, +"ops.l_optup":{"one":"a amélioré le système de ligne sur {where}","other":"a amélioré {n} systèmes de ligne ({where})"}, "ops.l_paid":"Coût : {cost} d'entrée, {mo}/mois.", "ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"}, "ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"}, @@ -3256,6 +3258,8 @@ "ops.o_ix_d":"Chaque semaine : rejoindre les route servers et solliciter chaque membre partant sur chacun de tes ports d'exchange.", "ops.o_optics":"Allumer plus de fibre", "ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.", +"ops.o_optup":"Améliorer le transport optique", +"ops.o_optup_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Choisissez un système de ligne, et chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit.", "ops.o_pni":"PNI avec les gros", "ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.", "ops.o_ports":"Garder de la marge sur les ports de peering", @@ -3276,6 +3280,8 @@ "ops.p_paid":"Peering payant", "ops.p_pick":"Optiques", "ops.p_prov":"Fournisseur", +"ops.p_swap":"Optiques plus grandes", +"ops.p_sys":"Système de ligne", "ops.p_tier":"Taille", "ops.p_x":"Marge", "ops.paused":"En pause", @@ -3290,6 +3296,7 @@ "ops.shift_report":"La semaine de {name}", "ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture", "ops.standing_orders":"Ordres permanents", +"ops.sys_next":"Le suivant, quand c’est plein", "ops.template":"Nouveau POP depuis le modèle", "ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.", "ops.tpl_bb":"Haut débit", diff --git a/site/i18n/it.js b/site/i18n/it.js index af05b1c..e745eff 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3224,6 +3224,8 @@ "ops.l_decom":{"one":"ha restituito una wave piccola su {where}","other":"ha restituito {n} wave piccole ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"ha acceso un canale su {where}","other":"ha acceso {n} canali ({where})"}, +"ops.l_optswap":{"one":"ha scambiato un’ottica con una più grande su {where}","other":"ha scambiato {n} ottiche con altre più grandi ({where})"}, +"ops.l_optup":{"one":"ha potenziato il line system su {where}","other":"ha potenziato {n} line system ({where})"}, "ops.l_paid":"Costo: {cost} subito, {mo}/mese.", "ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"}, "ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"}, @@ -3256,6 +3258,8 @@ "ops.o_ix_d":"Ogni settimana: entra nei route server e chiedi il peering a ogni membro disponibile su ciascuna delle tue porte di exchange.", "ops.o_optics":"Accendi più fibra", "ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.", +"ops.o_optup":"Potenzia il trasporto ottico", +"ops.o_optup_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Scegli un line system e ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte.", "ops.o_pni":"PNI con i grandi", "ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.", "ops.o_ports":"Margine sulle porte di peering", @@ -3276,6 +3280,8 @@ "ops.p_paid":"Peering a pagamento", "ops.p_pick":"Ottiche", "ops.p_prov":"Fornitore", +"ops.p_swap":"Ottiche più grandi", +"ops.p_sys":"Line system", "ops.p_tier":"Taglia", "ops.p_x":"Margine", "ops.paused":"In pausa", @@ -3290,6 +3296,7 @@ "ops.shift_report":"La settimana di {name}", "ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta", "ops.standing_orders":"Ordini permanenti", +"ops.sys_next":"Il successivo, quando è pieno", "ops.template":"Nuovo POP da modello", "ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.", "ops.tpl_bb":"Banda larga", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 084cdaf..2ff2e89 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3224,6 +3224,8 @@ "ops.l_decom":{"one":"devolveu uma wave pequena em {where}","other":"devolveu {n} waves pequenas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"acendeu um canal em {where}","other":"acendeu {n} canais ({where})"}, +"ops.l_optswap":{"one":"trocou uma óptica por uma maior em {where}","other":"trocou {n} ópticas por maiores ({where})"}, +"ops.l_optup":{"one":"melhorou o sistema de linha em {where}","other":"melhorou {n} sistemas de linha ({where})"}, "ops.l_paid":"Custo: {cost} de entrada, {mo}/mês.", "ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"}, "ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"}, @@ -3256,6 +3258,8 @@ "ops.o_ix_d":"Toda semana: entrar nos route servers e pedir peering a cada membro disposto em cada uma das suas portas de exchange.", "ops.o_optics":"Acender mais fibra", "ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.", +"ops.o_optup":"Melhorar o transporte óptico", +"ops.o_optup_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Escolha um sistema de linha e cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite.", "ops.o_pni":"PNI com os grandes", "ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.", "ops.o_ports":"Folga nas portas de peering", @@ -3276,6 +3280,8 @@ "ops.p_paid":"Peering pago", "ops.p_pick":"Ópticas", "ops.p_prov":"Provedor", +"ops.p_swap":"Ópticas maiores", +"ops.p_sys":"Sistema de linha", "ops.p_tier":"Tamanho", "ops.p_x":"Folga", "ops.paused":"Em pausa", @@ -3290,6 +3296,7 @@ "ops.shift_report":"A semana de {name}", "ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura", "ops.standing_orders":"Ordens permanentes", +"ops.sys_next":"O próximo, quando cheio", "ops.template":"Novo POP por modelo", "ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.", "ops.tpl_bb":"Banda larga", diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 8f9f78e..da183e6 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -22,12 +22,16 @@ const OPS=[ {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}}, {k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}}, {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}}, + // Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to + // a chosen line system. A line system swap is a day without that fiber: only where the traffic gets around it. + {k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}, + sys:{d:'next',v:['next','roadm','cl'],l:N_('ops.p_sys'),f:v=>v==='next'?tr('ops.sys_next'):DF_SYS[v].n},swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}}, {k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>v?tr('common.on'):tr('common.off')}}}, ]; const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); const OPS_TPL=['bb','transit','ix','kit']; // What the shift log can say. One line per day: "{name} did this, that and the other." -const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; +const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),optup:N_('ops.l_optup'),optswap:N_('ops.l_optswap'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_FF_RATE={oncall:1/150,bgp:1/60}; @@ -206,6 +210,33 @@ const OPS_RUN={ const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}}, + optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0; + const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l)); + const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a)); + for(const l of ls){ + // The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot. + const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]S.day)&&X.can('optup',cost)){tries++;const ok=opsDarkOk(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT); + if(ok){const s0=l.sys,top=goal==='next'?to:goal; + for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;} + // The fiber is dark until tomorrow: its optics wait. + if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);continue;}}}} + // Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and + // the old optics go on the shelf as spares. + if(!swap)continue; + for(let step=0;step<8&&full(l)&&hot(l);step++){const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1; + const lit=Object.keys(cnt).sort((a,b)=>optG(a,l)-optG(b,l)),o1=lit[0];if(!o1)break; + const ports=(o,c)=>S.pops[c]?chPorts(o,c):0,room=(o2,c)=>!S.pops[c]||portsUsed(c)+ports(o2,c)-ports(o1,c)<=portsMax(c)+1e-9; + // Asked with one small channel already out: a full fiber refuses any optic. + const ch0=l.ch,i1=ch0.indexOf(o1);l.ch=ch0.filter((k,i)=>i!==i1);let o2; + try{o2=Object.keys(OPT).filter(o=>optG(o,l)>optG(o1,l)&&!chWhy(l,o)&&room(o,l.a)&&room(o,l.b)).sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0];}finally{l.ch=ch0;}if(!o2)break; + const n2=(cnt[o2]||0)+1,cost=opticCountCost(l,o2,n2);if(!X.can('optup',cost))break; + const was=dfCap(l); + X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2}); + if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;}); + if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));}}}, caches(X){const g=opsP('caches','g'); for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue; const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; @@ -232,11 +263,24 @@ const OPS_RUN={ if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}}, }; +// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once, +// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week +// (not saved: after a reload it is simply tested again). +const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'}; +// Another live path between the fiber's two cities, without it: a plain walk, no routing. +function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);} + const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} +// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing +// is the yardstick (routed again first if this shift already changed the network); R is put back after. +function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){compute();X.dirty=false;} + const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{}; + try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);} + finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}} // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first. function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true); const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} -const OPS_ORDER=['repair','routers','transit','ports','optics','caches','ix','pni','decom']; +const OPS_ORDER=['repair','routers','transit','ports','optup','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. diff --git a/src/i18n/en.js b/src/i18n/en.js index 6f9778d..da93f15 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3225,6 +3225,8 @@ "ops.l_decom":{"one":"handed back a small wave on {where}","other":"handed back {n} small waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"lit a channel on {where}","other":"lit {n} channels ({where})"}, +"ops.l_optswap":{"one":"swapped an optic for a bigger one on {where}","other":"swapped {n} optics for bigger ones ({where})"}, +"ops.l_optup":{"one":"upgraded the line system on {where}","other":"upgraded {n} line systems ({where})"}, "ops.l_paid":"Cost: {cost} up front, {mo}/mo.", "ops.l_peer":{"one":"peered with a network at {where}","other":"peered with {n} networks at {where}"}, "ops.l_pni":{"one":"ordered a PNI in {where}","other":"ordered {n} PNIs ({where})"}, @@ -3257,6 +3259,8 @@ "ops.o_ix_d":"Every week: join the route servers and ask every willing member at each of your exchange ports.", "ops.o_optics":"Light more fiber", "ops.o_optics_d":"Add optics to dark fiber that runs hot, and light new fiber the day it is handed over.", +"ops.o_optup":"Upgrade optical transport", +"ops.o_optup_d":"On fiber that is full and runs hot, move the line system up a size, or trade the smallest channels for bigger optics (the old ones go on the shelf). Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so only where the traffic gets around it and no customer rides it, one a night.", "ops.o_pni":"PNI with the big ones", "ops.o_pni_d":"Every week: order a PNI with every willing network sending enough traffic at your POPs, at each network's own minimum size.", "ops.o_ports":"Keep peering headroom", @@ -3277,6 +3281,8 @@ "ops.p_paid":"Paid peering", "ops.p_pick":"Optics", "ops.p_prov":"Provider", +"ops.p_swap":"Bigger optics", +"ops.p_sys":"Line system", "ops.p_tier":"Size", "ops.p_x":"Headroom", "ops.paused":"Paused", @@ -3291,6 +3297,7 @@ "ops.shift_report":"{name}'s week", "ops.spent_and_mo":"This month: {price} up front, {mo}/mo on the bill", "ops.standing_orders":"Standing orders", +"ops.sys_next":"Next one, when full", "ops.template":"New POP from template", "ops.template_note":"Pick what {name} sets up when you open a city from the template. The standing orders take it from there.", "ops.tpl_bb":"Broadband", diff --git a/tests/intern-optical-upgrade.test.js b/tests/intern-optical-upgrade.test.js new file mode 100644 index 0000000..a18ad12 --- /dev/null +++ b/tests/intern-optical-upgrade.test.js @@ -0,0 +1,121 @@ +// The intern upgrades optical transport: line systems up a size (only where the traffic gets around the day-long swap and +// no customer rides the fiber), optics traded for bigger ones on full, hot fiber, or every fiber up to a chosen line system. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Frankfurt (transit) and Amsterdam (broadband) joined by a full Rainbow-in-a-Box fiber of 16×400G, and the long way +// round through Paris on two waves. Level 6: every line system and optic unlocked. Change Freeze: no fat fingers. +const BASE = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + + "for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" + + "S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" + + "S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," + + "{id:'w1',a:'fra',b:'par',kind:'wave',tier:4,km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:4,km:430,cut:0,mo:1}];compute();" + + "ACT.opsHire({id:'kevin'});S.ops.floor=0;S.ops.cap.optup=0;closeModal()"; +function game(t, extra) { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const order = (ev, p) => ev(`S.ops.on.optup=true;S.ops.p.optup=${JSON.stringify(p)}`); +// The fiber runs at 90% of what it carries. +const heat = ev => ev("R.load.f=dfCap(S.links[0])*0.9"); +const fiber = ev => JSON.parse(ev("JSON.stringify({sys:S.links[0].sys,ch:S.links[0].ch.join(),down:S.links[0].eqDown>S.day})")); + +test('a full, hot fiber gets the next line system where the traffic gets around it, at the price of the click', t => { + const { ev, errors } = game(t); + order(ev, { at: 80 }); + const want = ev('sysUpCost(S.links[0])'), served = ev('R.served'), c0 = ev('S.cash'); + heat(ev); + ev('opsDay(S.day)'); + assert.equal(fiber(ev).sys, 'roadm', 'up to the ROADMaster'); + assert.equal(c0 - ev('S.cash'), want, 'the shift paid exactly what Upgrade costs'); + assert.equal(fiber(ev).down, true, 'the swap takes the fiber down for the day, as by hand'); + assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through, the long way round'); + assert.match(ev('opsLine(S.ops.log[0])'), /upgraded the line system on Frankfurt–Amsterdam ⇧ROADM/); + // Not hot enough, or not full: nothing. + const { ev: ev2 } = game(t); + order(ev2, { at: 80 }); + ev2('R.load.f=dfCap(S.links[0])*0.5;opsDay(S.day)'); + ev2('S.links[0].ch.pop();R.load.f=dfCap(S.links[0])*0.95;S.day++;opsDay(S.day)'); + assert.equal(fiber(ev2).sys, 'lite', 'a fiber with a free channel gets more optics from Light more fiber, not a new line system'); + assert.deepEqual(errors, []); +}); + +test('no way around, or a customer on the fiber: no swap; bigger optics instead, one channel at a time', t => { + // Without the waves through Paris, Amsterdam would be cut off for the day. + const { ev, errors } = game(t, "S.links=S.links.filter(l=>l.kind==='df');compute()"); + order(ev, { at: 80 }); + heat(ev); + const c0 = ev('dfCap(S.links[0])'), cash0 = ev('S.cash'); + ev('opsDay(S.day)'); + assert.equal(fiber(ev).sys, 'lite', 'no outage'); + assert.equal(fiber(ev).down, false); + assert.ok(ev('dfCap(S.links[0])') > c0, 'more capacity from bigger optics'); + assert.match(fiber(ev).ch, /zr8/, 'Sizzle 800ZR+ in place of some 400ZR+'); + assert.equal(ev("S.links[0].ch.length"), 16, 'still sixteen channels'); + assert.ok(ev("S.spares.zr4") > 0, 'the old optics went on the shelf'); + assert.ok(cash0 - ev('S.cash') > 0); + assert.match(ev('opsLine(S.ops.log[0])'), /swapped \d+ optics for bigger ones \(Frankfurt–Amsterdam 400G→800G\)/); + // A customer's wave on the fiber: the intern never swaps its line system, even with a way around. + const { ev: ev2 } = game(t, "S.links[0].ch.length=15;S.biz.push({id:'cw',name:'Wave',city:'fra',city2:'ams',type:'wwave',link:'f',slots:1,bw:400,rate:1})"); + order(ev2, { at: 80, swap: false }); + heat(ev2); + ev2('opsDay(S.day)'); + assert.equal(fiber(ev2).sys, 'lite'); + assert.deepEqual(errors, []); +}); + +test('a chosen line system: every fiber below it is moved up, two steps in one night if need be, one fiber a night', t => { + const { ev, errors } = game(t, "S.links[0].ch=['zr4'];" + + "for(const [i,a,b] of [[2,'fra','par'],[3,'par','ams']])S.links.push({id:'g'+i,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:'t'+i,ready:0,cut:0,mo:1,pairs:1});compute()"); + order(ev, { sys: 'cl', at: 90 }); + const want = ev("sysCost('roadm')+sysCost('cl')"); + const sys = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='df').map(l=>l.sys))")); + const c0 = ev('S.cash'); + ev('opsDay(S.day)'); + assert.equal(sys().filter(s => s === 'cl').length, 1, 'one fiber a night, cold or not'); + assert.equal(c0 - ev('S.cash'), want, 'both steps in one night: one outage, not two'); + for (let n = 0; n < 6 && sys().some(s => s !== 'cl'); n++) ev('S.day+=2;compute();opsDay(S.day)'); + assert.deepEqual(sys(), ['cl', 'cl', 'cl', 'cl'].slice(0, sys().length), 'the rest on the nights after'); + // Nothing is ever moved down. + ev("S.ops.p.optup.sys='roadm';S.day+=2;compute();opsDay(S.day)"); + assert.ok(sys().every(s => s === 'cl')); + // A fiber with no way around is tested once, then left alone for a week: no routing every night for nothing. + ev("S.links=S.links.filter(l=>l.id==='f');S.links[0].sys='lite';S.ops.p.optup.sys='cl';S.day+=2;compute()"); + const runs = () => ev('window.__runs||0'); + ev("window.__runs=0;const c0=compute;compute=function(){window.__runs++;return c0.apply(this,arguments);};opsDay(S.day)"); + assert.equal(sys()[0], 'lite'); + assert.equal(runs(), 0, 'no other path at all: not even one routing to find out'); + ev("S.links.push({id:'w9',a:'fra',b:'ams',kind:'wave',tier:0,km:450,cut:0,mo:1});S.day+=OPTUP_WAIT;window.__runs=0;opsDay(S.day)"); + assert.equal(runs(), 1, 'a path, too thin: one routing to find out'); + assert.equal(sys()[0], 'lite'); + ev('S.day++;window.__runs=0;opsDay(S.day)'); + assert.equal(runs(), 0, 'and not again the next night'); + assert.deepEqual(errors, []); +}); + +test('the budget holds, the setting is saved, and the sheet shows it as lists', t => { + const { ev, dom, errors } = game(t); + order(ev, { at: 80 }); + ev('S.ops.cap.optup=10000'); + heat(ev); + ev('opsDay(S.day)'); + assert.equal(fiber(ev).sys, 'lite', 'a $10k budget does not buy a line system'); + assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')")); + const back = v => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.ops.p.optup=${v};sanitize(s);return JSON.stringify(s.ops.p.optup);})()`); + assert.deepEqual(JSON.parse(back("{sys:'cl',swap:false,at:70}")), { at: 70, sys: 'cl', swap: false }); + assert.deepEqual(JSON.parse(back("{sys:'lite',swap:'yes'}")), {}); + assert.deepEqual(JSON.parse(back('undefined')), {}, 'an old save without the order'); + ev("const s=JSON.parse(JSON.stringify(S));delete s.ops.on.optup;sanitize(s);window.__off=s.ops.on.optup"); + assert.equal(ev('__off'), false, 'off in an old save'); + dom.window.innerWidth = 360; + ev("ACT.phoneTab({t:'noc'})"); + dom.window.document.querySelector('#leftBody [data-act="opsOpen"]').click(); + const sel = [...dom.window.document.querySelectorAll('#modalCard select[data-chg="opsParam"]')].find(s => s.dataset.args === '{"k":"optup","p":"sys"}'); + assert.deepEqual([...sel.options].map(o => o.textContent), ['Next one, when full', 'ROADMaster 9000', 'ROADMaster 9000 C+L']); + assert.match(dom.window.document.getElementById('modalCard').textContent, /Upgrade optical transport/); + assert.deepEqual(errors, []); +}); From 2b48a6ad653a489baf50daee33f9da68f99e4519 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 00:41:42 +0100 Subject: [PATCH 2/8] A build standard for the whole network, kept by the intern One sheet sets the target state for every POP, port and fiber: router model and count, a second building, a generator, LAG members (split over both buildings), an exchange port wherever there is one, PNIs spread over the cities that pay, the line system, the fastest optics that reach and wave sizes. S.popStd keeps its name; an old {g,rt} standard loads with the same meaning. One read-only plan prices every job with the game's own cost helpers, POPs busiest first, then ports, then fiber hottest first. The sheet's summary, the MCP quote, "Bring everything up now" and the new "Keep to the build standard" order all use it, so the quote is what the click spends. The order works a few jobs a shift through the budget and the cash floor: a second router before a swap on a busy POP, no generator under a nogen covenant, no De-Kicks, a line system swap only where the fiber is quiet or a parallel link carries it, one a shift. New POPs get the POP part of the standard, and the template's kit no longer pays for it twice. opsMoNow counts generators and second buildings. --- CHANGELOG.md | 1 + site/i18n/de.js | 50 +- site/i18n/es.js | 50 +- site/i18n/fr.js | 50 +- site/i18n/it.js | 50 +- site/i18n/pt.js | 50 +- src/agent/10-domains.js | 2 + src/agent/20-commands.js | 14 +- src/agent/30-docs.js | 2 +- src/agent/50-screen.js | 2 +- src/agent/60-dispatch.js | 3 +- src/game/10-catalog/30-supply-chain.js | 3 +- src/game/60-features/95-standing-orders.js | 44 +- src/game/60-features/96-pop-standard.js | 217 +++++++- src/game/80-simulation/50-sanitize.js | 4 +- src/game/90-actions/85-routing-and-routers.js | 6 +- src/game/90-actions/88-build-standard.js | 14 + src/game/90-actions/88-ops.js | 8 +- src/game/90-actions/89-game-and-settings.js | 2 +- src/game/90-actions/90-action-helpers.js | 2 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/57-ops-panel.js | 4 +- src/game/93-ui/59-build-standard.js | 38 ++ src/i18n/en.js | 50 +- tests/build-standard.test.js | 518 ++++++++++++++++++ tests/i18n.test.js | 4 +- tests/mcp-commands.test.js | 24 + 27 files changed, 1153 insertions(+), 61 deletions(-) create mode 100644 src/game/90-actions/88-build-standard.js create mode 100644 src/game/93-ui/59-build-standard.js create mode 100644 tests/build-standard.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 382ce54..fad4db7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. +- Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. ## [3.0.0] — 2026-11-06 diff --git a/site/i18n/de.js b/site/i18n/de.js index 36c6582..4e82c6e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -397,6 +397,48 @@ "broker.win_text":"{name} (AS{asn}) hat in {days} Tagen eigene Kabel auf {n} Kontinente verlegt und verkauft anderen Carriern Kapazität für {mo} im Monat. Die Ozeane sind jetzt dein Graben.", "broker.won_on_date":"Gewonnen am {date}: Deine eigenen Kabel überspannen die Ozeane, und Carrier zahlen dir für ihre Nutzung.", "broker.your_glass_gear_is_already_yours":"Als Kabelmakler gehören dir jede Fiber, jedes Leitungssystem, jede Optik, jedes Seekabel und die Router, um sie zu beleuchten, schon jetzt, egal was das Level sagt.", +"bstd.all_up":"Alles entspricht dem Standard.", +"bstd.any_model":"beliebiges Modell", +"bstd.applied":{"one":"Ein Job für den Build-Standard erledigt, {cost}.","other":"{n} Jobs für den Build-Standard erledigt, {cost}."}, +"bstd.applied_none":"Für den Build-Standard ließ sich gerade nichts machen.", +"bstd.apply_nothing":"Nichts unter dem Standard", +"bstd.apply_now":"Jetzt alles hochziehen · {cost}", +"bstd.apply_wait":"Nichts zu tun, bis diese Glasfasern frei sind", +"bstd.at_every_pop":"An jedem POP", +"bstd.at_least_n":"Mindestens {n}", +"bstd.below":"Heute unter dem Standard", +"bstd.both_buildings":"Über beide Gebäude", +"bstd.cost_mo":"Laufende Kosten", +"bstd.cost_now":"Um jetzt alles hochzuziehen", +"bstd.edit":"Build-Standard bearbeiten", +"bstd.every_exchange":"Wo es einen IX gibt", +"bstd.fastest":"Die schnellste, die reicht", +"bstd.fiber_note":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel: nur wenn sie ruhig ist oder ein paralleler Link ihre Last trägt.", +"bstd.from_level":"(Level {lv})", +"bstd.g_fiber":"Glasfaser und Waves", +"bstd.g_port":"Ports und Peering", +"bstd.generator":"Generator", +"bstd.held":{"one":"Eine Glasfaser behält vorerst ihr Line System, bis sie ruhig ist oder ein paralleler Link ihre Last für den Tag trägt, an dem sie dunkel ist. Bis dahin bekommt sie die schnellste Optik, die ihr Line System nimmt.","other":"{n} Glasfasern behalten vorerst ihr Line System, bis sie ruhig sind oder ein paralleler Link ihre Last für den Tag trägt, an dem sie dunkel sind. Bis dahin bekommen sie die schnellste Optik, die ihr Line System nimmt."}, +"bstd.hire_note":"Stell in Ops einen NOC-Praktikanten ein, dann hält er jeden POP, Port und jede Glasfaser auf dem Standard: ein paar Jobs pro Tag, die meistbelasteten zuerst, im Monatsbudget und nur mit Geld übrig.", +"bstd.in_n_cities":"In mindestens {n} Städten", +"bstd.intern_keeps":"{name} hält das Netz auf Standard", +"bstd.keep":"So lassen", +"bstd.l_ix":"IX-Port", +"bstd.l_lag":"LAG-Member", +"bstd.l_model":"Router-Modell", +"bstd.l_pni":"PNIs pro Netz", +"bstd.l_site2":"Zweites Gebäude", +"bstd.l_split":"LAGs aufteilen", +"bstd.left":{"one":"Noch eine Sache liegt darunter und wartet auf Geld, eine ruhige Glasfaser oder eine Erweiterung.","other":"Noch {n} Sachen liegen darunter und warten auf Geld, eine ruhige Glasfaser oder eine Erweiterung."}, +"bstd.n_more_targets":{"one":"{n} weiteres Ziel","other":"{n} weitere Ziele"}, +"bstd.new_pops_note":"Ein neuer POP bekommt das sofort, solange er noch leer ist: kein Wartungsfenster. Reicht das Geld nicht, bekommt er, was passt. Ein noch gesperrtes Modell heißt: das beste freigeschaltete darunter.", +"bstd.none_set":"Noch kein Standard: Jedes Ziel steht auf „So lassen“.", +"bstd.now_line":"Standard: {list}", +"bstd.or_better":"{x} oder besser", +"bstd.port_note":"LAGs und Aufteilung gelten für Transit-, IX- und PNI-Ports. Ein neues PNI-Member ist eine Erweiterung und kommt erst Wochen später.", +"bstd.second_building":"zweites Gebäude", +"bstd.tagline":"Ein Design fürs ganze Netz: was jeder POP, Port und jede Glasfaser haben soll. Neue POPs bekommen den POP-Teil am Tag der Eröffnung; dein Praktikant oder der Button unten zieht den Rest nach.", +"bstd.title":"Build-Standard", "businesses.a_free_pni_with_voda_phony":"Ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.", "businesses.agi_lab_allegedly":"AGI-Labor (angeblich)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI-Labore (angeblich), die KI-WANs mit 12,8 bis 25,6 Tbps wollen, und kostenlose PNIs mit Du-opoly und Ooh-redoo. Hardware: Mikrowtik-CCR-3.2T-Router.", @@ -3237,6 +3279,7 @@ "ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"}, "ops.l_rs":{"one":"hat sich einem Route Server angeschlossen","other":"hat sich {n} Route Servern angeschlossen"}, "ops.l_snag":{"one":"ist bei {where} hängen geblieben und hat den Auftrag pausiert, bis du draufschaust","other":"ist bei {n} Aufträgen hängen geblieben ({where}) und hat sie pausiert, bis du draufschaust"}, +"ops.l_std":{"one":"hat {where} auf den Build-Standard gebracht","other":"hat {n} Jobs für den Build-Standard erledigt ({where})"}, "ops.l_transit":{"one":"hat Transit in {where} aufgestockt","other":"hat {n}-mal Transit aufgestockt ({where})"}, "ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.", "ops.model_next":"Nächste Generation, wenn ausgelastet", @@ -3270,6 +3313,8 @@ "ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.", "ops.o_routers":"Router voraus halten", "ops.o_routers_desc":"Einen Router dazustellen oder auf die nächste Generation tauschen, wo ein zweiter Router den Traffic trägt, sobald Last oder Ports eine Grenze überschreiten. Wähl ein Modell, und jeder POP mit einem kleineren wird darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.", +"ops.o_std":"Build-Standard einhalten", +"ops.o_std_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur auf einer ruhigen Glasfaser.", "ops.o_transit":"Transit-Reserve halten", "ops.o_transit_d":"Transit an jedem POP über einem Vielfachen seiner 30-Tage-Spitze halten: ein LAG-Member dazu oder eine Portgröße hoch.", "ops.ops":"Ops", @@ -3302,6 +3347,7 @@ "ops.template":"Neuer POP aus der Vorlage", "ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.", "ops.tpl_bb":"Breitband", +"ops.tpl_bstd":"Build-Standard", "ops.tpl_done":"{name} hat {city} eröffnet: {list}.", "ops.tpl_ix":"IX-Port", "ops.tpl_just_pop":"nur den POP", @@ -3800,12 +3846,12 @@ "pnis.us_east_is_sold_out_until":"US East ist bis auf Weiteres ausverkauft. „Bis auf Weiteres“ ist auch ausverkauft.", "pop_std.city_gets_the_standard_cost":"{city} bekommt den Standard: {n} × {model} für {cost}.", "pop_std.clear":"Entfernen", +"pop_std.includes_the_build_standard":"Inklusive deines Build-Standards: {list}, {cost} + {mo}/Monat. Reicht das Geld nicht, bekommt der POP, was passt.", "pop_std.includes_the_standard_n_model":"Inklusive deiner Standard-Router: {n} × {model}, {cost} + {mo}/Monat. Reicht das Geld nicht, bekommt der POP, was passt.", "pop_std.make_this_the_standard":"Zum Standard machen", -"pop_std.new_pops_now_start_with":"Neue POPs starten jetzt mit {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"Neue POPs starten jetzt mit {list}.", "pop_std.none":"Keiner", "pop_std.not_all_of_the_standard":"Nicht genug Geld oder Level für den ganzen Standard in {city}: Er bekam, was passte.", -"pop_std.standard_for_new_pops":"Standard für neue POPs", "pops_transit_ix.40_off_for_6_months":"40 % Rabatt für 6 Monate", "pops_transit_ix.40_off_ix_for_6_months":"40 % Rabatt auf {ix} für 6 Monate.
Dein Account Manager ist erleichtert. Das Kleingedruckte liest du später.", "pops_transit_ix.after_consulting_with_management_the":"„Nach Rücksprache mit dem Management …“
Der Preis ist gestiegen. Das Management wurde konsultiert.", diff --git a/site/i18n/es.js b/site/i18n/es.js index d447ada..2b78345 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -395,6 +395,48 @@ "broker.win_text":"{name} (AS{asn}) tendió sus propios cables hasta {n} continentes y vende {mo} al mes de capacidad a otros operadores, en {days} días. Los océanos son ahora tu zanja.", "broker.won_on_date":"Ganado el {date}: tus propios cables cruzan los océanos y los operadores te pagan por usarlos.", "broker.your_glass_gear_is_already_yours":"Como bróker de cables, toda la fibra, los sistemas de línea, los ópticos, los cables submarinos y los routers para iluminarlos ya son tuyos, diga lo que diga el nivel.", +"bstd.all_up":"Todo cumple el estándar.", +"bstd.any_model":"cualquier modelo", +"bstd.applied":{"one":"Un trabajo hecho para el estándar de red, {cost}.","other":"{n} trabajos hechos para el estándar de red, {cost}."}, +"bstd.applied_none":"Ahora mismo no se pudo hacer nada para el estándar de red.", +"bstd.apply_nothing":"Nada por debajo del estándar", +"bstd.apply_now":"Ponerlo todo al día ahora · {cost}", +"bstd.apply_wait":"Nada que hacer hasta que esas fibras estén libres", +"bstd.at_every_pop":"En cada POP", +"bstd.at_least_n":"Al menos {n}", +"bstd.below":"Por debajo del estándar hoy", +"bstd.both_buildings":"Repartidos en los dos edificios", +"bstd.cost_mo":"Costes mensuales", +"bstd.cost_now":"Para ponerlo todo al día ahora", +"bstd.edit":"Editar el estándar de red", +"bstd.every_exchange":"Donde haya un IX", +"bstd.fastest":"La más rápida que llegue", +"bstd.fiber_note":"Cambiar el sistema de línea deja la fibra apagada un día: solo si va tranquila o un enlace paralelo lleva su carga.", +"bstd.from_level":"(nivel {lv})", +"bstd.g_fiber":"Fibra y ondas", +"bstd.g_port":"Puertos y peering", +"bstd.generator":"generador", +"bstd.held":{"one":"Una fibra mantiene por ahora su sistema de línea, hasta que vaya tranquila o un enlace paralelo pueda llevar su carga el día que quede apagada. Mientras tanto recibe la óptica más rápida que admite su sistema de línea.","other":"{n} fibras mantienen por ahora su sistema de línea, hasta que vayan tranquilas o un enlace paralelo pueda llevar su carga el día que queden apagadas. Mientras tanto reciben la óptica más rápida que admite su sistema de línea."}, +"bstd.hire_note":"Contrata a un becario del NOC en Ops y mantendrá cada POP, puerto y fibra en el estándar: unos pocos trabajos al día, los más cargados primero, dentro de un presupuesto mensual y solo con dinero de sobra.", +"bstd.in_n_cities":"En al menos {n} ciudades", +"bstd.intern_keeps":"{name} mantiene la red en el estándar", +"bstd.keep":"Dejar como está", +"bstd.l_ix":"Puerto en un IX", +"bstd.l_lag":"Miembros de LAG", +"bstd.l_model":"Modelo de router", +"bstd.l_pni":"PNI por red", +"bstd.l_site2":"Segundo edificio", +"bstd.l_split":"Repartir los LAG", +"bstd.left":{"one":"Queda una cosa por debajo, esperando dinero, una fibra tranquila o que llegue una ampliación.","other":"Quedan {n} cosas por debajo, esperando dinero, una fibra tranquila o que llegue una ampliación."}, +"bstd.n_more_targets":{"one":"{n} objetivo más","other":"{n} objetivos más"}, +"bstd.new_pops_note":"Un POP nuevo recibe esto enseguida, mientras sigue vacío: sin ventana de mantenimiento. Si falta dinero, recibe lo que alcance. Un modelo aún bloqueado significa el mejor desbloqueado por debajo.", +"bstd.none_set":"Aún no hay estándar: todos los objetivos dicen Dejar como está.", +"bstd.now_line":"Estándar: {list}", +"bstd.or_better":"{x} o mejor", +"bstd.port_note":"Los LAG y el reparto valen para los puertos de tránsito, IX y PNI. Un miembro nuevo de PNI es una ampliación y llega semanas después.", +"bstd.second_building":"segundo edificio", +"bstd.tagline":"Un solo diseño para toda la red: lo que debe tener cada POP, puerto y fibra. Los POP nuevos reciben la parte del POP el día que abren; tu becario, o el botón de abajo, pone el resto al día.", +"bstd.title":"Estándar de red", "businesses.a_free_pni_with_voda_phony":"Un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio de AGI (supuestamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratorios de AGI (supuestamente) que quieren WAN de IA de 12.8 a 25.6 Tbps, y PNIs gratis con Du-opoly y Ooh-redoo. Equipo: routers Mikrowtik CCR 3.2T.", @@ -3235,6 +3277,7 @@ "ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"}, "ops.l_rs":{"one":"se unió a un route server","other":"se unió a {n} route servers"}, "ops.l_snag":{"one":"se atascó con {where} y la pausó hasta que le eches un vistazo","other":"se atascó con {n} órdenes ({where}) y las pausó hasta que les eches un vistazo"}, +"ops.l_std":{"one":"puso {where} al nivel del estándar de red","other":"hizo {n} trabajos para el estándar de red ({where})"}, "ops.l_transit":{"one":"amplió el tránsito en {where}","other":"amplió el tránsito {n} veces ({where})"}, "ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.", "ops.model_next":"Siguiente generación, si va lleno", @@ -3268,6 +3311,8 @@ "ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.", "ops.o_routers":"Routers por delante", "ops.o_routers_desc":"Añadir un router, o pasar a la siguiente generación donde un segundo router lleve el tráfico, cuando la carga o los puertos pasen de un nivel. Elige un modelo y cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.", +"ops.o_std":"Mantener el estándar de red", +"ops.o_std_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia en una fibra tranquila.", "ops.o_transit":"Margen de tránsito", "ops.o_transit_d":"Mantener el tránsito de cada POP por encima de un múltiplo de su pico de 30 días: un miembro LAG más o un tamaño de puerto mayor.", "ops.ops":"Ops", @@ -3300,6 +3345,7 @@ "ops.template":"POP nuevo desde plantilla", "ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.", "ops.tpl_bb":"Banda ancha", +"ops.tpl_bstd":"estándar de red", "ops.tpl_done":"{name} abrió {city}: {list}.", "ops.tpl_ix":"Puerto IX", "ops.tpl_just_pop":"solo el POP", @@ -3798,12 +3844,12 @@ "pnis.us_east_is_sold_out_until":"US East está agotado hasta nuevo aviso. El nuevo aviso también está agotado.", "pop_std.city_gets_the_standard_cost":"{city} recibe el estándar: {n} × {model} por {cost}.", "pop_std.clear":"Quitar", +"pop_std.includes_the_build_standard":"Incluye tu estándar de red: {list}, {cost} + {mo}/mes. Si falta dinero, el POP recibe lo que alcance.", "pop_std.includes_the_standard_n_model":"Incluye tus routers estándar: {n} × {model}, {cost} + {mo}/mes. Si falta dinero, el POP recibe lo que alcance.", "pop_std.make_this_the_standard":"Convertir en estándar", -"pop_std.new_pops_now_start_with":"Los nuevos POP empiezan ahora con {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"Los nuevos POP empiezan ahora con {list}.", "pop_std.none":"Ninguno", "pop_std.not_all_of_the_standard":"No hay dinero o nivel para todo el estándar en {city}: recibió lo que cupo.", -"pop_std.standard_for_new_pops":"Estándar para nuevos POP", "pops_transit_ix.40_off_for_6_months":"40 % de descuento durante 6 meses", "pops_transit_ix.40_off_ix_for_6_months":"40 % de descuento en {ix} durante 6 meses.
Tu gestor de cuenta está aliviado. Lee la letra pequeña más tarde.", "pops_transit_ix.after_consulting_with_management_the":"«Tras consultar con la dirección…»
El precio subió. Se consultó a la dirección.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 908b461..d239d01 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -395,6 +395,48 @@ "broker.win_text":"{name} (AS{asn}) a posé ses propres câbles jusqu’à {n} continents et vend {mo} de capacité par mois à d’autres opérateurs, en {days} jours. Les océans sont ta tranchée maintenant.", "broker.won_on_date":"Gagné le {date} : tes propres câbles traversent les océans, et les opérateurs te paient pour s’en servir.", "broker.your_glass_gear_is_already_yours":"En courtier en câbles, toute la fibre, les systèmes de ligne, les optiques, les câbles sous-marins et les routeurs pour les allumer sont déjà à toi, quoi que dise le niveau.", +"bstd.all_up":"Tout est au standard.", +"bstd.any_model":"n’importe quel modèle", +"bstd.applied":{"one":"Un chantier fait pour le standard réseau, {cost}.","other":"{n} chantiers faits pour le standard réseau, {cost}."}, +"bstd.applied_none":"Rien n’a pu être fait pour le standard réseau pour l’instant.", +"bstd.apply_nothing":"Rien sous le standard", +"bstd.apply_now":"Tout mettre à niveau maintenant · {cost}", +"bstd.apply_wait":"Rien à faire tant que ces fibres ne sont pas libres", +"bstd.at_every_pop":"Dans chaque POP", +"bstd.at_least_n":"Au moins {n}", +"bstd.below":"Sous le standard aujourd’hui", +"bstd.both_buildings":"Répartis sur les deux bâtiments", +"bstd.cost_mo":"Coûts mensuels", +"bstd.cost_now":"Pour tout mettre à niveau maintenant", +"bstd.edit":"Modifier le standard réseau", +"bstd.every_exchange":"Partout où il y a un IX", +"bstd.fastest":"La plus rapide qui porte", +"bstd.fiber_note":"Changer le système de ligne éteint la fibre pendant un jour : seulement si elle est calme ou qu’un lien parallèle porte sa charge.", +"bstd.from_level":"(niveau {lv})", +"bstd.g_fiber":"Fibre et longueurs d’onde", +"bstd.g_port":"Ports et peering", +"bstd.generator":"groupe électrogène", +"bstd.held":{"one":"Une fibre garde son système de ligne pour l’instant, jusqu’à ce qu’elle soit calme ou qu’un lien parallèle puisse porter sa charge le jour où elle est éteinte. D’ici là, elle reçoit l’optique la plus rapide que son système de ligne accepte.","other":"{n} fibres gardent leur système de ligne pour l’instant, jusqu’à ce qu’elles soient calmes ou qu’un lien parallèle puisse porter leur charge le jour où elles sont éteintes. D’ici là, elles reçoivent l’optique la plus rapide que leur système de ligne accepte."}, +"bstd.hire_note":"Recrute un stagiaire NOC dans Ops et il garde chaque POP, port et fibre au standard : quelques chantiers par jour, les plus chargés d’abord, dans un budget mensuel et seulement avec de l’argent en trop.", +"bstd.in_n_cities":"Dans au moins {n} villes", +"bstd.intern_keeps":"{name} garde le réseau au standard", +"bstd.keep":"Laisser tel quel", +"bstd.l_ix":"Port IX", +"bstd.l_lag":"Membres de LAG", +"bstd.l_model":"Modèle de routeur", +"bstd.l_pni":"PNI par réseau", +"bstd.l_site2":"Second bâtiment", +"bstd.l_split":"Répartir les LAG", +"bstd.left":{"one":"Encore un élément en dessous : il attend de l’argent, une fibre calme ou une extension.","other":"Encore {n} éléments en dessous : ils attendent de l’argent, une fibre calme ou une extension."}, +"bstd.n_more_targets":{"one":"{n} autre objectif","other":"{n} autres objectifs"}, +"bstd.new_pops_note":"Un nouveau POP reçoit tout ça d’un coup, tant qu’il est vide : pas de fenêtre de maintenance. Si l’argent manque, il reçoit ce qui rentre. Un modèle pas encore débloqué veut dire le meilleur débloqué en dessous.", +"bstd.none_set":"Pas encore de standard : chaque objectif est sur Laisser tel quel.", +"bstd.now_line":"Standard : {list}", +"bstd.or_better":"{x} ou mieux", +"bstd.port_note":"LAG et répartition valent pour les ports de transit, IX et PNI. Un nouveau membre de PNI est une extension et arrive des semaines plus tard.", +"bstd.second_building":"second bâtiment", +"bstd.tagline":"Un seul design pour tout le réseau : ce que chaque POP, port et fibre doit avoir. Les nouveaux POP reçoivent la partie POP le jour de leur ouverture ; ton stagiaire, ou le bouton plus bas, met le reste à niveau.", +"bstd.title":"Standard réseau", "businesses.a_free_pni_with_voda_phony":"Un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.", "businesses.agi_lab_allegedly":"Labo d’AGI (soi-disant)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Des labos d’AGI (soi-disant) qui veulent des WAN IA de 12,8 à 25,6 Tbps, et des PNI gratuits avec Du-opoly et Ooh-redoo. Matos : routeurs Mikrowtik CCR 3.2T.", @@ -3235,6 +3277,7 @@ "ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"}, "ops.l_rs":{"one":"a rejoint un route server","other":"a rejoint {n} route servers"}, "ops.l_snag":{"one":"a calé sur {where} et l'a mis en pause en attendant que tu jettes un œil","other":"a calé sur {n} ordres ({where}) et les a mis en pause en attendant que tu jettes un œil"}, +"ops.l_std":{"one":"a mis {where} au standard réseau","other":"a fait {n} chantiers pour le standard réseau ({where})"}, "ops.l_transit":{"one":"a renforcé le transit à {where}","other":"a renforcé le transit {n} fois ({where})"}, "ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.", "ops.model_next":"Génération suivante, si chargé", @@ -3268,6 +3311,8 @@ "ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.", "ops.o_routers":"Garder les routeurs en avance", "ops.o_routers_desc":"Ajouter un routeur, ou passer à la génération suivante là où un second routeur porte le trafic, quand la charge ou les ports dépassent un seuil. Choisissez un modèle, et chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.", +"ops.o_std":"Tenir le standard réseau", +"ops.o_std_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que sur une fibre calme.", "ops.o_transit":"Garder de la marge de transit", "ops.o_transit_d":"Garder le transit de chaque POP au-dessus d'un multiple de son pic sur 30 jours : un membre LAG de plus, ou une taille de port au-dessus.", "ops.ops":"Ops", @@ -3300,6 +3345,7 @@ "ops.template":"Nouveau POP depuis le modèle", "ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.", "ops.tpl_bb":"Haut débit", +"ops.tpl_bstd":"standard réseau", "ops.tpl_done":"{name} a ouvert {city} : {list}.", "ops.tpl_ix":"Port IX", "ops.tpl_just_pop":"juste le POP", @@ -3798,12 +3844,12 @@ "pnis.us_east_is_sold_out_until":"US East est complet jusqu’à nouvel ordre. Le nouvel ordre est complet aussi.", "pop_std.city_gets_the_standard_cost":"{city} reçoit le standard : {n} × {model} pour {cost}.", "pop_std.clear":"Effacer", +"pop_std.includes_the_build_standard":"Inclut ton standard réseau : {list}, {cost} + {mo}/mois. Si l’argent manque, le POP reçoit ce qui rentre.", "pop_std.includes_the_standard_n_model":"Inclut tes routeurs standard : {n} × {model}, {cost} + {mo}/mois. Si l’argent manque, le POP reçoit ce qui rentre.", "pop_std.make_this_the_standard":"En faire le standard", -"pop_std.new_pops_now_start_with":"Les nouveaux POP démarrent désormais avec {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"Les nouveaux POP démarrent désormais avec {list}.", "pop_std.none":"Aucun", "pop_std.not_all_of_the_standard":"Pas assez d'argent ou de niveau pour tout le standard à {city} : il a reçu ce qui passait.", -"pop_std.standard_for_new_pops":"Standard des nouveaux POP", "pops_transit_ix.40_off_for_6_months":"40 % de remise pendant 6 mois", "pops_transit_ix.40_off_ix_for_6_months":"40 % de remise sur {ix} pendant 6 mois.
Ton account manager est soulagé. Lis les petites lignes plus tard.", "pops_transit_ix.after_consulting_with_management_the":"« Après consultation de la direction… »
Le prix a augmenté. La direction a été consultée.", diff --git a/site/i18n/it.js b/site/i18n/it.js index e745eff..49e3639 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -395,6 +395,48 @@ "broker.win_text":"{name} (AS{asn}) ha posato i propri cavi fino a {n} continenti e vende {mo} al mese di capacità ad altri operatori, in {days} giorni. Gli oceani ora sono la tua trincea.", "broker.won_on_date":"Vinto il {date}: i tuoi cavi attraversano gli oceani e gli operatori ti pagano per usarli.", "broker.your_glass_gear_is_already_yours":"Da broker di cavi, ogni fibra, sistema di linea, ottica, cavo sottomarino e i router per accenderli sono già tuoi, qualunque cosa dica il livello.", +"bstd.all_up":"Tutto è a standard.", +"bstd.any_model":"qualsiasi modello", +"bstd.applied":{"one":"Un lavoro fatto per lo standard di rete, {cost}.","other":"{n} lavori fatti per lo standard di rete, {cost}."}, +"bstd.applied_none":"Per ora non si è potuto fare niente per lo standard di rete.", +"bstd.apply_nothing":"Niente sotto lo standard", +"bstd.apply_now":"Porta tutto a standard ora · {cost}", +"bstd.apply_wait":"Niente da fare finché quelle fibre non sono libere", +"bstd.at_every_pop":"In ogni POP", +"bstd.at_least_n":"Almeno {n}", +"bstd.below":"Sotto lo standard oggi", +"bstd.both_buildings":"Su entrambi gli edifici", +"bstd.cost_mo":"Costi mensili", +"bstd.cost_now":"Per portare tutto a standard ora", +"bstd.edit":"Modifica lo standard di rete", +"bstd.every_exchange":"Ovunque ci sia un IX", +"bstd.fastest":"La più veloce che arriva", +"bstd.fiber_note":"Cambiare il sistema di linea spegne la fibra per un giorno: solo se è tranquilla o se un link parallelo ne regge il carico.", +"bstd.from_level":"(livello {lv})", +"bstd.g_fiber":"Fibra e wave", +"bstd.g_port":"Porte e peering", +"bstd.generator":"generatore", +"bstd.held":{"one":"Una fibra tiene per ora il suo sistema di linea, finché non è tranquilla o un link parallelo può reggerne il carico il giorno in cui resta spenta. Nel frattempo riceve l’ottica più veloce che il suo sistema di linea accetta.","other":"{n} fibre tengono per ora il loro sistema di linea, finché non sono tranquille o un link parallelo può reggerne il carico il giorno in cui restano spente. Nel frattempo ricevono l’ottica più veloce che il loro sistema di linea accetta."}, +"bstd.hire_note":"Assumi uno stagista NOC in Ops e terrà ogni POP, porta e fibra a standard: qualche lavoro al giorno, i più carichi prima, dentro un budget mensile e solo con soldi in avanzo.", +"bstd.in_n_cities":"In almeno {n} città", +"bstd.intern_keeps":"{name} tiene la rete a standard", +"bstd.keep":"Lascia com’è", +"bstd.l_ix":"Porta IX", +"bstd.l_lag":"Membri LAG", +"bstd.l_model":"Modello di router", +"bstd.l_pni":"PNI per rete", +"bstd.l_site2":"Secondo edificio", +"bstd.l_split":"Dividi i LAG", +"bstd.left":{"one":"Resta una cosa sotto lo standard: aspetta soldi, una fibra tranquilla o un ampliamento.","other":"Restano {n} cose sotto lo standard: aspettano soldi, una fibra tranquilla o un ampliamento."}, +"bstd.n_more_targets":{"one":"{n} altro obiettivo","other":"altri {n} obiettivi"}, +"bstd.new_pops_note":"Un POP nuovo riceve tutto subito, finché è vuoto: niente finestra di manutenzione. Se mancano i soldi, riceve quello che ci sta. Un modello non ancora sbloccato vuol dire il migliore sbloccato sotto di lui.", +"bstd.none_set":"Ancora nessuno standard: ogni obiettivo è su Lascia com’è.", +"bstd.now_line":"Standard: {list}", +"bstd.or_better":"{x} o meglio", +"bstd.port_note":"LAG e divisione valgono per le porte di transit, IX e PNI. Un nuovo membro di PNI è un ampliamento e arriva settimane dopo.", +"bstd.second_building":"secondo edificio", +"bstd.tagline":"Un solo design per tutta la rete: cosa deve avere ogni POP, porta e fibra. I POP nuovi ricevono la parte POP il giorno in cui aprono; il tuo stagista, o il pulsante qui sotto, porta il resto a standard.", +"bstd.title":"Standard di rete", "businesses.a_free_pni_with_voda_phony":"Un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.", "businesses.agi_lab_allegedly":"Laboratorio AGI (a sentir loro)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratori AGI (a sentir loro) che vogliono AI WAN da 12.8 a 25.6 Tbps, e PNI gratuiti con Du-opoly e Ooh-redoo. Gear: router Mikrowtik CCR 3.2T.", @@ -3235,6 +3277,7 @@ "ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"}, "ops.l_rs":{"one":"si è unito a un route server","other":"si è unito a {n} route server"}, "ops.l_snag":{"one":"si è bloccato su {where} e l'ha messo in pausa finché non dai un'occhiata","other":"si è bloccato su {n} ordini ({where}) e li ha messi in pausa finché non dai un'occhiata"}, +"ops.l_std":{"one":"ha portato {where} allo standard di rete","other":"ha fatto {n} lavori per lo standard di rete ({where})"}, "ops.l_transit":{"one":"ha aumentato il transit a {where}","other":"ha aumentato il transit {n} volte ({where})"}, "ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.", "ops.model_next":"Generazione successiva, se carico", @@ -3268,6 +3311,8 @@ "ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.", "ops.o_routers":"Router sempre avanti", "ops.o_routers_desc":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Scegli un modello e ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.", +"ops.o_std":"Tieni lo standard di rete", +"ops.o_std_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo su una fibra tranquilla.", "ops.o_transit":"Margine di transit", "ops.o_transit_d":"Tieni il transit di ogni POP sopra un multiplo del suo picco a 30 giorni: un membro LAG in più, o una porta più grande.", "ops.ops":"Ops", @@ -3300,6 +3345,7 @@ "ops.template":"Nuovo POP da modello", "ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.", "ops.tpl_bb":"Banda larga", +"ops.tpl_bstd":"standard di rete", "ops.tpl_done":"{name} ha aperto {city}: {list}.", "ops.tpl_ix":"Porta IX", "ops.tpl_just_pop":"solo il POP", @@ -3798,12 +3844,12 @@ "pnis.us_east_is_sold_out_until":"US East è esaurito fino a nuovo avviso. Anche il nuovo avviso è esaurito.", "pop_std.city_gets_the_standard_cost":"{city} riceve lo standard: {n} × {model} per {cost}.", "pop_std.clear":"Rimuovi", +"pop_std.includes_the_build_standard":"Include il tuo standard di rete: {list}, {cost} + {mo}/mese. Se mancano i soldi, il POP riceve quello che ci sta.", "pop_std.includes_the_standard_n_model":"Include i tuoi router standard: {n} × {model}, {cost} + {mo}/mese. Se mancano i soldi, il POP riceve quello che ci sta.", "pop_std.make_this_the_standard":"Rendilo lo standard", -"pop_std.new_pops_now_start_with":"I nuovi POP ora partono con {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"I nuovi POP ora partono con {list}.", "pop_std.none":"Nessuno", "pop_std.not_all_of_the_standard":"Non bastano soldi o livello per tutto lo standard a {city}: ha avuto quello che si poteva.", -"pop_std.standard_for_new_pops":"Standard per i nuovi POP", "pops_transit_ix.40_off_for_6_months":"40% di sconto per 6 mesi", "pops_transit_ix.40_off_ix_for_6_months":"40% di sconto su {ix} per 6 mesi.
Il tuo account manager tira un sospiro di sollievo. Le clausole in piccolo leggile dopo.", "pops_transit_ix.after_consulting_with_management_the":"“Dopo un confronto con il management…”
Il prezzo è salito. Il management è stato consultato.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 2ff2e89..9875919 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -395,6 +395,48 @@ "broker.win_text":"{name} (AS{asn}) lançou os próprios cabos até {n} continentes e vende {mo} por mês de capacidade a outras operadoras, em {days} dias. Os oceanos agora são a sua vala.", "broker.won_on_date":"Vencido em {date}: seus próprios cabos cruzam os oceanos e as operadoras pagam para usá-los.", "broker.your_glass_gear_is_already_yours":"Como corretor de cabos, toda fibra, sistema de linha, óptico, cabo submarino e os roteadores para acendê-los já são seus, diga o nível o que disser.", +"bstd.all_up":"Tudo está no padrão.", +"bstd.any_model":"qualquer modelo", +"bstd.applied":{"one":"Um trabalho feito para o padrão de rede, {cost}.","other":"{n} trabalhos feitos para o padrão de rede, {cost}."}, +"bstd.applied_none":"Nada pôde ser feito para o padrão de rede agora.", +"bstd.apply_nothing":"Nada abaixo do padrão", +"bstd.apply_now":"Colocar tudo no padrão agora · {cost}", +"bstd.apply_wait":"Nada a fazer até essas fibras ficarem livres", +"bstd.at_every_pop":"Em cada POP", +"bstd.at_least_n":"Pelo menos {n}", +"bstd.below":"Abaixo do padrão hoje", +"bstd.both_buildings":"Nos dois prédios", +"bstd.cost_mo":"Custos mensais", +"bstd.cost_now":"Para colocar tudo no padrão agora", +"bstd.edit":"Editar o padrão de rede", +"bstd.every_exchange":"Onde houver um IX", +"bstd.fastest":"A mais rápida que alcança", +"bstd.fiber_note":"Trocar o sistema de linha apaga a fibra por um dia: só quando ela está tranquila ou um link paralelo leva a carga.", +"bstd.from_level":"(nível {lv})", +"bstd.g_fiber":"Fibra e waves", +"bstd.g_port":"Portas e peering", +"bstd.generator":"gerador", +"bstd.held":{"one":"Uma fibra mantém por enquanto o seu sistema de linha, até ficar tranquila ou um link paralelo poder levar a carga dela no dia em que ela fica apagada. Até lá, ela recebe a óptica mais rápida que o seu sistema de linha aceita.","other":"{n} fibras mantêm por enquanto o seu sistema de linha, até ficarem tranquilas ou um link paralelo poder levar a carga delas no dia em que ficam apagadas. Até lá, elas recebem a óptica mais rápida que o seu sistema de linha aceita."}, +"bstd.hire_note":"Contrate um estagiário de NOC em Ops e ele mantém cada POP, porta e fibra no padrão: alguns trabalhos por dia, os mais carregados primeiro, dentro de um orçamento mensal e só com dinheiro sobrando.", +"bstd.in_n_cities":"Em pelo menos {n} cidades", +"bstd.intern_keeps":"{name} mantém a rede no padrão", +"bstd.keep":"Deixar como está", +"bstd.l_ix":"Porta no IX", +"bstd.l_lag":"Membros de LAG", +"bstd.l_model":"Modelo de roteador", +"bstd.l_pni":"PNIs por rede", +"bstd.l_site2":"Segundo prédio", +"bstd.l_split":"Dividir LAGs", +"bstd.left":{"one":"Ainda falta uma coisa abaixo do padrão, esperando dinheiro, uma fibra tranquila ou uma ampliação.","other":"Ainda faltam {n} coisas abaixo do padrão, esperando dinheiro, uma fibra tranquila ou uma ampliação."}, +"bstd.n_more_targets":{"one":"mais {n} meta","other":"mais {n} metas"}, +"bstd.new_pops_note":"Um POP novo recebe isso na hora, enquanto ainda está vazio: sem janela de manutenção. Se faltar dinheiro, recebe o que couber. Um modelo ainda bloqueado significa o melhor desbloqueado abaixo dele.", +"bstd.none_set":"Ainda sem padrão: toda meta está em Deixar como está.", +"bstd.now_line":"Padrão: {list}", +"bstd.or_better":"{x} ou melhor", +"bstd.port_note":"LAGs e divisão valem para portas de trânsito, IX e PNI. Um novo membro de PNI é uma ampliação e chega semanas depois.", +"bstd.second_building":"segundo prédio", +"bstd.tagline":"Um só design para a rede toda: o que cada POP, porta e fibra deve ter. POPs novos recebem a parte do POP no dia em que abrem; seu estagiário, ou o botão abaixo, coloca o resto no padrão.", +"bstd.title":"Padrão de rede", "businesses.a_free_pni_with_voda_phony":"Um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.", "businesses.agi_lab_allegedly":"Laboratório de AGI (supostamente)", "businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratórios de AGI (supostamente) querendo AI WANs de 12.8 a 25.6 Tbps, e PNIs grátis com a Du-opoly e a Ooh-redoo. Gear: routers Mikrowtik CCR 3.2T.", @@ -3235,6 +3277,7 @@ "ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"}, "ops.l_rs":{"one":"entrou em um route server","other":"entrou em {n} route servers"}, "ops.l_snag":{"one":"travou em {where} e pausou a ordem até você dar uma olhada","other":"travou em {n} ordens ({where}) e pausou-as até você dar uma olhada"}, +"ops.l_std":{"one":"colocou {where} no padrão de rede","other":"fez {n} trabalhos para o padrão de rede ({where})"}, "ops.l_transit":{"one":"reforçou o trânsito em {where}","other":"reforçou o trânsito {n} vezes ({where})"}, "ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.", "ops.model_next":"Próxima geração, quando lotado", @@ -3268,6 +3311,8 @@ "ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.", "ops.o_routers":"Roteadores à frente", "ops.o_routers_desc":"Adicionar um roteador, ou trocar para a próxima geração onde um segundo roteador segura o tráfego, quando a carga ou as portas passarem de um nível. Escolha um modelo e cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.", +"ops.o_std":"Manter o padrão de rede", +"ops.o_std_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda numa fibra tranquila.", "ops.o_transit":"Folga de trânsito", "ops.o_transit_d":"Manter o trânsito de cada POP acima de um múltiplo do seu pico de 30 dias: mais um membro LAG, ou um tamanho de porta acima.", "ops.ops":"Ops", @@ -3300,6 +3345,7 @@ "ops.template":"Novo POP por modelo", "ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.", "ops.tpl_bb":"Banda larga", +"ops.tpl_bstd":"padrão de rede", "ops.tpl_done":"{name} abriu {city}: {list}.", "ops.tpl_ix":"Porta de IX", "ops.tpl_just_pop":"só o POP", @@ -3798,12 +3844,12 @@ "pnis.us_east_is_sold_out_until":"US East está esgotado até segunda ordem. A segunda ordem também esgotou.", "pop_std.city_gets_the_standard_cost":"{city} recebe o padrão: {n} × {model} por {cost}.", "pop_std.clear":"Limpar", +"pop_std.includes_the_build_standard":"Inclui seu padrão de rede: {list}, {cost} + {mo}/mês. Se faltar dinheiro, o POP recebe o que couber.", "pop_std.includes_the_standard_n_model":"Inclui seus roteadores padrão: {n} × {model}, {cost} + {mo}/mês. Se faltar dinheiro, o POP recebe o que couber.", "pop_std.make_this_the_standard":"Tornar este o padrão", -"pop_std.new_pops_now_start_with":"Novos POPs agora começam com {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"Novos POPs agora começam com {list}.", "pop_std.none":"Nenhum", "pop_std.not_all_of_the_standard":"Sem dinheiro ou nível para todo o padrão em {city}: recebeu o que coube.", -"pop_std.standard_for_new_pops":"Padrão para novos POPs", "pops_transit_ix.40_off_for_6_months":"40% de desconto por 6 meses", "pops_transit_ix.40_off_ix_for_6_months":"40% de desconto no {ix} por 6 meses.
Seu account manager respirou aliviado. Leia as letras miúdas depois.", "pops_transit_ix.after_consulting_with_management_the":"“Depois de consultar a diretoria…”
O preço subiu. A diretoria foi consultada.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index f1b8a8f..4b199a2 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -38,6 +38,8 @@ const API_DOMAINS={ opsKey:{table:'OPSK',kind:'key'}, opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The build standard's targets (bstdSet). + bstdKey:{kind:'enum',values:()=>BSTD.map(x=>x.k)}, // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, callAmount:{kind:'enum',values:()=>CALL_AMTS.slice()}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index b575dcf..f4b8ca3 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -327,7 +327,7 @@ const API_CMD={ opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'], doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead, such as the model to standardize routers on.'}, opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'], - doc:'Step the monthly budget of an order that has one: 10k, 25k, 50k, 100k, 250k, no limit. With v (a position in that list, 0 first) it picks that one.'}, + doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'}, opsFloor:{args:[['v','string',false]],watch:['ops'], doc:'Step the floor under your cash that the intern keeps clear when paying for jobs: 0, 50k, 250k, 1M, 5M. With v (a position in that list, 0 first) it picks that one.'}, opsPop:{args:[['k','opsPopKind'],['city','cityId']],watch:['ops'], @@ -376,11 +376,16 @@ const API_CMD={ layShip:{args:[['id','entityId']],watch:['links.#id'], quote:a=>{const l=S.links.find(x=>x.id===a.id),q=l&&layQuote(l);return q?{setup:q.cost}:{};}, doc:'Book a second lay ship on your own cable before laying starts: it lays from the other end and halves that part of the build.'}, -/* ---------- standard POPs ---------- */ +/* ---------- the build standard ---------- */ popStdSet:{args:[['city','cityId']],watch:['popStd'], - doc:'Make a POP\'s routers the standard: every new POP starts with that model and that number of routers while it is still empty.'}, + doc:'Make a POP\'s build the standard\'s POP part: its router model, router count, second building and generator. New POPs start with them at once; the other targets are kept.'}, popStdClear:{args:[],watch:['popStd'], - doc:'Stop setting a standard; new POPs go back to one basic router.'}, + doc:'Clear the whole build standard; new POPs go back to one basic router.'}, + bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'], + doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'}, + bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'], + quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};}, + doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'}, /* ---------- utilities ---------- */ utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'], doc:'Join the route server at every IX you have a port at. One call does what the button does.'}, @@ -507,6 +512,7 @@ const API_VIEW={ keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'}, routingOpen:{args:[],doc:'Open the Routing & DDoS window: the traceroute, backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'}, opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'}, + bstdOpen:{args:[],doc:'Open the build standard sheet: every target, how many POPs, ports and links are below it, what bringing them up costs, and the intern\'s order that keeps them there.'}, salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'}, opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'}, utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 7644d07..30da327 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -61,7 +61,7 @@ const API_STATE_DOC={ ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, - popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, + popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, diff --git a/src/agent/50-screen.js b/src/agent/50-screen.js index 42503c6..9e754c3 100644 --- a/src/agent/50-screen.js +++ b/src/agent/50-screen.js @@ -15,7 +15,7 @@ function apiControls(root,player){ const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled} // A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value. :{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg, - select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled}; + select:b.dataset.chg,args:apiParse(b.dataset.args),value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled}; if(player)o.player=true; out.push(o);} return out;} diff --git a/src/agent/60-dispatch.js b/src/agent/60-dispatch.js index 94957fd..b6f0014 100644 --- a/src/agent/60-dispatch.js +++ b/src/agent/60-dispatch.js @@ -115,7 +115,8 @@ function apiClick(n,value){ if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`); if(b.disabled)apiFail(`"${b.label}" is greyed out.`); if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`); - const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args; + // A list sends its own arguments with the value picked, as the page's change handler does (96-map/95-clicks.js). + const name=b.select||b.act,args=b.select?{...(b.args||{}),v:value===undefined?undefined:String(value)}:b.args; if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`); const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`); if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};} diff --git a/src/game/10-catalog/30-supply-chain.js b/src/game/10-catalog/30-supply-chain.js index 95b8863..a93e9a2 100644 --- a/src/game/10-catalog/30-supply-chain.js +++ b/src/game/10-catalog/30-supply-chain.js @@ -26,7 +26,8 @@ const RCAGE=6,CAGE_MUL=1.5,CAGE_MO=2000; const routerCost=(g,rt)=>Math.round((ROUTER_COST+RG[g].cost*0.8)*((rt||1)>=RCAGE?CAGE_MUL:1)*hwMul('rt')*techMul(RG[g].lvl)); const routerMo=g=>ROUTER_MO+RG[g].mo,cageMo=rt=>Math.max(0,(rt||1)-RCAGE)*CAGE_MO; // Old routers go on eBuy when you swap models or remove one (#82), like spare optics (#45). Chassis age faster. -const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCost=(c,g)=>{const p=S.pops[c],rt=p.routers||1;return Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(p.rgen||0,rt));}; +// swapCostOf: the same price for a POP on model old with rt routers (the build standard plans a few steps ahead). +const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCostOf=(g,old,rt)=>Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(old,rt)),swapCost=(c,g)=>{const p=S.pops[c];return swapCostOf(g,p.rgen||0,p.routers||1);}; const RMAX=16; // The plain, badge-less model of each class is the default upgrade path; the others are side-grades. const mainRG=k=>RG.findIndex(r=>r.cls===k&&!r.badge); diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index da183e6..ce0dffb 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -17,6 +17,8 @@ const OPS=[ {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_desc'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}, // A model to standardize on: every POP on a smaller one is swapped to it, busiest first, within the budget. model:{d:'next',ok:v=>v==='next'||(Number.isInteger(v)&&!!RG[v]),l:N_('ops.p_model'),f:v=>v==='next'?tr('ops.model_next'):RG[v].n}}}, + // The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget. + {k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_d'),p:{}}, {k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}}, @@ -31,7 +33,7 @@ const OPS=[ const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); const OPS_TPL=['bb','transit','ix','kit']; // What the shift log can say. One line per day: "{name} did this, that and the other." -const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),optup:N_('ops.l_optup'),optswap:N_('ops.l_optswap'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; +const OPS_SAY={std:N_('ops.l_std'),transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),optup:N_('ops.l_optup'),optswap:N_('ops.l_optswap'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_FF_RATE={oncall:1/150,bgp:1/60}; @@ -103,7 +105,7 @@ const opsPaid=e=>e.up||e.mo?' '+tr('ops.l_paid',{cost:fmt$(e.up||0),mo:opsMo$(e. // What the network costs every month before traffic: what a job adds to the bill (ports, routers, rent, links, cache boxes). // PNIs count from the day they are ordered, at the size they are going to be. function opsMoNow(){let m=cachesMo(); - for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo;} + for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo+(p.gen?GEN_MO:0)+(p.site2?SITE2_MO:0);} for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0); for(const t of S.transit)m+=transitMo(t,0); for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);} @@ -137,6 +139,8 @@ const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);}; // The orders. Each takes the shift and does its jobs through the player's own actions. const OPS_RUN={ + // Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js). + std(X){bstdShift(X);}, repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');}, routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next', load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); @@ -206,7 +210,9 @@ const OPS_RUN={ // More of what is already lit, or else the most Gbps per dollar that reaches. Told to go big (#262), the intern // picks the most Gbps per channel it can afford for a new kind of optic, but never swaps what is already lit. const fit=Object.keys(OPT).filter(o=>!chWhy(l,o)),cheap=fit.slice().sort((a,b)=>gpd(b,l)-gpd(a,l)), - o=fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break; + // A build standard that wants the fastest optics gets those first, so the two orders never undo each other. + fast=bstdFast()&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)), + o=fast||fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break; const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}}, @@ -253,15 +259,10 @@ const OPS_RUN={ for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){ if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). - decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go. if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;} - for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; - let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); - const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); - // The spare is there for when the big link's trench is cut, so it has to live in another trench. - if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} - for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}}, + for(const ls of by.values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}, }; // Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once, // so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week @@ -276,11 +277,21 @@ function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return fa const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{}; try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);} finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}} -// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first. -function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; +// The waves decom hands back on one city pair (ls: every link between them): the smaller ones the rest carry with 25% to +// spare, smallest first, less the spare it keeps. cf: each link's capacity (the build standard asks with the sizes its +// wave upgrades will give, so it never upgrades one that goes back). +function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||cf(l)>cf(a)?l:a,null),out=[];if(!big)return out; + let cap=live.reduce((a,l)=>a+cf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); + const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&cf(l)b.link===l.id)).sort((a,b)=>cf(b)-cf(a)); + // The spare is there for when the big link's trench is cut, so it has to live in another trench. + if(opsP('decom','keep')&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} + for(const l of small.reverse()){if(cap-cf(l)(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true); - const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} -const OPS_ORDER=['repair','routers','transit','ports','optup','optics','caches','ix','pni','decom']; + const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l&&!gone.includes(x));try{return was.every(chk);}finally{S.links=all;}} +const OPS_ORDER=['repair','std','routers','transit','ports','optup','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. @@ -306,8 +317,9 @@ function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))retur if(T.transit&&!scnRule('noTransit')){net=opsProv(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} // Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those. // The standard routers go in first (#261), so they are in the price and the kit is priced for them. - const sq=popStdQuote();if(sq){cost+=sq.cost;parts.push(tr('ops.tpl_std'));} - S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:sq?sq.rt:1,gen:false,rgen:sq?sq.g:0}; + // The standard's building and generator too, so the kit only prices what the standard leaves out: nothing twice. + const sq=popStdQuote();if(sq){cost+=sq.cost;parts.push(sq.site2||sq.gen?tr('ops.tpl_bstd'):tr('ops.tpl_std'));} + S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:sq?sq.rt:1,gen:!!(sq&&sq.gen),rgen:sq?sq.g:0,...(sq&&sq.site2?{site2:true}:{})}; try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} if(T.kit){kit=utilityKit(c);if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}}}finally{delete S.pops[c];} return {cost,net:net&&net.id,ix,kit:!!(kit&&kit.cost),parts};} diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index dad4b00..ae8aa3e 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -1,16 +1,207 @@ -/* ---------- The standard POP (#240) ---------- - Big networks run one design everywhere. A new POP gets the standard routers at once, while the box is still idle - (no maintenance window): the model if it is unlocked and affordable, then the extra routers as cash allows. */ +/* ---------- The build standard (#240, grown into a target state for every POP, port and fiber) ---------- + Big networks run one design everywhere. The standard says what every POP, port and fiber should have: the router + model and count, a second building and a generator, LAGs, an exchange port, PNIs spread over cities, the line + system, the optics and the waves. A new POP gets its POP part at once, while the box is still idle (no maintenance + window). The rest is brought up by the intern's "Keep to the build standard" order, or in one tap from the sheet. */ +// Every target, with the values its list offers ("keep" first: no target) and its default. Saved sparse: a target left +// at its default is not in the save, so an old {g, rt} standard is exactly the routers it always was. +const BSTD=[ + {k:'g',grp:'pop',l:N_('bstd.l_model'),d:'keep',v:()=>['keep',...RG.map((r,i)=>i).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cap-RG[b].cap||a-b)],ok:v=>v==='keep'||(Number.isInteger(v)&&!!RG[v])}, + {k:'rt',grp:'pop',l:N_('common.routers'),d:1,v:()=>[1,2,3,4,6,8,12,16],ok:v=>Number.isInteger(v)&&v>=1&&v<=RMAX}, + {k:'site2',grp:'pop',l:N_('bstd.l_site2'),d:false,v:()=>[false,true]}, + {k:'gen',grp:'pop',l:N_('common.backup_generator'),d:false,v:()=>[false,true]}, + {k:'lag',grp:'port',l:N_('bstd.l_lag'),d:1,v:()=>[1,2,4]}, + {k:'split',grp:'port',l:N_('bstd.l_split'),d:false,v:()=>[false,true]}, + {k:'ix',grp:'port',l:N_('bstd.l_ix'),d:false,v:()=>[false,true]}, + {k:'pni',grp:'port',l:N_('bstd.l_pni'),d:0,v:()=>[0,2,3]}, + {k:'sys',grp:'fiber',l:N_('common.line_system'),d:'keep',v:()=>['keep','roadm','cl']}, + {k:'opt',grp:'fiber',l:N_('common.optics'),d:'keep',v:()=>['keep','fast']}, + {k:'wv',grp:'fiber',l:N_('common.waves'),d:'keep',v:()=>['keep',...LT.map((x,i)=>i).filter(i=>i>0&&waveShown(i))],ok:v=>v==='keep'||(Number.isInteger(v)&&v>0&&!!LT[v])}, +]; +const BSTDK=Object.fromEntries(BSTD.map(x=>[x.k,x])),BSTD_MAX=16,BSTD_SYS={lite:0,roadm:1,cl:2}; +const bstdOk=(x,v)=>x.ok?x.ok(v):x.v().includes(v); +// The whole standard, every target filled in. d: a saved one (untrusted: anything odd reads as "keep"). +function bstd(d=S&&S.popStd){const o={},ob=d&&typeof d==='object'&&!Array.isArray(d)?d:{}; + for(const x of BSTD){const v=ob[x.k];o[x.k]=x.k==='rt'?(own(ob,'rt')?int(v,1,RMAX,1):1):own(ob,x.k)&&bstdOk(x,v)?v:x.d;}return o;} +// Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null. +function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;} +function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;} +// A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs. +const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen')); +// The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no +// bigger. Never a step down, never one that does not fit, and never one that would drop a POP out of the backbone core. +// c: an existing POP, or null for a new, empty one. -1: nothing to do. A vendor's demo unit (at its markup) only ever +// goes into a new POP, as before: swapping every POP onto one is the player's call, not the intern's. A new POP takes the +// model as chosen, even one smaller than the basic router (the Mikrowtik CCR has more ports): nothing is replaced there. +function bstdModel(g,c){if(g==='keep'||!RG[g])return -1;const p=c&&S.pops[c],cur=p?p.rgen||0:0,core=!!p&&coreRun()>0&&inCore(c); + const ok=i=>i>=0&&RG[i].cap<=RG[g].cap&&(!p||(RG[i].cap>RG[cur].cap&&!modelFits(c,i)&&(!core||rgCore(i,coreRun())))); + if((p?rgOpen(g):techOk('rg',g,RG[g].lvl))&&ok(g))return g;let b=-1; + for(let k=0;k<=4;k++){const i=mainRG(k);if(i!==g&&rgOpen(i)&&ok(i)&&(b<0||RG[i].cap>RG[b].cap))b=i;}return b;} // What the standard adds to a fresh POP, priced the way popStdApply pays for it, so it can be on the button (#261). -function popStdQuote(){const d=S.popStd;if(!d||pzOn())return null;const g=techOk('rg',d.g,RG[d.g].lvl)?d.g:0; - let cost=g?Math.max(0,Math.round(RG[g].cost*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(0,1)):0;for(let n=1;n0?m:0,rt=D.rt; + let cost=g?swapCostOf(g,0,1):0;for(let n=1;n=swapCost(city,d.g)){spend(swapCost(city,d.g));p.rgen=d.g;}else miss=true;} - while((p.routers||1)0?m:0].cap0&&m!==(p.rgen||0)){if(S.cash>=swapCost(city,m)){spend(swapCost(city,m));p.rgen=m;}else miss=true;} + while((p.routers||1)=SITE2_COST){spend(SITE2_COST);p.site2=true;p.site2Day=S.day;}else miss=true;} + if(D.gen&&!p.gen&&!bstdNoGen()){if(S.cash>=GEN_COST){spend(GEN_COST);p.gen=true;}else miss=true;} + if(c0===S.cash&&!miss)return; toast(miss?tr('pop_std.not_all_of_the_standard',{city:CITY[city].name}):tr('pop_std.city_gets_the_standard_cost',{city:CITY[city].name,n:p.routers||1,model:esc(RG[p.rgen||0].n),cost:fmt$(c0-S.cash)}),miss?'bad':'good');} -// The line in a POP's router section: the standard, and a button to make this POP's routers the standard. -function popStdHtml(c){const p=S.pops[c];if(!p||pzOn())return '';const d=S.popStd,same=d&&d.g===(p.rgen||0)&&d.rt===(p.routers||1); - return `
${tr('pop_std.standard_for_new_pops')}${d?`${d.rt} × ${esc(RG[d.g].n)}`:tr('pop_std.none')}
${same?'':btn(tr('pop_std.make_this_the_standard'),'popStdSet',{city:c},'ghost sm')}${d?btn(tr('pop_std.clear'),'popStdClear',{},'ghost sm'):''}
`;} +// The line in a POP's router section: the standard, a button to edit it, and one to make this POP's build the standard. +function popStdHtml(c){const p=S.pops[c];if(!p||pzOn())return '';const D=bstd(),on=!!S.popStd,mine=bstd(bstdPut({...D,g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen})), + same=on&&BSTD.every(x=>D[x.k]===mine[x.k]); + return `
${tr('bstd.title')}${on?esc(bstdLine(D)):tr('pop_std.none')}
${btn(tr('bstd.edit'),'bstdOpen',{},'sm')}${same?'':btn(tr('pop_std.make_this_the_standard'),'popStdSet',{city:c},'ghost sm')}${on?btn(tr('pop_std.clear'),'popStdClear',{},'ghost sm'):''}
`;} +// "2 × Absolute Unit 3.2T, second building, generator": the POP part, what a new POP gets. +function bstdPopParts(D){const a=[];if(D.g!=='keep'||D.rt>1)a.push(`${D.rt} × ${D.g==='keep'?tr('bstd.any_model'):RG[D.g].n}`);if(D.site2)a.push(tr('bstd.second_building'));if(D.gen)a.push(tr('bstd.generator'));return a;} +// The POP part first, then how many other targets. +function bstdLine(D){const a=bstdPopParts(D),n=['lag','split','ix','pni','sys','opt','wv'].filter(k=>D[k]!==BSTDK[k].d).length;if(n)a.push(trn('bstd.n_more_targets',n));return a.join(', ')||tr('pop_std.none');} + +/* What the standard still asks for, as jobs in the order they get done: POPs busiest first, then ports hottest first, + then fiber and waves hottest first. Pure: it reads S and R and changes nothing. Each job is priced with the game's + own helpers on a running copy of the few numbers earlier jobs change (routers, spares), so the sum is what the clicks + cost. Jobs that build on each other form a chain (ch: a POP's routers, a port, a fiber): when one cannot be done, the + rest of that chain waits. A job that needs another chain's work first (optics only the new router model takes, a split + that needs the second building) names that job in dep and waits for it too. Whether a fiber may go dark is settled + here, not on the way, so the plan is what the button does and its sum is the quote. + intern: only where the intern may work (per-POP exceptions). J.held: fibers whose line system has to wait. */ +function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J;const D=bstd(),here=c=>!intern||opsHere('std',c); + const load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); + const cs=Object.keys(S.pops).filter(here),ld={};for(const c of cs)ld[c]=load(c);cs.sort((a,b)=>ld[b]-ld[a]||(aS.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0); + const room=c=>rmn[c]??(rmn[c]=(V[c]?portsMax(c,V[c].g,V[c].rt)-portsUsed(c,V[c].g):portsMax(c)-portsUsed(c))-resv(c)+1e-9); + const take=(c,n,dry)=>{if(n<=0)return true;if(room(c){const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;}; + for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null; + const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;}; + const m=p.rupDay===S.day?-1:bstdModel(D.g,c); + if(m>=0){ + // One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window. + if(rt===1&&!popIdle(c))add(); + const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;} + while(rt{ACT.addSite({city:c});return !!S.pops[c].site2;},{c}); + if(D.gen&&!p.gen&&!bstdNoGen())job('pop','gen','e:'+c,c,GEN_COST,GEN_MO,()=>{if(bstdNoGen())return false;ACT.addGen({city:c});return !!S.pops[c].gen;},{c}); + V[c]={g,rt,site2:!!p.site2||D.site2,sw,s2};} + // Ports: LAG members up to the standard, then the members split over both buildings. + if(D.lag>1||D.split){const P=[]; + for(const t of S.transit)if(S.pops[t.city]&&here(t.city))P.push({k:'t',c:t.city,id:t.id,o:t,n:t.n||1,tier:t.tier,u:(R.useT[t.id]||0)/lagCap(PORT[t.tier].g,t.n)}); + for(const x of S.pni)if(S.pops[x.city]&&here(x.city)&&pniOn(x)&&!x.up)P.push({k:'p',c:x.city,id:x.id,o:x,n:x.n||1,tier:x.tier,u:(R.usePni[x.id]||0)/lagCap(pniG(x),x.n)}); + for(const x in S.ixp){const c=ixCity(x);if(!S.myIx[x]&&S.pops[c]&&here(c))P.push({k:'ix',c,id:x,n:(S.ixn||{})[x]||1,tier:S.ixp[x],u:(R.useIx[x]||0)/Math.max(1e-9,lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x]))});} + P.sort((a,b)=>b.u-a.u||(a.id!isDk(x)&&!S.myIx[x]&&!!ixName(x)&&S.ixp[x]===undefined);if(!x||!take(c,PORT_SLOT(0)))continue; + const ch='i:'+x,pm=ixPortMo(x,0);job('port','ix',ch,x+' +'+PORT[0].n,pm,pm,()=>{ACT.buyIx({city:x,tier:0});return S.ixp[x]!==undefined;},{c}); + bstdPort({k:'ix',c,id:x,n:1,tier:0,fresh:true},D,V[c],take,job);} + // PNIs spread out: every network you have a PNI with gets one in at least that many cities, where one is worth it. + if(D.pni){const by={};for(const p of S.pni)(by[p.net]||(by[p.net]=new Set())).add(p.city); + for(const net of Object.keys(by).sort()){let k=D.pni-by[net].size;if(k<=0||!isNet(net))continue; + const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;} + if(!q||!take(c,q.slots))continue;const tier=q.tier;k--; + job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}} + // Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too. + if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map(); + const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.idl.tier;t--){if(subWaveWhy(t,l.km,l.sub)||soldOut(l.a,l.b,t,l.cable)||!waveOk(l.a,l.b,t))continue;wv.set(l,t);break;} + if(wv.size&&opsHired()&&S.ops.on.decom){const by=new Map(),cf=x=>wv.has(x)?capOf(x)*LT[wv.get(x)].g/LT[x.tier].g:capOf(x); + for(const x of S.links)if(x.kind!=='vxc'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} + for(const k of new Set([...wv.keys()].map(edgeKey)))for(const x of opsDecomPick(by.get(k),cf))wv.delete(x);}} + for(const {l} of ls){const ch='l:'+l.id; + if(l.kind==='wave'){const t=wv.get(l);if(t){const nm=Math.round(waveMo(l.km,l.sub,t)*(l.mult||1));job('fiber','wv',ch,l.a+'|'+l.b,nm,nm-(l.mo||0),()=>{ACT.upLink({id:l.id,tier:t});return l.tier===t;},{l});}continue;} + if(l.eqDown>S.day)continue; + let sys=l.sys;const lit=l.ready<=S.day,nx=D.sys!=='keep'&&BSTD_SYS[sys]{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;} + if(lit)dk.set(l.id,busy);}} + // Optics for the line system the fiber will have. + if(D.opt==='fast'&&lit&&(l.ch||[]).length)J.push(...bstdOptJobs(l,sys,sp,V,take,ch));}} + return J;} +// One port's LAG members up to the standard, then split over both buildings. A PNI's new member is an augment that +// lands later; it remembers to split when it does. o.fresh: a port the plan is buying (the IX job before it). +function bstdPort(o,D,v,take,job){const {k,c,id}=o,ch=(o.fresh?'i:':'x:'+k+':')+id;let n=o.n; + const site2=v?v.site2:!!(S.pops[c]&&S.pops[c].site2),split=D.split&&site2, + // A second building still to buy is a job of its own: the split waits for it, or it would be tried every shift. + sx={c,...(v&&v.s2&&!S.pops[c].site2?{dep:[v.s2]}:{})}; + if(k==='p'){const x=o.o; + if(n{if((x.n||1)!==n0||x.up)return false;ACT.lagP({id,d:1});return !!x.up||(x.n||1)>n0;},{c});n++;} + if(split&&n>=2&&x.site!=='ab')job('port','split',ch,c,0,0,()=>{if(!S.pops[c].site2)return false;if(x.up){if(x.up.n<2)return false;x.up.site='ab';return true;} + if((x.n||1)<2)return false;ACT.siteSet({k:'p',id,s:'ab'});return x.site==='ab';},sx); + return;} + const t=k==='t'?o.o:null,tier=o.tier,each=k==='t'?PORT[tier].setup:ixPortMo(id,tier); + while(n{if((t.n||1)!==n0)return false;ACT.lagT({id,d:1});return (t.n||1)>n0;} + :()=>{const m=(S.ixn||{})[id]||1;if(m!==n0)return false;ACT.lagIx({city:id,d:1});return ((S.ixn||{})[id]||1)>m;},{c});n++;} + const cur=k==='t'?t.site:(S.ixSite||{})[id]; + if(split&&n>=2&&cur!=='ab')job('port','split',ch,k==='t'?c:id,0,0,()=>{if(!S.pops[c].site2)return false; + if(k==='t'){if((t.n||1)<2)return false;ACT.siteSet({k:'t',id,s:'ab'});return t.site==='ab';} + if(((S.ixn||{})[id]||1)<2)return false;ACT.siteSet({k:'ix',id,s:'ab'});return (S.ixSite||{})[id]==='ab';},sx);} +// Can it see the fastest optic that reaches, ignoring the free-slot check (a swap frees its own slot first)? rg: each +// end's router model once the plan's swaps are in, so the optics a new model takes are part of the plan. +const bstdOptFits=(l,o,sys,rg)=>{const O=OPT[o];return techOk('opt',o,O.lvl)&&(O.sys!=='roadm'||isRdm(sys))&&!!optMode(o,l)&&[l.a,l.b].every(c=>!S.pops[c]||RG[rg(c)].cls>=O.rg);}; +const bstdCnt=(l,o)=>(l.ch||[]).filter(k=>k===o).length; +// Swap a fiber's slower optics for the fastest that reaches on it, one job per kind, slowest first: the old ones go on +// the spares shelf (setChCount), the new ones come from the shelf first. sp: spares as earlier jobs leave them. +function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen||0),fits=Object.keys(OPT).filter(o=>bstdOptFits(l,o,sys,rg));if(!fits.length)return []; + const best=fits.sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0],bg=optG(best,l),g=c=>V[c]?V[c].g:undefined,out=[]; + // Optics only the new router model takes wait for its swap: until it is in, nothing is pulled. + const low=c=>!!S.pops[c]&&RG[S.pops[c].rgen||0].clsV[c]&&V[c].sw).filter(Boolean); + for(const o0 of [...new Set(l.ch||[])].filter(o=>OPT[o]&&optG(o,l)optG(a,l)-optG(b,l)||(aMath.max(0,chPorts(best,c,g(c))-chPorts(o0,c,g(c)));let k=bstdCnt(l,o0); + while(k>0&&!(take(l.a,per(l.a)*k,true)&&take(l.b,per(l.b)*k,true)))k--;if(!k)continue;take(l.a,per(l.a)*k);take(l.b,per(l.b)*k); + const r=REGEN_CH*(l.regen|0),c=optCost(best),s=Math.max(0,Math.min(k,sp[best]|0)),cost=s*Math.round(c*r)+(k-s)*Math.round(c*(1+r)); + sp[best]=(sp[best]|0)-s;sp[o0]=(sp[o0]|0)+k; + // price: what it costs when it runs. The plan's price counts on the shelf as the jobs before it leave it; one of those + // refused (budget, cash) leaves the shelf emptier, and the budget and the floor must see the real bill. + out.push({grp:'fiber',k:'opt',ch,w:l.a+'|'+l.b,cost,mo:0,l,...(dep.length?{dep}:{}),price:()=>opticCountCost(l,best,bstdCnt(l,best)+k), + go:()=>{const n0=bstdCnt(l,o0),h0=bstdCnt(l,best);if(n0((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); +function bstdDarkOk(l,ex){const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; + return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} +// Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. +// one: at most one fiber goes dark (the intern's shift); max: at most that many jobs tried, done or failed, so a shift's +// work stays bounded whatever goes wrong. Returns what was done. +function bstdDo(J,can,pay,one,max=1e9){const stop=new Set(),done=new Set(),dark=new Map();let n=0; + for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;} + if(j.dark&&!dark.has(j.l.id)&&((one&&dark.size)||!bstdDarkOk(j.l,dark))){stop.add(j.ch);continue;} + if(!can(j)){stop.add(j.ch);continue;}n++; + if(!pay(j)){stop.add(j.ch);continue;} + if(j.dark)dark.set(j.l.id,!!j.busy);done.add(j);} + return [...done];} +// What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs). +const bstdPrice=j=>j.price?j.price():j.cost; +// The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is +// what the button does, so its sum is the bill. held: the fibers whose line system waits ("fra|ams"); they are below it. +function bstdQuote(intern){const J=bstdPlan(intern),P=new Set(),Q=new Set(),L=new Set(J.held.map(l=>l.id));let cost=0,mo=0; + for(const j of J){cost+=j.cost;mo+=j.mo;if(j.grp==='pop')P.add(j.c);else if(j.grp==='port')Q.add(j.ch);else L.add(j.l.id);} + return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(l=>l.a+'|'+l.b)};} +// The optics order lights the standard's fastest optics while this order keeps to a standard that wants them. +const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast'); +// The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a time. +function bstdShift(X){bstdDo(bstdPlan(true),j=>X.can('std',bstdPrice(j),j.mo),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true),true,BSTD_MAX);} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 9f3361b..fea6574 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -62,8 +62,8 @@ function sanitize(s){ for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k]; if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};} // The backbone's technology: a save from before it with Auto-TE bought keeps the old rules on RSVP-TE (legacy). - // The standard POP build (#240): a router model and how many. - {const d=s.popStd;s.popStd=d&&typeof d==='object'&&Number.isInteger(d.g)&&RG[d.g]?{g:d.g,rt:int(d.rt,1,RMAX,1)}:null;} + // The build standard (#240): a router model and how many, and since then every other target; odd values read as "keep". + popStdSanitize(s); {const c=s.core&&typeof s.core==='object'?s.core:null,lv=c?int(c.lv,0,4,0):(s.te?2:0);s.core={lv,run:c?int(c.run,0,lv,lv):lv};if(c?c.legacy===true:!!s.te)s.core.legacy=true;if(c&&c.lab===true)s.core.lab=true;if(c&&c.since!==undefined)s.core.since=num(c.since,0);} s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null; s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); diff --git a/src/game/90-actions/85-routing-and-routers.js b/src/game/90-actions/85-routing-and-routers.js index 6a6822f..006635f 100644 --- a/src/game/90-actions/85-routing-and-routers.js +++ b/src/game/90-actions/85-routing-and-routers.js @@ -12,8 +12,10 @@ Object.assign(ACT,{ setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}}, route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);}, - popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd={g:p.rgen||0,rt:p.routers||1};toast(tr('pop_std.new_pops_now_start_with',{n:S.popStd.rt,model:esc(RG[S.popStd.g].n)}),'good');sfx('click');after();}, - popStdClear:()=>{S.popStd=null;sfx('click');after();}, + // This POP's build becomes the standard's POP part: its model, routers, second building and generator. + popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd=bstdPut({...bstd(),g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen}); + toast(tr('pop_std.new_pops_now_start_with_list',{list:esc(bstdPopParts(bstd()).join(', '))}),'good');sfx('click');after();if(bstdShown())bstdModal();}, + popStdClear:()=>{S.popStd=null;sfx('click');after();if(bstdShown())bstdModal();}, addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();}, models:()=>{UI.models=!UI.models;renderPanel();}, rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();}, diff --git a/src/game/90-actions/88-build-standard.js b/src/game/90-actions/88-build-standard.js new file mode 100644 index 0000000..f832604 --- /dev/null +++ b/src/game/90-actions/88-build-standard.js @@ -0,0 +1,14 @@ +// The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go. +Object.assign(ACT,{ + bstdOpen:()=>{if(S&&!pzOn())bstdModal();}, + // v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list). + bstdSet:({k,v})=>{if(!S||pzOn()||!own(BSTDK,k))return;const D=bstd(),x=opsPick(bstdOpts(k),D[k],v);if(x===undefined||!bstdOk(BSTDK[k],x))return; + D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);}, + // The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One + // recompute at the end, and one toast: what got done, and what still waits. + bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0; + opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go(),false).length;}); + after();const q=bstdQuote(false),left=q.pops+q.ports+q.links; + toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err'); + if(bstdShown())bstdModal();}, +}); diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js index 719dd85..e30678a 100644 --- a/src/game/90-actions/88-ops.js +++ b/src/game/90-actions/88-ops.js @@ -2,8 +2,10 @@ const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; // A pick from a list (v: its position, as the sheet's dropdown sends it), or without v the next value (the MCP tools step). const opsPick=(a,cur,v)=>{if(v===undefined)return opsCycle(a,cur);const i=Number(v);return Number.isInteger(i)&&i>=0&&i{opsModal();const j=JSON.stringify(args);for(const el of $('modalCard').querySelectorAll(`[data-chg="${act}"]`))if(el.dataset.args===j){el.focus();break;}}; +// The sheet is drawn again after a pick: keep the keyboard on the list that was used. The build standard sheet shows the +// std order's switch and budget too: a pick there stays there. +const opsSheet=()=>(bstdShown()?bstdModal:opsModal)(); +const opsRedraw=(act,args,draw=opsSheet)=>{draw();const j=JSON.stringify(args);for(const el of $('modalCard').querySelectorAll(`[data-chg="${act}"]`))if(el.dataset.args===j){el.focus();break;}}; Object.assign(ACT,{ opsOpen:()=>{if(S)opsModal();}, opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=monthIdx(S.day);O.intern=id;O.hired=S.day;O.wk=null; @@ -12,7 +14,7 @@ Object.assign(ACT,{ O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, - opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsModal();}, + opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsSheet();}, opsParam:({k,p,v})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p],x=opsPick(opsOpts(k,p),opsP(k,p),v);if(x===undefined||!(P.ok?P.ok(x):P.v.includes(x)))return; (S.ops.p[k]||(S.ops.p[k]={}))[p]=x;sfx('click');after();opsRedraw('opsParam',{k,p});}, opsCap:({k,v})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;const x=opsPick(opsCaps(k),opsCap(k),v);if(x===undefined)return;S.ops.cap[k]=x;sfx('click');after();opsRedraw('opsCap',{k});}, diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index a1671dc..1f8ad34 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -29,7 +29,7 @@ Object.assign(ACT,{ - + `);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index bed742e..098512a 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -43,7 +43,7 @@ function bbCost(c){return 15000+CITY[c].P*20;} /* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has: compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */ -const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv']); +const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd']); function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);} function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;} function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();} diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index ed2eb74..cf731e4 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -8,7 +8,7 @@ function cityPanel(c){ if(!p){ h+=`
${C.note?`

${esc(C.note)}

`:''} ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('city_panel.open_a_pop_here')}

${tr('city_panel.a_pop_point_of_presence_is')}

- ${C.ru?`

${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash${tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}

`:''))(popStdQuote())} + ${C.ru?`

${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash${q.site2||q.gen?tr('pop_std.includes_the_build_standard',{list:esc(bstdPopParts({g:q.g,rt:q.rt,site2:q.site2,gen:q.gen}).join(', ')),cost:fmt$(q.cost),mo:fmt$(q.mo)}):tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}

`:''))(popStdQuote())}

${tr('city_panel.or_drag_from_one_of_your')}

${opsTplHtml(c)}`}`; h+=offersHere(c); const trs=NETS.filter(n=>sellsAt(n,c)); diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index 3570d58..e2ba8a6 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -12,6 +12,7 @@ const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0); return `
${tr(d.t)}
${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO),big:fmt$(CACHE_BIG_MO)}):''}
+ ${k==='std'?`
${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}
${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}
`:''} ${on?`
${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')} ${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}
${sp||am?`
${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}
`:''} @@ -41,7 +42,8 @@ function opsReportHtml(){const O=S.ops,w=Math.floor(S.day/7),cur=O.wk&&O.wk.w=== const row=(t,x)=>`
${t}
${esc(opsWeekLine(x))}
`; return (rep?row(tr('ops.report_last'),rep):'')+(cur?row(tr('ops.report_now'),cur):'');} // The big one-off batches (#181, #192) live here now, next to the orders that run them every week. -const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}
`; +// The build standard too: its sheet works with or without an intern (targets, new POPs, everything up in one tap). +const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}${pzOn()?'':btn(tr('bstd.title'),'bstdOpen',{},'sm')}
`; // On a city without a POP: open it from the template in one tap. function opsTplHtml(c){if(!opsHired())return '';const q=opsTplQuote(c);if(!q)return ''; return `

${tr('ops.template')}

${esc(tr('ops.tpl_offer',{name:opsName(),list:[tr('ops.tpl_pop'),...q.parts].join(', ')}))}

${btn(tr('ops.tpl_open',{cost:fmt$(q.cost)}),'opsNewPop',{city:c},'pink',S.cash
`;} diff --git a/src/game/93-ui/59-build-standard.js b/src/game/93-ui/59-build-standard.js new file mode 100644 index 0000000..c6437b2 --- /dev/null +++ b/src/game/93-ui/59-build-standard.js @@ -0,0 +1,38 @@ +/* The build standard sheet: every target as a list (two to a row on a phone), grouped POP / ports and peering / fiber; + what is below the standard and what bringing it up costs, priced without changing anything; one tap to do it now; + and the intern's order that keeps it there. A bottom sheet on phones, like the Ops sheet it sits next to. */ +const BSTD_GRP=[['pop',N_('common.pops')],['port',N_('bstd.g_port')],['fiber',N_('bstd.g_fiber')]]; +// Every value a target can take, in the order its list shows them; the current one is always on the list. +function bstdOpts(k){const L=BSTDK[k].v(),cur=bstd()[k];if(!L.includes(cur))L.push(cur);return L;} +function bstdVal(k,v){if(v===BSTDK[k].d&&k!=='rt')return tr('bstd.keep'); + switch(k){case 'g':return RG[v].n+(rgOpen(v)?'':' '+tr('bstd.from_level',{lv:RG[v].lvl})); + case 'rt':return v>1?tr('bstd.at_least_n',{n:v}):tr('bstd.keep'); + case 'site2':case 'gen':return tr('bstd.at_every_pop'); + case 'lag':return tr('bstd.at_least_n',{n:v}); + case 'split':return tr('bstd.both_buildings'); + case 'ix':return tr('bstd.every_exchange'); + case 'pni':return tr('bstd.in_n_cities',{n:v}); + case 'sys':return tr('bstd.or_better',{x:DF_SYS[v].n}); + case 'opt':return tr('bstd.fastest'); + case 'wv':return tr('bstd.or_better',{x:LT[v].n});} + return String(v);} +const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]'); +function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std; + let h=`
${tr('ops.ops')}

${tr('bstd.title')}

+

${tr('bstd.tagline')}

`; + for(const [g,lab] of BSTD_GRP)h+=`

${tr(lab)}

${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}
+

${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note')}

`; + // What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose + // line system has to wait is below it too, but not on the bill. + const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length; + h+=`

${tr('bstd.below')}

${q.n||w?BSTD_GRP.map(([g,lab])=>`
${tr(lab)}${n[g]}
`).join('') + +`
${tr('bstd.cost_now')}${fmt$(q.cost)}
${tr('bstd.cost_mo')}${tr('common.price_mo',{price:opsMo$(q.mo)})}
` + +(w?`

${trn('bstd.held',w)}

`:'') + :`

${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}

`}
`; + // The intern keeps it there: the order's switch and budget, or a word on hiring one. + h+=`

${tr('ops.o_std')}

${hired?`
${esc(tr('bstd.intern_keeps',{name:opsName()}))}
${tr('ops.o_std_d')}
+
+ ${on?`
${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}
`:''}
` + :`

${tr('bstd.hire_note')}

${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}
`}
`; + h+=`
${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{},'pink',!q.n)}
`; + openModal(h,'ops');} diff --git a/src/i18n/en.js b/src/i18n/en.js index da93f15..3a0dd38 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -396,6 +396,48 @@ "broker.win_text":"{name} (AS{asn}) laid its own cables onto {n} continents and sells {mo} a month of capacity to other carriers, in {days} days. The oceans are your trench now.", "broker.won_on_date":"Won on {date}: your own cables span the oceans, and carriers pay you to use them.", "broker.your_glass_gear_is_already_yours":"As a Cable broker, every fiber, line system, optic, subsea cable and the routers to light them are yours already, whatever the level says.", +"bstd.all_up":"Everything meets the standard.", +"bstd.any_model":"any model", +"bstd.applied":{"one":"One job done for the build standard, {cost}.","other":"{n} jobs done for the build standard, {cost}."}, +"bstd.applied_none":"Nothing could be done for the build standard right now.", +"bstd.apply_nothing":"Nothing below the standard", +"bstd.apply_now":"Bring everything up now · {cost}", +"bstd.apply_wait":"Nothing to do until those fibers are free", +"bstd.at_every_pop":"At every POP", +"bstd.at_least_n":"At least {n}", +"bstd.below":"Below the standard today", +"bstd.both_buildings":"Across both buildings", +"bstd.cost_mo":"Running costs", +"bstd.cost_now":"To bring it all up now", +"bstd.edit":"Edit the build standard", +"bstd.every_exchange":"Wherever there is an IX", +"bstd.fastest":"Fastest that reaches", +"bstd.fiber_note":"A line system swap takes the fiber dark for a day: only on a quiet fiber, or where a parallel link carries its load.", +"bstd.from_level":"(level {lv})", +"bstd.g_fiber":"Fiber and waves", +"bstd.g_port":"Ports and peering", +"bstd.generator":"generator", +"bstd.held":{"one":"One fiber keeps its line system for now, until it is quiet or a parallel link can carry its load for the day it goes dark. Until then it gets the fastest optics its line system takes.","other":"{n} fibers keep their line system for now, until they are quiet or a parallel link can carry their load for the day they go dark. Until then they get the fastest optics their line system takes."}, +"bstd.hire_note":"Hire a NOC intern in Ops and they keep every POP, port and fiber to the standard: a few jobs a day, the busiest first, within a monthly budget and only with money to spare.", +"bstd.in_n_cities":"In at least {n} cities", +"bstd.intern_keeps":"{name} keeps the network to it", +"bstd.keep":"Keep as is", +"bstd.l_ix":"Exchange port", +"bstd.l_lag":"LAG members", +"bstd.l_model":"Router model", +"bstd.l_pni":"PNIs per network", +"bstd.l_site2":"Second building", +"bstd.l_split":"Split LAGs", +"bstd.left":{"one":"One thing is still below it, waiting for cash, a quiet fiber or an augment to land.","other":"{n} things are still below it, waiting for cash, a quiet fiber or an augment to land."}, +"bstd.n_more_targets":{"one":"{n} more target","other":"{n} more targets"}, +"bstd.new_pops_note":"A new POP gets these at once, while it is still empty: no maintenance window. Short on cash, it gets what fits. A model you have not unlocked yet means the best unlocked one below it.", +"bstd.none_set":"No standard yet: every target says Keep as is.", +"bstd.now_line":"Standard: {list}", +"bstd.or_better":"{x} or better", +"bstd.port_note":"LAGs and splits apply to transit, IX and PNI ports. A new PNI member is an augment and lands weeks later.", +"bstd.second_building":"second building", +"bstd.tagline":"One design for the whole network: what every POP, port and fiber should have. New POPs get the POP part the day they open; your intern, or the button below, brings the rest up to it.", +"bstd.title":"Build standard", "businesses.a_free_pni_with_voda_phony":"A free PNI with Voda-Phony. Gear: Absolute Unit 3.2T routers, 3.2T ports and 12.8T waves.", "businesses.agi_lab_allegedly":"AGI lab (allegedly)", "businesses.agi_labs_allegedly_wanting_ai_wans":"AGI labs (allegedly) wanting AI WANs of 12.8 to 25.6 Tbps, and free PNIs with Du-opoly and Ooh-redoo. Gear: Mikrowtik CCR 3.2T routers.", @@ -3236,6 +3278,7 @@ "ops.l_routers":{"one":"upgraded routers in {where}","other":"upgraded routers in {n} places ({where})"}, "ops.l_rs":{"one":"joined a route server","other":"joined {n} route servers"}, "ops.l_snag":{"one":"got stuck on {where} and paused it until you have a look","other":"got stuck on {n} orders ({where}) and paused them until you have a look"}, +"ops.l_std":{"one":"brought {where} up to the build standard","other":"did {n} jobs for the build standard ({where})"}, "ops.l_transit":{"one":"topped up transit in {where}","other":"topped up transit {n} times ({where})"}, "ops.locked":"The NOC hires interns from customer level {lv}.", "ops.model_next":"Next generation, when busy", @@ -3269,6 +3312,8 @@ "ops.o_repair_d":"Pay for the rush repair on every outage that has one, while the budget lasts.", "ops.o_routers":"Keep routers ahead", "ops.o_routers_desc":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level. Pick a model, and every POP on a smaller one is swapped to it, the busiest first, within the budget.", +"ops.o_std":"Keep to the build standard", +"ops.o_std_d":"Bring POPs, ports and fiber up to your build standard, the busiest first, a few jobs a shift. A second router goes in before a swap, and a line system only changes on a quiet fiber.", "ops.o_transit":"Keep transit headroom", "ops.o_transit_d":"Keep transit at each POP above a multiple of its 30-day peak: add a LAG member, or move up a port size.", "ops.ops":"Ops", @@ -3301,6 +3346,7 @@ "ops.template":"New POP from template", "ops.template_note":"Pick what {name} sets up when you open a city from the template. The standing orders take it from there.", "ops.tpl_bb":"Broadband", +"ops.tpl_bstd":"build standard", "ops.tpl_done":"{name} opened {city}: {list}.", "ops.tpl_ix":"IX port", "ops.tpl_just_pop":"just the POP", @@ -3799,12 +3845,12 @@ "pnis.us_east_is_sold_out_until":"US East is sold out until further notice. Further notice is also sold out.", "pop_std.city_gets_the_standard_cost":"{city} gets the standard: {n} × {model} for {cost}.", "pop_std.clear":"Clear", +"pop_std.includes_the_build_standard":"Includes your build standard: {list}, {cost} + {mo}/mo. Short on cash, the POP gets what fits.", "pop_std.includes_the_standard_n_model":"Includes your standard routers: {n} × {model}, {cost} + {mo}/mo. Short on cash, the POP gets what fits.", "pop_std.make_this_the_standard":"Make this the standard", -"pop_std.new_pops_now_start_with":"New POPs now start with {n} × {model}.", +"pop_std.new_pops_now_start_with_list":"New POPs now start with {list}.", "pop_std.none":"None", "pop_std.not_all_of_the_standard":"Not enough cash or level for the whole standard in {city}: it got what fit.", -"pop_std.standard_for_new_pops":"Standard for new POPs", "pops_transit_ix.40_off_for_6_months":"40% off for 6 months", "pops_transit_ix.40_off_ix_for_6_months":"40% off {ix} for 6 months.
Your account manager is relieved. Read the small print later.", "pops_transit_ix.after_consulting_with_management_the":"\"After consulting with management…\"
The price went up. Management was consulted.", diff --git a/tests/build-standard.test.js b/tests/build-standard.test.js new file mode 100644 index 0000000..faefc4f --- /dev/null +++ b/tests/build-standard.test.js @@ -0,0 +1,518 @@ +// The build standard: one target state for every POP, port and fiber, set in its own sheet, applied to new POPs at +// once, brought up by the intern's "Keep to the build standard" order or in one tap, and priced before anything changes. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt (one Edge Lord, broadband, 100G Cogentle transit) and Amsterdam (one router, nothing on it yet), level 7, +// PNIs up the moment they are ordered and Change Freeze (no fat fingers, no dice). +const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');S.rules.pnis='instant';" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});compute()"; +const AU = "RG.findIndex(r=>r.n==='Absolute Unit 3.2T')"; +const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()"); +const shift = ev => ev('opsDay(S.day)'); +function game(t, extra = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const pop = (ev, c) => JSON.parse(ev(`JSON.stringify(S.pops.${c})`)); +const std = (ev, d) => ev(`S.popStd=${lit(d)}`); +// A leased dark fiber between two POPs, built and lit with these optics. +const fiber = (ev, a, b, ch, sys = 'lite') => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'df',own:false,sys:'${sys}',ch:${lit(ch)},km:Math.round(kmBetween('${a}','${b}')),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});return id;})()`); + +test('the POP part: model, routers, second building and generator, the busiest POP first, at exactly what the plan priced', t => { + const { ev, errors } = game(t); + hire(ev); + std(ev, { g: ev(AU), rt: 2, site2: true, gen: true }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')), c0 = ev('S.cash'); + assert.equal(q.pops, 2); + shift(ev); + for (const c of ['fra', 'ams']) { + const p = pop(ev, c); + assert.deepEqual([p.rgen, p.routers, !!p.site2, !!p.gen], [ev(AU), 2, true, true], c); + } + assert.equal(c0 - ev('S.cash'), q.cost, 'the shift paid what the plan said'); + // Frankfurt has one router carrying broadband: a second went in first, so the swap rolled through. + assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false, 'no maintenance window'); + assert.match(ev('opsLine(S.ops.log[0])'), /build standard/); + assert.match(ev('opsLine(S.ops.log[0])'), /Frankfurt/); + assert.equal(ev('opsWhereOk(S.ops.log[0].r[0][2][0])'), true, 'the log survives a save'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdPlan(true))')), [], 'nothing left to do'); + // Its monthly books include the building and the generator now. + ev('compute()'); + assert.equal(ev('opsMoNow()') > ev('2*(SITE2_MO+GEN_MO)'), true); + assert.deepEqual(errors, []); +}); + +test('a busy POP with one router never gets a maintenance window; never a step down; the core keeps its routers', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + // A small budget: only the extra router fits this month, so the swap waits for it (and never goes ahead alone). + std(ev, { g: chonk, rt: 1 }); + ev(`S.ops.cap.std=OPS_CAPS.find(c=>c>=routerCost(1,1)&&cx[0]==='broke')"), 'the log says the budget ran out'); + ev('{const m0=monthIdx(S.day);while(monthIdx(S.day)===m0)S.day++;}S.ops.cap.std=0;compute();opsDay(S.day)'); + assert.deepEqual([pop(ev, 'fra').routers, pop(ev, 'fra').rgen], [2, chonk], 'then the swap rolls through'); + assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false); + // A smaller model as the standard: nobody is swapped back. + std(ev, { g: 1, rt: 1 }); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(pop(ev, 'fra').rgen, chonk); + // A POP in the backbone core is never swapped onto a model that cannot run it (the Whitebox 64 has no label stack for + // RSVP-TE): the best main-line model no bigger than it that can, instead. + const sonic = ev("RG.findIndex(r=>r.n==='Sonic the Whitebox 64')"); + ev(`S.pops.ams.rgen=RG.findIndex(r=>r.n==='Arrrhipster 7280R');S.pops.ams.routers=2`); + std(ev, { g: sonic, rt: 1 }); + assert.equal(ev("bstdModel(S.popStd.g,'ams')"), sonic, 'a plain IGP backbone takes any model'); + ev('S.core={lv:2,run:2}'); + assert.ok(ev("inCore('ams')")); + assert.equal(ev("bstdModel(S.popStd.g,'ams')"), chonk, 'RSVP-TE in the core: the Chonk 800 instead'); + assert.deepEqual(errors, []); +}); + +test('budget, cash floor, per-POP exceptions; without an intern nothing runs and no dice are rolled', t => { + const { ev, errors } = game(t); + std(ev, { rt: 2, gen: true }); + ev('S.ops.on.std=true'); + const r = ev('window.__n=0;window.__r=Math.random;Math.random=()=>{__n++;return __r()};const s=JSON.stringify(S);opsDay(S.day);Math.random=__r;s===JSON.stringify(S)&&__n===0'); + assert.equal(r, true, 'no intern: nothing happens, nothing random'); + hire(ev); + // Amsterdam is excepted: the intern never touches it. + ev("S.ops.skip.ams=['std']"); + // The floor: only what leaves the floor clear. A generator is $12k, a router more. + ev('S.ops.floor=50000;S.cash=50000+GEN_COST+1'); + shift(ev); + assert.deepEqual([pop(ev, 'fra').gen, pop(ev, 'fra').routers], [true, 1], 'the generator fit above the floor, the router did not'); + assert.ok(ev('S.cash') >= 50000, 'never below the floor'); + assert.deepEqual([pop(ev, 'ams').gen, pop(ev, 'ams').routers], [false, 1], 'the excepted POP is untouched'); + assert.equal(ev("bstdQuote(true).pops"), 1, 'the intern\'s own view leaves the exception out'); + assert.equal(ev("bstdQuote(false).pops"), 2, 'the sheet still shows it below the standard'); + // A monthly cap of setup fees. + ev("S.cash=1e8;S.ops.floor=0;S.ops.cap.std=10000;S.day++;opsDay(S.day)"); + assert.equal(pop(ev, 'fra').routers, 1, 'a router is more than the budget'); + assert.deepEqual(errors, []); +}); + +test('the bank that forbids generators gets none; DE-KICKS is skipped; an exchange port where there is one', t => { + const { ev, dom, errors } = game(t); + hire(ev); + ev("S.loans.push({id:'L1',bank:'storm',amount:1e6,covs:['nogen'],apr:0.05,term:24,pay:0,start:S.day,left:24})"); + std(ev, { gen: true, ix: true }); + assert.equal(ev('popStdQuote()'), null, 'a new POP is not quoted a generator either'); + shift(ev); + assert.equal(pop(ev, 'fra').gen, false); + assert.equal(pop(ev, 'ams').gen, false); + assert.equal(ev("COVS.nogen.ok()"), true, 'the covenant holds'); + // Frankfurt's exchange is DE-KICKS: that wants a sales call (a quote window), so the intern leaves it alone. + assert.equal(ev('isDk("fra")'), true); + assert.equal(ev('S.ixp.fra'), undefined); + assert.equal(ev('!!(S.dk&&S.dk.q)'), false, 'no DE-KICKS quote was asked for'); + assert.equal(dom.window.document.getElementById('modal').hidden, true, 'and no window opened'); + assert.equal(ev('S.ixp.ams'), 0, 'Amsterdam gets a 10G port'); + ev('ACT.bstdApply()'); + assert.equal(pop(ev, 'fra').gen, false, 'the button respects the covenant too'); + assert.deepEqual(errors, []); +}); + +test('ports: LAG members up to the standard, split over both buildings; PNIs spread to more cities; never fewer members', t => { + const { ev, errors } = game(t); + hire(ev); + const net = ev("NETS.find(n=>n.pops.includes('fra')&&n.pops.includes('ams')&&pniMin(n.id)===0&&peerOk(n.id,'pni','ams').ok&&peerOk(n.id,'pni','fra').ok).id"); + ev(`S.pops.fra.site2=true;S.pni.push({id:'P1',city:'fra',net:${lit(net)},tier:1,ready:S.day});ACT.buyIx({city:'ams',tier:1});(S.ixn=S.ixn||{}).ams=4;compute()`); + // The PNI list says a second one in Amsterdam is worth it. + ev(`const _v=pniVal;pniVal=(id,c)=>id===${lit(net)}&&c==='ams'?{..._v(id,c),worth:true,want:40,tier:1}:_v(id,c)`); + std(ev, { lag: 2, split: true, pni: 2 }); + shift(ev); + const t0 = JSON.parse(ev('JSON.stringify(S.transit[0])')); + assert.deepEqual([t0.n, t0.site], [2, 'ab'], 'transit: a second member, split over both buildings'); + const p = JSON.parse(ev(`JSON.stringify(S.pni.find(x=>x.id==='P1'))`)); + assert.deepEqual([p.n, p.site], [2, 'ab'], 'the PNI too'); + assert.equal(ev('S.ixn.ams'), 4, 'a bigger LAG stays as it is'); + assert.equal(ev(`S.pni.filter(x=>x.net===${lit(net)}).length`), 2, 'a PNI in a second city'); + assert.ok(ev(`S.pni.some(x=>x.net===${lit(net)}&&x.city==='ams')`)); + assert.equal(ev("S.ixSite&&S.ixSite.ams"), undefined, 'Amsterdam has one building: nothing to split'); + assert.deepEqual(errors, []); +}); + +test('fiber: the line system only on a quiet fiber or with a parallel link, one a shift; faster optics, old ones on the shelf; bigger waves', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4']); + ev("compute();for(const l of S.links)R.load[l.id]=0"); + std(ev, { sys: 'roadm', opt: 'fast' }); + const cap0 = ev(`S.links.find(l=>l.id===${lit(a)}).ch.reduce((s,o)=>s+optG(o,S.links.find(l=>l.id===${lit(a)})),0)`); + shift(ev); + const L = id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}))`)); + assert.deepEqual([L(a).sys, L(b).sys].sort(), ['lite', 'roadm'], 'one fiber goes dark per shift'); + const up = L(a).sys === 'roadm' ? a : b, other = up === a ? b : a; + assert.equal(L(up).eqDown, ev('S.day+1')); + assert.ok(L(up).ch.every(o => o === 'tp16'), 'its optics are the fastest that reach on the new line system: ' + L(up).ch); + // The other one only waits its turn: no optics in between that its own swap would put on the shelf a day later. + assert.ok(L(other).ch.every(o => o === 'zr4'), 'a quiet fiber waiting its turn keeps its optics: ' + L(other).ch); + assert.equal(ev('S.spares.zr4'), L(up).ch.length, 'the old optics of the swapped fiber went on the shelf'); + assert.equal(ev('S.spares.zr8'), undefined, 'and no stand-in optics were bought'); + // Busy and alone between its cities: it keeps its line system, and gets the fastest optics that one takes. + ev(`S.day+=2;compute();R.load[${lit(other)}]=capOf(S.links.find(l=>l.id===${lit(other)}))*0.9;opsDay(S.day)`); + assert.equal(L(other).sys, 'lite', 'not while it is busy and alone'); + assert.ok(L(other).ch.every(o => o === 'zr8'), 'the fastest the old line system takes: ' + L(other).ch); + assert.equal(ev('S.spares.zr4'), 3, 'all the old optics went on the shelf'); + // A parallel wave with room carries its load: now it can go dark for a day, and gets the bigger optics. + ev(`const o=S.links.find(l=>l.id===${lit(other)});UI.lmode='wave';UI.pending={a:o.a,b:o.b};ACT.buildLink({tier:3});S.day++;compute();R.load[o.id]=capOf(o)*0.9;for(const l of S.links)if(l.kind==='wave')R.load[l.id]=0;opsDay(S.day)`); + assert.equal(L(other).sys, 'roadm'); + assert.ok(L(other).ch.every(o => o === 'tp16'), L(other).ch); + assert.equal(ev('S.spares.zr8'), L(other).ch.length); + const cap1 = ev(`S.links.find(l=>l.id===${lit(a)}).ch.reduce((s,o)=>s+optG(o,S.links.find(l=>l.id===${lit(a)})),0)`); + assert.ok(cap1 > cap0, `capacity went up: ${cap0} → ${cap1}`); + // Waves: a bigger one than the standard stays as it is; a smaller one goes up. + const w = ev("S.links.find(l=>l.kind==='wave').id"); + assert.equal(L(w).tier, 3); + std(ev, { wv: 2 }); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(L(w).tier, 3, 'an 800G wave is never made smaller'); + std(ev, { wv: 3 }); + ev(`S.links.find(l=>l.id===${lit(w)}).tier=1;S.day++;compute();opsDay(S.day)`); + assert.equal(L(w).tier, 3, 'a 100G wave goes up to 800G'); + assert.deepEqual(errors, []); +}); + +test('quiet fibers take their line system one a shift and buy nothing in between: the intern spends what the quote said', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});ACT.buildPop({city:'lon'});for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); + const quiet = 'compute();for(const l of S.links)R.load[l.id]=0'; + ev(quiet); + std(ev, { sys: 'roadm', opt: 'fast' }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')), c0 = ev('S.cash'); + assert.deepEqual([q.links, q.held], [3, []]); + for (let d = 1; d <= 3; d++) { + ev(`${quiet};opsDay(S.day);S.day++`); + const ls = ids.map(id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}))`))); + assert.equal(ls.filter(l => l.sys === 'roadm').length, d, 'one more fiber a shift'); + for (const l of ls) assert.deepEqual(l.ch, l.sys === 'roadm' ? ['tp16', 'tp16'] : ['zr4', 'zr4'], 'tp16 on the new line system, the old optics until then'); + assert.equal(ev('S.spares.zr8'), undefined, 'no optics bought only to be shelved a day later'); + } + assert.equal(c0 - ev('S.cash'), q.cost, 'three shifts spent exactly the quote'); + assert.deepEqual(errors, []); +}); + +test('an optics swap is checked at what it costs when it runs: a refused job before it never lets one past the floor or the cap', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + // Paris's fiber is the hotter one: its zr8s go to tp16 first and onto the shelf, where Amsterdam's swap expects them. + const b = fiber(ev, 'fra', 'par', ['zr8', 'zr8'], 'roadm'), a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + const loads = `compute();for(const l of S.links)R.load[l.id]=0;R.load[${lit(b)}]=50;`; + ev(`S.spares={};${loads}`); + std(ev, { opt: 'fast' }); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdPlan(true).map(j=>[j.w,j.cost]))')), [['fra|par', 140000], ['fra|ams', 0]], 'priced as if the first one ran'); + const ch = id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}).ch)`)); + // The first is more than the budget: the second is not free then, and the cap and the floor see its real price. + ev(`S.ops.cap.std=10000;S.ops.floor=50000;S.cash=80000;S.ops.spent={};${loads}opsDay(S.day)`); + assert.equal(ev('S.cash'), 80000, 'nothing spent past the cap or the floor'); + assert.deepEqual([ch(a), ch(b)], [['zr4', 'zr4'], ['zr8', 'zr8']]); + assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')"), 'the log says the money ran out'); + ev(`S.ops.cap.std=0;S.day++;${loads}opsDay(S.day)`); + assert.equal(ev('S.cash'), 80000, 'no cap: the floor alone still holds'); + // Exactly enough above the floor for Amsterdam's own zr8s, bought new: it goes ahead, down to the floor and no further. + ev(`S.cash=50000+2*optCost('zr8');S.day++;${loads}opsDay(S.day)`); + assert.deepEqual(ch(a), ['zr8', 'zr8']); + assert.equal(ev('S.cash'), 50000); + // The button checks the price at the click too: never more than the cash in hand. + std(ev, { opt: 'fast' }); + ev(`S.spares={};S.links.find(l=>l.id===${lit(a)}).ch=['zr4','zr4'];S.cash=30000;${loads}ACT.bstdApply()`); + assert.deepEqual(ch(a), ['zr4', 'zr4'], 'two zr8 at $44k do not fit $30k'); + assert.equal(ev('S.cash'), 30000); + assert.deepEqual(errors, []); +}); + +test('a busy fiber with nothing parallel keeps its line system: the sheet, the button and the MCP quote say what the click buys', t => { + const h = load({ agent: true }); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev(BASE); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const a = fiber(ev, 'fra', 'ams', Array(6).fill('zr4')); + const busy = `compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`; + // tp16 on the shelf: the quote must not count on a line-system swap that will not happen today. + ev(`S.spares={tp16:6};${busy}`); + std(ev, { sys: 'roadm', opt: 'fast' }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')); + assert.deepEqual([q.held, q.links, q.n], [['fra|ams'], 1, 1]); + assert.equal(q.cost, 6 * ev("optCost('zr8')"), 'six zr8 for the line system it keeps'); + ev(`closeModal();${busy}`); + const dry = JSON.parse(ev("JSON.stringify(apiRun('bstdApply',{},{dryRun:true}))")); + assert.equal(dry.quote.setup, q.cost, 'the MCP quote is the same bill'); + assert.match(dry.quote.blocked[0], /^Frankfurt–Amsterdam: its line system waits/); + ev(`${busy}ACT.bstdOpen()`); + const doc = h.dom.window.document; + assert.match(doc.getElementById('modalCard').textContent, /One fiber keeps its line system for now/); + assert.equal(doc.querySelector('#modalCard [data-act="bstdApply"]').textContent, `Bring everything up now · ${ev(`fmt$(${q.cost})`)}`); + const c0 = ev('S.cash'); + ev(`${busy}document.querySelector('#modalCard [data-act="bstdApply"]').click()`); + assert.equal(c0 - ev('S.cash'), q.cost, 'the click spent the quote'); + const l = JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}))`)); + assert.deepEqual([l.sys, l.ch], ['lite', Array(6).fill('zr8')], 'and bought what it listed'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.spares)')), { tp16: 6, zr4: 6 }); + // Two busy fibers that carry each other: one goes dark, the other waits for tomorrow, and the quote knew. + const b = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + ev(`S.links.find(l=>l.id===${lit(a)}).ch=['zr4','zr4']`); + const both = `compute();for(const id of [${lit(a)},${lit(b)}])R.load[id]=capOf(S.links.find(l=>l.id===id))*0.4;`; + ev(both); + const q2 = JSON.parse(ev('JSON.stringify(bstdQuote(false))')), c1 = ev('S.cash'); + assert.deepEqual([q2.links, q2.held.length], [2, 1]); + ev(`${both}ACT.bstdApply()`); + assert.equal(c1 - ev('S.cash'), q2.cost); + assert.deepEqual(JSON.parse(ev(`JSON.stringify([${lit(a)},${lit(b)}].map(id=>S.links.find(l=>l.id===id).sys).sort())`)), ['lite', 'roadm'], 'never both dark on the same day'); + assert.deepEqual(errors, []); +}); + +test('optics a new router model takes are on the bill with it, and wait for its swap', t => { + const { ev, errors } = game(t); + // Edge Lords take no zr8: the Absolute Unit does. + ev('S.pops.ams.rgen=1;S.pops.fra.routers=2;S.pops.ams.routers=2'); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + ev('compute()'); + assert.equal(ev("RG[1].cls[j.k,j.w,j.dep?j.dep.length:0]))")); + assert.deepEqual(plan.filter(j => j[0] === 'opt'), [['opt', 'fra|ams', 2]], 'the optics wait for both swaps'); + // The intern: the swaps are over the budget, so the optics are not pulled out and put back. + hire(ev); + ev('S.ops.cap.std=50000;compute();opsDay(S.day)'); + assert.deepEqual(JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}).ch)`)), ['zr4', 'zr4']); + assert.ok(!(ev('S.ops.spent.std') > 0)); + // The button: the swaps and the optics, exactly the quote, and nothing left over. + ev('S.ops.on.std=false;compute()'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')), c0 = ev('S.cash'); + ev('ACT.bstdApply()'); + assert.equal(c0 - ev('S.cash'), q.cost); + assert.deepEqual(JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}).ch)`)), ['zr8', 'zr8']); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false))')), { cost: 0, mo: 0, pops: 0, ports: 0, links: 0, n: 0, held: [] }, 'one tap brought everything up'); + assert.deepEqual(errors, []); +}); + +test('waves the decom order is about to hand back are never upgraded first', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + ev("UI.lmode='wave';UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:3});for(let i=0;i<2;i++){UI.pending={a:'fra',b:'ams'};UI.route='diverse';ACT.buildLink({tier:1});}compute()"); + const waves = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='wave').map(l=>l.tier))")); + assert.deepEqual(waves(), [3, 1, 1]); + std(ev, { wv: 2 }); + assert.equal(ev('bstdQuote(true).n'), 2, 'without decom both small waves go up'); + ev('S.ops.on.decom=true'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')); + assert.equal(q.n, 1, 'decom keeps one spare in another trench and hands the other back: only the spare goes up'); + const c0 = ev('S.cash'); + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual(waves(), [3, 2], 'the spare went up, the other went back'); + assert.equal(c0 - ev('S.cash'), q.cost, 'no month of rent paid on a wave that went back'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ops.log[0].r.map(x=>[x[0],x[1]]))')), [['std', 1], ['decom', 1]]); + assert.deepEqual(errors, []); +}); + +test('a new POP gets the whole POP standard, priced on the button; the template\'s kit never pays for it twice', t => { + const { ev, dom, errors } = game(t); + std(ev, { g: ev(AU), rt: 2, site2: true, gen: true, lag: 2 }); + const q = JSON.parse(ev('JSON.stringify(popStdQuote())')); + assert.deepEqual([q.g, q.rt, q.site2, q.gen], [ev(AU), 2, true, true]); + ev("selectCity('par');renderPanel()"); + assert.match(dom.window.document.getElementById('panelBody').textContent, /Includes your build standard: 2 × Absolute Unit 3\.2T, second building, generator/); + let c0 = ev('S.cash'); + ev("ACT.buildPop({city:'par'})"); + assert.equal(c0 - ev('S.cash'), ev("popCost('par')") + q.cost, 'the button\'s price is what it costs'); + const p = pop(ev, 'par'); + assert.deepEqual([p.rgen, p.routers, p.site2, p.gen], [ev(AU), 2, true, true]); + // The template: broadband, transit, an IX port and the kit, all with the standard. The kit has nothing left to add. + hire(ev); + const tq = JSON.parse(ev("JSON.stringify(opsTplQuote('lon'))")); + assert.equal(tq.kit, false, 'the standard already has the generator, the building and the second router'); + assert.ok(tq.parts.includes('build standard')); + c0 = ev('S.cash'); + ev("ACT.opsNewPop({city:'lon'})"); + assert.equal(c0 - ev('S.cash'), tq.cost, 'the template costs what it quoted'); + assert.equal(pop(ev, 'lon').gen, true); + // Without a generator in the standard, the kit adds just that. + std(ev, { g: ev(AU), rt: 2, site2: true }); + const tq2 = JSON.parse(ev("JSON.stringify(opsTplQuote('mad'))")); + assert.equal(tq2.kit, true); + c0 = ev('S.cash'); + ev("ACT.opsNewPop({city:'mad'})"); + assert.equal(c0 - ev('S.cash'), tq2.cost); + assert.deepEqual([pop(ev, 'mad').gen, pop(ev, 'mad').routers], [true, 2]); + assert.deepEqual(errors, []); +}); + +test('"Bring everything up now" spends what the quote said and does what it listed; the quote changes nothing', t => { + const { ev, errors } = game(t); + ev(`S.pops.fra.routers=2;S.pops.fra.site2=true;ACT.buyIx({city:'ams',tier:0})`); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams'])S.pops[c].rgen=${chonk}`); + fiber(ev, 'fra', 'ams', ['zr4']); + ev("compute()"); + std(ev, { g: ev(AU), rt: 3, site2: true, gen: true, lag: 2, split: true, ix: true, sys: 'roadm', opt: 'fast' }); + const s0 = ev('JSON.stringify(S)'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')); + ev('ACT.bstdOpen()'); + assert.equal(ev('JSON.stringify(S)'), s0, 'the quote and the sheet leave the game alone'); + assert.ok(q.n > 0 && q.pops === 2 && q.ports >= 2 && q.links === 1, JSON.stringify(q)); + const c0 = ev('S.cash'); + ev("document.querySelector('#modalCard [data-act=\"bstdApply\"]').click()"); + assert.equal(c0 - ev('S.cash'), q.cost, 'it cost exactly the quote'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false))')), { cost: 0, mo: 0, pops: 0, ports: 0, links: 0, n: 0, held: [] }, 'and everything is up to the standard'); + assert.match(ev("document.getElementById('toasts').textContent"), /jobs done for the build standard/); + assert.match(ev("document.getElementById('modalCard').textContent"), /Everything meets the standard/); + assert.equal(ev('S.ixSite.ams'), 'ab'); + assert.deepEqual(errors, []); +}); + +test('saves: an old {g, rt} standard loads unchanged and still means the same; junk is repaired; none stays none', t => { + const { ev, errors } = game(t); + const back = d => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.popStd=${d};sanitize(s);return JSON.stringify(s.popStd);})()`); + assert.deepEqual(JSON.parse(back(`{g:${ev(AU)},rt:2}`)), { g: ev(AU), rt: 2 }, 'an old standard is exactly the routers it was'); + assert.equal(back('undefined'), 'null', 'an old save without one'); + assert.equal(back('null'), 'null'); + assert.equal(back("'x'"), 'null'); + assert.deepEqual(JSON.parse(back("{g:'x',rt:'7',site2:'yes',gen:true,lag:3,split:1,ix:true,pni:9,sys:'warp',opt:'fast',wv:99}")), { rt: 7, gen: true, ix: true, opt: 'fast' }, 'each odd value reads as keep'); + assert.equal(back('{g:999}'), 'null', 'nothing left is no standard'); + // The old meaning: a new POP gets those routers, and nothing else is done anywhere unless the order is switched on. + ev(`S=migrate(JSON.parse(JSON.stringify(Object.assign(S,{popStd:{g:${ev(AU)},rt:2}}))));delete S.ops.on.std;S=migrate(JSON.parse(JSON.stringify(S)))`); + assert.equal(ev('S.ops.on.std'), false, 'an old save has the order off'); + ev("ACT.buildPop({city:'par'})"); + assert.deepEqual([pop(ev, 'par').rgen, pop(ev, 'par').routers, !!pop(ev, 'par').site2, !!pop(ev, 'par').gen], [ev(AU), 2, false, false]); + // A model smaller than the basic router (the Mikrowtik has more ports) is still what a new POP gets, as it always was. + const mk = ev("RG.findIndex(r=>r.n==='Mikrowtik CCR')"); + assert.ok(ev(`RG[${mk}].cap { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const h = load(lang === 'en' ? {} : { lang }); + const { ev, dom, errors } = h; + ev(BASE); + dom.window.innerWidth = 360; + const doc = dom.window.document; + const leaks = () => { + const txt = doc.getElementById('modalCard').textContent; + assert.doesNotMatch(txt, /\b(bstd|ops|pop_std|common)\.[a-z_]+/, lang + ': a raw label'); + assert.doesNotMatch(txt, /\{[a-z]\w*\}|undefined|NaN/, lang); + }; + ev('ACT.menu()'); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the menu'); + leaks(); + // Every target is a list; pick its last value and the standard follows, the sheet stays open and in focus. + const keys = JSON.parse(ev('JSON.stringify(BSTD.map(x=>x.k))')); + assert.equal(doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]').length, keys.length); + for (const k of keys) { + const s = [...doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].find(x => JSON.parse(x.dataset.args).k === k); + assert.ok(s.closest('.ops-sel'), 'the Ops sheet\'s two-to-a-row lists'); + s.value = String(s.options.length - 1); + s.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.ok(ev('bstdShown()'), lang + ' ' + k); + assert.equal(doc.activeElement && doc.activeElement.dataset.args, JSON.stringify({ k }), 'the keyboard stays on the list'); + assert.notEqual(ev(`bstd()[${lit(k)}]`), ev(`BSTDK[${lit(k)}].d`), lang + ' ' + k); + } + leaks(); + if (lang === 'fr') assert.match(doc.getElementById('modalCard').textContent, /Répartis sur les deux bâtiments/, 'LAG is masculine'); + // The Ops sheet has a way in before anyone is hired too. + ev('ACT.opsOpen()'); + assert.equal(ev('opsHired()'), false); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the Ops sheet with no intern'); + // The intern's switch and budget sit in the sheet once one is hired, and stay there when used. + ev("ACT.opsHire({id:'annie'});closeModal();ACT.bstdOpen()"); + doc.querySelector('#modalCard [data-act="opsToggle"]').click(); + assert.ok(ev('S.ops.on.std') && ev('bstdShown()'), lang); + const cap = doc.querySelector('#modalCard select[data-chg="opsCap"]'); + cap.value = String(cap.options.length - 1); + cap.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(ev("opsCap('std')"), 0, lang); + assert.ok(ev('bstdShown()'), lang); + leaks(); + // From the Ops sheet and the city panel. + ev('ACT.opsOpen()'); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the Ops sheet'); + ev("closeModal();selectCity('fra');ACT.tab({t:'links'})"); + assert.doesNotMatch(doc.getElementById('panelBody').textContent, /\b(bstd|pop_std)\.[a-z_]+/, lang); + doc.querySelector('#panelBody [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the city panel'); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); + +test('puzzles have no standard; the MCP tools see every action', () => { + const { ev, errors } = load(); + ev(BASE); + std(ev, { rt: 2 }); + ev("ACT.puzzleMenu();ACT.pzStart({id:PZ[0].id})"); + assert.ok(ev('pzOn()')); + assert.equal(ev('popStdQuote()'), null); + assert.equal(ev('bstdPlan(false).length'), 0); + ev("ACT.bstdSet({k:'rt'})"); + assert.equal(ev('bstdShown()'), false); + assert.deepEqual(errors, []); +}); + +test('the big network: one shift of the order takes a few milliseconds', t => { + const { ev, errors } = load({ seed: 3 }); + t.after(() => ev('0')); + const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); + ev(`S.ops.intern='kevin';S.ops.on.std=true;S.ops.floor=0;S.ops.cap.std=0;S.rules.pnis='instant';S.popStd={g:${AU},rt:2,site2:true,gen:true,lag:2,split:true,ix:true,pni:2,sys:'cl',opt:'fast',wv:4}`); + const plan = ev('(()=>{const t=performance.now();for(let i=0;i<5;i++)bstdPlan(true);return (performance.now()-t)/5;})()'); + const jobs = ev('bstdPlan(true).length'); + const shiftMs = ev('(()=>{const t=performance.now();opsDay(S.day);return performance.now()-t;})()'); + console.log(`# big network: plan ${plan.toFixed(1)} ms (${jobs} jobs), one shift ${shiftMs.toFixed(1)} ms with its recompute`); + assert.ok(jobs > 0); + assert.ok(plan < 250, 'planning stays cheap: ' + plan); + assert.ok(ev("S.ops.log[0].r.find(x=>x[0]==='std')[1]") <= ev('BSTD_MAX'), 'a few jobs a shift'); + // Second buildings the month's budget cannot pay for: the LAG splits that need them wait with them, instead of being + // tried (two opsMoNow runs each) and failing at every POP, every shift. + ev('for(const t of S.transit)t.n=Math.max(2,t.n||1);S.ixn=S.ixn||{};for(const x in S.ixp)if(!S.myIx[x])S.ixn[x]=Math.max(2,S.ixn[x]||1);for(const p of S.pni)if(pniOn(p)&&!p.up)p.n=Math.max(2,p.n||1)'); + ev('for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.std=true;S.popStd={rt:1,site2:true,split:true};S.ops.cap.std=OPS_CAPS[0];window.__m=0;const _m=opsMoNow;opsMoNow=function(){__m++;return _m.apply(this,arguments);};compute()'); + assert.ok(ev("bstdPlan(true).filter(j=>j.k==='split'&&j.dep).length") > 100, 'many splits wait for a building'); + for (let d = 0; d < 3; d++) { + const ms = ev("(()=>{__m=0;S.day++;S.ops.mon=monthIdx(S.day);S.ops.spent.std=OPS_CAPS[0];const t=performance.now();opsDay(S.day);return performance.now()-t;})()"); + const did = ev("(S.ops.log[0].d===S.day&&(S.ops.log[0].r.find(x=>x[0]==='std')||[])[1])||0"); + console.log(`# big network, budget spent: shift ${ms.toFixed(1)} ms, ${did} splits done, ${ev('__m')} opsMoNow runs`); + assert.equal(ev('__m'), 2 * did, 'every job tried was one that could be done'); + assert.ok(did <= ev('BSTD_MAX')); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/i18n.test.js b/tests/i18n.test.js index cd780c4..a7ce585 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -35,7 +35,9 @@ function tour(ev) { ['scenarios', 'scenarioModal();closeModal()'], ['trace', "traceModal('fra');closeModal()"], ['route script', 'S.lvl=Math.max(S.lvl,3);S.cash+=1e6;ACT.coreUp();ACT.coreUp();ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'], ['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"], - ['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src); + ['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()'], + // The build standard sheet with every target set (and the game left as it was). + ['build standard', "{const was=S.popStd;S.popStd={g:3,rt:2,site2:true,gen:true,lag:2,split:true,ix:true,pni:2,sys:'roadm',opt:'fast',wv:2};ACT.bstdOpen();S.popStd=was;closeModal()}"]]) step(label, src); const failSrc = ev('fireFailure.toString()'); for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 9101521..91cce81 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -318,6 +318,30 @@ test('the dashboard, the bank, the left drawer and the puzzle box read as text; assert.deepEqual(s.errors(), []); }); +test('a list in a sheet sends its own arguments with the value picked: the build standard and the intern\'s budget', () => { + const { s, T, ev } = sandbox({ pops: [] }); + act(T, 'bstdOpen'); + const list = (sel, k) => T('screen').buttons.find((b) => b.select === sel && b.args && b.args.k === k); + const g = list('bstdSet', 'g'); + assert.ok(g, 'the router model list, with its target'); + const v = g.options[g.options.length - 1].value; + assert.equal(T('click', { button: g.n, value: v }).outcome, 'applied'); + assert.equal(ev('S.popStd.g'), ev(`bstdOpts('g')[${v}]`)); + const lag = list('bstdSet', 'lag'); + assert.equal(T('click', { button: lag.n, value: '1' }).outcome, 'applied'); + assert.equal(ev('S.popStd.lag'), 2); + ev('closeModal()'); + act(T, 'opsHire', { id: ev('Object.keys(INTERNS)[0]') }); + ev('closeModal()'); + act(T, 'opsToggle', { k: 'std' }); + act(T, 'opsOpen'); + const cap = list('opsCap', 'std'); + assert.ok(cap, 'the order\'s budget list'); + assert.equal(T('click', { button: cap.n, value: String(cap.options.length - 1) }).outcome, 'applied'); + assert.equal(ev("opsCap('std')"), 0, 'no limit'); + assert.deepEqual(s.errors(), []); +}); + test('new_game takes your own ASN and the sandbox chaos dial', () => { const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); assert.equal(T('new_game', { city: 'ams', asn: 213337, seed: 2 }).asn, 213337); From 95aa9b65326fe82b16eaa4e09f69759d46557bdc Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 00:42:39 +0100 Subject: [PATCH 3/8] Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard Off unless the page is built with MP_API set (MP_API=/api/mp npm run build): a plain build has no door, no chip and makes no requests. The session server is scripts/mp-server.js (npm run mp), plain node:http, which can also serve the built site so one process sits behind the reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups. A session has a six-character code, one seed and one rules preset, so every player starts in the same world, and up to twelve players with their own AS numbers. Saves go to the server on a new game day at most every 15 s and when the page hides, ordered by a sequence number (409 on a stale push, and the player picks which one to keep). Tokens live in localStorage, never in the save; the server keeps only their hash. A #mp= link moves a network to another device. The session panel shows the leaderboard, the feed and a short chat; each player's public card (tier, POPs, links, exchanges, transit, peak, customers, score) carries what in-game peering between players will need next. Server limits: body sizes, one upload per player, uploads per address and in total, sessions per hour, wrong-code lockout; addresses counted per IPv6 /64, X-Forwarded-For only with --trust-proxy. --- .gitignore | 1 + CHANGELOG.md | 1 + docs/MULTIPLAYER.md | 211 ++++++ package.json | 3 +- scripts/build.js | 10 +- scripts/dev.js | 7 +- scripts/lib/mp.js | 448 +++++++++++ scripts/mp-server.js | 117 +++ site/i18n/de.js | 59 ++ site/i18n/es.js | 59 ++ site/i18n/fr.js | 59 ++ site/i18n/it.js | 59 ++ site/i18n/pt.js | 59 ++ site/sw.js | 2 + src/agent/20-commands.js | 2 + src/agent/30-docs.js | 1 + src/game/00-core/20-analytics.js | 3 + src/game/60-features/20-scenarios.js | 5 +- src/game/60-features/80-new-game.js | 2 +- src/game/60-features/89-multiplayer.js | 180 +++++ src/game/80-simulation/50-sanitize.js | 2 +- src/game/90-actions/86-specialist.js | 4 +- src/game/90-actions/89-game-and-settings.js | 4 +- src/game/90-actions/90-action-helpers.js | 2 +- src/game/90-actions/91-slots.js | 2 +- src/game/90-actions/92-multiplayer.js | 34 + src/game/91-save.js | 3 +- src/game/91-slots.js | 11 +- src/game/93-ui/40-hud-and-panels.js | 1 + src/game/95-modals/40-title.js | 6 +- src/game/95-modals/45-slots.js | 2 +- src/game/95-modals/48-multiplayer.js | 73 ++ src/game/96-map/95-clicks.js | 2 +- src/game/99-loop.js | 7 +- src/i18n/en.js | 59 ++ src/styles/41-multiplayer.css | 36 + tests/harness.js | 5 +- tests/mp-server.test.js | 450 +++++++++++ tests/multiplayer.test.js | 790 ++++++++++++++++++++ 39 files changed, 2757 insertions(+), 24 deletions(-) create mode 100644 docs/MULTIPLAYER.md create mode 100644 scripts/lib/mp.js create mode 100644 scripts/mp-server.js create mode 100644 src/game/60-features/89-multiplayer.js create mode 100644 src/game/90-actions/92-multiplayer.js create mode 100644 src/game/95-modals/48-multiplayer.js create mode 100644 src/styles/41-multiplayer.css create mode 100644 tests/mp-server.test.js create mode 100644 tests/multiplayer.test.js diff --git a/.gitignore b/.gitignore index 24c9945..9027294 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ _site/ .DS_Store +mp-data/ diff --git a/CHANGELOG.md b/CHANGELOG.md index fad4db7..a6901a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. +- Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. diff --git a/docs/MULTIPLAYER.md b/docs/MULTIPLAYER.md new file mode 100644 index 0000000..37adcc3 --- /dev/null +++ b/docs/MULTIPLAYER.md @@ -0,0 +1,211 @@ +# Multiplayer (self-hosted copies) + +The game at [seriesoftub.es](https://seriesoftub.es) is hosted on GitHub Pages and nowhere else +([ADR 0001](adr/0001-github-pages-only.md)), so it has no server and no multiplayer. This page is for a copy you host +yourself: there, a small session server that ships with the source (`scripts/mp-server.js`) lets players build their +networks side by side. + +A plain `npm run build` is unchanged: the page has no multiplayer door, no chip and makes no request for it. Multiplayer +is switched on only when the build is told where the session server lives. + +## What it does (phase 1) + +- **Sessions by code.** One player starts a session from the title screen (Multiplayer: their network's name, home city + and rules preset, optionally a session name) and gets a six-character code such as `K7Q-2XD`. Friends join with that + code. Codes use Crockford's base32 (no I, L, O or U); they are case-insensitive, and the dash is optional. +- **One world.** Everyone in a session plays a Normal game with the creator's rules preset (Best Effort, Change Freeze, + On-call or BGP at 3 a.m.) and the session's random seed, so day 0 is the same world for all. The session hands each + player an AS number from 200000–214999 that nobody else in the session and no network on the map uses. Each network + is still simulated in its own player's browser; from the first different click on, the worlds drift apart. +- **Saves on the server.** Each network's save goes to the server on a new game day, at most every 15 seconds (gzipped + when it is big), and when the page is hidden or closed if anything changed since the last push (a paused game's + building too). Opening the network on any device fetches the server's save first and loads it if another device + played on. +- **Seeing each other.** Every push carries a small public *card*: day, tier, POPs, links between them (with capacity), + exchanges, transit providers, peering policy, reach, peak and served traffic, customers, revenue per month, cash as an + order of magnitude, and a score. The session panel (the 🌐 chip in the top bar, or the menu) shows the leaderboard + (Tier 1 first, then Tier 2, then traffic served), a feed (joins, leaves, Tier 2, Tier 1 and who got there first) and a + chat. While the panel is open it refreshes every 5 seconds; otherwise the roster rides along with each push. +- **Moving to another device.** The panel's "Move to another device" holds a link `https://your.host/#mp=CODE.pid.token`. + The part after `#` never reaches any server. Opening it (or copying the link) first sends this device's latest save, + and opening the link loads the network into that browser. Treat it like a password: anyone with it can play as you. + A browser keeps the link's token only once the server has accepted it, so a wrong or mistyped link never replaces the + one it already has; when the server cannot be reached, the link stays in the address bar for a reload to try again. +- **Offline.** The game never waits for the server. When it cannot be reached, the game says so once, keeps playing and + tries again later (30 s, then 1, 2, 4, at most 5 minutes apart; the open session panel keeps looking every 5 seconds + without stretching that wait). + +Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries +what that will need (POPs, links, exchanges, transit, peering policy, reach). + +## Build + +```bash +MP_API=/api/mp npm run build # _site/ with multiplayer on; the page talks to /api/mp on its own origin +``` + +`MP_API` must be a path on the same origin (letters, digits, `/`, `_`, `-`; no trailing slash, and not starting with +`//`, which a browser reads as another host). Anything else fails the build. Without it, or empty, the build is the +plain one. + +## Run the server + +```bash +node scripts/mp-server.js --site _site --data /var/lib/tubes-mp --port 8090 +# or: npm run mp -- --site _site --data /var/lib/tubes-mp +``` + +One process serves the API under `/api/mp` and, with `--site`, the built game too (like GitHub Pages would: `/` is +`index.html`, a missing file gets `404.html`, nothing outside the folder is ever served). It binds `127.0.0.1` by default: +put a reverse proxy with HTTPS in front. Plain `node:http`, no dependencies beyond Node 20 or newer. + +| Option | Default | | +|---|---|---| +| `--port N` | 8090 (or `$PORT`) | port to listen on | +| `--host H` | 127.0.0.1 | address to bind | +| `--data DIR` | `./mp-data` | sessions and saves; created if missing | +| `--site DIR` | none | also serve the built game from DIR | +| `--base PATH` | `/api/mp` | the API's path; must match `MP_API` | +| `--prune-days N` | 60 | sessions nobody touched for N days are deleted, at startup and daily | +| `--max-sessions N` | 1000 | sessions on this server | +| `--max-players N` | 12 | players per session (at most 12) | +| `--create-per-hour N` | 10 | new sessions one address may start per hour | +| `--sessions-per-hour N` | 100 | new sessions per hour on the whole server, from all addresses together | +| `--trust-proxy` | off | take the client's address from `X-Forwarded-For` (only behind your own proxy) | +| `--verbose` | off | one log line per API request (never tokens) | + +Behind a reverse proxy every request comes from the proxy's address, so the per-address limits only mean something with +`--trust-proxy` (the server then uses the last address in `X-Forwarded-For`, the one your proxy added); without it, all +players share one address's limits, such as 4 save uploads at once. An IPv6 address counts as its /64, since one phone +or home usually has a whole /64 to itself. + +To try it locally without a build: `npm run dev -- --mp` runs the API inside the dev server (sessions in `mp-data/`) and +turns multiplayer on in the dev page. Open a second window (a private one counts as another browser) to be the second +player. + +### nginx + +```nginx +server { + listen 443 ssl http2; + server_name tubes.example.org; + ssl_certificate /etc/letsencrypt/live/tubes.example.org/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/tubes.example.org/privkey.pem; + + client_max_body_size 5m; # a save is at most 4 MB + + location / { + proxy_pass http://127.0.0.1:8090; # the game and /api/mp, from the one process + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` + +Run the server with `--site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy`. + +### Caddy + +```caddy +tubes.example.org { + request_body { + max_size 5MB + } + reverse_proxy 127.0.0.1:8090 +} +``` + +Caddy sets `X-Forwarded-For` itself and gets the certificate on its own; run the server with `--trust-proxy` as above. + +### systemd + +```ini +[Unit] +Description=Series of Tubes multiplayer +After=network.target + +[Service] +ExecStart=/usr/bin/node /srv/tubes/scripts/mp-server.js --site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy +User=tubes +Restart=on-failure +StateDirectory=tubes-mp + +[Install] +WantedBy=multi-user.target +``` + +## Backups + +Everything is in the data folder: `.json` per session (settings, players, cards, feed, and each save's number) and +`..save` per player's save (its text exactly as the game sent it). Every write goes to a temporary file that is then renamed over the old one, so a +copy of the folder (`rsync`, a snapshot, `tar`) taken while the server runs holds whole files. Restore by stopping the +server, putting the files back and starting it again. A player's token is stored only as its SHA-256, so a backup cannot +be used to play as anyone. + +## Limits + +- 12 players per session, 1000 sessions per server (configurable). +- A save is at most 4 MB of text (the game gzips anything over 32 kB: the big test network, 236 kB of JSON, goes as about 50 kB). Other + requests are at most 16 kB. +- Chat lines: at most 200 characters, one a second and six per 30 seconds per player. The feed keeps the last 100 lines. +- Per address and hour (an IPv6 address counts as its /64): 10 new sessions, 60 joins, 120 wrong codes (after that, + every code is refused for a while from there, so guessing codes gets nowhere; a player who sends their own session's + code with its token is never refused for it). At most 100 new sessions an hour on the whole server. +- Saves and cards: one save upload at a time per player (another one meanwhile gets 429), at most 4 at once from one + address and 16 on the whole server (503 with `busy: true` beyond that; the game then tries again a little later, + quietly), and per player at most 20 saves and 60 cards a minute (the game sends one every 15 seconds at most). A + save's body must arrive within two minutes. A card alone is written to disk within two seconds, together with any + others that came in meanwhile. +- Network names: at most 32 characters; control characters, `<`, `>`, `&`, quotes and backticks are removed. The page + escapes everything other players wrote anyway. +- A page that is being hidden or closed can only send 64 KiB (the browser's limit for such requests, counted in bytes), + so a network whose save does not fit sends its card alone then; its save goes with the next push from that device. + +## How saves stay in order + +Each network in a session carries a save number (`S.mp.seq`). When a save is due to go to the server, the game picks +the next number before it writes the save, so the save kept in the browser and the one sent carry the same number; +reopening the network then finds nothing newer on the server unless another device pushed one. The server refuses a +number that is not newer than its own (HTTP 409, with its number), and only counts a save once it is on disk. Then the +player is told once that the network moved on elsewhere and chooses: load the newer save from the server (only one at +least as new as the server said it had: never an older one), or keep this one (at the end of the current game day it +goes with `force` and a number past the server's). + +The token is never part of the save: it lives in the browser's storage under `sot-mp::`. An exported or +imported save keeps its session but cannot talk to the server without the token (the game says it is no longer in its +session and plays on alone). + +## API + +JSON in and out, same origin, no cookies, no CORS headers. Every call but starting and joining needs +`Authorization: Bearer .`. Errors are `{"error": "…"}` with a fitting status (400, 401, 404, 405, 409, 413, +415, 429, 503). + +| Call | Body | Answer | +|---|---|---| +| `POST /api/mp/sessions` | `{net:{name,home}, preset, title?, avoid?}` | `201 {code, pid, token, seed, asn, preset, color, title}` | +| `POST /api/mp/sessions/:code/join` | `{net:{name,home}, avoid?}` | the same, for the joiner (`409 {full:true}` when full) | +| `GET /api/mp/sessions/:code` | | `{code, title, preset, seed, created, players:[{pid, name, asn, color, card, seen, joined}], feed}` | +| `PUT /api/mp/sessions/:code/card` | `{card}` | the roster | +| `PUT /api/mp/sessions/:code/save` | `{seq, at, data, card?, force?}` | `{ok, seq, at, roster}`, or `409 {seq, at}`; `429` while another one is on its way, `503` when the server is busy | +| `GET /api/mp/sessions/:code/save` | | `{seq, at, data}` (your own save only) | +| `POST /api/mp/sessions/:code/feed` | `{text}` | the roster | +| `DELETE /api/mp/sessions/:code/me` | | `{ok}`; the session goes when its last player leaves | + +`avoid` lists AS numbers the server must not hand out (the game sends the map's own networks in that range). `preset` is +one of `soft`, `freeze`, `oncall`, `bgp`. `data` is the save as the game writes it: JSON text, or `gz:` and base64. + +The card, as the server keeps it (unknown fields are dropped, numbers clamped, ids checked for shape; the page checks +the ids against its own catalogs again): `day`, `tier` (`t1`, `t2`, `t3`), `t1`, `lvl`, `pops` (city ids), `links` +(`[a, b, Gbps]`, up to 300), `ix`, `transit` (network ids), `ppol` (`open`, `selective`, `closed`), `reach` (0–1), +`peak`, `served` (Gbps), `cust`, `rev` (per month), `cashB` (−1 in debt, else the power of ten of the cash), `score`. +Cards are what each player's browser says: nothing on the server checks that a network really is that big. + +## Code + +- Server: `scripts/lib/mp.js` (the API and storage), `scripts/mp-server.js` (the command line and the static site). +- Game: `src/game/60-features/89-multiplayer.js` (state, sync, the card, the `#mp=` link), + `src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js` + (actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`. +- Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`. diff --git a/package.json b/package.json index 4e6ade7..2b3a9be 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,8 @@ "perf": "node scripts/perf-bench.js", "bench:gpu": "node scripts/gpu-bench.js", "mcp": "node scripts/mcp.js", - "mcp:browser": "node scripts/mcp.js --browser" + "mcp:browser": "node scripts/mcp.js --browser", + "mp": "node scripts/mp-server.js" }, "engines": { "node": ">=20" diff --git a/scripts/build.js b/scripts/build.js index 6c8971a..d884b46 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -6,6 +6,8 @@ // // npm run build VERSION, BUILD_DATE and OUT can be set in the environment // REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version +// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the +// page talks to scripts/mp-server.js at that path, same origin const fs = require('node:fs'); const path = require('node:path'); const { execFileSync } = require('node:child_process'); @@ -19,6 +21,10 @@ const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); }; if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`); if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`); if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`); +// Multiplayer is off unless MP_API names the session server's path on the page's own origin ("//host/x" would be +// another host, and the player's token would go there). +const MP_API = process.env.MP_API || ''; +if (MP_API && !/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(MP_API)) die(`MP_API '${MP_API}' must be a path on the same origin, like /api/mp`); fs.rmSync(OUT, { recursive: true, force: true }); fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true }); @@ -44,7 +50,9 @@ if (!html.includes(PH)) die('release-notes placeholder missing from the page'); // A release can also open with a story (prose before its first bullet), shown in full in "What's new". const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]'; if (!html.includes(PS)) die('release-story placeholder missing from the page'); -fs.writeFileSync(page, html.replace(PH, () => notes.replace(/ story.replace(/ notes.replace(/ story.replace(/ `'${MP_API}'`)); fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story) }, null, 2) + '\n'); // Nothing may ship half-stamped. diff --git a/scripts/dev.js b/scripts/dev.js index 2f4fab5..0f7cd54 100644 --- a/scripts/dev.js +++ b/scripts/dev.js @@ -7,6 +7,8 @@ // tools (node scripts/mcp.js --browser) drive the page this server serves. // Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the // relay's ws. For the production build as GitHub Pages will serve it: npm run serve. +// --mp also runs the multiplayer API (docs/MULTIPLAYER.md) at /api/mp, sessions kept in mp-data/, and turns multiplayer +// on in the page: two browser windows (or a private one) can then play one session locally. const fs = require('node:fs'); const http = require('node:http'); const path = require('node:path'); @@ -23,17 +25,19 @@ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; ch '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', '.webmanifest': 'application/manifest+json' }; const RELOAD = ''; +const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null; const clients = new Set(); function page() { const { html, map } = assemble({ dev: true }); // Errors report a line of the assembled page; the console also says which file under src/ that is. const hint = ``; - return html.replace('', `${hint}${RELOAD}`); + return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('', `${hint}${RELOAD}`); } const server = http.createServer((req, res) => { const url = new URL(req.url, 'http://localhost'); + if (MP && MP.handle(req, res)) return; if (url.pathname === '/__dev') { res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' }); res.write(': hi\n\n'); @@ -69,6 +73,7 @@ server.listen(PORT, HOST, () => { console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`); console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`); console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser'); + if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`); }); const shutdown = () => { relay.close(); process.exit(0); }; process.on('SIGINT', shutdown); diff --git a/scripts/lib/mp.js b/scripts/lib/mp.js new file mode 100644 index 0000000..051c1cc --- /dev/null +++ b/scripts/lib/mp.js @@ -0,0 +1,448 @@ +// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the +// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies. +// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the +// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API. +// +// Storage: one JSON file per session (DIR/.json: settings, players, cards, feed) and one file per player's save +// (DIR/..save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are +// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes +// part of a file name, and so is a player id. +const fs = require('node:fs'); +const path = require('node:path'); +const net = require('node:net'); +const crypto = require('node:crypto'); + +// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up. +const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; +const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/; +const PID_RE = /^[a-z0-9]{8}$/; +const TOKEN_RE = /^[0-9a-f]{64}$/; +const PRESETS = ['soft', 'freeze', 'oncall', 'bgp']; +const PPOL = ['open', 'selective', 'closed']; +const TIERS = ['t1', 't2', 't3']; +const ASN_LO = 200000, ASN_HI = 214999; +const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d']; +const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON) +const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 }; +const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places) +const FEED_MAX = 100, CHAT_MAX = 200; +const DAY = 86400000; + +// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant. +function normCode(s) { + if (typeof s !== 'string' || s.length > 20) return null; + const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0'); + return CODE_RE.test(c) ? c : null; +} +const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3); +const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; }; +const randPid = () => crypto.randomBytes(4).toString('hex'); +const sha = (t) => crypto.createHash('sha256').update(t).digest(); + +// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one +// space between words, at most max characters (whole characters, never half an emoji). +function cleanText(v, max) { + if (typeof v !== 'string') return ''; + const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim(); + return Array.from(s).slice(0, max).join('').trim(); +} +const cleanChat = (v) => { + if (typeof v !== 'string') return ''; + const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim(); + return Array.from(s).slice(0, CHAT_MAX).join('').trim(); +}; +const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); }; +const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d)); +// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one. +const ids = (v, re, max) => { + if (!Array.isArray(v)) return []; + const out = new Set(); + for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; } + return [...out]; +}; +const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/; + +/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its + catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */ +function cleanCard(c) { + if (!c || typeof c !== 'object' || Array.isArray(c)) return null; + const links = []; + if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) { + if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue; + links.push([l[0], l[1], num(l[2], 0, 1e7)]); + if (links.length >= 300) break; + } + return { + day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99), + pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64), + ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9), + cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15), + }; +} + +/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the + order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above + cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */ +function limiter(n, ms, cap = 20000) { + const m = new Map(); + const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; }; + return { + // Counts one more, unless the key is already at its limit. + ok(k, now) { + const a = live(k, now), ok = a.length < n; + if (ok) a.push(now); + m.delete(k); m.set(k, a); + for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; } + return ok; + }, + full: (k, now) => live(k, now).length >= n, + size: () => m.size, + }; +} + +/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an + IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */ +function addrKey(a) { + a = String(a || '').trim(); + if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0); + const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z); + const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1]; + const v = net.isIP(a); + if (v === 4) return a; + if (v !== 6) return null; + const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : []; + // The groups :: stands for (a dotted IPv4 at the end is two of them). + const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0); + const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail]; + return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64'; +} + +class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } } +const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); }; + +// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that +// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes. +function readJson(req, max, ms = 30000) { + return new Promise((resolve, reject) => { + const ct = String(req.headers['content-type'] || ''); + if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); } + const len = +req.headers['content-length']; + if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); } + let parts = [], n = 0, done = false; + const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); }; + const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms); + req.on('data', (b) => { + if (done) return; + n += b.length; + if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; } + parts.push(b); + }); + req.on('end', () => { + if (done) return; done = true; clearTimeout(tm); + let j; + try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); } + if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object')); + resolve(j); + }); + req.on('error', () => stop(new HttpError(400, 'request failed'))); + req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); }); + }); +} + +function send(res, status, body) { + if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; } + const txt = JSON.stringify(body); + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) }); + res.end(txt); +} + +/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API. + handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */ +function createMp(o = {}) { + const dir = path.resolve(o.dir || 'mp-data'); + const base = (o.base || '/api/mp').replace(/\/+$/, ''); + const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60; + const now = o.now || Date.now, log = o.log || ((s) => console.log(s)); + fs.mkdirSync(dir, { recursive: true }); + const file = (code) => path.join(dir, code + '.json'); + const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`); + const cache = new Map(), chains = new Map(), soon = new Map(); + let codes = new Set(), tmpN = 0; + const HOUR = 3600000, MIN = 60000; + const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR); + // However many addresses ask, the server fills up slowly: a full server takes days, not minutes. + const createAll = limiter(o.sessionsPerHour || 100, HOUR); + const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000); + // Wrong codes, counted per address: guessing codes runs out long before it finds one. + const missRate = limiter(o.missesPerHour || 120, HOUR); + // A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they + // stop one player from keeping the disk busy rewriting their session. + const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN); + // Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes. + const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4; + + // Atomic: write a temporary file next to it, then rename over the old one. + const writeAtomic = async (f, txt) => { + const tmp = `${f}.${process.pid}.${++tmpN}.tmp`; + await fs.promises.writeFile(tmp, txt); + await fs.promises.rename(tmp, f); + }; + // One session's writes happen one after another, in the order they were asked for. + const queue = (code, job) => { + const p = (chains.get(code) || Promise.resolve()).then(job, job); + const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); }); + chains.set(code, q); + q.then(() => { if (chains.get(code) === q) chains.delete(code); }); + return p; + }; + // A session that is gone (its last player left) is never written again, whatever was still on its way. + const persist = (s) => { + const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); } + s.touched = now(); + if (s.dead) return Promise.resolve(); + return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s))); + }; + // Cards change often and matter little: their session is written a moment later, once for all of that moment's. + const persistSoon = (s) => { + s.touched = now(); + if (s.dead || soon.has(s.code)) return; + const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000); + if (tm.unref) tm.unref(); + soon.set(s.code, tm); + }; + + function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } } + // Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes. + function prune() { + const cut = now() - pruneDays * DAY; let n = 0; + for (const f of fs.readdirSync(dir)) { + const p = path.join(dir, f); + let st; try { st = fs.statSync(p); } catch (e) { continue; } + if (!st.isFile()) continue; + if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; } + const m = /^([0-9A-Z]{6})\.json$/.exec(f); + const live = m && cache.get(m[1]); + if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; } + } + for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); } + scan(); + return n; + } + function drop(code) { + const s = cache.get(code); if (s) s.dead = true; + const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); } + for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true }); + cache.delete(code); codes.delete(code); + } + function load(code) { + if (!CODE_RE.test(code)) return null; + if (cache.has(code)) return cache.get(code); + if (!codes.has(code)) return null; + let s = null; + try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; } + if (!s || s.code !== code || !Array.isArray(s.players)) return null; + // A hand-edited or damaged file: players without an id or a token hash cannot be anyone. + s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string'); + for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) }; + if (!Array.isArray(s.feed)) s.feed = []; + cache.set(code, s); + return s; + } + prune(); + + // The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last. + const ipOf = (req) => { + if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; } + return addrKey(req.socket.remoteAddress) || '?'; + }; + // The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for + // a player who is not there. + function player(req, s) { + const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || '')); + if (!m) return null; + const p = s.players.find((x) => x.pid === m[1]); + const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]); + return crypto.timingSafeEqual(want, got) && p ? p : null; + } + const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; }; + // Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them. + const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p)); + const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); }; + const roster = (s) => ({ + code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created, + players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })), + feed: s.feed, + }); + // A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets + // the headline). A network that drops out and comes back is not news again. + function applyCard(s, p, c) { + const hit = p.hit || (p.hit = {}); + if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); } + else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); } + p.card = c; + } + function newPlayer(s, body, ip) { + const net = body.net && typeof body.net === 'object' ? body.net : {}; + const name = cleanText(net.name, 32); + if (!name) fail(400, 'name your network'); + const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null; + if (!home) fail(400, 'pick a home city'); + let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid)); + const token = crypto.randomBytes(32).toString('hex'); + const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a))); + for (const p of s.players) avoid.add(p.asn); + let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn)); + const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length]; + const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} }; + s.players.push(p); + event(s, 'join', p); + return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title }; + } + // The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped. + const readSave = async (code, pid) => { + const t = await fs.promises.readFile(saveFile(code, pid), 'utf8'); + if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } } + return t; + }; + // A save upload holds a place until it is done: one per player, a few per address and on the whole server. + function upTake(key, ip) { + if (up.has(key)) fail(429, 'a save of yours is still on its way'); + if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true }); + up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1); + return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); }; + } + + async function route(req, res, url) { + const rest = url.pathname.slice(base.length); + const t = now(), ip = ipOf(req), M = req.method; + if (rest === '/sessions') { + if (M !== 'POST') fail(405, 'method not allowed'); + const body = await readJson(req, LIMIT.small); + if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now'); + if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later'); + if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now'); + const preset = PRESETS.includes(body.preset) ? body.preset : null; + if (!preset) fail(400, 'unknown rules preset'); + let code; do code = randCode(); while (codes.has(code)); + const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] }; + const out = newPlayer(s, body, ip); + codes.add(code); cache.set(code, s); + await persist(s); + return send(res, 201, out); + } + const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest); + if (!m) fail(404, 'not found'); + const sub = m[2] || ''; + let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ } + const code = normCode(raw), s = code && load(code); + // A player of this very session, with their token, is never held up by somebody else's wrong codes from the same + // address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either. + const me = s ? player(req, s) : null; + if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later'); + if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later'); + if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); } + if (sub === '/join') { + if (M !== 'POST') fail(405, 'method not allowed'); + const body = await readJson(req, LIMIT.small); + if (!still(s)) fail(404, 'no such session'); + if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true }); + const out = newPlayer(s, body, ip); + await persist(s); + return send(res, 200, out); + } + if (sub === '') { + if (M !== 'GET') fail(405, 'method not allowed'); + authed(me); + return send(res, 200, roster(s)); + } + if (sub === '/card') { + if (M !== 'PUT') fail(405, 'method not allowed'); + const p = authed(me); + if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down'); + const body = await readJson(req, LIMIT.small); + if (!still(s, p)) fail(401, 'unauthorized'); + const c = cleanCard(body.card); + if (!c) fail(400, 'bad card'); + applyCard(s, p, c); + persistSoon(s); + return send(res, 200, roster(s)); + } + if (sub === '/save') { + if (M === 'GET') { + const p = authed(me); + if (!p.sv) fail(404, 'no save yet'); + let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); } + return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data }); + } + if (M !== 'PUT') fail(405, 'method not allowed'); + const p = authed(me), key = code + '.' + p.pid; + const free = upTake(key, ip); + try { + if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down'); + const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS); + if (!still(s, p)) fail(401, 'unauthorized'); + const seq = body.seq, data = body.data; + if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer'); + if (typeof data !== 'string' || !data.length) fail(400, 'no save data'); + if (data.length > MAX_SAVE) fail(413, 'save too large'); + if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save'); + const card = body.card === undefined ? undefined : cleanCard(body.card); + if (card === null) fail(400, 'bad card'); + const old = p.sv; + // Another device of the same player saved a newer game: never overwrite it unless the player says so. + if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at }); + const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq; + // The session says it has this save only once the save is on disk. + await queue(code, () => writeAtomic(saveFile(code, p.pid), data)); + if (!still(s, p)) fail(401, 'unauthorized'); + p.sv = { seq: sq, at, size: data.length }; + if (card) applyCard(s, p, card); + await persist(s); + return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) }); + } finally { free(); } + } + if (sub === '/feed') { + if (M !== 'POST') fail(405, 'method not allowed'); + const p = authed(me), body = await readJson(req, LIMIT.small); + if (!still(s, p)) fail(401, 'unauthorized'); + const text = cleanChat(body.text); + if (!text) fail(400, 'say something'); + if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little'); + event(s, 'chat', p, { text }); + await persist(s); + return send(res, 200, roster(s)); + } + if (sub === '/me') { + if (M !== 'DELETE') fail(405, 'method not allowed'); + const p = authed(me); + s.players = s.players.filter((x) => x !== p); + await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true })); + if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); } + event(s, 'leave', p); + await persist(s); + return send(res, 200, { ok: true }); + } + fail(404, 'not found'); + } + + function handle(req, res) { + let url; + try { url = new URL(req.url, 'http://x'); } catch (e) { return false; } + if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false; + const t0 = Date.now(); + res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); }); + route(req, res, url).catch((e) => { + // A body nobody read (refused before it was needed) is drained, so the client still gets its answer. + if (!req.complete && !req.destroyed) req.resume(); + if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) }); + log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`); + send(res, 500, { error: 'server error' }); + }); + return true; + } + // Everything written before the process goes, sessions waiting for their moment too. + const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); }; + return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size }; +} + +module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE }; diff --git a/scripts/mp-server.js b/scripts/mp-server.js new file mode 100644 index 0000000..64c86f4 --- /dev/null +++ b/scripts/mp-server.js @@ -0,0 +1,117 @@ +#!/usr/bin/env node +// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es +// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build. +// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so +// one process can sit behind a reverse proxy. +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const { createMp } = require('./lib/mp'); + +const HELP = `Series of Tubes multiplayer server + + node scripts/mp-server.js [options] (npm run mp -- [options]) + + --port N port to listen on (default 8090, or $PORT) + --host H address to bind (default 127.0.0.1: put a reverse proxy in front) + --data DIR where sessions and saves are kept (default ./mp-data, created if missing) + --site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build) + --base PATH the API's path (default /api/mp; the page's MP_API must match) + --prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60) + --max-sessions N at most N sessions on this server (default 1000) + --max-players N at most N players per session (default 12, at most 12) + --create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64) + --sessions-per-hour N new sessions on the whole server per hour (default 100) + --trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy) + --verbose log one line per API request (never tokens) + --help this text + +Storage: DIR/.json per session and DIR/..save per player's save. Back up DIR. +API (JSON; every call but create and join needs Authorization: Bearer .): + POST /api/mp/sessions {net:{name,home},preset,title?} start a session + POST /api/mp/sessions/:code/join {net:{name,home}} join one + GET /api/mp/sessions/:code roster, cards and feed + PUT /api/mp/sessions/:code/card {card} your public card + PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one) + GET /api/mp/sessions/:code/save your save + POST /api/mp/sessions/:code/feed {text} a chat line + DELETE /api/mp/sessions/:code/me leave +`; + +const argv = process.argv.slice(2); +if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); } +const die = (m) => { console.error(`error: ${m}`); process.exit(2); }; +const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']); +for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`); +const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; }; +const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; }; + +const PORT = pos('--port', +process.env.PORT || 8090, 65535); +const HOST = opt('--host') || '127.0.0.1'; +const DATA = path.resolve(opt('--data') || 'mp-data'); +const SITE = opt('--site') ? path.resolve(opt('--site')) : null; +const BASE = opt('--base') || '/api/mp'; +// A path, never "//host/..." (which a browser reads as another host). +if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp'); +if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`); +if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`); + +const mp = createMp({ + dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000), + maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100), + trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'), +}); + +const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', + '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', + '.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' }; +// The page, the service worker and the files that change between releases are always checked; the rest may be cached. +const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//; + +// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either. +const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } }; +const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); }; + +// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE. +function serveSite(req, res) { + if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); } + let rel; + try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; } + let file = null; + if (rel !== null && !rel.includes('\0')) { + if (rel.endsWith('/')) rel += 'index.html'; + const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel)); + if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); } + } + const status = file ? 200 : 404; + if (!file) file = path.join(SITE, '404.html'); + if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); } + const r = path.relative(SITE, file).split(path.sep).join('/'); + res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' }); + if (req.method === 'HEAD') return res.end(); + fs.createReadStream(file).on('error', () => res.destroy()).pipe(res); +} + +const server = http.createServer((req, res) => { + try { + if (mp.handle(req, res)) return; + if (SITE) return serveSite(req, res); + res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' }); + res.end('{"error":"not found"}'); + } catch (e) { + // One line, never a stack: whatever went wrong, a request should not be able to fill the log. + console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`); + if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' }); + res.end('{"error":"server error"}'); + } +}); +server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } }); +server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); }); +server.listen(PORT, HOST, () => { + const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`; + console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`); +}); +setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref(); +const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); }; +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); diff --git a/site/i18n/de.js b/site/i18n/de.js index 4e82c6e..94cc2cd 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3085,6 +3085,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.", "modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…", "modals.your_own_subsea_cable_level_n":"Eigenes Seekabel Level {n} oder Tier 1", +"mp.code":"Session-Code", +"mp.copy_link":"Link kopieren", +"mp.door_d":"Eine Welt, die Netze deiner Freunde neben deinem: Code teilen und um Tier 1 wetteifern.", +"mp.err_code":"Ein Session-Code hat sechs Buchstaben und Ziffern, etwa K7Q-2XD.", +"mp.err_full":"Diese Session ist voll: Alle Plätze darin sind vergeben.", +"mp.err_no_session":"Mit diesem Code gibt es keine Session.", +"mp.err_offline":"Der Multiplayer-Server ist gerade nicht erreichbar. Versuch es gleich noch mal.", +"mp.err_refused":"Das hat der Server nicht angenommen. Versuch einen anderen Netznamen.", +"mp.err_server_full":"Der Server nimmt gerade keine neuen Sessions an.", +"mp.err_slow":"Zu viele Versuche von hier. Warte kurz und versuch es noch mal.", +"mp.feed":"Feed", +"mp.feed_empty":"Noch nichts. Sag hallo!", +"mp.feed_join":"{name} ist der Session beigetreten.", +"mp.feed_leave":"{name} hat die Session verlassen.", +"mp.feed_t1":"{name} ist jetzt auch Tier 1.", +"mp.feed_t1first":"{name} ist das erste Tier 1 in dieser Session!", +"mp.feed_t2":"{name} ist jetzt Tier 2.", +"mp.intro":"Alle bauen ihr eigenes Netz in derselben Welt, ab demselben Tag 0, mit denselben Regeln. Rangliste und Feed zeigen, wer vorne liegt.", +"mp.join":"Beitreten", +"mp.join_a_session":"Einer Session beitreten", +"mp.join_note":"Welt und Regeln kommen von dem, der die Session gestartet hat, und deine AS-Nummer bekommst du von der Session.", +"mp.joined":"Du bist Session {code} beigetreten. Öffne die Session, um zu sehen, wer vorne liegt.", +"mp.keep_mine":"Diesen behalten", +"mp.leaderboard":"Rangliste", +"mp.leave":"Session verlassen", +"mp.leave_d":"{name} bleibt auf diesem Gerät als eigenes Spiel. Die Session vergisst es, und sein Spielstand auf dem Server wird gelöscht.", +"mp.leave_q":"Session {code} verlassen?", +"mp.left":"Du hast die Session verlassen. {name} spielt hier allein weiter.", +"mp.link_bad":"Dieser Multiplayer-Link hat nicht funktioniert: Er ist alt, oder dieses Netz hat nie in der Session gespeichert.", +"mp.link_copied":"Link kopiert. Öffne ihn auf deinem anderen Gerät.", +"mp.load_newer":"Neueren Spielstand laden", +"mp.loaded_newer":"Den neueren Spielstand von {name} aus der Session geladen ({date}).", +"mp.loading":"Frage den Server…", +"mp.move_device":"Auf ein anderes Gerät umziehen", +"mp.move_note":"Öffne diesen Link auf deinem anderen Handy oder Computer, um dort mit diesem Netz weiterzumachen. Es zählt, welches Gerät zuletzt speichert.", +"mp.move_warn":"Wer diesen Link hat, kann als du spielen. Behalte ihn für dich.", +"mp.moved_on_elsewhere":"Die Session ist woanders weitergelaufen. Dein Netz wurde seitdem auf einem anderen Gerät gespielt. Lade jenen Spielstand, oder behalte deinen hier und überschreib den auf dem Server.", +"mp.multiplayer":"Multiplayer", +"mp.n_customers":{"one":"{n} Kunde","other":"{n} Kunden"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"hat noch keinen Tag beendet", +"mp.no_newer":"Die Session hat keinen neueren Spielstand von {name}. Dieser bleibt und geht beim nächsten Speichern an den Server.", +"mp.not_in_session":"Dieses Netz ist nicht mehr in seiner Session. Es spielt hier allein weiter.", +"mp.play_with_friends":"Mit Freunden spielen", +"mp.save_unreadable":"Der Spielstand dieses Netzes in der Session war nicht lesbar. Es geht mit dem hier weiter.", +"mp.say":"Sag was", +"mp.send":"Senden", +"mp.server_away":"Der Multiplayer-Server ist weg. Dein Netz spielt hier weiter und holt auf, sobald er zurück ist.", +"mp.session":"Multiplayer-Session", +"mp.session_code":"Session {code}", +"mp.session_live":"Session {code} läuft. Teil den Code: Wer beitritt, baut in derselben Welt.", +"mp.session_title":"Name der Session (optional)", +"mp.share_line":"Komm in meine Series-of-Tubes-Session {code}: {url}", +"mp.share_note":"Freunde treten vom Startbildschirm aus bei: Multiplayer, dann dieser Code.", +"mp.slow_down":"Mach mal langsam: eine Zeile pro Sekunde.", +"mp.start_a_session":"Session starten", +"mp.talking":"Spreche mit dem Server…", +"mp.welcome_device":"{name} ist auf dieses Gerät umgezogen. Willkommen zurück in Session {code}.", +"mp.you":"du", "networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.", "networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.", "networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2b78345..cf40d69 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.", "modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…", "modals.your_own_subsea_cable_level_n":"Tu propio cable submarino nivel {n} o Tier 1", +"mp.code":"Código de la sesión", +"mp.copy_link":"Copiar el enlace", +"mp.door_d":"Un mundo, las redes de tus amigos junto a la tuya: comparte un código y compite por llegar a Tier 1.", +"mp.err_code":"Un código de sesión tiene seis letras y cifras, como K7Q-2XD.", +"mp.err_full":"Esa sesión está llena: no queda ningún hueco libre.", +"mp.err_no_session":"No hay ninguna sesión con ese código.", +"mp.err_offline":"Ahora mismo no se puede contactar con el servidor multijugador. Inténtalo de nuevo en un momento.", +"mp.err_refused":"El servidor no lo aceptó. Prueba con otro nombre de red.", +"mp.err_server_full":"El servidor no acepta sesiones nuevas ahora mismo.", +"mp.err_slow":"Demasiados intentos desde aquí. Espera un poco y vuelve a intentarlo.", +"mp.feed":"Actividad", +"mp.feed_empty":"Nada todavía. ¡Saluda!", +"mp.feed_join":"{name} se unió a la sesión.", +"mp.feed_leave":"{name} dejó la sesión.", +"mp.feed_t1":"{name} también es Tier 1.", +"mp.feed_t1first":"¡{name} es el primer Tier 1 de esta sesión!", +"mp.feed_t2":"{name} llegó a Tier 2.", +"mp.intro":"Cada uno construye su propia red en el mismo mundo, desde el mismo día 0 y con las mismas reglas. La clasificación y la actividad muestran quién va delante.", +"mp.join":"Unirse", +"mp.join_a_session":"Unirse a una sesión", +"mp.join_note":"El mundo y las reglas los pone quien empezó la sesión, y la sesión te da tu número de AS.", +"mp.joined":"Te uniste a la sesión {code}. Abre la sesión para ver quién va delante.", +"mp.keep_mine":"Quedarme con esta", +"mp.leaderboard":"Clasificación", +"mp.leave":"Dejar la sesión", +"mp.leave_d":"{name} se queda en este dispositivo como una partida propia. La sesión se olvida de ella y su partida guardada en el servidor se borra.", +"mp.leave_q":"¿Dejar la sesión {code}?", +"mp.left":"Dejaste la sesión. {name} sigue jugando aquí por su cuenta.", +"mp.link_bad":"Ese enlace multijugador no funcionó: es antiguo, o esa red nunca guardó en la sesión.", +"mp.link_copied":"Enlace copiado. Ábrelo en tu otro dispositivo.", +"mp.load_newer":"Cargar la más reciente", +"mp.loaded_newer":"Se cargó desde la sesión la partida más reciente de {name} ({date}).", +"mp.loading":"Preguntando al servidor…", +"mp.move_device":"Pasar a otro dispositivo", +"mp.move_note":"Abre este enlace en tu otro móvil u ordenador para seguir allí con esta red. Gana el dispositivo que guarde el último.", +"mp.move_warn":"Cualquiera con este enlace puede jugar como tú. Guárdalo para ti.", +"mp.moved_on_elsewhere":"Esta sesión siguió en otro sitio. Desde entonces tu red se jugó en otro dispositivo. Carga esa partida, o quédate con esta y sobrescríbela.", +"mp.multiplayer":"Multijugador", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"aún no ha terminado ningún día", +"mp.no_newer":"La sesión no tiene una partida más reciente de {name}. Se queda esta, que irá al servidor con el próximo guardado.", +"mp.not_in_session":"Esta red ya no está en su sesión. Sigue jugando aquí por su cuenta.", +"mp.play_with_friends":"Jugar con amigos", +"mp.save_unreadable":"No se pudo leer la partida de esta red en la sesión. Se sigue con la de aquí.", +"mp.say":"Di algo", +"mp.send":"Enviar", +"mp.server_away":"El servidor multijugador no está. Tu red sigue jugando aquí y se pone al día cuando vuelva.", +"mp.session":"Sesión multijugador", +"mp.session_code":"Sesión {code}", +"mp.session_live":"La sesión {code} está en marcha. Comparte el código: quien se una construye en el mismo mundo.", +"mp.session_title":"Nombre de la sesión (opcional)", +"mp.share_line":"Únete a mi sesión de Series of Tubes {code}: {url}", +"mp.share_note":"Tus amigos se unen desde la pantalla de inicio: Multijugador y luego este código.", +"mp.slow_down":"Más despacio: una línea por segundo.", +"mp.start_a_session":"Empezar una sesión", +"mp.talking":"Hablando con el servidor…", +"mp.welcome_device":"{name} se pasó a este dispositivo. Bienvenido de nuevo a la sesión {code}.", +"mp.you":"tú", "networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.", "networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index d239d01..f1c7c81 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.", "modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…", "modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin niveau {n} ou Tier 1", +"mp.code":"Code de la session", +"mp.copy_link":"Copier le lien", +"mp.door_d":"Un seul monde, les réseaux de tes amis à côté du tien : partage un code et fonce vers le Tier 1.", +"mp.err_code":"Un code de session a six lettres et chiffres, comme K7Q-2XD.", +"mp.err_full":"Cette session est pleine : toutes les places sont prises.", +"mp.err_no_session":"Aucune session n'a ce code.", +"mp.err_offline":"Le serveur multijoueur est injoignable pour l'instant. Réessaie dans un moment.", +"mp.err_refused":"Le serveur n'a pas accepté. Essaie un autre nom de réseau.", +"mp.err_server_full":"Le serveur n'accepte pas de nouvelles sessions pour l'instant.", +"mp.err_slow":"Trop d'essais depuis ici. Attends un peu et réessaie.", +"mp.feed":"Fil", +"mp.feed_empty":"Rien pour l'instant. Dis bonjour !", +"mp.feed_join":"{name} a rejoint la session.", +"mp.feed_leave":"{name} a quitté la session.", +"mp.feed_t1":"{name} est Tier 1 aussi.", +"mp.feed_t1first":"{name} est le premier Tier 1 de cette session !", +"mp.feed_t2":"{name} est passé Tier 2.", +"mp.intro":"Chacun construit son propre réseau dans le même monde, depuis le même jour 0, avec les mêmes règles. Le classement et le fil montrent qui mène.", +"mp.join":"Rejoindre", +"mp.join_a_session":"Rejoindre une session", +"mp.join_note":"Le monde et les règles viennent de qui a lancé la session, et la session te donne ton numéro d'AS.", +"mp.joined":"Tu as rejoint la session {code}. Ouvre la session pour voir qui mène.", +"mp.keep_mine":"Garder celle-ci", +"mp.leaderboard":"Classement", +"mp.leave":"Quitter la session", +"mp.leave_d":"{name} reste sur cet appareil comme une partie à part entière. La session l'oublie, et sa sauvegarde sur le serveur est supprimée.", +"mp.leave_q":"Quitter la session {code} ?", +"mp.left":"Tu as quitté la session. {name} continue ici en solo.", +"mp.link_bad":"Ce lien multijoueur n'a pas marché : il est trop vieux, ou ce réseau n'a jamais sauvegardé dans la session.", +"mp.link_copied":"Lien copié. Ouvre-le sur ton autre appareil.", +"mp.load_newer":"Charger la plus récente", +"mp.loaded_newer":"Sauvegarde plus récente de {name} chargée depuis la session ({date}).", +"mp.loading":"Je demande au serveur…", +"mp.move_device":"Passer sur un autre appareil", +"mp.move_note":"Ouvre ce lien sur ton autre téléphone ou ordinateur pour continuer ce réseau là-bas. C'est l'appareil qui sauvegarde en dernier qui gagne.", +"mp.move_warn":"Quiconque a ce lien peut jouer à ta place. Garde-le pour toi.", +"mp.moved_on_elsewhere":"Cette session a avancé ailleurs. Ton réseau a été joué sur un autre appareil depuis. Charge cette sauvegarde, ou garde celle-ci et écrase l'autre.", +"mp.multiplayer":"Multijoueur", +"mp.n_customers":{"one":"{n} client","other":"{n} clients"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"mp.no_card":"n'a pas encore fini de journée", +"mp.no_newer":"La session n'a pas de sauvegarde plus récente de {name}. Celle-ci reste, et part au serveur à la prochaine sauvegarde.", +"mp.not_in_session":"Ce réseau n'est plus dans sa session. Il continue ici en solo.", +"mp.play_with_friends":"Jouer avec des amis", +"mp.save_unreadable":"La sauvegarde de ce réseau dans la session est illisible. On continue avec celle d'ici.", +"mp.say":"Dis quelque chose", +"mp.send":"Envoyer", +"mp.server_away":"Le serveur multijoueur est absent. Ton réseau continue ici et se met à jour à son retour.", +"mp.session":"Session multijoueur", +"mp.session_code":"Session {code}", +"mp.session_live":"La session {code} est lancée. Partage le code : qui la rejoint construit dans le même monde.", +"mp.session_title":"Nom de la session (facultatif)", +"mp.share_line":"Rejoins ma session Series of Tubes {code} : {url}", +"mp.share_note":"Tes amis rejoignent depuis l'écran d'accueil : Multijoueur, puis ce code.", +"mp.slow_down":"Doucement : une ligne par seconde.", +"mp.start_a_session":"Lancer une session", +"mp.talking":"Je parle au serveur…", +"mp.welcome_device":"{name} est passé sur cet appareil. Bon retour dans la session {code}.", +"mp.you":"toi", "networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.", "networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.", "networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 49e3639..1db1657 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.", "modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…", "modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino livello {n} o Tier 1", +"mp.code":"Codice della sessione", +"mp.copy_link":"Copia il link", +"mp.door_d":"Un solo mondo, le reti dei tuoi amici accanto alla tua: condividi un codice e corri verso il Tier 1.", +"mp.err_code":"Un codice di sessione ha sei lettere e cifre, tipo K7Q-2XD.", +"mp.err_full":"Quella sessione è piena: tutti i posti sono occupati.", +"mp.err_no_session":"Non c'è nessuna sessione con quel codice.", +"mp.err_offline":"Il server multigiocatore non è raggiungibile adesso. Riprova tra un attimo.", +"mp.err_refused":"Il server non l'ha accettato. Prova un altro nome per la rete.", +"mp.err_server_full":"Il server non accetta nuove sessioni in questo momento.", +"mp.err_slow":"Troppi tentativi da qui. Aspetta un po' e riprova.", +"mp.feed":"Bacheca", +"mp.feed_empty":"Ancora niente. Saluta!", +"mp.feed_join":"{name} è entrato nella sessione.", +"mp.feed_leave":"{name} ha lasciato la sessione.", +"mp.feed_t1":"Anche {name} è Tier 1.", +"mp.feed_t1first":"{name} è il primo Tier 1 di questa sessione!", +"mp.feed_t2":"{name} è arrivato a Tier 2.", +"mp.intro":"Ognuno costruisce la propria rete nello stesso mondo, dallo stesso giorno 0 e con le stesse regole. Classifica e bacheca mostrano chi è in testa.", +"mp.join":"Entra", +"mp.join_a_session":"Entra in una sessione", +"mp.join_note":"Il mondo e le regole li sceglie chi ha avviato la sessione, e il numero di AS te lo dà la sessione.", +"mp.joined":"Sei entrato nella sessione {code}. Apri la sessione per vedere chi è in testa.", +"mp.keep_mine":"Tieni questa", +"mp.leaderboard":"Classifica", +"mp.leave":"Lascia la sessione", +"mp.leave_d":"{name} resta su questo dispositivo come partita a sé. La sessione se ne dimentica e il suo salvataggio sul server viene cancellato.", +"mp.leave_q":"Lasciare la sessione {code}?", +"mp.left":"Hai lasciato la sessione. {name} continua qui per conto suo.", +"mp.link_bad":"Quel link multigiocatore non ha funzionato: è vecchio, oppure quella rete non ha mai salvato nella sessione.", +"mp.link_copied":"Link copiato. Aprilo sull'altro dispositivo.", +"mp.load_newer":"Carica quello più recente", +"mp.loaded_newer":"Caricato dalla sessione il salvataggio più recente di {name} ({date}).", +"mp.loading":"Chiedo al server…", +"mp.move_device":"Passa a un altro dispositivo", +"mp.move_note":"Apri questo link sull'altro telefono o computer per continuare lì con questa rete. Vince il dispositivo che salva per ultimo.", +"mp.move_warn":"Chiunque abbia questo link può giocare al posto tuo. Tienilo per te.", +"mp.moved_on_elsewhere":"Questa sessione è andata avanti altrove. Da allora la tua rete è stata giocata su un altro dispositivo. Carica quel salvataggio, oppure tieni questo e sovrascrivilo.", +"mp.multiplayer":"Multigiocatore", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clienti"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POP"}, +"mp.no_card":"non ha ancora finito un giorno", +"mp.no_newer":"La sessione non ha un salvataggio più recente di {name}. Resta questo, che andrà al server al prossimo salvataggio.", +"mp.not_in_session":"Questa rete non è più nella sua sessione. Continua qui per conto suo.", +"mp.play_with_friends":"Gioca con gli amici", +"mp.save_unreadable":"Non si riesce a leggere il salvataggio di questa rete nella sessione. Si continua con quello qui.", +"mp.say":"Scrivi qualcosa", +"mp.send":"Invia", +"mp.server_away":"Il server multigiocatore non risponde. La tua rete continua a giocare qui e si rimette in pari quando torna.", +"mp.session":"Sessione multigiocatore", +"mp.session_code":"Sessione {code}", +"mp.session_live":"La sessione {code} è partita. Condividi il codice: chi entra costruisce nello stesso mondo.", +"mp.session_title":"Nome della sessione (facoltativo)", +"mp.share_line":"Entra nella mia sessione di Series of Tubes {code}: {url}", +"mp.share_note":"Gli amici entrano dalla schermata iniziale: Multigiocatore, poi questo codice.", +"mp.slow_down":"Piano: una riga al secondo.", +"mp.start_a_session":"Avvia una sessione", +"mp.talking":"Parlo con il server…", +"mp.welcome_device":"{name} è passata su questo dispositivo. Bentornato nella sessione {code}.", +"mp.you":"tu", "networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.", "networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.", "networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9875919..311571c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3083,6 +3083,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.", "modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…", "modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino nível {n} ou Tier 1", +"mp.code":"Código da sessão", +"mp.copy_link":"Copiar o link", +"mp.door_d":"Um só mundo, as redes dos seus amigos ao lado da sua: compartilhe um código e corra para o Tier 1.", +"mp.err_code":"Um código de sessão tem seis letras e números, como K7Q-2XD.", +"mp.err_full":"Essa sessão está cheia: todas as vagas já estão ocupadas.", +"mp.err_no_session":"Não existe sessão com esse código.", +"mp.err_offline":"Não dá para falar com o servidor multijogador agora. Tente de novo daqui a pouco.", +"mp.err_refused":"O servidor não aceitou. Tente outro nome de rede.", +"mp.err_server_full":"O servidor não está aceitando sessões novas agora.", +"mp.err_slow":"Tentativas demais daqui. Espere um pouco e tente de novo.", +"mp.feed":"Mural", +"mp.feed_empty":"Nada ainda. Diga oi!", +"mp.feed_join":"{name} entrou na sessão.", +"mp.feed_leave":"{name} saiu da sessão.", +"mp.feed_t1":"{name} também é Tier 1.", +"mp.feed_t1first":"{name} é o primeiro Tier 1 desta sessão!", +"mp.feed_t2":"{name} chegou a Tier 2.", +"mp.intro":"Cada um constrói a própria rede no mesmo mundo, a partir do mesmo dia 0 e com as mesmas regras. O ranking e o mural mostram quem está na frente.", +"mp.join":"Entrar", +"mp.join_a_session":"Entrar numa sessão", +"mp.join_note":"O mundo e as regras vêm de quem começou a sessão, e a sessão te dá o seu número de AS.", +"mp.joined":"Você entrou na sessão {code}. Abra a sessão para ver quem está na frente.", +"mp.keep_mine":"Ficar com esta", +"mp.leaderboard":"Ranking", +"mp.leave":"Sair da sessão", +"mp.leave_d":"{name} fica neste dispositivo como um jogo próprio. A sessão se esquece dela, e o jogo salvo dela no servidor é apagado.", +"mp.leave_q":"Sair da sessão {code}?", +"mp.left":"Você saiu da sessão. {name} continua aqui por conta própria.", +"mp.link_bad":"Esse link multijogador não funcionou: é antigo, ou essa rede nunca salvou na sessão.", +"mp.link_copied":"Link copiado. Abra no seu outro dispositivo.", +"mp.load_newer":"Carregar o mais recente", +"mp.loaded_newer":"Carregado da sessão o jogo salvo mais recente de {name} ({date}).", +"mp.loading":"Perguntando ao servidor…", +"mp.move_device":"Passar para outro dispositivo", +"mp.move_note":"Abra este link no seu outro celular ou computador para continuar com esta rede lá. Vale o dispositivo que salvar por último.", +"mp.move_warn":"Qualquer um com este link pode jogar como você. Guarde só para você.", +"mp.moved_on_elsewhere":"Esta sessão seguiu em outro lugar. Desde então sua rede foi jogada em outro dispositivo. Carregue aquele jogo salvo, ou fique com este e sobrescreva o outro.", +"mp.multiplayer":"Multijogador", +"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"ainda não terminou nenhum dia", +"mp.no_newer":"A sessão não tem um jogo salvo mais recente de {name}. Este fica e vai para o servidor no próximo salvamento.", +"mp.not_in_session":"Esta rede não está mais na sua sessão. Ela continua jogando aqui por conta própria.", +"mp.play_with_friends":"Jogar com amigos", +"mp.save_unreadable":"Não deu para ler o jogo salvo desta rede na sessão. Seguimos com o daqui.", +"mp.say":"Diga algo", +"mp.send":"Enviar", +"mp.server_away":"O servidor multijogador sumiu. Sua rede continua jogando aqui e se atualiza quando ele voltar.", +"mp.session":"Sessão multijogador", +"mp.session_code":"Sessão {code}", +"mp.session_live":"A sessão {code} está no ar. Compartilhe o código: quem entrar constrói no mesmo mundo.", +"mp.session_title":"Nome da sessão (opcional)", +"mp.share_line":"Entre na minha sessão de Series of Tubes {code}: {url}", +"mp.share_note":"Os amigos entram pela tela inicial: Multijogador, depois este código.", +"mp.slow_down":"Calma: uma linha por segundo.", +"mp.start_a_session":"Começar uma sessão", +"mp.talking":"Falando com o servidor…", +"mp.welcome_device":"{name} passou para este dispositivo. Bem-vindo de volta à sessão {code}.", +"mp.you":"você", "networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.", "networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.", "networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.", diff --git a/site/sw.js b/site/sw.js index 745bafa..4cf8fa4 100644 --- a/site/sw.js +++ b/site/sw.js @@ -15,6 +15,8 @@ self.addEventListener('activate', (e) => { self.addEventListener('fetch', (e) => { const req = e.request; if (req.method !== 'GET') return; + // Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached. + if (req.cache === 'no-store' || req.headers.has('authorization')) return; const url = new URL(req.url); // The update check must always ask the network. if (url.origin === location.origin && url.pathname === '/version.json') return; diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index f4b8ca3..9d4f554 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -600,6 +600,7 @@ const API_WHY={ time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save', slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', + mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session', }; const API_DENY={ speed:'time',phonePlay:'time',phoneSpeed:'time', @@ -607,5 +608,6 @@ const API_DENY={ exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp', install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 30da327..fb43b45 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -62,6 +62,7 @@ const API_STATE_DOC={ core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, + mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, diff --git a/src/game/00-core/20-analytics.js b/src/game/00-core/20-analytics.js index b273f59..327918f 100644 --- a/src/game/00-core/20-analytics.js +++ b/src/game/00-core/20-analytics.js @@ -7,6 +7,9 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[]; // A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases. const RELEASE_STORY=/*__RELEASE_STORY__*/[]; const IS_DEV=APP_VERSION.startsWith('__'); +// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build. +// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests. +const MP_API=/*__MP_API__*/''; // Only report from the real site; previews, localhost and the Claude viewer stay silent. const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'}; (function(){ diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 9b8e154..e6e4956 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -44,6 +44,8 @@ function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal'; + // A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world. + if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;} // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} @@ -55,4 +57,5 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); toast(S.scn?`${esc(S.scn.name)}
${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); // A Normal game asks for its charter first; the tutorial starts once it is signed. - renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}} + renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();} + if(S.mp)mpStartTell();} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index c661e15..3559593 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, - done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null}; } diff --git a/src/game/60-features/89-multiplayer.js b/src/game/60-features/89-multiplayer.js new file mode 100644 index 0000000..50b0c13 --- /dev/null +++ b/src/game/60-features/89-multiplayer.js @@ -0,0 +1,180 @@ +/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) ================= + Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here + runs. Players share a session by a six-character code: each builds their own network in the same world (one seed, + one rules preset), each network's save is also kept on the server (so it can move to another device), and a small + public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing + when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in + S (saves get exported and shared): it lives in this browser's storage, sot-mp::. */ +const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i; +// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive +// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request, +// with room to spare), else the card alone. +const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat']; +/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the + last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */ +const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false}; +const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn()); +const mpShow=c=>c.slice(0,3)+'-'+c.slice(3); +// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32). +function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;} +const mpPath=(m,p)=>'/sessions/'+m.code+(p||''); +const mpTokK=(c,p)=>'sot-mp:'+c+':'+p; +function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;} +function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}} +// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses. +const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64); +function mpSanitize(s){const m=s.mp; + if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;} + s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall', + color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};} +// What the server said when a session started or someone joined: checked before it becomes S.mp. +function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null; + return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};} +/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with + {status, j} on an HTTP error, so callers can tell "no such session" from "server away". */ +function mpReq(method,p,body,o={}){ + if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0})); + const h={};if(body!==undefined)h['content-type']='application/json'; + // o.tok: a token not stored yet (a #mp= link's, until the server takes it). + if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;} + const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0; + let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});} + catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));} + return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}), + e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});} +/* The public card: what the leaderboard shows (and what peering between players will need later). */ +function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){} + const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map(); + for(const l of S.links){if(l.ready>S.day)continue;const k=l.ab[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];}); + const served=R.served||0; + return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64), + ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0), + cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};} +/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own + catalogs. Names and chat stay text: everything that shows them escapes them. */ +function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null; + const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[]; + return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500), + links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]), + ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9), + cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};} +function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null; + const txt=(v,max)=>typeof v==='string'?v.slice(0,max):''; + const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0), + color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)})); + const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''})); + return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};} +// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last. +const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0; +function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);} +/* ---------- staying in step with the server ---------- */ +function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();} +/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once + (429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away": + wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say + the server is away, but never stretches the wait. */ +function mpFail(e,poll){const st=e&&e.status; + if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;} + if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;} + if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);} + if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}} +const mpHid=()=>MP.leaving||document.visibilityState==='hidden'; +// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only +// when something changed since the last push. +function mpSig(t){let h=0x811c9dc5;for(let i=0;i>>0).toString(36)+'.'+t.length;} +// The request's size in bytes (UTF-8), which is what the keepalive limit counts. +function mpBytes(t){let n=t.length;for(let i=0;i127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;} +/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the + player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page + is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in + a puzzle: save() returns before then. */ +function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0; + const hid=mpHid(),now=performance.now(); + // One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush). + if(MP.busy&&!hid)return 0; + const ask=MP.now;MP.now=false; + if(MP.force&&(hid||now>=MP.wait))return 1; + if(S.day===MP.day)return hid||ask?2:0; + return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;} +/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is + picked before the text is made, so the save here and the one on the server carry the same: reopening this device + then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */ +function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st)); + if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}} + if(d)mpPush(txt);return txt;} +/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it + goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */ +function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return; + const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;} + // A push still on its way while the page goes away with a newer save: that one is cut short, this one goes. + if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}} + MP.cur=me;MP.busy=true;MP.last=performance.now(); + const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})}); + // Only a save that went counts as this day's push; a card alone does not. + const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));}; + const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);}; + const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}}; + const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController(); + mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);}; + if(hid){const b=txt.lengthsend('/save',body(data),false); + if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);} +// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request). +if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});} +function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);} +// Pushes this network's save now if it changed since the last push (before a link to another device is handed out). +function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);} +// The server's save text as a game state: unzipped, parsed, and only if it is this very network. +function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save')); + return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));} +function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false; + if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);} +/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead. + Nothing is pushed until the answer is in. */ +function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud(); + // A push of the page going away meanwhile is its own: only an answer to this question frees the next one. + const free=()=>{if(!MP.cur)MP.busy=false;}; + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();}, + e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});} +// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten). +function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);} +function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return; + // A day still routing in the worker finishes first. + if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;} + mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0); + S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()}); + renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();}) + .catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});} +function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));} +/* ---------- a link to the same network on another device ---------- + /#mp=..: the fragment never reaches a server. At boot (before the slots are picked) the save + is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab + too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the + server took it: a wrong or old link never replaces nor deletes the one this browser already has. */ +const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';}; +function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null; + if(!h){go();return;} + try{history.replaceState(null,'',location.pathname+location.search);}catch(e){} + const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();}; + if(!code){fin({bad:1});return;} + const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);}; + // The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again. + const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500; + if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});}; + const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken); + if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});}; + // Opening it fetches the server's save when that one is newer. A link with another token is asked about first. + if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;} + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network'); + delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{ + const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep(); + slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});})) + .then(()=>fin({code}),no);} +// Said once the game is on screen (or the title is). +function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null; + if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad'); + else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index fea6574..e6c94b3 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -110,7 +110,7 @@ function sanitize(s){ three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} - specSanitize(s); + specSanitize(s);mpSanitize(s); pieSanitize(s);pieIncFix(s); if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js index cd59ae5..089794d 100644 --- a/src/game/90-actions/86-specialist.js +++ b/src/game/90-actions/86-specialist.js @@ -8,5 +8,7 @@ Object.assign(ACT,{ toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, seatNo:()=>{S.seatOff=null;after();}, charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal(); - toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}after();}, + toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();} + // A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js). + if(UI.mpLater)mpStartTell();after();}, }); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 1f8ad34..412f0c2 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -23,13 +23,13 @@ Object.assign(ACT,{ importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; // An import is a new network next to the others: the one playing here is saved and kept. - try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, + try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');if(MP_API)mpResume();}, menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`} - +
`);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 098512a..735a4da 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -43,7 +43,7 @@ function bbCost(c){return 15000+CITY[c].P*20;} /* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has: compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */ -const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd']); +const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd','mp']); function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);} function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;} function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();} diff --git a/src/game/90-actions/91-slots.js b/src/game/90-actions/91-slots.js index 86ca1d8..060ad56 100644 --- a/src/game/90-actions/91-slots.js +++ b/src/game/90-actions/91-slots.js @@ -31,4 +31,4 @@ function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;U // Back from the title (or a puzzle) into a loaded network. function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} - closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');} + closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();} diff --git a/src/game/90-actions/92-multiplayer.js b/src/game/90-actions/92-multiplayer.js new file mode 100644 index 0000000..5515551 --- /dev/null +++ b/src/game/90-actions/92-multiplayer.js @@ -0,0 +1,34 @@ +// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build +// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js). +Object.assign(ACT,{ + mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml()); + const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;}); + const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});}, + mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();}, + mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle'); + mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});}, + mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;} + const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra'; + mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});}, + mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}}); + // About to move to another device: the server gets what this one has first, so the link opens it as it is now. + const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();}, + mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));}, + // The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast. + mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}}; + try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}}, + mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp; + mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});}, + mpLeaveAsk:()=>{if(!mpIs())return;openModal(`

${tr('mp.leave_q',{code:mpShow(S.mp.code)})}

${tr('mp.leave_d',{name:esc(S.name)})}

${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}
`);}, + // Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too). + mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset(); + closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');}; + mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});}, + // Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded: + // "Load the newer save" never takes the player back to an older one. + mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1); + mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;} + m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);}, + // Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day). + mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();}, +}); diff --git a/src/game/91-save.js b/src/game/91-save.js index faea37c..a7a45d6 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -14,7 +14,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; UI.lastSave=performance.now(); // Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do. if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return; - const txt=JSON.stringify(packSave(st)); + // A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js). + const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st)); let tier=null;if(st===S)try{tier=tierLabel();}catch(e){} const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)}; if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));} diff --git a/src/game/91-slots.js b/src/game/91-slots.js index c647112..8bcb1e1 100644 --- a/src/game/91-slots.js +++ b/src/game/91-slots.js @@ -22,8 +22,11 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null; tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz, // A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is // usually in the game, and the save itself is fine once it is fixed. - ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false})};} -const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier}); + ...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}), + // A network in a multiplayer session: ., so a link from another device finds it again. + ...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};} +// mp is always there (null outside a session), so a network that left its session loses its badge in the list. +const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null}); function slotKeys(){const out=[];try{for(let i=0;i({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}} function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id); gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return; - if(m)Object.assign(x,slotClean({...x,...m}));else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} + if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}} const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at); // ---------- one writer per slot ---------- // The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a @@ -88,7 +91,7 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false; if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;} if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq); - const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})); + const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c); slotIdxPut(list);return true;} function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}} // ---------- opening, leaving, losing ---------- diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index f05d9f8..b3052f9 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -6,6 +6,7 @@ function renderHUD(){ // A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud). {const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();} $('muteBtn').style.opacity=UI.muted?.4:1; + if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle if(!S)return; if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;} {const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 54b3867..e71afef 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -22,7 +22,7 @@ function showTitle(){ ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} ${many?slotsHtml():''}
- ${doorsHtml()} + ${doorsHtml()}${MP_API?mpDoorHtml():''} ${homePick()}

${homeWhat()}

${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); @@ -44,8 +44,10 @@ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; // The chosen preset in one line: its joke, then what actually changes. const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; +// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js). +const presetBtns=pr=>`
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

`; function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; return `
${DOORS.map(([k,i,n,d])=>``).join('')}
-
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

+
${presetBtns(pr)}
${Object.entries(CHAOS).map(([k,C])=>``).join('')}

🔒 ${tr('title.rules_are_picked_once_and_locked')}

`;} diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js index 047c54d..690d2e3 100644 --- a/src/game/95-modals/45-slots.js +++ b/src/game/95-modals/45-slots.js @@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'? // The network to continue: the most recent one that is not open in another window (or damaged). function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;} function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete'); - const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier); + const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6))); return bits.filter(Boolean).join(' · ');} function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network')); const tag=busy?`${tr('slots.open_in_another_window')}`:top?`▶ ${tr('slots.continue')}`:''; diff --git a/src/game/95-modals/48-multiplayer.js b/src/game/95-modals/48-multiplayer.js new file mode 100644 index 0000000..77767c9 --- /dev/null +++ b/src/game/95-modals/48-multiplayer.js @@ -0,0 +1,73 @@ +/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session + panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn + when the build stamped MP_API. Everything another player wrote is escaped here. */ +const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')}; +const mpDoorHtml=()=>`
`; +function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'; + return `
🌐 ${tr('mp.multiplayer')}

${tr('mp.play_with_friends')}

+

${tr('mp.intro')}

+ + ${homePick()}

${homeWhat()}

+

${tr('mp.start_a_session')}

${presetBtns(pr)} + +
${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}
+

${tr('mp.join_a_session')}

+
${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}
+

${tr('mp.join_note')}

+ +
${btn(tr('common.back'),'mpBack',{},'ghost')}
`;} +function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;} +function mpErr(e){const st=e&&e.status;sfx('err'); + toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');} +const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;}; +// The server said yes: the token goes to this browser's storage, the rest into a new game. +function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;} + mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});} +// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the +// leaderboard at once, and a link to another device works from the start. +function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};} +// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code +// waits until it is signed (ACT.charter), or its buttons could not be pressed. +function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null; + const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}]; + toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);} +/* ---------- the session panel ---------- */ +function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `

${tr('mp.not_in_session')}

`; + // Another device moved on: the toast with the choice is long gone, the choice stays here until it is made. + const st=MP.stale?`

${tr('mp.moved_on_elsewhere')}

${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}
`:''; + if(st)return st;if(!r)return `

${tr('mp.loading')}

`;const me=S&&S.mp&&S.mp.pid; + return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me; + const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`; + return `
${i+1}
${esc(p.name)}${mine?` ${tr('mp.you')}`:''}
${meta}
${p.seen?slotAgo(p.seen):''}
`;}).join('');} +function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `

${tr('mp.feed_empty')}

`; + const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';}; + return f.map(x=>{const who=`${esc(x.name)}`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who}); + return `
${t}${x.at?slotAgo(x.at):''}
`;}).join('');} +function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m); + return `
🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}

${m.title?esc(m.title):tr('mp.session_code',{code})}

+
${tr('mp.code')}${code}
${btn(tr('common.share'),'mpShare',{},'pink')}
+

${tr('mp.share_note')}

+

${tr('mp.leaderboard')}

${mpBoardHtml()}
+

${tr('mp.feed')}

${btn(tr('mp.send'),'mpChat',{},'')}
${mpFeedHtml()}
+ ${link?`
${tr('mp.move_device')}

${tr('mp.move_note')}

${tr('mp.move_warn')}

${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}
`:''} +
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}
`;} +// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays. +function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();} +// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone. +function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);} +function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);} +/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session): + there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu + button instead. Made the first time a session network is on screen. */ +function mpHud(){let c=$('hMp');const on=mpIs(); + if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen'; + c.innerHTML='';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling); + const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);} + const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return; + const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—'; + c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color; + $('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';} +// Share text: the phone's share sheet, or the clipboard. +function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'); + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;} + try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index c10b794..88644c8 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','mpDoor','mpBack','mpStart','mpJoin'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 41f70a8..5a61189 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -43,7 +43,7 @@ function boot(data){ if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();} else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv; let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} - if(okSave){slotIn(UI.slot,stamp);UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); + if(okSave){slotIn(UI.slot,stamp);if(MP_API)mpResume();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1); if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});} @@ -51,8 +51,9 @@ function boot(data){ // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}} - renderHUD();renderLeft(); + renderHUD();renderLeft();if(MP_API)mpBootTell(); window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } -if(NOC.win)nocWinBoot();else if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); +// A #mp= link (a multiplayer network moving to this device) is read first: it picks the slot slotBoot opens. +if(NOC.win)nocWinBoot();else if(!RW_IN)mpBoot(()=>slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}))); diff --git a/src/i18n/en.js b/src/i18n/en.js index 3a0dd38..ef47c7b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3084,6 +3084,65 @@ "modal_and_names.the_real_thing_follow_a_packet":"The real thing: follow a packet from Wi-Fi to undersea fiber.", "modals.lay_your_own_subsea_cable":"Lay your own subsea cable…", "modals.your_own_subsea_cable_level_n":"Your own subsea cable level {n} or Tier 1", +"mp.code":"Session code", +"mp.copy_link":"Copy the link", +"mp.door_d":"One world, your friends' networks next to yours: share a code and race to Tier 1.", +"mp.err_code":"A session code has six letters and digits, like K7Q-2XD.", +"mp.err_full":"That session is full: every seat in it is taken.", +"mp.err_no_session":"There is no session with that code.", +"mp.err_offline":"The multiplayer server cannot be reached right now. Try again in a moment.", +"mp.err_refused":"The server did not take that. Try another network name.", +"mp.err_server_full":"The server is not taking new sessions right now.", +"mp.err_slow":"Too many tries from here. Wait a little and try again.", +"mp.feed":"Feed", +"mp.feed_empty":"Nothing yet. Say hello!", +"mp.feed_join":"{name} joined the session.", +"mp.feed_leave":"{name} left the session.", +"mp.feed_t1":"{name} is Tier 1 too.", +"mp.feed_t1first":"{name} is the first Tier 1 in this session!", +"mp.feed_t2":"{name} made Tier 2.", +"mp.intro":"Everyone builds their own network in the same world, from the same day 0, under the same rules. The leaderboard and the feed show who is ahead.", +"mp.join":"Join", +"mp.join_a_session":"Join a session", +"mp.join_note":"The world and the rules come from whoever started the session, and the session hands you your AS number.", +"mp.joined":"You joined session {code}. Open the session to see who is ahead.", +"mp.keep_mine":"Keep this one", +"mp.leaderboard":"Leaderboard", +"mp.leave":"Leave the session", +"mp.leave_d":"{name} stays on this device as a game of its own. The session forgets it, and its save on the server is deleted.", +"mp.leave_q":"Leave session {code}?", +"mp.left":"You left the session. {name} plays on here on its own.", +"mp.link_bad":"That multiplayer link did not work: it is old, or that network never saved to the session.", +"mp.link_copied":"Link copied. Open it on your other device.", +"mp.load_newer":"Load the newer save", +"mp.loaded_newer":"Loaded the newer save of {name} from the session ({date}).", +"mp.loading":"Asking the server…", +"mp.move_device":"Move to another device", +"mp.move_note":"Open this link on your other phone or computer to carry on with this network there. Whichever device saves last wins.", +"mp.move_warn":"Anyone with this link can play as you. Keep it to yourself.", +"mp.moved_on_elsewhere":"This session moved on elsewhere. Your network was played on another device since. Load that save, or keep this one and overwrite it.", +"mp.multiplayer":"Multiplayer", +"mp.n_customers":{"one":"{n} customer","other":"{n} customers"}, +"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"}, +"mp.no_card":"has not finished a day yet", +"mp.no_newer":"The session has no newer save of {name}. This one stays, and goes to the server with the next save.", +"mp.not_in_session":"This network is no longer in its session. It keeps playing here on its own.", +"mp.play_with_friends":"Play with friends", +"mp.save_unreadable":"The session's save of this network could not be read. Playing on with the one here.", +"mp.say":"Say something", +"mp.send":"Send", +"mp.server_away":"The multiplayer server is away. Your network keeps playing here and catches up when it is back.", +"mp.session":"Multiplayer session", +"mp.session_code":"Session {code}", +"mp.session_live":"Session {code} is live. Share the code: whoever joins builds in the same world.", +"mp.session_title":"Session name (optional)", +"mp.share_line":"Join my Series of Tubes session {code}: {url}", +"mp.share_note":"Friends join from the title screen: Multiplayer, then this code.", +"mp.slow_down":"Slow down a little: one line a second.", +"mp.start_a_session":"Start a session", +"mp.talking":"Talking to the server…", +"mp.welcome_device":"{name} moved to this device. Welcome back to session {code}.", +"mp.you":"you", "networks.a_mobile_network_named_after_the":"A mobile network named after the sound of a toast. Cheers to every 5G tower.", "networks.a_spanish_carrier_starring_in_every":"A Spanish carrier starring in every Latin American market, at least until it sells the next one.", "networks.a_tiny_telco_in_a_country":"A tiny telco in a country where the world’s cables come ashore. Prices to match.", diff --git a/src/styles/41-multiplayer.css b/src/styles/41-multiplayer.css new file mode 100644 index 0000000..ccd50e6 --- /dev/null +++ b/src/styles/41-multiplayer.css @@ -0,0 +1,36 @@ +/* Multiplayer (only in a copy built with MP_API): the title row, the start/join sheet, the session panel, the HUD chip. */ +.mpdoor-row{margin-top:8px}.mpdoor{width:100%;background:var(--soft)} +.mpbox{border:2px dashed var(--line);border-radius:14px;padding:4px 12px 10px;margin-top:12px} +.mpbox h3,.mp-panel h3{font-family:var(--display);font-size:18px;margin:10px 0 4px} +.mpjoin,.mpchat{display:flex;gap:8px;align-items:center} +.mpjoin input.t,.mpchat input.t{flex:1 1 auto;min-width:0;width:auto} +#mpCode{text-transform:uppercase;letter-spacing:.12em;font-size:18px} +.mpchat input.t{font-size:16px;padding:6px 10px} +.mpcode{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:14px;padding:8px 12px;background:var(--soft);margin-top:10px} +.mpcode small{display:block;font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)} +.mpcode b{font-family:var(--display);font-size:28px;letter-spacing:.08em;line-height:1.1} +.mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px} +.mpfeed{max-height:220px;overflow:auto;margin-top:6px} +.mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0} +.mprow.me{border-color:var(--me);background:#FFF2F8} +.mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere} +.mprow b{font-family:var(--display);font-size:15px} +.mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto} +.mpdot{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);flex:0 0 auto} +.mpseen,.mpf small{color:var(--ink2);font-size:11px;white-space:nowrap;flex:0 0 auto} +.mpf{display:flex;align-items:baseline;gap:8px;font-size:13px;line-height:1.35} +.mpf .mpdot{width:9px;height:9px;border-width:1.5px} +.mpf.t1first{font-weight:800} +.mpmove{margin-top:12px}.mpmove summary{cursor:pointer;font-weight:800} +.mpmove input.t{font-size:12px;font-family:monospace;padding:6px 8px} +#hud .mpchip{border-width:3px} +/* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step: + where you stand shows as a badge on the menu button, which also opens the session. */ +#hud .menubtn{position:relative} +.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--ink);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} +#hud.fit3 .mpchip{display:none !important} +#hud.fit3 .mpbadge{display:block} +@media (max-width:760px){ + .mpcode b{font-size:24px} + .mpbadge{display:block} +} diff --git a/tests/harness.js b/tests/harness.js index a9f897a..2be9e95 100644 --- a/tests/harness.js +++ b/tests/harness.js @@ -14,8 +14,10 @@ const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html); // opts.file: a built or older page to load instead (the perf bench, the release build test). // opts.agent: the development page, with src/agent/. +// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start. function load(opts = {}) { - const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); + let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent); + if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp)); const errors = []; const vc = new VirtualConsole(); vc.on('jsdomError', (e) => { @@ -38,6 +40,7 @@ function load(opts = {}) { // channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload. if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts); for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v); + if (opts.fetch) window.fetch = opts.fetch; if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage }); // A non-English game: jsdom does not fetch the dictionary script, so register it up front. // (opts.dir: the folder the dictionary comes from, e.g. a build's _site/i18n.) diff --git a/tests/mp-server.test.js b/tests/mp-server.test.js new file mode 100644 index 0000000..7fbe90b --- /dev/null +++ b/tests/mp-server.test.js @@ -0,0 +1,450 @@ +// The multiplayer server (scripts/mp-server.js, docs/MULTIPLAYER.md), run for real on a free port with its own data +// folder: sessions, joining, who may read and write what, saves that never overwrite a newer one, cards cleaned of +// junk, limits, leaving, data that survives a restart, and the built site served without escaping its folder. The +// tests of what happens while a request is still on its way run the API in this process (inproc), where a request can +// be held half-sent and the limits made small. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const http = require('node:http'); +const { spawn, execFileSync } = require('node:child_process'); +const { until, freePort, kill } = require('./net'); +const { createMp, cleanCard, addrKey, limiter } = require('../scripts/lib/mp'); + +const root = path.join(__dirname, '..'); +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-')); +const children = new Set(); +test.after(async () => { for (const c of children) await kill(c); fs.rmSync(tmp, { recursive: true, force: true }); }); + +async function start(opts = {}) { + const port = await freePort(), data = opts.data || fs.mkdtempSync(path.join(tmp, 'data-')); + const args = ['scripts/mp-server.js', '--port', String(port), '--data', data, '--create-per-hour', '50', ...(opts.args || [])]; + const child = spawn(process.execPath, args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); + children.add(child); + let out = ''; + child.stdout.on('data', (b) => { out += b; }); + child.stderr.on('data', (b) => { out += b; }); + assert.ok(await until(() => /multiplayer: http/.test(out) || child.exitCode !== null), 'the server starts'); + assert.equal(child.exitCode, null, out); + const url = `http://127.0.0.1:${port}`; + const api = async (method, p, body, auth, headers = {}) => { + const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body) }); + const t = await r.text(); + let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } + return { status: r.status, json: j, type: r.headers.get('content-type'), text: t }; + }; + return { child, port, url, data, api, out: () => out, stop: async () => { await kill(child); children.delete(child); } }; +} +// A raw request, so paths reach the server exactly as written (fetch would tidy up ".."). +const raw = (port, p) => new Promise((res, rej) => { + const r = http.request({ host: '127.0.0.1', port, path: p, method: 'GET' }, (x) => { let b = ''; x.on('data', (c) => { b += c; }); x.on('end', () => res({ status: x.statusCode, body: b, type: x.headers['content-type'] })); }); + r.on('error', rej); r.end(); +}); +const make = (api, name = 'Packet Pals', home = 'fra', extra = {}) => api('POST', '/sessions', { net: { name, home }, preset: 'oncall', ...extra }); +// The API in this process, with its own options (small limits), on a free port. +async function inproc(t, opts = {}) { + const dir = opts.dir || fs.mkdtempSync(path.join(tmp, 'data-')); + const mp = createMp({ dir, log: () => {}, ...opts }); + const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + t.after(() => new Promise((r) => { server.closeAllConnections(); server.close(r); })); + const port = server.address().port, url = `http://127.0.0.1:${port}`; + const api = async (method, p, body, auth, headers = {}) => { + const r = await fetch(url + '/api/mp' + p, { method, headers: { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers }, body: body === undefined ? undefined : JSON.stringify(body) }); + const t = await r.text(); + let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } + return { status: r.status, json: j }; + }; + return { mp, dir, port, api }; +} +// A request sent all but the last byte of its body: it stays on its way until release(). +function held(port, method, p, body, auth, headers = {}) { + const b = Buffer.from(JSON.stringify(body)); + let r; + const done = new Promise((res, rej) => { + r = http.request({ host: '127.0.0.1', port, path: '/api/mp' + p, method, headers: { 'content-type': 'application/json', 'content-length': b.length, ...(auth ? { authorization: `Bearer ${auth.pid}.${auth.token}` } : {}), ...headers } }, + (x) => { let t = ''; x.on('data', (c) => { t += c; }); x.on('end', () => { let j = null; try { j = JSON.parse(t); } catch (e) { /* not JSON */ } res({ status: x.statusCode, json: j }); }); }); + r.on('error', rej); + r.write(b.subarray(0, b.length - 1)); + }); + return { done, release: () => { r.end(b.subarray(b.length - 1)); return done; } }; +} +const joinAs = (api, code, name, headers) => api('POST', `/sessions/${code}/join`, { net: { name, home: 'ams' } }, null, headers); + +test('mp server: --help documents it; --base is a path on this server, never another host', () => { + const t = execFileSync(process.execPath, ['scripts/mp-server.js', '--help'], { cwd: root, encoding: 'utf8' }); + for (const k of ['--port', '--host', '--data', '--site', '--prune-days', '--trust-proxy', '--sessions-per-hour', 'Authorization: Bearer', '/api/mp/sessions/:code/save']) assert.ok(t.includes(k), k); + for (const b of ['//evil-host/mp', '//api', 'api/mp', '/api/mp/']) assert.throws(() => execFileSync(process.execPath, ['scripts/mp-server.js', '--base', b, '--port', '1'], { cwd: root, stdio: 'pipe' }), /--base must be a path/, b); +}); + +test('mp server: start, join, roster; names cleaned; codes typed any way', async () => { + const s = await start(); + const a = await make(s.api, ' & "Co" ', 'fra', { preset: 'bgp', title: 'Friday night', avoid: [200000, 200001] }); + assert.equal(a.status, 201); + assert.match(a.json.code, /^[0-9A-HJKMNP-TV-Z]{6}$/); + assert.match(a.json.pid, /^[a-z0-9]{8}$/); + assert.match(a.json.token, /^[0-9a-f]{64}$/); + assert.ok(Number.isInteger(a.json.seed) && a.json.seed >= -(2 ** 31) && a.json.seed < 2 ** 31); + assert.ok(a.json.asn >= 200000 && a.json.asn <= 214999); + assert.equal(a.json.preset, 'bgp'); + assert.equal(a.json.title, 'Friday bnight/b'); + // Joined by the code as a person types it: lower case, with a dash. + const typed = (a.json.code.slice(0, 3) + '-' + a.json.code.slice(3)).toLowerCase(); + const b = await s.api('POST', `/sessions/${typed}/join`, { net: { name: 'Bee', home: 'nyc' }, preset: 'soft' }); + assert.equal(b.status, 200); + assert.equal(b.json.code, a.json.code); + assert.equal(b.json.seed, a.json.seed, 'one world: the same seed'); + assert.equal(b.json.preset, 'bgp', 'and the creator\'s rules'); + assert.notEqual(b.json.asn, a.json.asn); + assert.notEqual(b.json.color, a.json.color); + const r = await s.api('GET', `/sessions/${a.json.code}`, undefined, a.json); + assert.equal(r.status, 200); + assert.equal(r.type, 'application/json; charset=utf-8'); + assert.deepEqual(r.json.players.map((p) => p.name), ['img src=x onerror=alert(1) Co', 'Bee']); + assert.ok(r.json.players.every((p) => !('th' in p) && !('token' in p) && !('sv' in p)), 'no secrets in the roster'); + assert.deepEqual(r.json.feed.map((f) => f.k), ['join', 'join']); + assert.ok(!JSON.stringify(r.json).includes(a.json.token)); + // Junk names and homes are refused. + for (const net of [{ name: ' ', home: 'fra' }, { name: '<>&', home: 'fra' }, { name: 'ok', home: '../x' }, { name: 'ok' }]) assert.equal((await s.api('POST', '/sessions', { net, preset: 'oncall' })).status, 400, JSON.stringify(net)); + assert.equal((await s.api('POST', '/sessions', { net: { name: 'x', home: 'fra' }, preset: 'sandbox' })).status, 400, 'only the Normal presets'); + assert.equal((await s.api('POST', '/sessions', { net: { name: 'x'.repeat(80), home: 'fra' }, preset: 'soft' })).json.pid.length, 8); + await s.stop(); +}); + +test('mp server: every call but start and join needs the player\'s token', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const p = `/sessions/${a.code}`; + assert.equal((await s.api('GET', p)).status, 401); + assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: b.token })).status, 401, 'someone else\'s token'); + assert.equal((await s.api('GET', p, undefined, { pid: a.pid, token: '0'.repeat(64) })).status, 401); + assert.equal((await s.api('GET', p, undefined, { pid: 'zzzzzzzz', token: a.token })).status, 401); + assert.equal((await s.api('GET', p, undefined, null, { authorization: 'Bearer nonsense' })).status, 401); + assert.equal((await s.api('PUT', p + '/card', { card: {} })).status, 401); + assert.equal((await s.api('PUT', p + '/save', { seq: 1, at: 1, data: '{}' })).status, 401); + assert.equal((await s.api('GET', p + '/save')).status, 401); + assert.equal((await s.api('POST', p + '/feed', { text: 'hi' })).status, 401); + assert.equal((await s.api('DELETE', p + '/me')).status, 401); + assert.equal((await s.api('GET', p, undefined, a)).status, 200); + assert.equal((await s.api('GET', '/sessions/ZZZZZZ', undefined, a)).status, 404); + assert.equal((await s.api('DELETE', p, undefined, a)).status, 405); + assert.equal((await s.api('GET', '/nope')).status, 404); + await s.stop(); +}); + +test('mp server: a save never overwrites a newer one unless forced', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const p = `/sessions/${a.code}/save`; + assert.equal((await s.api('GET', p, undefined, a)).status, 404, 'nothing saved yet'); + const s1 = await s.api('PUT', p, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }, a); + assert.equal(s1.status, 200); + assert.equal(s1.json.seq, 1); + assert.equal(s1.json.roster.players.length, 2, 'the roster rides along'); + assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 1, at: 1000, data: '{"v":1,"day":3}' }); + assert.equal((await s.api('GET', p, undefined, b)).status, 404, 'only your own save'); + const stale = await s.api('PUT', p, { seq: 1, at: 2000, data: '{"v":1,"day":1}' }, a); + assert.equal(stale.status, 409); + assert.equal(stale.json.seq, 1); + assert.equal((await s.api('PUT', p, { seq: 0, at: 1, data: '{}' }, a)).status, 400); + assert.equal((await s.api('PUT', p, { seq: 1.5, at: 1, data: '{}' }, a)).status, 400); + assert.equal((await s.api('PUT', p, { seq: 9, at: 1, data: 'not a save' }, a)).status, 400); + const g = await s.api('PUT', p, { seq: 2, at: 3000, data: 'gz:H4sIAAAA' }, a); + assert.equal(g.json.seq, 2, 'compressed saves are kept as they are'); + const f = await s.api('PUT', p, { seq: 1, at: 4000, data: '{"v":1,"day":9}', force: true }, a); + assert.equal(f.status, 200); + assert.equal(f.json.seq, 3, 'forced: it becomes the newest'); + assert.deepEqual((await s.api('GET', p, undefined, a)).json, { seq: 3, at: 4000, data: '{"v":1,"day":9}' }); + await s.stop(); +}); + +test('mp server: cards keep only what the leaderboard needs, and tell the feed about Tier 1', async () => { + const s = await start(); + const a = (await make(s.api)).json, b = (await s.api('POST', `/sessions/${a.code}/join`, { net: { name: 'Bee', home: 'nyc' } })).json; + const junk = { day: 1e12, name: 'Evil', asn: 1, tier: 't0', t1: 'yes', lvl: -5, pops: ['fra', 'fra', '', text: '', at: 1 }, { k: 'join', pid: 'eeeeeeee', name: 'x', at: 1 }, { k: 'evil', name: 'x', at: 1 }]; + f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me(), evil, { pid: '../../x', name: 'bad' }], feed) }]]; + ev('ACT.mpOpen({})'); + assert.ok(await until(() => ev("document.querySelectorAll('#mpBoard .mprow').length===2"))); + for (const id of ['mpBoard', 'mpFeed']) { + const el = doc.getElementById(id); + assert.equal(el.querySelector('img,script,i:not(.mpdot)'), null, `${id}: no markup from the server`); + } + assert.ok(doc.getElementById('mpBoard').textContent.includes(''), 'the name shows as text'); + assert.ok(doc.getElementById('mpFeed').textContent.includes(' /^background: ?#[0-9a-f]{6};?$/i.test(d.getAttribute('style'))), 'colours are colours'); + assert.match(doc.querySelector('#mpBoard .mprow').textContent, /Tier 1/, 'Tier 1 leads the board'); + assert.match(doc.querySelector('#mpBoard .mprow').textContent, /2 POPs/, 'with only real cities'); + assert.equal(ev('window.__xss'), undefined); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: the session panel and the chip on a phone; chat, leaving', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = await started({ fetch: f, load: { gzip: false } }); + const doc = dom.window.document; + ev('window.innerWidth=360;window.innerHeight=740;renderAll()'); + assert.equal(ev('isPhone()'), true); + const chip = doc.getElementById('hMp'); + assert.ok(chip && !chip.hidden, 'the chip is there'); + assert.match(chip.textContent, /K7Q-2XD/); + // A phone's top bar has no room for it (cash and the date would be cut): hide-sm. Where you stand is a badge on the + // menu button instead, there and on a tablet whose top bar still wraps at fitHud's last step (no layout in jsdom). + assert.ok(chip.classList.contains('hide-sm'), 'not in a phone\'s top bar'); + const badge = doc.querySelector('#hud .menubtn #hMpB'); + assert.ok(badge && !badge.hidden, 'a badge on the menu button'); + const css = [...doc.querySelectorAll('style')].map((x) => x.textContent).join(''); + assert.match(css, /#hud\.fit3 \.mpchip\{display:none !important\}/, 'a tablet drops the chip before the top bar wraps'); + assert.match(css, /\.mpbadge\{display:block\}/); + ev('ACT.menu({})'); + assert.ok(doc.querySelector('#modalCard .mtile[data-act=mpOpen]'), 'the menu has the session'); + f.routes = [[/^GET \/api\/mp\/sessions\/K7Q2XD$/, { status: 200, json: roster([me({ day: 1, tier: 't2', t1: false, pops: ['fra'], links: [], ix: [], transit: [], ppol: 'open', reach: 0.5, peak: 3, served: 2, cust: 1, rev: 1, cashB: 5, score: 1 }), { ...me(null), pid: 'bbbbbbbb', name: 'Bee', color: '#ff4f9a' }], [{ k: 'join', pid: PID, name: 'Packet Pals', at: Date.now() }]) }], + [/feed$/, (c) => c.body.text === 'fast' ? { status: 429, json: { error: 'slow' } } : { status: 200, json: roster([me()], [{ k: 'chat', pid: PID, name: 'Packet Pals', text: c.body.text, at: Date.now() }]) }], + [/^DELETE .*\/me$/, { status: 200, json: { ok: true } }]]; + doc.querySelector('#modalCard .mtile[data-act=mpOpen]').click(); + assert.ok(await until(() => doc.querySelectorAll('#mpBoard .mprow').length === 2)); + const card = doc.getElementById('modalCard'); + assert.ok(card.querySelector('.btns.cta'), 'the main buttons stay in reach (sticky on a phone)'); + assert.equal(card.querySelector('.mpcode b').textContent, 'K7Q-2XD'); + assert.ok(card.querySelector('details.mpmove #mpLink'), 'the link to another device, folded away'); + assert.match(card.querySelector('#mpLink').value, /#mp=K7Q2XD\.abcd1234\.[0-9a-f]{64}$/); + assert.match(doc.querySelector('#mpBoard .mprow.me').textContent, /you/); + assert.match(doc.getElementById('mpBoard').textContent, /has not finished a day yet/); + assert.equal(ev("$('hMpRank').textContent"), '🌐 #1/2'); + assert.equal(badge.textContent, '#1'); + // Chat. + ev("document.getElementById('mpSay').value='hello there';ACT.mpChat({})"); + assert.ok(await until(() => /hello there/.test(doc.getElementById('mpFeed').textContent))); + assert.equal(doc.getElementById('mpSay').value, '', 'the line went'); + ev("$('toasts').innerHTML='';document.getElementById('mpSay').value='fast';ACT.mpChat({})"); + assert.ok(await until(() => /Slow down/.test(ev("$('toasts').textContent")))); + // Landscape on a phone: still a phone layout. + ev('window.innerWidth=740;window.innerHeight=360;renderAll()'); + assert.ok(doc.getElementById('mpPanel')); + // Leaving: the network stays, the session and the token go. + ev('ACT.mpLeaveAsk({})'); + assert.match(doc.getElementById('modalCard').textContent, /Leave session K7Q-2XD\?/); + ev('ACT.mpLeave({})'); + assert.ok(await until(() => ev('S.mp===null'))); + assert.equal(ev(`localStorage.getItem('sot-mp:${CODE}:${PID}')`), null); + assert.equal(doc.getElementById('hMp').hidden, true); + assert.equal(badge.hidden, true); + assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp, null, 'saved without it'); + assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'and the list of networks forgets the session too'); + assert.doesNotMatch(ev('slotListHtml()'), /K7Q-2XD/); + ev('dayTick();save(true)'); + assert.equal(ev('slotIdx().find(e=>e.id===UI.slot).mp'), undefined, 'for good'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: the server away: the game plays on, backs off, says so once', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = await started({ fetch: f }); + f.routes = [[/./, new Error('offline')]]; + ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===1'))); + assert.ok(ev('MP.wait>performance.now()'), 'it waits before the next try'); + assert.match(ev("$('toasts').textContent"), /server is away/); + ev('dayTick();MP.last-=16000;save(true)'); + assert.equal(f.saves().length, 2, 'not while it waits'); + ev("$('toasts').innerHTML='';MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===2'))); + assert.equal(ev("$('toasts').textContent"), '', 'told once'); + // Too many at once (429, or the server's own 503 "busy") is not "away": a short wait, quietly, and the back-off stays + // where it was. Behind a proxy without --trust-proxy every player is one address, so this happens to honest players. + for (const r of [{ status: 429, json: { error: 'slow down' } }, { status: 503, json: { error: 'busy', busy: true } }]) { + f.routes = [[/save$/, r]]; + ev("MP.told=false;MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('!MP.busy&&MP.wait>performance.now()'))); + assert.equal(ev('MP.fails'), 2, String(r.status)); + assert.ok(ev('MP.wait-performance.now()') <= 30000); + assert.equal(ev("$('toasts').textContent"), '', 'nothing to tell'); + } + // A proxy's own 503 (the server behind it is down) is "away". + f.routes = [[/save$/, { status: 503, json: null }]]; + ev("MP.wait=0;dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.fails===3'))); + assert.match(ev("$('toasts').textContent"), /server is away/); + f.routes = [okSave]; + ev('MP.wait=0;dayTick();MP.last-=16000;save(true)'); + assert.ok(await until(() => ev('MP.fails===0&&!MP.told')), 'back: all forgotten'); + assert.ok(ev('S.day') >= 4, 'and the game went on all along'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: S.mp from a save is checked; saves without it load as before', () => { + const { ev, errors } = load({ mp: MPA, fetch: fake() }); + ev(`ACT.start({});if(UI.pendGame)ACT.pitchSkip();${quiet}`); + assert.equal(ev('S.mp'), null, 'a game outside a session'); + const fix = (m, mode = 'normal') => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mode=${lit(mode)};s.mp=${lit(m)};return JSON.stringify(sanitize(s).mp);})()`)); + assert.deepEqual(fix({ code: CODE, pid: PID, asn: 999, seed: 1e12, preset: 'sandbox', color: 'javascript:x', title: 'x'.repeat(99), seq: -4, token: TOK, extra: 1 }), + { code: CODE, pid: PID, asn: 200000, seed: 2147483647, preset: 'oncall', color: '#ff4f9a', title: 'x'.repeat(40), seq: 0 }); + for (const bad of [null, 7, 'K7Q2XD', [], { code: '../../x', pid: PID }, { code: CODE, pid: 'ABC' }, { code: 'k7q2xd', pid: PID }]) assert.equal(fix(bad), null, JSON.stringify(bad)); + assert.equal(fix({ code: CODE, pid: PID }, 'sandbox'), null, 'only a Normal game can be in a session'); + // An old save: no mp at all. + ev('const s=JSON.parse(JSON.stringify(S));delete s.mp;S=migrate(s);compute();dayTick();save(true)'); + assert.equal(ev('S.mp'), null); + assert.equal(ev("'mp' in S"), true); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('S.mp'), null, 'and it round-trips'); + assert.equal(ev("slotClean({id:'abc',mp:'K7Q2XD.abcd1234'}).mp"), 'K7Q2XD.abcd1234'); + assert.equal(ev("slotClean({id:'abc',mp:'.x'}).mp"), undefined, 'the slot list checks it too'); + assert.deepEqual(errors, []); +}); + +test('multiplayer: two players against the real server: start, join, see each other', async (t) => { + const { createMp } = require('../scripts/lib/mp'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-mp-e2e-')); + const mp = createMp({ dir, log: () => {} }); + const server = http.createServer((req, res) => { if (!mp.handle(req, res)) { res.writeHead(404); res.end(); } }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + t.after(() => { server.close(); fs.rmSync(dir, { recursive: true, force: true }); }); + const base = `http://127.0.0.1:${server.address().port}`; + // The page's fetch, on the real network (the page's own AbortSignal stays behind: it belongs to another realm). + const net = (u, o = {}) => { const { signal, ...rest } = o; return fetch(base + u, rest); }; + const a = await started({ fetch: net, name: 'Alpha Net' }); + const code = a.ev('S.mp.code'); + const b = load({ mp: MPA, fetch: net, seed: 777 }); + b.ev(`UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Beta Net';ACT.pickStart({city:'nyc'});document.getElementById('mpCode').value=${lit(code.toLowerCase())};ACT.mpJoin({})`); + assert.ok(await until(() => b.ev('!!(S&&S.mp)')), 'B joined'); + b.ev(quiet); + assert.equal(b.ev('S.mp.seed'), a.ev('S.mp.seed'), 'one world'); + assert.equal(b.ev('S.rules.preset'), 'bgp', 'one set of rules'); + assert.notEqual(b.ev('S.asn'), a.ev('S.asn')); + assert.equal(b.ev('S.home'), 'nyc'); + await until(() => b.ev('!MP.busy')); + a.ev('mpRefresh()'); + assert.ok(await until(() => a.ev('MP.roster&&MP.roster.players.length===2')), 'A sees B'); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.players.map(p=>p.name))')), ['Alpha Net', 'Beta bNet/b']); + assert.equal(a.ev("MP.roster.players[1].card&&MP.roster.players[1].card.pops.join()"), 'nyc', 'and B\'s card'); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(MP.roster.feed.map(f=>f.k))')), ['join', 'join']); + // A plays on a few days and pushes; B's panel shows it. + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + assert.equal(a.ev('S.mp.seq'), 2); + b.ev('ACT.mpOpen({})'); + assert.ok(await until(() => /Alpha Net/.test(b.ev("document.getElementById('mpBoard').textContent")))); + b.ev("document.getElementById('mpSay').value='hi from B';ACT.mpChat({})"); + assert.ok(await until(() => /hi from B/.test(b.ev("document.getElementById('mpFeed').textContent")))); + // B moves to another device by its link. + const link = b.ev('mpLink(S.mp)'); + await until(() => b.ev('!MP.busy')); + const c = load({ mp: MPA, fetch: net, url: link }); + assert.ok(await until(() => c.ev('!!(S&&S.mp&&UI.started)')), 'B on the other device'); + assert.equal(c.ev('S.name'), 'Beta Net'); + assert.equal(c.ev('S.home'), 'nyc'); + for (const h of [a, b, c]) { assert.deepEqual(h.errors, []); h.dom.window.close(); } + await mp.flush(); +}); + +test('multiplayer: the save here and the one on the server carry the same number: reopening finds nothing newer', async () => { + const srv = store(), f = fake(srv.routes); + const a = await started({ fetch: f }); + const slot = (h) => JSON.parse(h.ev('localStorage.getItem(SLOT_K+UI.slot)')); + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + assert.equal(srv.st.save.seq, 2); + assert.equal(JSON.parse(srv.st.save.data).mp.seq, 2, 'the server\'s copy says 2'); + assert.equal(slot(a).mp.seq, 2, 'and so does the one here: the number was picked before the save was written'); + // Closing the tab after a new day: the last save goes as a keepalive request, numbered the same here and there. + a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))"); + assert.equal(f.calls.at(-1).keepalive, true); + await until(() => a.ev('!MP.busy')); + assert.equal(srv.st.save.seq, 3); + assert.equal(slot(a).mp.seq, 3); + assert.equal(slot(a).day, srv.day()); + const storage = storageOf(a); + a.dom.window.close(); + // Reopened on the same device: nothing newer on the server, nothing loaded, nothing said. + const g = fake(srv.routes); + const b = load({ mp: MPA, fetch: g, storage }); + assert.ok(await until(() => g.calls.some((c) => /K7Q2XD$/.test(c.url))), 'asked, then took the roster'); + await flush(); + assert.doesNotMatch(b.ev("$('toasts').textContent"), /Loaded the newer save/); + // A push still on its way when the page goes away: the newer save goes anyway, and cuts the slower one short. + b.ev(quiet); + srv.st.hold = true; + b.ev('dayTick();MP.last-=16000;save(true)'); + const slow = g.calls.at(-1); + assert.equal(slow.keepalive, false); + assert.equal(b.ev('MP.busy'), true); + const k = g.calls.length; + b.ev('for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)'); + assert.equal(g.calls.length, k, 'one push at a time while the page is on screen'); + b.ev("window.dispatchEvent(new Event('pagehide'))"); + const last = g.calls.at(-1); + assert.equal(last.keepalive, true); + assert.equal(last.body.seq, slow.body.seq + 1); + assert.equal(JSON.parse(last.body.data).day, b.ev('S.day'), 'the days played meanwhile go too'); + assert.equal(slow.signal.aborted, true, 'the slower one was cut short'); + await until(() => b.ev('!MP.busy')); + assert.equal(srv.day(), b.ev('S.day')); + assert.equal(slot(b).mp.seq, srv.st.save.seq); + // Reopened once more: the server's copy is this one, so the days stay. + const day = b.ev('S.day'), again = storageOf(b); + b.dom.window.close(); + const c = load({ mp: MPA, fetch: fake(srv.routes), storage: again }); + await flush(10); + assert.equal(c.ev('S.day'), day); + assert.doesNotMatch(c.ev("$('toasts').textContent"), /Loaded the newer save|moved on elsewhere/); + for (const h of [b, c]) assert.deepEqual(h.errors, []); + assert.deepEqual(a.errors, []); + c.dom.window.close(); +}); + +test('multiplayer: the server briefly away when the network opens is no conflict later', async () => { + const srv = store(), a = await started({ fetch: fake(srv.routes) }); + a.ev("ACT.launchBB({city:'fra'});dayTick();MP.last-=16000;save(true)"); + await until(() => a.ev('!MP.busy')); + a.ev("dayTick();window.dispatchEvent(new Event('pagehide'))"); + await until(() => a.ev('!MP.busy')); + const storage = storageOf(a); + a.dom.window.close(); + const g = fake([[/./, new Error('offline')]]); + const b = load({ mp: MPA, fetch: g, storage }); + assert.ok(await until(() => b.ev('MP.fails===1'))); + b.ev(quiet + "for(let i=0;i<10;i++)dayTick();MP.wait=0;MP.last-=16000"); + g.routes = srv.routes; + b.ev('save(true)'); + await until(() => b.ev('!MP.busy')); + assert.equal(b.ev('MP.stale'), false, 'one device, so no "moved on elsewhere"'); + assert.equal(srv.day(), b.ev('S.day')); + assert.deepEqual(b.errors, []); + b.dom.window.close(); +}); + +test('multiplayer: hiding the page sends what changed on the same game day, only then, in a request that fits', async () => { + const srv = store(), f = fake(srv.routes); + const { dom, ev, errors } = await started({ fetch: f }); + const n = () => f.saves().length, k = n(); + // A paused game: the player builds, and the day never moves. + ev("ACT.launchBB({city:'fra'})"); + assert.equal(n(), k, 'same day, page on screen: nothing yet'); + ev(hide()); + assert.equal(n(), k + 1, 'hidden: what changed goes'); + assert.equal(f.saves().at(-1).keepalive, true); + assert.ok(JSON.parse(f.saves().at(-1).body.data).pops.fra.bb, 'with the change'); + await until(() => ev('!MP.busy')); + ev(hide()); + assert.equal(n(), k + 1, 'hidden again, nothing changed: nothing sent'); + // Moving to another device: the link goes with what this one has now. + ev(hide(false) + "S.name='Packet Pals Two';ACT.mpOpen({});ACT.mpCopyLink({})"); + assert.equal(n(), k + 2); + assert.equal(JSON.parse(f.saves().at(-1).body.data).name, 'Packet Pals Two'); + await until(() => ev('!MP.busy')); + ev("S.name='Packet Pals Three';const d=document.querySelector('#mpPanel details.mpmove');d.open=true;d.dispatchEvent(new Event('toggle'))"); + assert.equal(n(), k + 3, 'opening "Move to another device" pushes too'); + await until(() => ev('!MP.busy')); + // A keepalive request may carry 64 KiB in all: the request is measured, in bytes, quotes escaped, card and all. + ev('closeModal();' + hide()); + const send = (t) => { ev(`dayTick();S.mp.seq++;mpPush(${lit(t)})`); const c = f.calls.at(-1); return c.url.replace(/.*\//, ''); }; + assert.equal(send('{"x":"' + 'a'.repeat(50000) + '"}'), 'save', '50 kB of plain text fits'); + await until(() => ev('!MP.busy')); + assert.equal(send('{"x":[' + Array(10000).fill('"ab"').join(',') + ']}'), 'card', '50 kB of text with quotes does not'); + await until(() => ev('!MP.busy')); + assert.equal(send('{"x":"' + 'é'.repeat(40000) + '"}'), 'card', '40 000 characters of two bytes do not'); + await until(() => ev('!MP.busy')); + for (const c of f.calls.filter((x) => x.keepalive)) assert.ok(Buffer.byteLength(c.raw) < 63000, `${c.url}: ${Buffer.byteLength(c.raw)} bytes`); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: "Load the newer save" never loads an older one; "Keep this one" waits for the day to end', async () => { + const srv = store(), f = fake(srv.routes); + const { dom, ev, errors } = await started({ fetch: f }); + const day0 = srv.st.save; + ev("ACT.launchBB({city:'fra'});for(let i=0;i<5;i++)dayTick();MP.last-=16000;save(true)"); + await until(() => ev('!MP.busy')); + // The server says it has a newer save (409, number 3) but holds an older one (number 1, day 0). + srv.st.save = day0; + f.routes = [[/^PUT .*\/save$/, { status: 409, json: { error: 'newer', seq: 3, at: 1 } }], ...srv.routes]; + ev("$('toasts').innerHTML='';dayTick();MP.last-=16000;save(true)"); + assert.ok(await until(() => ev('MP.stale'))); + const day = ev('S.day'); + ev('ACT.mpNewer({})'); + assert.ok(await until(() => /no newer save/.test(ev("$('toasts').textContent")))); + assert.equal(ev('S.day'), day, 'not rolled back to day 0'); + assert.equal(ev('MP.stale'), false); + f.routes = srv.routes; + ev('dayTick();MP.last-=16000;save(true)'); + await until(() => ev('!MP.busy')); + assert.equal(srv.day(), ev('S.day'), 'and the next push puts this one on the server'); + // Another device pushed number 9 meanwhile; the player keeps theirs, clicking while the day is still routing. + srv.st.save = { ...srv.st.save, seq: 9 }; + ev('dayTick();MP.last-=16000;save(true)'); + assert.ok(await until(() => ev('MP.stale&&MP.staleSeq===9'))); + const k = f.saves().length; + ev('RW.job={};ACT.mpKeep({})'); + assert.equal(f.saves().length, k, 'never half a day'); + ev('RW.job=null;rwDayDone()'); + const kept = f.saves().at(-1); + assert.equal(f.saves().length, k + 1, 'the day\'s end pushes it'); + assert.equal(kept.body.force, true); + assert.equal(kept.body.seq, 10, 'past the server\'s number, so it keeps the one it was sent'); + await until(() => ev('!MP.busy')); + assert.equal(srv.st.save.seq, 10); + assert.equal(JSON.parse(ev('localStorage.getItem(SLOT_K+UI.slot)')).mp.seq, 10); + assert.equal(ev('MP.force'), false); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: a #mp= link never replaces nor deletes the token this browser has; a busy network is not copied', async () => { + const srv = store(), b = browser(), tab1 = new Map(); + const real = (c) => c.method === 'POST' || c.headers.authorization === `Bearer ${PID}.${TOK}`; + const guarded = srv.routes.map(([re, h]) => [re, (c) => (real(c) ? (typeof h === 'function' ? h(c) : h) : { status: 401, json: { error: 'unauthorized' } })]); + const f1 = fake(guarded); + const t1 = await started({ fetch: f1, load: { browser: b, tab: tab1 } }); + t1.ev("ACT.launchBB({city:'fra'});for(let i=0;i<3;i++)dayTick();MP.last-=16000;save(true)"); + await until(() => t1.ev('!MP.busy')); + const link = t1.ev('mpLink(S.mp)'), wrong = link.replace(/[0-9a-f]{64}$/, '0'.repeat(64)), tok = () => b.ls.get(`sot-mp:${CODE}:${PID}`); + const slots = () => JSON.parse(b.ls.get('sot-slots')).slots.length; + // A wrong link (a rival's, or one mistyped character) while the game is open in another tab. + const t2 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /did not work/.test(t2.ev("$('toasts').textContent")))); + assert.equal(tok(), TOK, 'the real token stays'); + assert.equal(slots(), 1); + t1.ev('dayTick();MP.last-=16000;save(true)'); + assert.equal(f1.calls.at(-1).headers.authorization, `Bearer ${PID}.${TOK}`, 'and the open tab plays on in its session'); + await until(() => t1.ev('!MP.busy')); + assert.equal(t1.ev('MP.gone'), false); + // The right link, while the network is open in the other tab: no second copy, the choice to take it over. + const t3 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: link }); + assert.ok(await until(() => t3.ev("!!document.querySelector('#modal [data-act=slotTake]')")), 'offered to take it over'); + assert.equal(slots(), 1, 'not copied into a second slot'); + // The server away: the link may be fine, so it is not called bad, stays for a reload, and no token changes. + b.close(t1.dom.window); + const t4 = load({ mp: MPA, fetch: fake([[/./, new Error('offline')]]), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /cannot be reached/.test(t4.ev("$('toasts').textContent")))); + assert.equal(t4.ev('location.hash'), new URL(wrong).hash, 'kept for a reload'); + assert.equal(tok(), TOK); + // A wrong link once the game's tab is closed: still told, still the real token. + const t5 = load({ mp: MPA, fetch: fake(guarded), browser: b, tab: new Map(), url: wrong }); + assert.ok(await until(() => /did not work/.test(t5.ev("$('toasts').textContent")))); + assert.equal(tok(), TOK); + assert.equal(t5.ev('location.hash'), '', 'a bad link is gone from the address bar'); + // A fresh browser, server away: nothing stored at all. + const b2 = browser(), t6 = load({ mp: MPA, fetch: fake([[/./, { status: 503, json: { error: 'busy' } }]]), browser: b2, tab: new Map(), url: link }); + assert.ok(await until(() => /cannot be reached/.test(t6.ev("$('toasts').textContent")))); + assert.equal(b2.ls.get(`sot-mp:${CODE}:${PID}`), undefined); + for (const h of [t1, t2, t3, t4, t5, t6]) assert.deepEqual(h.errors.filter((e) => !/moving the network here failed/.test(e)), []); + for (const h of [t1, t2, t3, t4, t5, t6]) h.dom.window.close(); +}); + +test('multiplayer: the session panel\'s refresh while the server is away says so once and never stretches the wait', async () => { + const f = fake([okStart, okSave, [/^GET /, { status: 200, json: roster([me()]) }]]); + const { dom, ev, errors } = await started({ fetch: f }); + ev('ACT.mpOpen({})'); + await flush(); + f.routes = [[/./, new Error('offline')]]; + ev("$('toasts').innerHTML=''"); + for (let i = 0; i < 6; i++) { ev('mpPollTick()'); await flush(); } + assert.equal(f.calls.filter((c) => c.method === 'GET').length >= 6, true, 'it still looks every few seconds'); + assert.equal(ev('MP.fails'), 1); + assert.ok(ev('MP.wait-performance.now()') <= 30000, 'the push back-off stays at its first step'); + assert.equal(ev("$('toasts').textContent.split('server is away').length-1"), 1, 'said once'); + f.routes = [okSave, [/^GET /, { status: 200, json: roster([me()]) }]]; + ev('mpPollTick()'); + assert.ok(await until(() => ev('MP.fails===0&&MP.wait===0')), 'back: all forgotten'); + const k = f.calls.length; + ev('closeModal();mpPollTick()'); + assert.equal(f.calls.length, k, 'a closed panel stops asking'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('multiplayer: with a charter to sign first, the session code and its Share button wait for it', async () => { + const f = fake([okStart, okSave]); + const { dom, ev, errors } = load({ mp: MPA, fetch: f }); + const doc = dom.window.document; + ev("window.__TUBES_CHARTER__=true;UI.pitched=true;ACT.mpDoor({});document.getElementById('mpName').value='Packet Pals';ACT.presetSet({p:'bgp'});ACT.mpStart({})"); + assert.ok(await until(() => ev('!!(S&&S.mp)'))); + assert.equal(ev("$('modal').className"), 'charter', 'the charter comes first'); + assert.equal(doc.querySelector('#toasts [data-act=mpShare]'), null, 'no buttons under it that cannot be pressed'); + ev('ACT.charter({k:Object.keys(CHARTERS)[0]})'); + const share = doc.querySelector('#toasts [data-act=mpShare]'); + assert.ok(share, 'signed: the code to share'); + assert.match(doc.getElementById('toasts').textContent, /K7Q-2XD/); + share.click(); + assert.match(doc.getElementById('toasts').textContent, /Join my Series of Tubes session K7Q-2XD/, 'and its button works'); + assert.deepEqual(errors, []); + dom.window.close(); +}); From 2cd6b71198d3b11f863ff2772c4e923bf7c249c9 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:01:50 +0100 Subject: [PATCH 4/8] =?UTF-8?q?Dark=20mode:=20Light,=20Dark=20or=20Auto=20?= =?UTF-8?q?under=20Settings=20=E2=80=BA=20Theme=20(#80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A device preference (localStorage sot-theme, never in the save), applied by a small script in before the first paint, so there is no flash; Auto follows prefers-color-scheme live, and a choice reaches other tabs and the NOC window. Panels, HUD, drawers, toasts, modals, the phone tab bar, charts, puzzles, the architect and Pie Control take their colours from custom properties with night values (AA text contrast); light tints keep their old colour as the fallback, so the light look is unchanged. Both map renderers read a light and a dark palette (96-map/15-palette.js): sea, land, clouds, coastlines, labels and the tube outline. A theme switch repaints the cached layers once (the WebGL land buffers are rebuilt once); nothing changes per frame. The multiplayer leaderboard's own row and the menu rank badge follow the theme too. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 6 +- site/i18n/de.js | 4 + site/i18n/es.js | 4 + site/i18n/fr.js | 4 + site/i18n/it.js | 4 + site/i18n/pt.js | 4 + src/agent/20-commands.js | 2 +- src/game/60-features/30-conferences.js | 2 +- src/game/60-features/36-specialist.js | 6 +- src/game/60-features/37-cable-broker.js | 4 +- .../85-incidents/10-incidents-and-ddos.js | 2 +- src/game/85-incidents/40-chaos-monkey.js | 2 +- src/game/90-actions/10-interface.js | 1 + src/game/90-actions/95-puzzles.js | 2 +- src/game/93-ui/15-theme.js | 27 ++ src/game/93-ui/30-install.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/94-dashboard/65-chart-legend.js | 5 +- src/game/96-map/15-palette.js | 11 + src/game/96-map/30-settings.js | 1 + src/game/96-map/50-link-geometry.js | 2 +- src/game/96-map/57-webgl-background.js | 33 +- src/game/96-map/58-webgl-links.js | 16 +- src/game/96-map/60-draw.js | 32 +- src/game/96-map/80-cities.js | 4 +- src/game/96-map/85-puzzle-cities.js | 2 +- src/game/96-map/89-pie-globe.js | 3 +- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 4 + src/index.html | 9 + src/styles/00-base.css | 8 +- src/styles/05-theme.css | 23 ++ src/styles/10-hud.css | 4 +- src/styles/20-drawers.css | 20 +- src/styles/30-toasts.css | 6 +- src/styles/36-ops.css | 6 +- src/styles/38-pie-globe.css | 2 +- src/styles/40-modal.css | 58 +-- src/styles/41-multiplayer.css | 4 +- src/styles/42-chart-tooltips.css | 4 +- src/styles/45-noc-window.css | 2 +- src/styles/60-phone.css | 18 +- src/styles/70-puzzles.css | 38 +- src/styles/71-architect.css | 16 +- tests/build.test.js | 2 +- tests/dark-mode.test.js | 380 ++++++++++++++++++ 49 files changed, 645 insertions(+), 155 deletions(-) create mode 100644 src/game/93-ui/15-theme.js create mode 100644 src/game/96-map/15-palette.js create mode 100644 src/styles/05-theme.css create mode 100644 tests/dark-mode.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a6901a9..e349380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. +- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 77b2a1e..aad1e5e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,13 +38,13 @@ hoisted across files, and top-level statements run in path order. Find code by n | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | | `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers | | `91-save.js`, `92-audio.js` | Save, export and import; sound effects | -| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | +| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the theme (light, dark or Auto: `15-theme.js`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning | | `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints | | `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals | -| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation | +| `96-map/` | The canvas: resize, the map's colours per theme (`15-palette.js`), land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation | | `99-loop.js` | `frame()` and `boot()` | -`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone. +`src/styles/` holds the CSS the same way: base, the dark theme's colours (`05-theme.css`), HUD, drawers, toasts, modal, tablet, then phone. `src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it); diff --git a/site/i18n/de.js b/site/i18n/de.js index 94cc2cd..405ba56 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4540,12 +4540,15 @@ "settings.always_2d":"Immer 2D", "settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.", "settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.", +"settings.auto_follows_your_device_s_light":"Auto folgt der Hell- oder Dunkel-Einstellung deines Geräts. Dunkel schont nachts die Augen und auf OLED-Bildschirmen den Akku.", "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.", "settings.customers_and_alerts":"Kunden und Warnungen", +"settings.dark":"Dunkel", "settings.diagnostic_info":"Diagnoseinfos", "settings.display_and_sound":"Anzeige und Ton", "settings.for_bug_reports_shows_your_screen":"Für Fehlerberichte: zeigt in einer Ecke die Größe deines Bildschirms, wie die Karte gezeichnet wird (Grafikkarte oder 2D, und warum) und wie schnell.", "settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen", +"settings.light":"Hell", "settings.map_drawing":"Kartendarstellung", "settings.n_min":"{n} Min.", "settings.n_sec":"{n} s", @@ -4559,6 +4562,7 @@ "settings.the_agent_moves_it":"Der Agent stellt sie", "settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt", "settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.", +"settings.theme":"Design", "settings.this_browser_cannot_so_the_map":"Dieser Browser kann das nicht, also wird die Karte in 2D gezeichnet.", "settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen", "settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.", diff --git a/site/i18n/es.js b/site/i18n/es.js index cf40d69..427ba64 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Siempre 2D", "settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.", "settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.", +"settings.auto_follows_your_device_s_light":"Auto sigue el ajuste claro u oscuro de tu dispositivo. El oscuro descansa la vista de noche y ahorra batería en pantallas OLED.", "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.", "settings.customers_and_alerts":"Clientes y alertas", +"settings.dark":"Oscuro", "settings.diagnostic_info":"Información de diagnóstico", "settings.display_and_sound":"Pantalla y sonido", "settings.for_bug_reports_shows_your_screen":"Para informar de fallos: muestra en una esquina el tamaño de tu pantalla, cómo se dibuja el mapa (tarjeta gráfica o 2D, y por qué) y a qué velocidad.", "settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue", +"settings.light":"Claro", "settings.map_drawing":"Dibujo del mapa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"Lo mueve el agente", "settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente", "settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Este navegador no puede, así que el mapa se dibuja en 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta", "settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f1c7c81..2a134ae 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Toujours en 2D", "settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.", "settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.", +"settings.auto_follows_your_device_s_light":"Auto suit le réglage clair ou sombre de ton appareil. Le sombre repose les yeux la nuit et économise la batterie sur les écrans OLED.", "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.", "settings.customers_and_alerts":"Clients et alertes", +"settings.dark":"Sombre", "settings.diagnostic_info":"Infos de diagnostic", "settings.display_and_sound":"Affichage et son", "settings.for_bug_reports_shows_your_screen":"Pour signaler un bug : affiche dans un coin la taille de ton écran, comment la carte est dessinée (carte graphique ou 2D, et pourquoi) et à quelle vitesse.", "settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer", +"settings.light":"Clair", "settings.map_drawing":"Dessin de la carte", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"L'agent l'avance", "settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue", "settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.", +"settings.theme":"Thème", "settings.this_browser_cannot_so_the_map":"Ce navigateur ne peut pas, la carte est donc dessinée en 2D.", "settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent", "settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 1db1657..2d75e8e 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Sempre 2D", "settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.", "settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.", +"settings.auto_follows_your_device_s_light":"Auto segue l’impostazione chiara o scura del tuo dispositivo. Lo scuro riposa gli occhi di notte e fa risparmiare batteria sugli schermi OLED.", "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.", "settings.customers_and_alerts":"Clienti e avvisi", +"settings.dark":"Scuro", "settings.diagnostic_info":"Info di diagnostica", "settings.display_and_sound":"Schermo e audio", "settings.for_bug_reports_shows_your_screen":"Per segnalare bug: mostra in un angolo le dimensioni dello schermo, come viene disegnata la mappa (scheda grafica o 2D, e perché) e a che velocità.", "settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA", +"settings.light":"Chiaro", "settings.map_drawing":"Disegno della mappa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"Lo muove l'agente", "settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente", "settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Questo browser non può, quindi la mappa è disegnata in 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento", "settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 311571c..f65faba 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4538,12 +4538,15 @@ "settings.always_2d":"Sempre 2D", "settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.", "settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.", +"settings.auto_follows_your_device_s_light":"Auto segue a configuração clara ou escura do seu aparelho. O escuro descansa os olhos à noite e economiza bateria em telas OLED.", "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.", "settings.customers_and_alerts":"Clientes e alertas", +"settings.dark":"Escuro", "settings.diagnostic_info":"Informações de diagnóstico", "settings.display_and_sound":"Tela e som", "settings.for_bug_reports_shows_your_screen":"Para reportar bugs: mostra em um canto o tamanho da sua tela, como o mapa é desenhado (placa de vídeo ou 2D, e por quê) e a que velocidade.", "settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar", +"settings.light":"Claro", "settings.map_drawing":"Desenho do mapa", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4557,6 +4560,7 @@ "settings.the_agent_moves_it":"O agente move-o", "settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga", "settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.", +"settings.theme":"Tema", "settings.this_browser_cannot_so_the_map":"Este navegador não consegue, então o mapa é desenhado em 2D.", "settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito", "settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 9d4f554..6d3f47b 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -607,7 +607,7 @@ const API_DENY={ start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', - animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',themeSet:'prefs',vpSet:'prefs', mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp', install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; diff --git a/src/game/60-features/30-conferences.js b/src/game/60-features/30-conferences.js index c3cc0eb..4eb5bea 100644 --- a/src/game/60-features/30-conferences.js +++ b/src/game/60-features/30-conferences.js @@ -19,7 +19,7 @@ function confTick(d){S.confReg=S.confReg||{}; toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');} capDealTick(d);} function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return ''; - return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} + return `

${tr('common.conferences')}

${cb?`
${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}
${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}
`:''}${up.map(confRow).join('')}`;} function confRow(cf){const reg=S.confReg&&S.confReg[cf.key],open=cf.day>S.day,sp=confSp(cf),cost=confCost(cf),lk=cf.cap&&glassLvl()'+tr('conferences.sponsor')+'':reg?''+tr('common.registered')+'':open?'':''+tr('common.registration_closed')+''); const btns=!open||reg==='sp'?'':(reg?'':lk?btn(tr('sites_and_service.level_n',{n:CAP_LV}),'confGo',{key:cf.key},'sm',true):btn(tr('conferences.attend_cost',{cost:fmt$(cost)}),'confGo',{key:cf.key},'sm',S.cash!S.pops[c]).reduce((x,c)=>x+newPopCost(c),0); - return `
🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}
${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
+ return `
🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}
${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${tr('specialist.your_own_fiber_pairs_on_a')}${pop?' '+tr('specialist.includes_pops_at_the_landings_price',{price:fmt$(pop)}):''}
${SEAT_N.map(n=>{const c=seatCost(o.km,n)+pop;return btn(`${trn('specialist.n_fiber_pairs',n)} ${fmt$(c)} · ${tr('common.price_mo',{price:fmt$(seatMo(o.km,n))})}`,'seatBuy',{n},'sm',S.cash
`;} function seatPanel(l){if(!l.seat)return '';return `
${tr('specialist.consortium_seat')}${esc(l.cname||'')} · ${trn('specialist.n_fiber_pairs',Math.max(1,l.pairs|0))}

${tr('specialist.the_consortium_runs_the_cable_your')}

`;} @@ -97,8 +97,8 @@ function charterAsk(){if(!charterDue()||!$('modal').hidden||window.__TUBES_TEST_ function charterCard(){if(S.scn||S.mode!=='normal')return ''; if(broker())return baronCard(); if(charter()!=='boutique')return ''; - if(S.solWon)return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}
`; - const r=solRoutes();return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}
${r.slice(0,SOL_ROUTES).map(x=>`
✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} < ${x.l.toFixed(1)}
`).join('')}
`;} + if(S.solWon)return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}
`; + const r=solRoutes();return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}
${r.slice(0,SOL_ROUTES).map(x=>`
✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} < ${x.l.toFixed(1)}
`).join('')}
`;} // Once a day: seats expire or call, the boutique checks its win and carriers call the broker. function specDay(d){if(broker())brokerDay(d);if(S.seatOff&&S.seatOff.exp<=d)S.seatOff=null; if(!S.seatOff&&!S.scn&&S.mode!=='puzzle'&&lvl()>=SEAT_LV&&hstr(S.asn+'|seatcall|'+d)%SEAT_ODDS===0)seatConf(null); diff --git a/src/game/60-features/37-cable-broker.js b/src/game/60-features/37-cable-broker.js index b63ed87..b85582d 100644 --- a/src/game/60-features/37-cable-broker.js +++ b/src/game/60-features/37-cable-broker.js @@ -20,8 +20,8 @@ function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap return Object.values(by).some(s=>s.size>=2);} const baronOk=()=>cableConts()>=BARON_CONT&&capSalesMo()>=BARON_MO; // On the goals tab, under the charter: how far Glass Baron is. -function baronCard(){if(S.baronWon)return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}
`; - return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}
`;} +function baronCard(){if(S.baronWon)return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}
`; + return `
🌊 ${tr('broker.glass_baron')}
${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}
`;} function showBaronWin(){openModal(`

🌊 ${tr('broker.glass_baron')}

${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:S.day,n:BARON_CONT,mo:fmt$(capSalesMo())})}

${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}
`);} /* Carriers call the broker now and then (about three times a year, from day 60) with a capacity deal on a route the capacity conferences trade: the same deals at the same terms, without the trip. Picked by a hash of the day, so a diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index db254dc..ae6107e 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -120,7 +120,7 @@ function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pop function ddosPanel(){return S?ddosAll().filter(a=>S.pops[a.city]).map(ddosOne).join(''):'';} const ddCities=l=>{const u=[...new Set(l)];return u.slice(0,3).map(c=>CITY[c].name).join(', ')+(u.length>3?' +'+(u.length-3):'');}; function ddosOne(a){const V=DDOS_VEC[a.vec]||{n:'?',fs:false},m=ddosReport(a),row=(ok,t)=>`
${ok===true?'✓':ok===false?'~':'—'} ${t}
`; - let h=`
🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}
+ let h=`
🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}
${esc(ddosWho(a))} · ${tr('ui.n_d_left',{n:Math.max(1,a.until-S.day)})}${a.carpet?' · '+tr('ddos.carpet'):''}
`; if(!m)return h+'
'; const engIdle=hasScrub()&&!a.bh&&m.eng<1&&S.scrubMode==='ondemand'&&S.ddosAuto&&S.ddosAuto.scrub===false&&a.eng===undefined; diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 6798c37..513979b 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -50,4 +50,4 @@ function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0 if(typeof mkEnd==='function')mkEnd(ok,true);} // The NOC tab's card while it is here. function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost(); - return `
🐒 ${tr('chaos_monkey.loose')}
${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}
${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash
`;} + return `
🐒 ${tr('chaos_monkey.loose')}
${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}
${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash
`;} diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 7a0715e..80ec9fc 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -23,6 +23,7 @@ const ACT={ leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=glassLvl()>=3?'roadm':'lite';openLinkModal(a,b);}, dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);}, mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();}, + themeSet:({v})=>{if(!themePick(v))return;refreshSettings();}, animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();}, soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();}, langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();}, diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 881800c..560d802 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -62,6 +62,6 @@ Object.assign(ACT,{ // open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's // routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone. // This file is the last of the actions, so every one is here to wrap. -const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','themeSet','updateLater','updateNow','vpSet','whatsNewShow']); const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']); for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/93-ui/15-theme.js b/src/game/93-ui/15-theme.js new file mode 100644 index 0000000..c081ce1 --- /dev/null +++ b/src/game/93-ui/15-theme.js @@ -0,0 +1,27 @@ +/* ---------- Light or dark (#80) ---------- + Settings › Theme: Auto follows the device's light or dark setting, or the player picks one. A choice per device + (localStorage sot-theme, like the animation and map settings), not part of the save. The page's reads it and + sets before the first paint, so a dark screen never flashes light; this keeps it in step when the + choice or the device's setting changes. The panels follow at once (CSS custom properties, 00-base.css); the map + keeps pictures painted in the old colours, so it paints them again, once (themeRepaint()). */ +const THEME_OPTS=['auto','light','dark'],THEME_BAR={light:'#57C4E5',dark:'#0E2A44'}; // the browser bar: --sea +const THEME={pref:'auto',dark:false,mq:null,on:null}; +function themeRead(){let v=null;try{v=localStorage.getItem('sot-theme');}catch(e){}return THEME_OPTS.includes(v)?v:'auto';} +const themeSys=()=>{try{return !!(THEME.mq&&THEME.mq.matches);}catch(e){return false;}}; +// The page's colours from the choice (and the device's setting, on Auto). A switch repaints the map's cached pictures. +function themeApply(repaint=true){const dark=THEME.pref==='dark'||(THEME.pref==='auto'&&themeSys()),was=THEME.dark,R0=document.documentElement; + THEME.dark=dark;R0.setAttribute('data-theme',dark?'dark':'light'); + for(const [n,v] of [['theme-color',THEME_BAR[dark?'dark':'light']],['color-scheme',dark?'dark':'light']]){const m=document.querySelector(`meta[name="${n}"]`);if(m)m.setAttribute('content',v);} + if(repaint&&was!==dark)themeRepaint();return dark;} +function themePick(v){if(!THEME_OPTS.includes(v))return false;THEME.pref=v;try{v==='auto'?localStorage.removeItem('sot-theme'):localStorage.setItem('sot-theme',v);}catch(e){}themeApply();return true;} +// Reads the choice and listens to the device's setting, which Auto follows as it changes (a phone at dusk). +function themeInit(){THEME.pref=themeRead();THEME.on=()=>{if(THEME.pref==='auto')themeApply();}; + try{THEME.mq=window.matchMedia?matchMedia('(prefers-color-scheme: dark)'):null;}catch(e){} + const q=THEME.mq;if(q){try{q.addEventListener?q.addEventListener('change',THEME.on):q.addListener(THEME.on);}catch(e){}} + THEME.dark=document.documentElement.getAttribute('data-theme')==='dark';return themeApply(false);} +/* What the map painted in the old colours: the land (the 2D picture, the card's coastlines), every sprite (labels, + cities), the Pie globe unless the player chose its day or night. All painted again on the next frame, not every frame. */ +function themeRepaint(){WL.key=null;FRAME.length=0;UI.drawnAt=0;spritesReset();glLandDrop(); + let g=null;try{g=localStorage.getItem('sot-globe');}catch(e){}if(!g){PG.night=THEME.dark;PG.g=null;PG.dirty=true;}} +// Picked in another tab: this one follows, and so does the NOC window on a second screen. +if(!RW_IN){themeInit();addEventListener('storage',e=>{if(e.key==='sot-theme'||e.key===null){THEME.pref=themeRead();themeApply();}});} diff --git a/src/game/93-ui/30-install.js b/src/game/93-ui/30-install.js index 73e0c71..17d0f33 100644 --- a/src/game/93-ui/30-install.js +++ b/src/game/93-ui/30-install.js @@ -8,7 +8,7 @@ function installRow(){if(isStandalone())return ''; return `
📲 ${tr('install.best_played_as_an_app')}
${tr('install.full_screen_works_offline_one_tap')}${isIOS()?' '+tr('install.install_it_before_you_start_a'):''}
${btn(tr('common.install'),'install',{},'pink sm')}
`;} /* Phones get a real pitch before a new game: an installed app is full screen, works offline, and on iPhone keeps its save away from Safari's clean-ups. Storage is separate on iOS, so installing first matters. */ -const SHARE_SVG=''; +const SHARE_SVG=''; const needPitch=()=>isPhone()&&!isStandalone(); function installSteps(){ if(isIOS())return `
  1. ${tr('install.tap_share_icon_in_the_browser',{icon:SHARE_SVG})}
  2. ${tr('install.tap_add_to_home_screen_you')}
  3. ${tr('install.open_series_of_tubes_from_your')}
`; diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index b3052f9..fe442ca 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -44,7 +44,7 @@ function renderLeft(){checkLayer(); }else if(UI.left==='deals'){ {const st=custStats();if(st.n)h+=`
${tr('common.your_customers')} ${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} h+=salesCard()+clDealsHtml()+confSection()+seatSection(); - {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} + {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 628dc3a..43a2309 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -49,7 +49,7 @@ function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; }finally{S=save;R=live;UI.hotMap=hot;TE_CACHE=cache;}} function linkCheckModal(l){const t=linkTrial(l.id);if(!t)return; const title=t.split?tr('link_panels.this_backhoe_wins'):t.loss>.01?tr('link_panels.connected_but_tight'):tr('link_panels.one_backhoe_is_not_enough'); - openModal(`

${tr('common.redundancy_check')}

${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}

${title}

${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}

${tr('link_panels.additional_traffic_lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('common.service_affected')}

${t.losses.map(x=>`
${esc(x.name)}−${fmtG(x.g)}
`).join('')}`:''}${t.busy.length?`

${tr('link_panels.full_links_during_the_test')}

${t.busy.slice(0,6).map(x=>`
${esc(x.name)}${fmtG(x.g)} / ${fmtG(x.cap)}
`).join('')}`:''}

${tr('link_panels.snapshot_only_one_selected_link')}

${btn(tr('common.close'),'closeModal',{},'ghost')}
`,'link-check');} + openModal(`

${tr('common.redundancy_check')}

${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}

${title}

${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}

${tr('link_panels.additional_traffic_lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('common.service_affected')}

${t.losses.map(x=>`
${esc(x.name)}−${fmtG(x.g)}
`).join('')}`:''}${t.busy.length?`

${tr('link_panels.full_links_during_the_test')}

${t.busy.slice(0,6).map(x=>`
${esc(x.name)}${fmtG(x.g)} / ${fmtG(x.cap)}
`).join('')}`:''}

${tr('link_panels.snapshot_only_one_selected_link')}

${btn(tr('common.close'),'closeModal',{},'ghost')}
`,'link-check');} function linkCheckControl(l){return `

${tr('common.redundancy_check')}

${tr('link_panels.what_happens_if_this_link_fails')}

${btn(tr('common.check_redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}
`;} // At its own POP a carrier's port always takes that carrier's traffic (25-direct-egress.js). From POPs with no port of it, the // traffic goes to the nearest transit port, or across your network to this one. Only worth asking when something else could take it. @@ -169,7 +169,7 @@ function svgChart(rows,stackKeys,lines,fmtY,id){ for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`${fmtY(v)}`;} const base=rows.map(()=>0); for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=``;top.forEach((v,i)=>base[i]=v);} - for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} + for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} g+=`${dateStr(rows[0].d)}${dateStr(rows[rows.length-1].d)}`; return `${g}`;} // For a network you currently reach over transit: the cheapest way to move it to peering. diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 2703cd9..b1e662f 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -7,7 +7,7 @@ function renderDash(){checkLayer(); const tile=(l,v,sub)=>`
${l}
${v}
${sub?`
${sub}
`:''}
`; let h=`
AS${S.asn} · ${esc(S.name)} · ${tierLabel()}

${tr('common.noc_dashboard')}

`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}
-

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}
+

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; diff --git a/src/game/94-dashboard/65-chart-legend.js b/src/game/94-dashboard/65-chart-legend.js index 63cfdfa..c6bdc71 100644 --- a/src/game/94-dashboard/65-chart-legend.js +++ b/src/game/94-dashboard/65-chart-legend.js @@ -1,13 +1,14 @@ /* The NOC charts: legend entries switch a series on and off (the scale follows what is left), and hovering or touching a chart shows every visible series on that day. View state only: UI.chartOff is never saved. */ const CHARTS={ - traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'#1E2640':EGC[k][1]}, + traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'var(--text)':EGC[k][1]}, mix:{stack:['c','p','ix','t'],lines:[],fmt:v=>fmtG(v),name:k=>EGC[k][0],col:k=>EGC[k][1]}, // the Traffic tab's table money:{stack:[],lines:['rev','cost'],fmt:v=>fmt$(v),name:k=>k==='rev'?tr('common.revenue'):tr('common.costs'),col:k=>k==='rev'?'#16A866':'#FF4D5E'} }; const chartKeys=C=>[...C.stack,...C.lines]; +// The demand line's key is a dashed outline, in the line's own colour (dark ink by day, light text at night). function chartLegend(id,label){const C=CHARTS[id],off=(UI.chartOff&&UI.chartOff[id])||{}; - return `
${chartKeys(C).map(k=>``).join('')}
`;} + return `
${chartKeys(C).map(k=>``).join('')}
`;} Object.assign(ACT,{ chartToggle:({c,k})=>{const C=CHARTS[c];if(!C||!chartKeys(C).includes(k))return; const off=((UI.chartOff=UI.chartOff||{})[c]=UI.chartOff[c]||{});if(off[k])delete off[k];else off[k]=1; diff --git a/src/game/96-map/15-palette.js b/src/game/96-map/15-palette.js new file mode 100644 index 0000000..0e3fca2 --- /dev/null +++ b/src/game/96-map/15-palette.js @@ -0,0 +1,11 @@ +/* The map's colours by theme (#80): the cartoon day, and a night under the same stickers (cities and markers keep + theirs; a dark outline round a white sticker reads on either). Both renderers read them when they paint: the 2D map + in drawFrame()/paintWorld(), the card in glBegin()/glFrame() (glPal()). Labels: the pill, its text and its edge. + What is only an outline turns light at night, or it would vanish into the dark land and sea: the tubes' casing + (casing) and a puzzle's stepping-stone ring (via). */ +const MAP_PAL={ + light:{sea:'#62CBEA',sea2:'#43AED6',wave:'rgba(255,255,255,.45)',cloud:'rgba(255,255,255,.55)',shadow:'rgba(20,90,130,.35)',sand:'#F8E6A8',land:'#9BDA6C',hill:'#86CB5B',shine:'rgba(255,255,255,.18)',coast:'#1E2640', + pill:'#FFFFFF',pillInk:'#1E2640',pillEdge:'#1E2640',halo:'rgba(255,255,255,.85)',casing:'#1E2640',via:'rgba(30,38,64,.7)'}, + dark:{sea:'#173E5E',sea2:'#0B2440',wave:'rgba(160,210,255,.14)',cloud:'rgba(200,220,255,.1)',shadow:'rgba(0,0,0,.35)',sand:'#4E5440',land:'#2E5A3A',hill:'#284F31',shine:'rgba(255,255,255,.05)',coast:'#081020', + pill:'#1A2340',pillInk:'#E9EFFB',pillEdge:'#070B16',halo:'rgba(8,16,32,.85)',casing:'#A9B7D8',via:'rgba(233,239,251,.75)'}}; +const MPAL=()=>THEME.dark?MAP_PAL.dark:MAP_PAL.light; diff --git a/src/game/96-map/30-settings.js b/src/game/96-map/30-settings.js index fcc7dac..fdf4132 100644 --- a/src/game/96-map/30-settings.js +++ b/src/game/96-map/30-settings.js @@ -31,6 +31,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`
${tr('settings.display_and_sound')} + ${seg(tr('settings.theme'),'themeSet',THEME.pref,[['auto',tr('common.auto')],['light',tr('settings.light')],['dark',tr('settings.dark')]],tr('settings.auto_follows_your_device_s_light'))} ${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))} ${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))} ${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 288553c..b792d3b 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -43,7 +43,7 @@ function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='lin const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C); for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]mx)mx=q[0];}if(mx<-20||mn>CW+20)continue; if(!G&&(hot||!cached)){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,m[0],m[1]-8);} + if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,MPAL().halo,3,m[0],m[1]-8);} ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} diff --git a/src/game/96-map/57-webgl-background.js b/src/game/96-map/57-webgl-background.js index c245aee..c2a97de 100644 --- a/src/game/96-map/57-webgl-background.js +++ b/src/game/96-map/57-webgl-background.js @@ -2,8 +2,10 @@ the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry built once, so panning and zooming repaint nothing; only the waves and the clouds move. */ const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends -const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)'); -const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)'); +// The theme's colours (MPAL(), 15-palette.js) as the card takes them, worked out again only when the theme changes. +const GLP={m:null}; +function glPal(){const m=MPAL();if(GLP.m!==m)Object.assign(GLP,{m,seaTop:glPm(m.sea),seaBot:glPm(m.sea2),cloud:glPm(m.cloud),shadow:glPm(m.shadow),grass:glPm(m.land), + hill:glPm(m.hill),shine:glPm(m.shine),wave:glColor(m.wave),sand:glColor(m.sand),edge:glColor(m.coast),casing:glColor(m.casing)});return GLP;} // The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each // pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow). const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam; @@ -49,7 +51,7 @@ function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GL function coastFan(P,out){let a=0;const n=P.length;for(let i=0;i{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return; const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return; coastFan(P,fan); @@ -57,10 +59,14 @@ function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@' const s0=sand.length/LINE_STRIDE;for(let i=0;i+1new Float32Array(a); - G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE, - hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length}; + // The buffers are kept with the land, so a theme change can let them go (the coastlines' colours are in them). + const bufs=[],V=(sz,div,a)=>{const x=glVao(gl,sz,div,new Float32Array(a));bufs.push(x);return x.v;}; + G={fan:V([2],0,fan),nFan:fan.length/2,sand:V([4,4,4,4],1,sand),edge:V([4,4,4,4],1,edge),nSeg:sand.length/LINE_STRIDE, + hills:V([4],1,hills),shine:V([4],1,shine),nHill:HILLS.length,bufs}; glMem(gl,'the land');return GLX.land[key]=G;} +// A theme change (themeRepaint()): every level of the land is built again, in the new colours, when next drawn. +function glLandDrop(){const gl=GLX.gl,L=GLX.land;GLX.land={};if(!gl||!L)return; + try{if(gl.isContextLost())return;for(const G of Object.values(L))for(const x of G.bufs||[]){gl.deleteVertexArray(x.v);gl.deleteBuffer(x.b);}}catch(e){}} // Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map. // The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D // canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea. @@ -75,16 +81,15 @@ function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col); for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}} // In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline. -function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)); - glLandFill(gl,G,ks,5,7,LAND_SHADOW); +function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z)),P=glPal(); + glLandFill(gl,G,ks,5,7,P.shadow); glLines(gl,G.sand,G.nSeg,ks); - glLandFill(gl,G,ks,0,0,LAND_GRASS); - glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE); + glLandFill(gl,G,ks,0,0,P.grass); + glEllipses(gl,G.hills,G.nHill,ks,P.hill);glEllipses(gl,G.shine,G.nHill,ks,P.shine); glLines(gl,G.edge,G.nSeg,ks);} // The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are // written into the same array every frame (no garbage for the collector to pick up while you play). -const WAVE_COL=glColor('rgba(255,255,255,.45)'); -function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0; +function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900,WAVE_COL=glPal().wave;let m=0; for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3,m0=m; // Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame). for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y; @@ -100,7 +105,7 @@ function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)retu const F=A.subarray(0,n),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW); gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);gl.colorMask(false,false,false,false); gl.useProgram(P.p);gl.bindVertexArray(GLX.cl.v);gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,F.length/4); - gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,CLOUD_COL);gl.disable(gl.STENCIL_TEST);} + gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,glPal().cloud);gl.disable(gl.STENCIL_TEST);} // The cables, as drawCables() strokes them: rebuilt only when the highlighted city or the architect view changes. function glCables(gl,ks,selC,ar){const key=[selC,ar]; if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[]; @@ -119,7 +124,7 @@ function glBegin(now,ks){const gl=GLX.gl,c=GLX.c,f=GLX.f;glShow(true);GLS.frame= gl.viewport(0,0,c.width,c.height);gl.clearColor(0,0,0,0);gl.clearDepth(1);gl.clearStencil(0);gl.colorMask(true,true,true,true);gl.depthMask(true); gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT|gl.STENCIL_BUFFER_BIT); gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);gl.disable(gl.STENCIL_TEST); - glFill(gl,SEA_TOP,SEA_BOT); + const P=glPal();glFill(gl,P.seaTop,P.seaBot); glLand(gl,ks); glWaves(gl,now,ks); glClouds(gl,now,ks); diff --git a/src/game/96-map/58-webgl-links.js b/src/game/96-map/58-webgl-links.js index 04ec434..93c37a4 100644 --- a/src/game/96-map/58-webgl-links.js +++ b/src/game/96-map/58-webgl-links.js @@ -24,7 +24,7 @@ function glJoin(A,i0,i1,closed){closed=closed&&i1-i0>2; meet, their round ends overlap: each keeps only its side of the corner's bisector, so a see-through line (the halo, the cables, the waves, the fiber's dots) is blended once there, as the 2D canvas strokes a path once. */ const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;layout(location=3) in vec4 aN; -uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uBusy;uniform int uPass; +uniform vec2 uView;uniform vec3 uCam,uCas;uniform float uWMul,uDpr,uBusy;uniform int uPass; out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol,vK;flat out vec2 vDash,vEnd; // The corner's bisector between directions u and v, in the segment's own frame (t along it, n across), and whether there is one. vec3 cut(vec2 u,vec2 v,vec2 t,vec2 n){vec2 m=u+v;float l=length(m);if(length(u)<.5||length(v)<.5||l<1e-3)return vec3(0.);m/=l;return vec3(dot(t,m),dot(n,m),1.);} @@ -32,7 +32,7 @@ vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}., void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h; float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false; if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;} - else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);} + else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(uCas,1.);} else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;} else if(uPass==${LP.plain})col.a=aC.x; if(skip){gl_Position=vec4(2.,2.,2.,1.);return;} @@ -103,7 +103,9 @@ function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl; if(net)glBuild(ML.LG,ML.GM,ML.looks); if(net||GLX.key[1]!==selId){glHalo(ML.LG,ML.GM,ML.looks,selId);GLX.key=[ML,selId];} gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.depthMask(true); - const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + // The casing is the theme's (glPal()), a uniform: the tubes' buffers keep only their own colours. + const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),cas=glPal().casing,lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass); + gl.uniform3f(L.u.uCas,cas[0],cas[1],cas[2]); for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}; if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass); if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0); @@ -111,11 +113,11 @@ function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl; // The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D. if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);} gl.bindVertexArray(null);} -// The link being dragged out (x,y in CSS px): the dark dotted line, then the pink one running along it, over the tubes -// and, since the pictures are drawn after it, under the cities, as in 2D. -const DRAG_INK=glColor('#1E2640'),DRAG_PINK=glColor('#FF4F9A'); +// The link being dragged out (x,y in CSS px): the dotted line in the tubes' casing colour, then the pink one running +// along it, over the tubes and, since the pictures are drawn after it, under the cities, as in 2D. +const DRAG_PINK=glColor('#FF4F9A'); function glDrag(ax,ay,tx,ty,now){const gl=GLX.gl,A=GLX.da||(GLX.da=new Float32Array(2*LINE_STRIDE)),z=cam.z,mx=x=>(x-CW/2)/z+cam.x,my=y=>(y-CH/2)/z+cam.y; - glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,DRAG_INK); + glSegAt(A,0,mx(ax),my(ay),mx(tx),my(ty),0,7,7,LINE_ROUND,1,glPal().casing); glSegAt(A,1,mx(ax),my(ay),mx(tx),my(ty),-now/30/z,4,7,LINE_ROUND,1,DRAG_PINK); gl.bindBuffer(gl.ARRAY_BUFFER,GLX.dv.b);gl.bufferData(gl.ARRAY_BUFFER,A,gl.DYNAMIC_DRAW); gl.disable(gl.DEPTH_TEST);glLines(gl,GLX.dv.v,2,[0]);gl.bindVertexArray(null);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 4753041..721926a 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -16,21 +16,21 @@ function drawFrame(now){ // WebGL on: the sea, land, waves, clouds and cables are on the card (glBegin); the 2D canvas below them stays empty. // Off (2D chosen, no game, a puzzle, the card given up), its layers are hidden here, before anything can return early. if(G){try{glBegin(now,ks);}catch(e){throw glErr(e);}} - else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z); + else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z),mp=MPAL(); ctx.setTransform(DPR,0,0,DPR,0,0); // sea - const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH); + const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,mp.sea);g.addColorStop(1,mp.sea2);ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH); for(const k of ks){ ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2)); // waves: one path, one stroke - ctx.strokeStyle='rgba(255,255,255,.45)';ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath(); + ctx.strokeStyle=mp.wave;ctx.lineWidth=2/z;ctx.lineCap='round';ctx.beginPath(); const ph0=now/900;for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;ctx.moveTo(x-9+o,y);ctx.quadraticCurveTo(x-4.5+o,y-4,x+o,y);ctx.quadraticCurveTo(x+4.5+o,y+4,x+9+o,y);}ctx.stroke(); } for(const k of ks){if(wl)drawWorldLayer(wl,k,z,ks[0]);else{ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));paintWorld(ctx,z,false);}} for(const k of ks){ ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2)); // clouds - ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath(); + ctx.fillStyle=mp.cloud;ctx.beginPath(); for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill(); } } @@ -41,7 +41,7 @@ function drawFrame(now){ drawCables(ks); // links AR_PILLS.length=0; - const far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY; + const far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY,cas=MPAL().casing; // WebGL on: the card draws every line and packet now, and the rest (labels, markers, cities…) goes on the overlay. if(G)try{glFrame(ML,ks,far,busy,now,sc);}catch(e){throw glErr(e);} for(let gi=0;gi{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;ipolyAtXY(SX,SY,gm.cum,t); @@ -75,7 +75,7 @@ function drawFrame(now){ [mxx,my]=at(.5);} if(bld){if(far)stamp('bldfar',12,12,6,6,1,mxx,my,g=>{g.fillStyle='#FF8A3D';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,4,0,7);g.fill();g.stroke();});else drawCone(mxx,my,now);} else if(cut&&!vx){if(far)stamp('cutfar',14,14,7,7,1,mxx,my,g=>{g.fillStyle='#FF4D5E';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,5,0,7);g.fill();g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText('!',0,0.5);});else if(!arPz)drawBackhoe(mxx,my,now,l.sub);} - else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):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);pill(t,ctx.font,tw,17,8,'#fff','#1E2640','#1E2640',2,mxx,my-0.5,1.5);} + else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):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);const mp=MPAL();pill(t,ctx.font,tw,17,8,mp.pill,mp.pillInk,mp.pillEdge,2,mxx,my-0.5,1.5);} // Every puzzle: say whether the tubes between two cities share one trench or take separate paths. if(pz&&!cut&&!bld&&(many||arPaths(l)>1)&&(many||lineIdx(l,PI.get(edgeKey(l)))===0))AR_PILLS.push([mxx,my+(sel||!S.ar?19:0),many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:arPaths(l)}),many]); } @@ -88,7 +88,7 @@ function drawFrame(now){ if(UI.snap){const B=CITY[UI.snap.id];const wx=A.x+wrapDx(A.x,B.x);for(const k of [-1,1]){const [px,py]=toS(A.x,A.y,k),[qx]=toS(wx,B.y,k);if(Math.abs(qx-CW/2)c)c=p[0];if(p[1]>d)d=p[1];}return [a,b,c,d];} function drawCone(x,y,now){stamp('cone',26,28,13,13,1,x,y-12+Math.sin(now/300)*1.5,()=>{ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();});} // Static land + cable map, rendered once per zoom bucket into an offscreen canvas. -function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL; - for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();} - c.strokeStyle='#F8E6A8';c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} - c.fillStyle='#9BDA6C';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();} - c.fillStyle='#86CB5B';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill(); - c.fillStyle='rgba(255,255,255,.18)';c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill(); - c.strokeStyle='#1E2640';c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} +function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL,mp=MPAL(); + for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle=mp.shadow;for(const p of LANDP)c.fill(p);c.restore();} + c.strokeStyle=mp.sand;c.lineWidth=10/z;c.lineJoin='round';for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} + c.fillStyle=mp.land;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.fill(p);c.restore();} + c.fillStyle=mp.hill;c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x+r*1.4,y);c.ellipse(x,y,r*1.4,r*.8,0,0,Math.PI*2);}c.fill(); + c.fillStyle=mp.shine;c.beginPath();for(const [x,y,r] of HILLS){c.moveTo(x-r*.3+r*.6,y-r*.25);c.ellipse(x-r*.3,y-r*.25,r*.6,r*.3,0,0,Math.PI*2);}c.fill(); + c.strokeStyle=mp.coast;c.lineWidth=2.5/z;for(const o of [0,W,-W]){c.save();c.translate(o,0);for(const p of LANDP)c.stroke(p);c.restore();} if(withCables)for(const off of [0,W,-W]){c.save();c.translate(off,0);for(const cp of CABLE_PAIRS){const C=CAB[cp.cid];c.globalAlpha=0.4;c.strokeStyle=cableCol(C);c.lineWidth=1.6/z;c.lineJoin='round';c.setLineDash(C.age==='old'?[6/z,5/z]:[]);c.beginPath();c.moveTo(cp.pts[0][0],cp.pts[0][1]);for(let i=1;icityFarStatic(C,p,down,sel,hov,ph)); if(CM.dish&&CM.dish.has(C.id))dishBadge(sx+(p?10:6),sy+(p?6:5),CM.dish.get(C.id),CM.dl&&CM.dl[C.id]); 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; - pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);} + const mp=MPAL();pill(t,ctx.font,tw,16,8,p?'#FF4F9A':mp.pill,p?'#FFFFFF':mp.pillInk,mp.pillEdge,1.6,sx,ly,1);} } function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640'; if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-ph;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;ctx.strokeStyle='#1E2640';} @@ -141,7 +141,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){ // label if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){ ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=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; - pill(t,ctx.font,tw,19,9,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',2,sx,ly+0.5,0.5); + const mp=MPAL();pill(t,ctx.font,tw,19,9,p?'#FF4F9A':mp.pill,p?'#FFFFFF':mp.pillInk,mp.pillEdge,2,sx,ly+0.5,0.5); } } diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index a501622..e84d84a 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -7,7 +7,7 @@ function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; ctx.save();ctx.lineWidth=3; if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} - else{const a=animOn()?.55+.35*Math.sin(now/300):.8,gold=S.ar&&S.ar.gold.includes(v.C.id),dk=S.ar&&arDarkNow(v.C.id);ctx.strokeStyle=dk?`rgba(255,77,94,${a})`:gold?`rgba(224,160,0,${p?1:a})`:k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(gold||dk)ctx.lineWidth=5;if(k==='via')ctx.setLineDash([5,5]); + else{const a=animOn()?.55+.35*Math.sin(now/300):.8,gold=S.ar&&S.ar.gold.includes(v.C.id),dk=S.ar&&arDarkNow(v.C.id);ctx.strokeStyle=dk?`rgba(255,77,94,${a})`:gold?`rgba(224,160,0,${p?1:a})`:k==='goal'?`rgba(255,79,154,${p?1:a})`:MPAL().via;if(gold||dk)ctx.lineWidth=5;if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly,v.dem); const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx-r*.75,y-r*.75);}} // top left: the IX badge has the top right diff --git a/src/game/96-map/89-pie-globe.js b/src/game/96-map/89-pie-globe.js index 89fe3ed..c6abf57 100644 --- a/src/game/96-map/89-pie-globe.js +++ b/src/game/96-map/89-pie-globe.js @@ -13,7 +13,8 @@ const PG_ST={ const PG={cv:null,ctx:null,get:null,raf:0,last:0,t:0,yaw:-20,tilt:18,vy:0,drag:null,night:null,anim:true,dirty:true, data:null,dAt:-1e9,sig:'',sm:[],dish:[],fl:[],hi:null,pads:[],lch:[],fly:[],on:null,g:null,frames:0,m:new Float64Array(9)}; let PG_LAND=null,PG_LAND_DIR=null,PG_TURN=1,PG_GRID=null,PG_LIGHT=null,PG_STAR=null; -const pgNightPref=()=>{if(PG.night===null){try{PG.night=localStorage.getItem('sot-globe')==='night';}catch(e){PG.night=false;}}return PG.night;}; +// Day or night as the player last chose it; until then, as the theme (#80). +const pgNightPref=()=>{if(PG.night===null){try{const g=localStorage.getItem('sot-globe');PG.night=g?g==='night':THEME.dark;}catch(e){PG.night=THEME.dark;}}return PG.night;}; // Unit vectors for the land rings (LANDS_LL), the graticule, city lights and stars: worked out once, on first open. function pgUnit(lo,la,a,i){const b=la*PG_D,c=Math.cos(b),o=lo*PG_D;a[i]=c*Math.cos(o);a[i+1]=c*Math.sin(o);a[i+2]=Math.sin(b);} // One land ring, clipped to the near side (as map libraries clip). The coast runs to where it meets the horizon; from there the diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 88644c8..fc74819 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','mpDoor','mpBack','mpStart','mpJoin'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','themeSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','mpDoor','mpBack','mpStart','mpJoin'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/i18n/en.js b/src/i18n/en.js index ef47c7b..0c4838e 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4539,12 +4539,15 @@ "settings.always_2d":"Always 2D", "settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.", "settings.auto_draws_the_map_with_your":"Auto draws the map with your graphics card when the browser allows it, which keeps big networks smooth. Always 2D works everywhere but is slower on big maps.", +"settings.auto_follows_your_device_s_light":"Auto follows your device’s light or dark setting. Dark is easier on the eyes at night and saves battery on OLED screens.", "settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.", "settings.customers_and_alerts":"Customers and alerts", +"settings.dark":"Dark", "settings.diagnostic_info":"Diagnostic info", "settings.display_and_sound":"Display and sound", "settings.for_bug_reports_shows_your_screen":"For bug reports: shows in a corner your screen's size, how the map is drawn (graphics card or 2D, and why) and how fast.", "settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game", +"settings.light":"Light", "settings.map_drawing":"Map drawing", "settings.n_min":"{n} min", "settings.n_sec":"{n} s", @@ -4558,6 +4561,7 @@ "settings.the_agent_moves_it":"The agent moves it", "settings.the_clock_while_an_agent_plays":"The clock while an agent plays", "settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.", +"settings.theme":"Theme", "settings.this_browser_cannot_so_the_map":"This browser cannot, so the map is drawn in 2D.", "settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy", "settings.while_agent_mode_is_on_the":"While agent mode is on, the clock is not yours. With a pace it runs by itself and cannot be paused by hand, not even by an open window (yours included), and it waits while no agent is connected. Or the agent moves it, and nothing happens until it asks for days. The page connects to the local agent relay (npm run dev hosts one), so tools like the MCP server can drive this game while you watch.", diff --git a/src/index.html b/src/index.html index 87083cb..2f730a1 100644 --- a/src/index.html +++ b/src/index.html @@ -85,6 +85,15 @@ "author": { "@type": "Person", "name": "Frederic Jung", "url": "https://github.com/fjaeckel" } } + diff --git a/src/styles/00-base.css b/src/styles/00-base.css index dc23fc4..c13c729 100644 --- a/src/styles/00-base.css +++ b/src/styles/00-base.css @@ -1,7 +1,9 @@ -/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). Single committed bright look. */ +/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). + Two looks, light and dark (05-theme.css): --ink is the stickers' dark outline (and text on bright fills) in both, + --text the text on the panels. */ :root{ --sea:#57C4E5; --sea2:#3AA6CF; --wave:#9BE2F2; --land:#9BDA6C; --land2:#7FC455; --sand:#F8E6A8; - --ink:#1E2640; --ink2:#55608A; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; + --ink:#1E2640; --ink2:#55608A; --text:#1E2640; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; --me:#FF4F9A; --sun:#FFD23F; --ok:#22C47A; --warn:#FFAA1F; --bad:#FF4D5E; --t1:#7B61FF; --t2:#2F8CFF; --cdn:#FF8A3D; --eye:#16A866; --display:'Baloo 2','Trebuchet MS',system-ui,sans-serif; @@ -14,7 +16,7 @@ body{margin:0} .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .ver{font-size:11.5px;color:var(--ink2);margin-top:10px} .ver a{color:inherit} -body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} +body{background:var(--sea);color:var(--text);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} #map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab} #map.linking{cursor:crosshair} /* The WebGL tubes and the 2D overlay above them (58-webgl-links.js): pictures only, the map underneath takes the pointer. */ diff --git a/src/styles/05-theme.css b/src/styles/05-theme.css new file mode 100644 index 0000000..dce9763 --- /dev/null +++ b/src/styles/05-theme.css @@ -0,0 +1,23 @@ +/* Dark (#80): , set by the page's from Settings › Theme (93-ui/15-theme.js). The panels take + the night colours of the NOC window: dark paper, light text, the stickers' outlines darker still. Light tints (a goal + to work on, a toast, a pick) are written where they are used as var(--tint-…, light colour): only this look sets them. + Text on bright fills (yellow buttons, warning tags) stays dark ink in both looks. */ +:root[data-theme="dark"]{ + color-scheme:dark; + --sea:#0E2A44; --ink:#070B16; --ink2:#A9B7D8; --text:#E9EFFB; --paper:#1A2340; --soft:#232E50; --line:#364470; --eye:#2BC987; + --tint-y:#3B3418; --tint-g:#173B2C; --tint-r:#45212B; --tint-p:#43213D; --tint-b:#17324F; --tint-v:#2C2752; --tint-o:#42301A; + --tint-n:#252F4C; --tint-nl:var(--line); --tx-red:#FF8E9B; --tx-amber:#FFB65C; + scrollbar-color:#4A5B8E transparent; +} +/* The green of good news is lighter as text on dark paper; a tag keeps the deeper green under its white letters. */ +:root[data-theme="dark"] .tag.eye{background:#16A866} +/* A ghost button on dark paper: a shade lighter, so it still reads as a button. */ +:root[data-theme="dark"] .b.ghost,:root[data-theme="dark"] .x{background:var(--soft)} +/* The dropdowns' arrow is a picture: drawn again in the light text colour. */ +:root[data-theme="dark"] select.pick{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%23E9EFFB' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +/* Badge variants: the frost and the fire, at night. */ +:root[data-theme="dark"] .bdg.on.v-freeze{background:linear-gradient(160deg,#15344C,#0F4562);box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px var(--paper)} +:root[data-theme="dark"] .bdg.on.v-bgp{background:linear-gradient(160deg,#3E2A16,#55280F)} +:root[data-theme="dark"] .bdg.v-bgp .bv,:root[data-theme="dark"] .bdg.on.v-bgp .bv{color:#FF8A5C} +:root[data-theme="dark"] .bdg.v-freeze .bv{color:#7FD3F5} +:root[data-theme="dark"] .legend .lg:hover{background:rgba(233,239,251,.08)} diff --git a/src/styles/10-hud.css b/src/styles/10-hud.css index e00a535..2362dd3 100644 --- a/src/styles/10-hud.css +++ b/src/styles/10-hud.css @@ -16,7 +16,7 @@ #hNoc{position:relative}#hNoc .badge{position:absolute;top:-8px;right:-8px;background:var(--me);color:#fff;border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 6px;line-height:16px} .speed{flex-direction:row;align-items:center;gap:4px;padding:4px 6px} .speed button{border:2.5px solid var(--ink);background:var(--paper);border-radius:9px;min-width:34px;height:32px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13px} -.speed button.on{background:var(--sun)} +.speed button.on{background:var(--sun);color:var(--ink)} .spacer{flex:1} .noc{cursor:pointer;border:3px solid var(--ink)} .hotk{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 4px;border-radius:12px;border:2px solid var(--ink,#1E2640);font:900 11px Nunito,sans-serif;margin-right:8px;color:#fff;background:#FF4D5E} @@ -24,7 +24,7 @@ .noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite} .noc.hot .lbl{color:#FFE1E4} #hCust .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--bad);color:#fff;font-size:11px;line-height:18px;text-align:center;vertical-align:3px;margin-left:2px} -#hCust.hot{background:#FFE1E4} +#hCust.hot{background:var(--tint-r,#FFE1E4)} @keyframes throb{50%{transform:scale(1.05)}} .minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%} .minibar i{display:block;height:100%;background:var(--ok)} diff --git a/src/styles/20-drawers.css b/src/styles/20-drawers.css index 31fc819..a34dfd1 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -20,8 +20,8 @@ .x{margin-left:auto;border:2.5px solid var(--ink);background:var(--paper);border-radius:10px;width:32px;height:32px;font-size:20px;line-height:1;cursor:pointer;font-weight:900;flex:none} .facts{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} .fact{background:var(--soft);border:2px solid var(--ink);border-radius:9px;padding:1px 8px;font-size:12px;font-weight:700} -.fact.bad{background:#FFE3E3}.latwarn{background:#FFF1F1;border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} -.fact.ixf{background:#FFF3C4} +.fact.bad{background:var(--tint-r,#FFE3E3)}.latwarn{background:var(--tint-r,#FFF1F1);border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} +.fact.ixf{background:var(--tint-y,#FFF3C4)} .fact.mine{background:var(--me);color:#fff} .fact.down{background:var(--bad);color:#fff} section{padding:10px 0;border-bottom:2px dashed var(--line)} @@ -37,13 +37,13 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .row .nm{font-weight:800;font-size:13.5px;line-height:1.2} .row .meta{font-size:11.5px;color:var(--ink2);line-height:1.3} .btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px} -.why{font-size:11px;color:#B23A48;font-weight:700;margin-top:3px;line-height:1.3} +.why{font-size:11px;color:var(--tx-red,#B23A48);font-weight:700;margin-top:3px;line-height:1.3} -.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s} +.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s;color:var(--ink)} .b:hover{filter:brightness(1.05)} .b:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .b:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:0 3px 0 var(--ink)} -.b.ghost{background:var(--paper)} +.b.ghost{background:var(--paper);color:var(--text)} .b.pink{background:var(--me);color:#fff} .b.red{background:var(--bad);color:#fff} .b.green{background:var(--ok);color:#fff} @@ -52,14 +52,14 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px} .logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em} -.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:var(--ink2)} +.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:#55608A} .tag.t1{background:var(--t1)} .tag.t2{background:var(--t2)} .tag.cdn{background:var(--cdn)} .tag.eye{background:var(--eye)} .tag.open{background:var(--ok)} .tag.selective{background:var(--warn);color:var(--ink)} .tag.restrictive{background:var(--bad)} .tag.paid{background:var(--me)} -.tag.st{background:var(--paper);color:var(--ink)} +.tag.st{background:var(--paper);color:var(--text)} /* PNI list (#175): one status chip per network, a one-line value, folded groups. Chips wrap on narrow screens. */ .tag.worth{background:var(--warn);color:var(--ink)} .pchips{display:flex;flex-wrap:wrap;gap:4px;margin:3px 0} -.pchip{display:inline-block;max-width:100%;border:1.5px solid var(--ink);border-radius:999px;padding:0 7px;font-size:11px;font-weight:800;line-height:1.5;background:var(--paper);color:var(--ink);overflow-wrap:anywhere} +.pchip{display:inline-block;max-width:100%;border:1.5px solid var(--ink);border-radius:999px;padding:0 7px;font-size:11px;font-weight:800;line-height:1.5;background:var(--paper);color:var(--text);overflow-wrap:anywhere} .pchip.pk-here,.pchip.pk-else{background:var(--ok);color:#fff} .pchip.pk-ix{background:var(--t2);color:#fff} .pchip.pk-none{background:var(--bad);color:#fff} @@ -79,12 +79,12 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .goal .ck{width:22px;height:22px;border:2.5px solid var(--ink);border-radius:7px;flex:none;display:grid;place-items:center;font-weight:900;background:var(--paper);font-size:13px} .goal.done .ck{background:var(--ok);color:#fff} .goal.done .gt{text-decoration:line-through;color:var(--ink2)} -.goal.cur{background:#FFF6CF;margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} +.goal.cur{background:var(--tint-y,#FFF6CF);margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} .goal .gt{font-weight:900;font-size:13.5px} .goal .gd{font-size:12px;color:var(--ink2);line-height:1.4;margin-top:2px} .goal .gr{font-size:11px;font-weight:900;color:var(--eye);margin-top:2px} .empty{color:var(--ink2);font-size:12.5px;line-height:1.45;padding:6px 0} -.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:#FFF0F1} +.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:var(--tint-r,#FFF0F1)} .inc .nm{font-weight:900} .inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35} diff --git a/src/styles/30-toasts.css b/src/styles/30-toasts.css index 0086d63..c82aa74 100644 --- a/src/styles/30-toasts.css +++ b/src/styles/30-toasts.css @@ -1,15 +1,15 @@ /* toasts */ #toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 14px);display:flex;flex-direction:column-reverse;gap:8px;z-index:8;width:min(460px,calc(100% - 32px));pointer-events:none} .toast{pointer-events:none;background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:9px 12px;display:flex;gap:10px;align-items:center;animation:pop .25s cubic-bezier(.3,1.6,.6,1)} -.toast.good{background:#DFFBEA} .toast.bad{background:#FFE1E4} .toast.goal{background:#FFF3C4} +.toast.good{background:var(--tint-g,#DFFBEA)} .toast.bad{background:var(--tint-r,#FFE1E4)} .toast.goal{background:var(--tint-y,#FFF3C4)} .toast .b{pointer-events:auto} .seg{display:flex;flex-wrap:wrap;gap:6px} .seg .b{white-space:normal;text-align:left} /* A segmented control: one framed row of equal tabs, the active one filled like the HUD's speed buttons (Pie Control). */ .segc{display:flex;gap:3px;padding:3px;margin:6px 0 10px;border:3px solid var(--ink);border-radius:14px;background:var(--soft);box-shadow:3px 3px 0 var(--ink)} -.segc button{flex:1 1 0;min-width:0;min-height:40px;padding:3px 2px;border:2.5px solid transparent;border-radius:10px;background:none;color:var(--ink);font-family:var(--display);font-weight:800;font-size:min(13.5px,3.6vw);line-height:1.1;cursor:pointer;overflow-wrap:anywhere;hyphens:auto} +.segc button{flex:1 1 0;min-width:0;min-height:40px;padding:3px 2px;border:2.5px solid transparent;border-radius:10px;background:none;color:var(--text);font-family:var(--display);font-weight:800;font-size:min(13.5px,3.6vw);line-height:1.1;cursor:pointer;overflow-wrap:anywhere;hyphens:auto} .segc button:hover{background:var(--paper)} -.segc button.on{background:var(--sun);border-color:var(--ink)} +.segc button.on{background:var(--sun);border-color:var(--ink);color:var(--ink)} .segc button:focus-visible{outline:3px solid var(--me);outline-offset:1px} .toast .tx{flex:1;font-size:13px;line-height:1.35} .toast .tx b{font-family:var(--display);font-size:14.5px} diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css index e00dd87..94ba823 100644 --- a/src/styles/36-ops.css +++ b/src/styles/36-ops.css @@ -1,5 +1,5 @@ /* Standing orders: the intern's card in the NOC and the Ops sheet */ -.ops-card{border:2px solid #8E5CF7;background:#F7F2FF;border-radius:12px;padding:8px 10px;margin:8px 0} +.ops-card{border:2px solid #8E5CF7;background:var(--tint-v,#F7F2FF);border-radius:12px;padding:8px 10px;margin:8px 0} .ops-card .nm{font-weight:800} .ops-o{border:2px solid var(--line);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)} .ops-o.on{border-color:var(--ok)} @@ -12,10 +12,10 @@ .ops-p .b{white-space:normal;text-align:left;min-height:36px} /* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */ .ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} -.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--ink);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} +.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} .ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} .ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} -.ops-rep{border-left:3px solid #8E5CF7;background:#F7F2FF;border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere} +.ops-rep{border-left:3px solid #8E5CF7;background:var(--tint-v,#F7F2FF);border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere} .ops-rep .eyebrow{margin-bottom:2px} /* Pie Control's Company tab ends with the Founder's feed: a quiet section, older posts folded away. */ .pie-feed{border-top:2px solid var(--line);margin-top:12px;padding-top:4px} diff --git a/src/styles/38-pie-globe.css b/src/styles/38-pie-globe.css index 867140e..83ec44c 100644 --- a/src/styles/38-pie-globe.css +++ b/src/styles/38-pie-globe.css @@ -9,7 +9,7 @@ .pft-cr,.pft-d{margin:6px 0} .pft-cr .kv span,.pft-d .kv span{min-width:0;overflow-wrap:anywhere} .pft-list{display:flex;flex-direction:column;gap:6px} -.pft-row{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border:2px solid var(--line);border-radius:12px;background:var(--paper);color:var(--ink);font:inherit;text-align:left;cursor:pointer;box-sizing:border-box} +.pft-row{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border:2px solid var(--line);border-radius:12px;background:var(--paper);color:var(--text);font:inherit;text-align:left;cursor:pointer;box-sizing:border-box} .pft-row.on{border-color:var(--me);box-shadow:0 0 0 2px var(--me) inset} .pft-ic{font-size:20px;flex:none} .pft-m{flex:1;min-width:0;display:flex;flex-direction:column} diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 32acfbd..c07d336 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -2,13 +2,13 @@ .seg.site{margin-top:4px;align-items:center} .seg.site .meta{margin-right:4px} .badges{display:grid;grid-template-columns:repeat(auto-fill,minmax(118px,1fr));gap:6px} -.bdg{border:2px solid #C9CEDD;border-radius:12px;padding:6px 7px;background:#F3F4F8;opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} +.bdg{border:2px solid var(--tint-nl,#C9CEDD);border-radius:12px;padding:6px 7px;background:var(--tint-n,#F3F4F8);opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} .bdg .bi{font-size:20px;filter:grayscale(1)} -.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--ink)} +.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--text)} .bdg .br{font:900 10px Nunito,sans-serif;color:var(--rc);text-transform:uppercase;letter-spacing:.04em} -.bdg .bd{font-size:11px;color:#5A6280;line-height:1.25} +.bdg .bd{font-size:11px;color:var(--ink2);line-height:1.25} .bdg.ever{opacity:.85;border-style:dashed;border-color:var(--rc)} -.bdg.on{opacity:1;border-color:var(--rc);background:#fff;box-shadow:0 2px 0 var(--rc)} +.bdg.on{opacity:1;border-color:var(--rc);background:var(--paper);box-shadow:0 2px 0 var(--rc)} .bdg.on .bi,.bdg.ever .bi{filter:none} .bdg .bv{font:900 10px Nunito,sans-serif;letter-spacing:.02em} .bdg.on.v-freeze{background:linear-gradient(160deg,#F2FBFF,#D6F1FC);border-color:#5BC0EB;box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px #fff} @@ -17,19 +17,19 @@ .bdg.v-bgp .bv{color:#C8102E} .bdg.ever.v-freeze{border-color:#5BC0EB}.bdg.ever.v-bgp{border-color:#FF5A1F} .bshelf{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 8px} -.bsh{font:800 12px Nunito,sans-serif;border:2px solid #C9CEDD;border-radius:999px;padding:2px 9px;background:#fff;white-space:nowrap} +.bsh{font:800 12px Nunito,sans-serif;border:2px solid var(--tint-nl,#C9CEDD);border-radius:999px;padding:2px 9px;background:var(--paper);white-space:nowrap} .bsh.v-freeze{border-color:#5BC0EB}.bsh.v-oncall{border-color:#FFD23F}.bsh.v-bgp{border-color:#FF5A1F} .bsh.cur{box-shadow:0 2px 0 var(--ink)} .bvt.v-freeze{color:#2A8DB8;font-weight:900}.bvt.v-bgp{color:#FF5A1F;font-weight:900} -.scn{display:flex;gap:10px;align-items:center;border:2px solid #DDE1EC;border-radius:12px;padding:8px 10px;margin-top:8px} -.scn.wk{border-color:var(--me);background:#FFF0F6} +.scn{display:flex;gap:10px;align-items:center;border:2px solid var(--tint-nl,#DDE1EC);border-radius:12px;padding:8px 10px;margin-top:8px} +.scn.wk{border-color:var(--me);background:var(--tint-p,#FFF0F6)} .scn .nm{font-weight:900} .term{background:#1E2640;color:#7CFFB2;font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;padding:10px 12px;border-radius:10px;overflow-x:auto;white-space:pre;margin:8px 0} .trsel{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin-top:8px} .trsel label{display:flex;flex-direction:column;font:800 12px Nunito,sans-serif;gap:2px} .trsel select{font:700 14px Nunito,sans-serif;padding:4px 6px;border:2px solid var(--ink);border-radius:8px;max-width:240px} -.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:#fff} -#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:#fff;border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} +.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:var(--paper)} +#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} #coach .ct{flex:1;font-weight:800;font-size:14px;line-height:1.35} #coach .cs{display:block;font:900 10px Nunito,sans-serif;color:var(--me);text-transform:uppercase;letter-spacing:.05em} .coach-glow{animation:coachglow 1s ease-in-out infinite;position:relative;z-index:2} @@ -43,13 +43,13 @@ .btns.tcta .b{margin:0;display:flex;align-items:center;justify-content:center;text-align:center;line-height:1.15;white-space:normal;hyphens:auto;-webkit-hyphens:auto;min-height:40px;padding:4px 6px;font-size:14px} .btns.tcta .b.big{grid-column:1/-1;font-size:18px;padding:7px 18px 5px} /* Dropdowns that look like the game's buttons. 16px text: iOS zooms into anything smaller when it is tapped. */ -select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--ink);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} +select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--text);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} select.pick:focus-visible{outline:3px solid #FF4F9A;outline-offset:2px} label.f+select.pick{width:100%} .thb{font:inherit;font-weight:900;background:none;border:0;padding:0;cursor:pointer;color:inherit} -.ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:#FFF6EC;border-radius:6px} -.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:#fff}.ibx .nm{font-weight:800} -.aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:#F3ECFF;border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--ink)} +.ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:var(--tint-o,#FFF6EC);border-radius:6px} +.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)}.ibx .nm{font-weight:800} +.aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:var(--tint-v,#F3ECFF);border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--text)} .tehelp h3{margin:14px 0 4px}.tehelp ul{margin:4px 0;padding-left:18px}.tehelp li{margin:4px 0;font-size:13.5px;line-height:1.4}.tehelp dt{margin-top:8px}.tehelp dd{margin:2px 0 0;font-size:13px;line-height:1.4;color:var(--ink2)}.tehelp code{font:600 12.5px ui-monospace,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border-radius:6px;padding:1px 6px;word-break:break-word} .terec{display:flex;align-items:center;gap:10px;justify-content:space-between;border-top:2px dashed var(--line,#DDE3EE);padding:8px 0}.terec .btn{flex:none} .tecode{width:100%;box-sizing:border-box;font:600 13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border:3px solid var(--ink);border-radius:10px;padding:10px;margin-top:8px;resize:vertical;tab-size:2} @@ -79,7 +79,7 @@ label.f+select.pick{width:100%} .loan{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px;display:flex;gap:10px;align-items:flex-start} .loan .grow{flex:1;min-width:0} .loan .terms{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0} -.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun)} +.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun);color:var(--ink)} #dash{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:15;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))} #dashCard{max-width:980px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)} .dgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:10px 0} @@ -110,18 +110,18 @@ label.f+select.pick{width:100%} .title-art h1 span{color:var(--me)} .tagline{color:var(--ink2);font-size:14.5px;line-height:1.45;margin:10px 0 14px} label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px} -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);color:var(--ink);-webkit-text-fill-color:var(--ink)} +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);color:var(--text);-webkit-text-fill-color:var(--text)} .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .network-name{flex-wrap:nowrap}.nmwrap{position:relative;flex:1 1 auto;min-width:0}.nmwrap input.t{width:100%;padding-right:44px;font-size:16px} .reroll{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:32px;height:32px;border-radius:50%;border:2px solid var(--ink);background:#22C47A;color:#fff;font:900 18px/1 var(--display);cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.reroll:active{transform:translateY(-50%) rotate(-90deg)} -.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:92px;font-size:15px;padding:8px 6px}.asnwrap input.t::placeholder{color:var(--ink2);opacity:.7}.asnwrap input.t.bad{border-color:#E03A3A;background:#FFE8E8} +.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:92px;font-size:15px;padding:8px 6px}.asnwrap input.t::placeholder{color:var(--ink2);opacity:.7}.asnwrap input.t.bad{border-color:#E03A3A;background:var(--tint-r,#FFE8E8)} .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} +.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(--text);text-decoration:none} +.plug:hover{background:var(--tint-y,#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}.starts .start:last-child:nth-child(odd){grid-column:1/-1} .start{border:3px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--paper);cursor:pointer;text-align:left;box-shadow:0 3px 0 var(--ink)} .starts.one{grid-template-columns:1fr} -.start.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 3px 0 var(--me)} +.start.on{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 3px 0 var(--me)} .start b{font-family:var(--display);font-size:17px;display:block} .start span{font-size:12px;color:var(--ink2);line-height:1.3;display:block} /* Home cities: compact tiles stacked in one column, the dropdown for any other city last. */ @@ -132,13 +132,13 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .door i,.preset i,.chs i{font-style:normal;font-size:26px;line-height:1.1} .door b,.preset b,.chs b{font-family:var(--display);font-size:18px;line-height:1.1} .door span,.preset span,.chs span{font-size:12.5px;color:var(--ink2);line-height:1.3} -.door.on,.preset.on,.chs.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.door.on,.preset.on,.chs.on{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 4px 0 var(--me)} .door.on::after,.preset.on::after,.chs.on::after{content:"✓";position:absolute;top:6px;right:9px;font:900 15px var(--display);color:var(--me)} .door[data-door=puzzle],.door[data-door=scn]{background:var(--soft)} .presets{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px} .preset small{font-size:11px;color:var(--ink2);line-height:1.3;margin-top:4px;border-top:2px dashed var(--line);padding-top:4px} -.preset[data-preset=bgp].on{background:#FFE9D6;border-color:#FF6A2B;box-shadow:0 4px 0 #FF6A2B}.preset[data-preset=bgp].on::after{color:#FF6A2B} -.preset[data-preset=freeze].on{background:#E2F5FF;border-color:var(--sea2);box-shadow:0 4px 0 var(--sea2)}.preset[data-preset=freeze].on::after{color:var(--sea2)} +.preset[data-preset=bgp].on{background:var(--tint-o,#FFE9D6);border-color:#FF6A2B;box-shadow:0 4px 0 #FF6A2B}.preset[data-preset=bgp].on::after{color:#FF6A2B} +.preset[data-preset=freeze].on{background:var(--tint-b,#E2F5FF);border-color:var(--sea2);box-shadow:0 4px 0 var(--sea2)}.preset[data-preset=freeze].on::after{color:var(--sea2)} .chaos{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px} .chs{padding:7px 8px 6px}.chs i{font-size:20px}.chs b{font-size:15px}.chs span{font-size:11px} .lockn{margin:8px 0 0} @@ -152,7 +152,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .setline select.pick{min-height:36px;padding:4px 30px 4px 10px;border-width:2px;border-radius:10px;box-shadow:0 2px 0 var(--ink);background-position:right 9px center} .tiers{display:grid;gap:7px;margin-top:10px} .tierbtn{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:13px;padding:8px 12px;background:var(--paper);cursor:pointer;box-shadow:0 3px 0 var(--ink);text-align:left} -.tierbtn:hover{background:#FFF6CF} +.tierbtn:hover{background:var(--tint-y,#FFF6CF)} .tierbtn:disabled{opacity:.4;cursor:not-allowed} .tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px} .tierbtn .grow{flex:1} @@ -169,7 +169,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .slots{display:flex;flex-direction:column;gap:7px;margin-bottom:6px;max-height:min(46vh,330px);overflow:auto;padding:2px 2px 5px} .slot{display:flex;align-items:stretch;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);flex:none;transition:transform .08s ease,box-shadow .08s ease} .slot:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)} -.slot.top{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.slot.top{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 4px 0 var(--me)} .slot.busy{background:var(--soft);border-style:dashed} .slot.broken{opacity:.75;border-style:dashed} .slot-go{flex:1;min-width:0;display:flex;align-items:center;gap:10px;background:none;border:0;padding:8px 6px 8px 11px;font:inherit;color:inherit;text-align:left;cursor:pointer;min-height:52px} @@ -181,7 +181,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .slot.busy .tag{color:var(--ink2)} .slot .sm{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right} .slot .sm em{font:800 15px var(--display);font-style:normal} -.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--ink);cursor:pointer;border-radius:0 13px 13px 0} +.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--text);cursor:pointer;border-radius:0 13px 13px 0} .slot-more:hover,.slot-go:hover{background:rgba(255,79,154,.06)} .slot-go:focus-visible,.slot-more:focus-visible{outline:3px solid #FF4F9A;outline-offset:-3px} .ibx.space{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ibx.space .btns{margin:0} @@ -194,21 +194,21 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .tcont .b{white-space:normal;max-width:100%;overflow-wrap:anywhere;line-height:1.15} #modalCard{overflow-x:hidden} .menu-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:10px} -.mtile{border:3px solid var(--ink);border-radius:14px;background:var(--paper);box-shadow:0 3px 0 var(--ink);padding:8px 4px 7px;display:flex;flex-direction:column;align-items:center;gap:2px;cursor:pointer;font:800 13px/1.15 var(--display);color:var(--ink);text-align:center;min-height:68px;justify-content:center} +.mtile{border:3px solid var(--ink);border-radius:14px;background:var(--paper);box-shadow:0 3px 0 var(--ink);padding:8px 4px 7px;display:flex;flex-direction:column;align-items:center;gap:2px;cursor:pointer;font:800 13px/1.15 var(--display);color:var(--text);text-align:center;min-height:68px;justify-content:center} .mtile i{font-style:normal;font-size:22px;line-height:1}.mtile:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .menu-links{margin:12px 0 0;text-align:center;line-height:2;color:var(--ink2)} .menu-links .lnk{background:none;border:0;padding:4px 2px;font-weight:700;font-size:14px;font-family:inherit;color:var(--ink2);text-decoration:underline;text-underline-offset:3px;cursor:pointer} .menu-plugs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:12px} -.mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--ink);text-decoration:none;background:var(--soft);display:flex;align-items:center} +.mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--text);text-decoration:none;background:var(--soft);display:flex;align-items:center} /* Find a city: big tap targets, the first result (what Enter picks) highlighted. */ .findlist{margin-top:8px} -.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--ink);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} +.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--text);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} .findrow .nm,.findrow .meta{display:block} .findrow.on{background:var(--soft);border-radius:10px} .findrow:hover{background:var(--soft)} /* The charter picker (36-specialist.js): three big choices, one tap each, nothing else to close it with. */ .chpick h2{margin:2px 0 4px}.chpick .tagline{margin:0 0 6px} -.chopt{display:flex;align-items:flex-start;gap:12px;width:100%;margin-top:8px;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;background:var(--paper);box-shadow:0 3px 0 var(--ink);font:inherit;color:var(--ink);text-align:left;cursor:pointer} +.chopt{display:flex;align-items:flex-start;gap:12px;width:100%;margin-top:8px;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;background:var(--paper);box-shadow:0 3px 0 var(--ink);font:inherit;color:var(--text);text-align:left;cursor:pointer} .chopt:hover,.chopt:focus-visible{background:var(--soft)}.chopt:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .chi{font-size:28px;line-height:1.1;flex:none}.cht{display:flex;flex-direction:column;gap:2px;min-width:0} .cht b{font:800 17px/1.2 var(--display)}.cht span{font-size:13px;line-height:1.35;color:var(--ink2)} diff --git a/src/styles/41-multiplayer.css b/src/styles/41-multiplayer.css index ccd50e6..2552670 100644 --- a/src/styles/41-multiplayer.css +++ b/src/styles/41-multiplayer.css @@ -12,7 +12,7 @@ .mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px} .mpfeed{max-height:220px;overflow:auto;margin-top:6px} .mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0} -.mprow.me{border-color:var(--me);background:#FFF2F8} +.mprow.me{border-color:var(--me);background:var(--tint-p,#FFF2F8)} .mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere} .mprow b{font-family:var(--display);font-size:15px} .mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto} @@ -27,7 +27,7 @@ /* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step: where you stand shows as a badge on the menu button, which also opens the session. */ #hud .menubtn{position:relative} -.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--ink);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} +.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--text);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} #hud.fit3 .mpchip{display:none !important} #hud.fit3 .mpbadge{display:block} @media (max-width:760px){ diff --git a/src/styles/42-chart-tooltips.css b/src/styles/42-chart-tooltips.css index 34334c6..99b2712 100644 --- a/src/styles/42-chart-tooltips.css +++ b/src/styles/42-chart-tooltips.css @@ -8,7 +8,9 @@ .chtip div span{margin-left:auto;padding-left:10px;font-variant-numeric:tabular-nums} .chtip i{width:9px;height:9px;border-radius:3px;border:1px solid #fff} .chtip .tot{border-top:1px solid rgba(255,255,255,.35);margin-top:4px;padding-top:3px} -.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--ink)} +.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--text)} +/* The charts' grid and axis labels follow the theme (their attributes give the light look's colours). */ +.chart line{stroke:var(--line)}.chart text{fill:var(--ink2)} .mix[data-mix]{cursor:help} .nw-chart[data-ch]{touch-action:pan-y;cursor:crosshair} .noc-window .chtip{border:1px solid #3A4A78} diff --git a/src/styles/45-noc-window.css b/src/styles/45-noc-window.css index e215a87..03d3330 100644 --- a/src/styles/45-noc-window.css +++ b/src/styles/45-noc-window.css @@ -75,7 +75,7 @@ body.noc-window [data-act="dashClose"]{display:none} .nw-bar{height:7px;border-radius:9px;background:#26324F;overflow:hidden;margin:3px 0} .nw-bar i{display:block;height:100%;border-radius:9px} .nw-pc{font-family:var(--display);font-size:16px;min-width:42px;text-align:right} -.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;color:#1E2640} +.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;--soft:#EEF5FB;--text:#1E2640;color:#1E2640} .nw-btns .meta{color:#9FB0D3} .nw-row{display:flex;align-items:center;gap:8px;padding:4px 0} .nw-row .nw-pm{flex:1} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index 8e28606..9cfe4ce 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -3,15 +3,15 @@ (play, speed, goals, deals, NOC, networks), and bottom sheets you drag up, down or away. */ html,body{overscroll-behavior:none} .dtabs{position:sticky;top:-12px;z-index:3;display:flex;gap:6px;overflow-x:auto;margin:10px -4px 4px;padding:8px 4px;background:var(--paper);border-bottom:2.5px solid var(--ink);scrollbar-width:none} -.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:#fff;padding:5px 12px;cursor:pointer;color:var(--ink)} +.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:var(--paper);padding:5px 12px;cursor:pointer;color:var(--text)} .dtabs button.on{background:var(--pink,#FF4F9A);color:#fff} .dtabs .cnt{display:inline-block;margin-left:5px;min-width:16px;padding:0 4px;border-radius:8px;background:var(--bad);color:#fff;font-size:10.5px;line-height:16px;text-align:center} -.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:#FFF6CF} +.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:var(--tint-y,#FFF6CF)} .pcard .pt{font-weight:900;font-size:15px;margin:1px 0 2px}.pcard .kv{margin-top:5px}.pcard .bar{margin-top:2px} -.pcard.lv{background:#EAF6FF} -.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:#FFF4D6;border:2px solid var(--ink);border-radius:10px;padding:6px 8px} +.pcard.lv{background:var(--tint-b,#EAF6FF)} +.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:var(--tint-y,#FFF4D6);border:2px solid var(--ink);border-radius:10px;padding:6px 8px} .isteps{padding-left:22px;margin:8px 0 4px}.isteps li{margin:5px 0;line-height:1.38;font-size:14px}.isteps svg{vertical-align:-3px} -.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:#FFF4D6} +.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--tint-y,#FFF4D6)} /* iPhone home-screen app with a viewport shorter than the screen: the page box takes the real screen height and becomes the containing block for everything fixed, so bottom-anchored UI reaches the bottom. */ html.iosfix,html.iosfix body{height:var(--app-h)} @@ -29,10 +29,10 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #leftToggle{display:none !important} #tabbar{display:flex;position:fixed;left:0;right:0;bottom:0;z-index:9;height:var(--tabbar);padding:6px max(6px,env(safe-area-inset-right,0px)) env(safe-area-inset-bottom,0px) max(6px,env(safe-area-inset-left,0px));background:var(--paper);border-top:3px solid var(--ink);box-sizing:border-box;gap:2px;align-items:stretch} #tabbar button{flex:1 1 0;min-width:0;border:0;background:transparent;border-radius:12px;font:inherit;font-weight:900;font-size:10.5px;color:var(--ink2);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;padding:2px 0;position:relative} - #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--ink)} - #tabbar button.on{background:var(--soft);color:var(--ink)} + #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--text)} + #tabbar button.on{background:var(--soft);color:var(--text)} #tabbar button.play .ic{font-size:21px} - #tabbar button.play.paused{background:#FFE3F0} + #tabbar button.play.paused{background:var(--tint-p,#FFE3F0)} #tabbar .cnt{position:absolute;top:2px;right:calc(50% - 22px);min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:var(--me);color:#fff;font-size:10px;line-height:16px;box-sizing:border-box} #tabbar .cnt.red{background:var(--bad)} #tabbar .cnt.dot{min-width:0;width:10px;height:10px;padding:0;top:6px;right:calc(50% - 16px)} @@ -85,7 +85,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar } /* Installed as an app: no browser chrome, so leave room for the notch and the home indicator. */ @media (display-mode: standalone){ - body{background:#57C4E5} + body{background:var(--sea)} } /* Whatever the language, the HUD stays on one row: fitHud() drops chips until it fits. */ #hud.fit1 .hide-md2,#hud.fit2 .hide-md{display:none !important} diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index ace2ce8..16ae092 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -4,20 +4,20 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB #pzBox .pzh{display:flex;align-items:center;gap:8px}#pzBox h3{font-size:19px} .pzj{margin:4px 0 6px;font-size:12.5px;color:var(--ink2);line-height:1.35} .pzs{display:flex;gap:6px;margin:6px 0}.pzs span{flex:1;display:flex;flex-direction:column;align-items:center;border:2.5px solid var(--ink);border-radius:11px;padding:3px 0;font-size:20px;filter:grayscale(1);opacity:.45;transition:transform .25s,opacity .25s} -.pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:#FFF3C4;transform:scale(1.05)} -.pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:#fff} +.pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:var(--tint-y,#FFF3C4);transform:scale(1.05)} +.pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:var(--paper)} .pzc i{font-style:normal} -.pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} +.pzc.s1{background:var(--tint-p,#FFE3F0)}.pzc.s2{background:var(--ok);color:#fff} .pzsrc{font-size:12px;font-weight:800;color:var(--ink2);margin:4px 0} .pzfl{margin:4px 0 6px}.pzf{margin:4px 0;padding:3px 6px;border:2px solid var(--line);border-radius:10px}.pzf.ok{border-color:var(--ok)} .pzf .kv{font-size:12px;gap:6px}.pzf .bar{margin:2px 0}.pzf .meta .bad{color:var(--bad);font-weight:900}.pzf .seg.pzrt{margin-top:3px} -.pzpair{border-top:2px dashed var(--line);padding-top:4px;margin-top:4px}.pzhave{font-size:13px;font-weight:800;margin:6px 0;padding:4px 8px;border-radius:10px;background:#FFF4D6} -.pznote{font-weight:800;font-size:13.5px;margin:8px 0;padding:8px 10px;border:2.5px solid var(--ink);border-radius:12px;background:#FFF3C4} -.row.on{background:#FFE3F0;border-radius:10px} +.pzpair{border-top:2px dashed var(--line);padding-top:4px;margin-top:4px}.pzhave{font-size:13px;font-weight:800;margin:6px 0;padding:4px 8px;border-radius:10px;background:var(--tint-y,#FFF4D6)} +.pznote{font-weight:800;font-size:13.5px;margin:8px 0;padding:8px 10px;border:2.5px solid var(--ink);border-radius:12px;background:var(--tint-y,#FFF3C4)} +.row.on{background:var(--tint-p,#FFE3F0);border-radius:10px} .pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} .pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} .pzn1{font-size:12.5px;font-weight:800;margin:6px 0;padding:4px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} -.pzn1.on{border-color:var(--ok);background:#DFFBEA;color:var(--ink);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} +.pzn1.on{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} @keyframes pzglow{50%{box-shadow:0 0 0 4px rgba(34,196,122,.25)}} #pzBox .btns{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} #pzBox .grab{display:none} @@ -30,9 +30,9 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzgi{width:24px;flex:none;text-align:center;font-size:16px}.pzgi i{font-style:normal;display:inline-block;width:20px;height:20px;border:2px solid var(--line);border-radius:50%;font:900 11px/16px var(--body);color:var(--ink2);box-sizing:border-box} .pzgv{font-size:12.5px;font-weight:800;color:var(--ink2);white-space:nowrap} .pzgoal.done b{font-weight:700;color:var(--ink2)}.pzgoal:not(.done):not(.cur){opacity:.6} -.pzgoal.cur{background:#FFF4D6;border:2px solid var(--warn);border-radius:12px;padding:6px 8px;margin:3px 0} +.pzgoal.cur{background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px;padding:6px 8px;margin:3px 0} .pzgh{font-size:13px;line-height:1.4;margin:3px 0 1px 32px}#pzBox .pzgh .pzshow{margin:2px 0 0 2px;padding:2px 10px;min-height:0;vertical-align:middle} -.pzchips{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0}.pzchip{font-size:12px;font-weight:800;border:2px solid var(--ok);border-radius:999px;padding:1px 9px;background:#fff;white-space:nowrap}.pzchip b{font-weight:900} +.pzchips{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0}.pzchip{font-size:12px;font-weight:800;border:2px solid var(--ok);border-radius:999px;padding:1px 9px;background:var(--paper);white-space:nowrap}.pzchip b{font-weight:900} .pzprog{margin:6px 0 4px}.pzpack{font-size:17px;margin:14px 0 2px}.pzst{font-size:12px;letter-spacing:-1px;white-space:nowrap} .scn.lock{opacity:.5} .pzres{position:relative}.pzstars{display:flex;justify-content:center;gap:10px;margin:10px 0 2px} @@ -61,20 +61,20 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzd-nm{flex:1 1 auto;min-width:0;font:800 15px/1.2 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .pzd-stars{display:flex;gap:2px;flex:none} .pzd-st{display:inline-grid;place-items:center;width:22px;height:22px;border:2px solid var(--line);border-radius:50%;font:900 11px var(--body);color:var(--ink2);box-sizing:border-box} - .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} + .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} .pzd-bud{flex:none;font-weight:900;font-size:12.5px;font-variant-numeric:tabular-nums;white-space:nowrap}.pzd-bud.bad{color:var(--bad)} #pzBox.dock .pzd-bar .b.sm{min-width:36px;min-height:36px;padding:2px 8px;font-size:16px} - .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:#FFF4D6;border:2px solid var(--warn);border-radius:12px} - .pzd-goal.done{background:#DFFBEA;border-color:var(--ok)}.pzd-goal.bad{background:#FFE6E9;border-color:var(--bad)} + .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px} + .pzd-goal.done{background:var(--tint-g,#DFFBEA);border-color:var(--ok)}.pzd-goal.bad{background:var(--tint-r,#FFE6E9);border-color:var(--bad)} #pzBox.dock .arsteps{margin:6px 0 4px}#pzBox.dock .arsteps i{height:6px}#pzBox.dock .arbrief{font-size:13px;margin:0 0 2px} #pzBox.dock .arsites{display:contents}#pzBox.dock .arsite{font-size:12px;padding:2px 8px} body.pz.sheet-open #pzBox.dock .arbrief,body.pz.sheet-open #pzBox.dock .arsteps{display:none} .pzd-goal{flex-wrap:wrap}.pzd-gi{flex:none;font-size:16px}.pzd-gt{flex:1 1 170px;min-width:0;font-size:13px;line-height:1.3}.pzd-gt b{font-weight:800} .pzd-ga{flex:none;display:flex;flex-direction:column;gap:4px}#pzBox.dock .pzd-ga{margin-left:auto}#pzBox.dock .pzd-ga .b{min-height:32px;padding:2px 10px;font-size:13px;white-space:nowrap} .pzd-chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px} - .pzd-chip{font:800 12px/1.2 var(--body);color:var(--ink);background:#fff;border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} + .pzd-chip{font:800 12px/1.2 var(--body);color:var(--text);background:var(--paper);border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} .pzd-chip b{font-weight:900;font-variant-numeric:tabular-nums}.pzd-chip .bad{color:var(--bad)} - .pzd-chip.ok{border-color:var(--ok);background:#DFFBEA}.pzd-chip.part{border-color:var(--warn);background:#FFF4D6}.pzd-chip.none{border-color:var(--bad);background:#FFE6E9} + .pzd-chip.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA)}.pzd-chip.part{border-color:var(--warn);background:var(--tint-y,#FFF4D6)}.pzd-chip.none{border-color:var(--bad);background:var(--tint-r,#FFE6E9)} .pzd-chip.rule{cursor:default;color:var(--ink2)} /* The card: as tall as its tab, under the bar at most; tabs keep each part short enough to need no scrolling. */ body.pz #panel{max-height:calc(100% - var(--pzdock,60px) - 18px - env(safe-area-inset-top,0px)) !important} @@ -85,14 +85,14 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzd-body{padding:0 14px calc(10px + env(safe-area-inset-bottom,0px))} .pzd-tabs{display:flex;gap:4px;margin:6px 0 8px;border-bottom:2px solid var(--line)} .pzd-tabs button{flex:1;font:800 13px var(--body);color:var(--ink2);background:none;border:0;border-bottom:3px solid transparent;margin-bottom:-2px;padding:6px 2px;min-height:36px} - .pzd-tabs button.on{color:var(--ink);border-bottom-color:var(--me)} - .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:#FFE3F0;border-radius:8px} + .pzd-tabs button.on{color:var(--text);border-bottom-color:var(--me)} + .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:var(--tint-p,#FFE3F0);border-radius:8px} .pzd-to{flex-wrap:wrap}.pzd-foot{justify-content:flex-end} .pzd-models{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:5px;margin-top:6px} - .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--ink);background:#fff;border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} + .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--text);background:var(--paper);border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} .pzd-mh{display:flex;gap:6px;width:100%;align-items:baseline}.pzd-mh b{flex:1 1 auto;min-width:0;font-size:12.5px;font-weight:900;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.pzd-mh span{flex:none;font-weight:900;font-size:12.5px} .pzd-model small{font-size:11px;color:var(--ink2);line-height:1.25;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} - .pzd-model.on{background:#FFE3F0;border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} + .pzd-model.on{background:var(--tint-p,#FFE3F0);border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} .pzd-rt{margin:6px 0 0}.pzd-rt .b{min-height:34px} .pzd-tiers{display:grid;grid-template-columns:1fr 1fr;gap:6px}.pzd-tiers .b{margin:0;display:flex;flex-direction:column;align-items:center;gap:0;white-space:normal;line-height:1.15;padding:4px 6px}.pzd-tiers .b small{font-size:11px} /* What a routing metric does, and the redundancy check's question, are on the desktop card; here the buttons speak. */ @@ -110,4 +110,4 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pznew{display:inline-block;font:900 10.5px/1.2 var(--body);font-style:normal;text-transform:uppercase;letter-spacing:.04em;background:var(--me);color:#fff;border:2px solid var(--ink);border-radius:999px;padding:1px 7px;white-space:nowrap;vertical-align:1px} .door .pznew{position:absolute;top:-9px;right:8px;transform:rotate(4deg);animation:pznew 2.4s ease-in-out infinite} @keyframes pznew{50%{transform:rotate(-3deg) scale(1.08)}} -.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--ink)} +.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--text)} diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css index e4f6d62..627673c 100644 --- a/src/styles/71-architect.css +++ b/src/styles/71-architect.css @@ -1,18 +1,18 @@ /* Architect runs (prototype): the brief, its sites, the review line */ -.arsteps{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:#fff} +.arsteps{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:var(--paper)} .arsteps i.done{background:var(--ok)}.arsteps i.on{background:#FFD23F} .arbrief{margin:2px 0 8px;font-size:14.5px;font-weight:800;line-height:1.35} .arsites{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0 6px} -.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:#fff;color:var(--ink2)} -.arsite.ok{border-color:var(--ok);color:var(--ink)}.arsite.gold{border-color:#E5484D;background:#FFE8E8} -.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--ink)}.arline.bad{color:var(--bad)} +.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:var(--paper);color:var(--ink2)} +.arsite.ok{border-color:var(--ok);color:var(--text)}.arsite.gold{border-color:#E5484D;background:var(--tint-r,#FFE8E8)} +.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--text)}.arline.bad{color:var(--bad)} .arshape{font-size:12.5px;font-weight:900;margin:4px 0} .arrev{font-size:12.5px;font-weight:800;margin:6px 0;padding:5px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} -.arrev.on{border-color:#FF8A3D;background:#FFF0E3;color:var(--ink)}.arrev.ok{border-color:var(--ok);background:#DFFBEA;color:var(--ink)} -.arrev.bad{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} +.arrev.on{border-color:#FF8A3D;background:var(--tint-o,#FFF0E3);color:var(--text)}.arrev.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text)} +.arrev.bad{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} #pzBox .arbtns .b.big{flex:1 1 100%} .artubes{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:800;margin:4px 0}.artubes b{font-size:15px;letter-spacing:2px;color:var(--me)} -.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:#B86A00}.artubes.over b{color:#B86A00} +.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:var(--tx-amber,#B86A00)}.artubes.over b{color:var(--tx-amber,#B86A00)} /* Laptops and up: a bigger card, easier to read at a glance */ @media (min-width:761px) and (min-height:501px){ #pzBox.ar{width:390px;padding:14px 18px 16px} @@ -24,4 +24,4 @@ #pzBox.ar .artubes b{font-size:19px}#pzBox.ar .pzbud .bar{height:12px} #pzBox.ar .arbtns .b.sm{font-size:13px;padding:5px 11px} } -.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} +.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} diff --git a/tests/build.test.js b/tests/build.test.js index 4b3b2c4..cbc6d78 100644 --- a/tests/build.test.js +++ b/tests/build.test.js @@ -52,7 +52,7 @@ test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at for (const dev of [false, true]) { const { html, map } = assemble({ dev }); assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})'); - assert.equal([...new JSDOM(html).window.document.scripts].filter((s) => !s.attributes.length).length, 2, 'the language loader and the game: one inline game script'); + assert.equal([...new JSDOM(html).window.document.scripts].filter((s) => !s.attributes.length).length, 3, 'the theme, the language loader and the game: one inline game script'); assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial'); } }); diff --git a/tests/dark-mode.test.js b/tests/dark-mode.test.js new file mode 100644 index 0000000..59b7d41 --- /dev/null +++ b/tests/dark-mode.test.js @@ -0,0 +1,380 @@ +// Dark mode (#80): Settings › Theme is Auto (the device's light or dark setting), Light or Dark, a choice kept on the +// device (localStorage sot-theme), never in the save. The page's sets before the first paint; +// the panels follow through CSS custom properties, and the map paints its sea, land, clouds and labels in the night +// colours in both renderers, painting its cached layers again once when the theme changes (not on every frame). +// jsdom has no matchMedia: the tests lend the page one, before it is parsed (the harness's browser hook) or after. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); +const { load, browser, flush } = require('./harness'); +const { assemble } = require('../scripts/lib/page'); + +// A device setting the test can flip: matchMedia('(prefers-color-scheme: dark)') with change listeners. +const device = (dark) => { + const q = { matches: dark, media: '(prefers-color-scheme: dark)', fns: [], + addEventListener(t, f) { if (t === 'change') this.fns.push(f); }, removeEventListener(t, f) { this.fns = this.fns.filter((x) => x !== f); }, + set(v) { this.matches = v; for (const f of this.fns.slice()) f({ matches: v }); } }; + return { q, attach(w) { w.matchMedia = (m) => (/prefers-color-scheme:\s*dark/.test(m) ? q : { matches: false, addEventListener() {}, removeEventListener() {} }); } }; +}; +const meta = (doc, n) => doc.querySelector(`meta[name="${n}"]`).getAttribute('content'); +// WCAG contrast between two #RRGGBB colours. +const lum = (h) => { h = h.replace('#', ''); const c = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)); return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; }; +const cr = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); }; +// Only the page's , up to its styles, as the browser runs it before the first paint: the game script at the end +// of (which sets the theme as well, but late) is not there. ls: what window.localStorage gives, or throws. +const headOnly = (dark, ls) => { + const html = assemble().html, head = html.slice(0, html.indexOf('')); + const block = (sel) => { const i = css.indexOf(sel + '{'); assert.ok(i >= 0, sel); return css.slice(i, css.indexOf('}', i)); }; + const dark = block(':root[data-theme="dark"]'), light = block(':root'); + const val = (b, k) => { const m = new RegExp(`--${k}:\\s*([^;\\n]+);`).exec(b); return m && m[1].trim(); }; + // Every var(--tint-…, light) and var(--tx-…, light) in the styles and the game's own markup has a dark value. + const src = css + fs.readdirSync(path.join(__dirname, '..', 'src', 'game'), { recursive: true }).filter((f) => f.endsWith('.js')).map((f) => fs.readFileSync(path.join(__dirname, '..', 'src', 'game', f), 'utf8')).join('\n'); + const used = new Set([...src.matchAll(/var\(--((?:tint|tx)-[a-z]+),\s*#[0-9A-Fa-f]{3,6}\)/g)].map((m) => m[1])); + assert.ok(used.size >= 8, `tints in use (${[...used]})`); + for (const k of used) assert.ok(val(dark, k), `--${k} has a dark value`); + // Every plain var(--x) in the styles is defined for the light look (dark only overrides). + for (const m of css.matchAll(/var\(--([a-z0-9-]+)\)/g)) if (!/^(tabbar|app-h|c|rc|d|x|t|r|dl|pzdock)$/.test(m[1])) assert.ok(val(light, m[1]), `--${m[1]} is defined`); + const bgs = ['paper', 'soft', 'tint-y', 'tint-g', 'tint-r', 'tint-p', 'tint-b', 'tint-v', 'tint-o', 'tint-n'].map((k) => [k, val(dark, k)]); + for (const t of ['text', 'ink2', 'eye']) for (const [k, b] of bgs) assert.ok(cr(val(dark, t), b) >= 4.5, `--${t} on --${k}: ${cr(val(dark, t), b).toFixed(2)}`); + for (const t of ['tx-red', 'tx-amber']) assert.ok(cr(val(dark, t), val(dark, 'paper')) >= 4.5, `--${t} on the dark paper`); + // The outline stays dark in both looks, so text on bright fills (yellow buttons, warning tags) keeps reading. + assert.ok(cr(val(dark, 'ink'), '#FFD23F') >= 7, 'dark ink on the yellow buttons'); + // Badge labels (10px, so 4.5:1) on their night cards: each variant's gradient, and the dimmed card of one not earned now. + const rules = css.replace(/\/\*[\s\S]*?\*\//g, '').split('}').map((r) => { const i = r.indexOf('{'); return i < 0 ? null : { sel: r.slice(0, i).split(',').map((x) => x.trim()), body: r.slice(i + 1) }; }).filter(Boolean); + const decl = (sel, prop) => { let v = null; for (const r of rules) if (r.sel.includes(sel)) { const m = new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`).exec(r.body); if (m) v = m[1].trim(); } return v; }; + const D = ':root[data-theme="dark"] '; + for (const v of ['freeze', 'bgp']) { + const label = decl(D + `.bdg.v-${v} .bv`, 'color') || decl(`.bdg.v-${v} .bv`, 'color'), stops = decl(D + `.bdg.on.v-${v}`, 'background').match(/#[0-9A-Fa-f]{6}/g); + assert.ok(label && stops.length >= 2, v); + for (const b of [...stops, val(dark, 'tint-n')]) assert.ok(cr(label, b) >= 4.5, `the ${v} badge label ${label} on ${b}: ${cr(label, b).toFixed(2)}`); + } + // The dashboard's Demand key is an outline in its line's colour (--text): dark ink by day as before, light at night. + assert.equal(val(light, 'text'), val(light, 'ink'), 'by day the key looks as it always did'); + assert.ok(cr(val(dark, 'text'), val(dark, 'paper')) >= 3, 'at night the key\'s outline shows on the card'); +}); + +test('the dashboard\'s Demand key matches its dashed line, by night too', () => { + const { dom, ev, errors } = load({ storage: { 'sot-theme': 'dark' } }); + ev(started + "for(let i=0;i<3;i++)dayTick();ACT.dash({});"); + const card = dom.window.document.getElementById('dashCard'); + const line = card.querySelector('svg path[stroke-dasharray="5 4"]'); + assert.ok(line, 'the dashed Demand line'); + const stroke = /stroke:\s*([^;"]+)/.exec(line.getAttribute('style'))[1].trim(); + const key = [...card.querySelectorAll('.legend .lg')].find((b) => JSON.parse(b.dataset.args).k === 'dem').querySelector('i'); + assert.equal(key.style.borderStyle, 'dashed'); + assert.equal(key.style.borderColor, stroke, 'the key is outlined in the line\'s own colour'); + assert.equal(stroke, 'var(--text)'); + assert.deepEqual(errors, []); + dom.window.close(); +}); From eac06043002ad9f41515fe84c682b36883cf86b3 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:04:00 +0100 Subject: [PATCH 5/8] IPv4 address space: scarce, bought, leased, leased out; IPv6 is free (#150) A rule (ip4), on in On-call and BGP at 3 a.m., off in the gentler presets, sandbox and puzzles; scenarios only when they opt in. You start with a /21 from the registry, sized so the early game never notices (a gameplay-rules F1 test plays six start cities for 50 days). Business customers need a block by kind and size; broadband homes take what is left and the rest go behind CGNAT, which costs a box per home and annoys some customers. An offer that does not fit cannot be signed and says why, and a customer that cannot grow at renewal stays its size. The bank's Address space section buys and sells blocks on a transfer market with a gentle trend, leases blocks in, and leases spare blocks out for monthly income, in real CIDR sizes (/24 to /16), at most 256 blocks (what a save keeps). Old saves get what they already use, plus room, so nothing changes on load. The dashboard's AS box now lists the blocks you announce. --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 1 + scripts/lib/fuzz-page.js | 5 +- scripts/lib/route-fuzz.js | 2 + site/i18n/de.js | 48 ++ site/i18n/es.js | 48 ++ site/i18n/fr.js | 48 ++ site/i18n/it.js | 48 ++ site/i18n/pt.js | 48 ++ src/agent/10-domains.js | 3 + src/agent/20-commands.js | 21 +- src/agent/30-docs.js | 3 +- src/game/40-progress/30-rules.js | 15 +- src/game/60-features/33-address-space.js | 89 ++++ src/game/60-features/38-sales-desk.js | 4 +- src/game/60-features/39-sales-auto.js | 2 +- src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/30-compute.js | 3 +- src/game/80-simulation/50-sanitize.js | 1 + .../80-simulation/75-customer-lifecycle.js | 14 +- src/game/88-days/10-day-tick.js | 1 + src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/54-address-space.js | 29 ++ src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 2 +- src/game/94-dashboard/60-dashboard.js | 4 +- src/game/94-dashboard/70-bank.js | 2 +- src/game/94-dashboard/72-address-space.js | 22 + src/game/95-modals/40-title.js | 2 +- src/i18n/en.js | 48 ++ tests/address-space.test.js | 442 ++++++++++++++++++ tests/gameplay-rules.test.js | 20 +- tests/mcp-commands.test.js | 2 +- tests/sales-desk.test.js | 2 + 34 files changed, 957 insertions(+), 32 deletions(-) create mode 100644 src/game/60-features/33-address-space.js create mode 100644 src/game/90-actions/54-address-space.js create mode 100644 src/game/94-dashboard/72-address-space.js create mode 100644 tests/address-space.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 294d399..6f149f4 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -46,7 +46,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | | M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. | -| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4 and CGNAT (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | | M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | | M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | | M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). | @@ -64,7 +64,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | -| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. | +| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. | | F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | | F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | | F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | diff --git a/CHANGELOG.md b/CHANGELOG.md index e349380..e5f8d8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. +- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). ## [3.0.0] — 2026-11-06 diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 5b05a14..61f7ce9 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -185,5 +185,8 @@ return { a, b, c }; }; const acts = () => Object.keys(ACT); - window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen }; + // Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls + // it only while the base has no such rule, so the pages play the same game until it lands. + const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } }; + window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen, noIp4 }; })(); diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index dfca595..580dcac 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -95,6 +95,8 @@ function playGame(pages, seed, opts = {}) { preset: kind === 'sandbox' ? r.pick(['none', 'calm', 'normal', 'spicy']) : r.pick(PRESETS), id: kind === 'scenario' ? r.pick(L.scn) : kind === 'puzzle' ? r.pick(L.pz) : kind === 'architect' ? r.pick(L.ar) : undefined }; const [s0, s1] = both('start', st); + // A base without scarce IPv4 (#150) plays the classic game: both pages switch the rule off. Once it is on main, both play it. + if (!base.call('acts').includes('ip4Buy')) both('noIp4'); same('start', s0, s1); note('start ' + JSON.stringify(st)); // A normal game signs its charter first: a popup on newer pages (which seeded pages skip), a card on older ones. Both diff --git a/site/i18n/de.js b/site/i18n/de.js index 405ba56..a152ee3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2640,6 +2640,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gefallen.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gestiegen.", "interface.you_bought_out_bank_they_flew":"Du hast {bank} ausbezahlt.
Sie sind weitergeflogen, um ein anderes Startup zu finden.", +"ip4.block_size":"Blockgröße", +"ip4.blocks":"Deine Blöcke", +"ip4.bought":"Einen {p}-Block ({n} Adressen) für {price} gekauft.", +"ip4.bought_on":"Gekauft {date}", +"ip4.business":"Von Geschäftskunden genutzt", +"ip4.buy":"Kaufen {price}", +"ip4.cgnat_boxes":"CGNAT-Boxen", +"ip4.cgnat_note":"Mehr Haushalte pro Adresse macht Platz für Kunden, aber Spiele und Portweiterleitungen leiden: {p} der Rechnung eines CGNAT-Haushalts gehen als Erstattung zurück.", +"ip4.cgnat_ratio":"CGNAT: Haushalte pro Adresse", +"ip4.costs_row":"IPv4-Mieten und CGNAT", +"ip4.free":"Frei für neue Kunden (Haushalte kommen zuerst hinter CGNAT)", +"ip4.from_rir":"Von der RIR", +"ip4.give_back":"Zurückgeben", +"ip4.held":"Die RIR überträgt diesen Block erst ab {date} wieder.", +"ip4.homes":"Breitband-Haushalte", +"ip4.homes_cgnat":"{n}, davon {p} hinter CGNAT", +"ip4.in_use":"Deine Kunden brauchen diese Adressen: steck mehr Haushalte hinter CGNAT oder hol dir erst einen weiteren Block.", +"ip4.lease":"Mieten {price}/Monat", +"ip4.lease_out":"Vermieten +{price}/Monat", +"ip4.leased_in":"Einen {p}-Block ({n} Adressen) für {price}/Monat gemietet.", +"ip4.leased_in_mo":"Gemietet · {price}/Monat", +"ip4.leased_out":"Dein {p}-Block ist vermietet: +{price}/Monat.", +"ip4.leased_out_mo":"Vermietet · +{price}/Monat", +"ip4.leases_in":"Gemietete Blöcke", +"ip4.leases_out":"Vermietete Blöcke", +"ip4.market":"Transfermarkt", +"ip4.market_note":"IPv4 kostet etwa {px} pro Adresse (große Blöcke etwas weniger), zur Miete {lin} pro Adresse und Monat, und vermietet bringt es nach dem Anteil des Brokers {lout}. Ein Verkauf bringt {p} des Preises, und ein Block darf erst zwei Jahre nach seinem letzten Transfer wieder übertragen werden.", +"ip4.movable_from":"wieder übertragbar ab {date}", +"ip4.n_addresses":{"one":"{n} Adresse","other":"{n} Adressen"}, +"ip4.n_homes_per_address":{"one":"{n} Haushalt pro Adresse","other":"{n} Haushalte pro Adresse"}, +"ip4.no_grow":"{name} ({city}) wollte auf {bw} wachsen, aber du hattest keine freien IPv4-Adressen dafür.", +"ip4.no_space":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder steck mehr Haushalte hinter CGNAT.", +"ip4.note":"IPv6 ist kostenlos und unendlich. IPv4 ist seit Jahren aus: Geschäftskunden brauchen öffentliche Blöcke davon, und Haushalte, die nicht mehr reinpassen, teilen sich Adressen hinter CGNAT (IPv6-Traffic läuft an der Box vorbei).", +"ip4.off":"Nach den Regeln dieses Spiels gibt es IPv4 reichlich.", +"ip4.offer_needs":"Braucht einen IPv4-Block {p} ({n} Adressen); nur {free} frei.", +"ip4.preset_plenty":"IPv4 gibt es reichlich für alle.", +"ip4.preset_scarce":"IPv4 ist knapp: kaufen, mieten oder hinter CGNAT teilen.", +"ip4.really_sell":"Wirklich für {price} verkaufen?", +"ip4.refunds":"Erstattungen an genervte Gamer", +"ip4.section":"Adressraum", +"ip4.sell":"Verkaufen {price}", +"ip4.sold":"Dein {p}-Block ist für {price} verkauft.", +"ip4.squeezed":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Haushalten pro Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.", +"ip4.take_back":"Zurückholen", +"ip4.toast_cgnat":"Dein IPv4 ist voll. {p} deiner Haushalte teilen sich jetzt Adressen hinter CGNAT, und ein paar Gamer haben schon geschrieben.", +"ip4.toast_out":"IPv4 ist aus. Selbst bei {r} Haushalten pro Adresse passt nicht jeder hinter CGNAT: kauf oder miete einen Block bei der Bank.", +"ip4.too_many":"Du hast {n} IPv4-Blöcke, mehr kann ein Netz nicht führen. Verkauf kleine Blöcke oder gib sie zurück, um Platz für einen größeren zu schaffen.", +"ip4.yours":"Deine IPv4-Adressen", "ix_downgrade.pni_downgraded":"Das PNI mit {net} in {city} ist jetzt {port}.", "ix_downgrade.port_downgraded_at_ix":"Der Port bei {ix} ist jetzt {port}.", "ix_downgrade.transit_downgraded":"{net}-Transit in {city} ist jetzt {port}.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 427ba64..1f8b28a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin bajó un {p} % de camino a tu cuenta.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin subió un {p} % de camino a tu cuenta.", "interface.you_bought_out_bank_they_flew":"Compraste {bank}.
Se fueron volando a buscar otra startup.", +"ip4.block_size":"Tamaño del bloque", +"ip4.blocks":"Tus bloques", +"ip4.bought":"Has comprado un {p} ({n} direcciones) por {price}.", +"ip4.bought_on":"Comprado el {date}", +"ip4.business":"Usadas por clientes empresariales", +"ip4.buy":"Comprar {price}", +"ip4.cgnat_boxes":"Equipos CGNAT", +"ip4.cgnat_note":"Más hogares por dirección liberan espacio para clientes, pero los juegos y el port forwarding sufren: el {p} de la factura de un hogar con CGNAT se devuelve en reembolsos.", +"ip4.cgnat_ratio":"CGNAT: hogares por dirección", +"ip4.costs_row":"Alquiler de IPv4 y CGNAT", +"ip4.free":"Libres para nuevos clientes (los hogares pasan antes a CGNAT)", +"ip4.from_rir":"Del RIR", +"ip4.give_back":"Devolver", +"ip4.held":"El RIR no volverá a transferir ese bloque antes del {date}.", +"ip4.homes":"Hogares con banda ancha", +"ip4.homes_cgnat":"{n}, {p} detrás de CGNAT", +"ip4.in_use":"Tus clientes necesitan esas direcciones: pon más hogares detrás de CGNAT o consigue antes otro bloque.", +"ip4.lease":"Alquilar {price}/mes", +"ip4.lease_out":"Ceder en alquiler +{price}/mes", +"ip4.leased_in":"Has alquilado un {p} ({n} direcciones) por {price}/mes.", +"ip4.leased_in_mo":"Alquilado · {price}/mes", +"ip4.leased_out":"Tu {p} está cedido en alquiler: +{price}/mes.", +"ip4.leased_out_mo":"Cedido en alquiler · +{price}/mes", +"ip4.leases_in":"Bloques alquilados", +"ip4.leases_out":"Bloques cedidos en alquiler", +"ip4.market":"Mercado de transferencias", +"ip4.market_note":"IPv4 se vende a unos {px} por dirección (los bloques grandes, algo menos), se alquila a {lin} por dirección al mes y, cedido en alquiler, rinde {lout} tras la comisión del bróker. Una venta paga el {p} del precio, y un bloque solo puede volver a transferirse dos años después de su último traspaso.", +"ip4.movable_from":"transferible desde el {date}", +"ip4.n_addresses":{"one":"{n} dirección","other":"{n} direcciones"}, +"ip4.n_homes_per_address":{"one":"{n} hogar por dirección","other":"{n} hogares por dirección"}, +"ip4.no_grow":"{name} ({city}) quería crecer a {bw}, pero no tenías direcciones IPv4 libres para ello.", +"ip4.no_space":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares detrás de CGNAT.", +"ip4.note":"IPv6 es gratis e infinito. IPv4 se agotó hace años: los clientes empresariales necesitan bloques públicos, y los hogares que no caben comparten direcciones detrás de CGNAT (el tráfico IPv6 rodea la caja).", +"ip4.off":"Con las reglas de esta partida sobra IPv4.", +"ip4.offer_needs":"Necesita un {p} de IPv4 ({n} direcciones); solo hay {free} libres.", +"ip4.preset_plenty":"IPv4 de sobra para todos.", +"ip4.preset_scarce":"IPv4 escasea: cómpralo, alquílalo o compártelo detrás de CGNAT.", +"ip4.really_sell":"¿Vender de verdad por {price}?", +"ip4.refunds":"Reembolsos a gamers enfadados", +"ip4.section":"Espacio de direcciones", +"ip4.sell":"Vender {price}", +"ip4.sold":"Has vendido tu {p} por {price}.", +"ip4.squeezed":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares por dirección. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.", +"ip4.take_back":"Recuperar", +"ip4.toast_cgnat":"Tu IPv4 está lleno. El {p} de tus hogares comparte ahora direcciones detrás de CGNAT, y algunos gamers ya han escrito.", +"ip4.toast_out":"Sin IPv4. Ni con {r} hogares por dirección cabe todo el mundo en el CGNAT: compra o alquila un bloque en el banco.", +"ip4.too_many":"Tienes {n} bloques IPv4, el máximo que puede llevar una red. Vende o devuelve bloques pequeños para hacer sitio a uno más grande.", +"ip4.yours":"Tus direcciones IPv4", "ix_downgrade.pni_downgraded":"El PNI con {net} en {city} ahora es {port}.", "ix_downgrade.port_downgraded_at_ix":"El puerto en {ix} es ahora de {port}.", "ix_downgrade.transit_downgraded":"El tránsito de {net} en {city} ahora es {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 2a134ae..7729036 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"Le TubeCoin a perdu {p} % en route vers ton compte.", "interface.tubecoin_moved_up_p_on_the":"Le TubeCoin a pris {p} % en route vers ton compte.", "interface.you_bought_out_bank_they_flew":"Tu as racheté la part de {bank}.
Ils se sont envolés à la recherche d’une autre startup.", +"ip4.block_size":"Taille du bloc", +"ip4.blocks":"Tes blocs", +"ip4.bought":"Tu as acheté un {p} ({n} adresses) pour {price}.", +"ip4.bought_on":"Acheté le {date}", +"ip4.business":"Utilisées par les clients pros", +"ip4.buy":"Acheter {price}", +"ip4.cgnat_boxes":"Boîtiers CGNAT", +"ip4.cgnat_note":"Plus de foyers par adresse libère de la place pour les clients, mais les jeux et la redirection de ports en pâtissent : {p} de la facture d’un foyer derrière le CGNAT repart en remboursements.", +"ip4.cgnat_ratio":"CGNAT : foyers par adresse", +"ip4.costs_row":"Locations IPv4 et CGNAT", +"ip4.free":"Libres pour de nouveaux clients (les foyers passent d’abord derrière le CGNAT)", +"ip4.from_rir":"Attribué par le RIR", +"ip4.give_back":"Le rendre", +"ip4.held":"Le RIR ne transférera pas ce bloc avant le {date}.", +"ip4.homes":"Foyers en haut débit", +"ip4.homes_cgnat":"{n}, dont {p} derrière le CGNAT", +"ip4.in_use":"Tes clients ont besoin de ces adresses : mets plus de foyers derrière le CGNAT ou trouve d’abord un autre bloc.", +"ip4.lease":"Louer {price}/mois", +"ip4.lease_out":"Mettre en location +{price}/mois", +"ip4.leased_in":"Tu as loué un {p} ({n} adresses) pour {price}/mois.", +"ip4.leased_in_mo":"Loué · {price}/mois", +"ip4.leased_out":"Ton {p} est en location : +{price}/mois.", +"ip4.leased_out_mo":"Mis en location · +{price}/mois", +"ip4.leases_in":"Blocs loués", +"ip4.leases_out":"Blocs mis en location", +"ip4.market":"Marché des transferts", +"ip4.market_note":"L’IPv4 se vend environ {px} l’adresse (un peu moins pour les gros blocs), se loue {lin} l’adresse par mois et, mis en location, rapporte {lout} après la part du courtier. Une vente rapporte {p} du prix, et un bloc ne peut être transféré à nouveau que deux ans après son dernier transfert.", +"ip4.movable_from":"transférable à partir du {date}", +"ip4.n_addresses":{"one":"{n} adresse","other":"{n} adresses"}, +"ip4.n_homes_per_address":{"one":"{n} foyer par adresse","other":"{n} foyers par adresse"}, +"ip4.no_grow":"{name} ({city}) voulait passer à {bw}, mais tu n’avais pas d’adresses IPv4 libres pour ça.", +"ip4.no_space":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers derrière le CGNAT.", +"ip4.note":"L’IPv6 est gratuit et sans fin. L’IPv4 est épuisé depuis des années : les clients pros ont besoin de blocs publics, et les foyers qui ne rentrent plus partagent des adresses derrière le CGNAT (le trafic IPv6 contourne la boîte).", +"ip4.off":"Avec les règles de cette partie, l’IPv4 ne manque pas.", +"ip4.offer_needs":"Il lui faut un {p} d’IPv4 ({n} adresses) ; seulement {free} libres.", +"ip4.preset_plenty":"De l’IPv4 à volonté pour tout le monde.", +"ip4.preset_scarce":"L’IPv4 est rare : achète-le, loue-le ou partage-le derrière le CGNAT.", +"ip4.really_sell":"Vraiment vendre pour {price} ?", +"ip4.refunds":"Remboursements aux gamers grincheux", +"ip4.section":"Espace d’adressage", +"ip4.sell":"Vendre {price}", +"ip4.sold":"Ton {p} est vendu pour {price}.", +"ip4.squeezed":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers par adresse. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.", +"ip4.take_back":"Le reprendre", +"ip4.toast_cgnat":"Ton IPv4 est plein. {p} de tes foyers partagent maintenant des adresses derrière le CGNAT, et quelques gamers ont déjà écrit.", +"ip4.toast_out":"Plus d’IPv4. Même à {r} foyers par adresse, le CGNAT ne suffit pas pour tout le monde : achète ou loue un bloc à la banque.", +"ip4.too_many":"Tu as {n} blocs IPv4, le maximum qu’un réseau peut garder. Vends ou rends de petits blocs pour faire de la place à un plus grand.", +"ip4.yours":"Tes adresses IPv4", "ix_downgrade.pni_downgraded":"Le PNI avec {net} à {city} est maintenant en {port}.", "ix_downgrade.port_downgraded_at_ix":"Le port chez {ix} est maintenant en {port}.", "ix_downgrade.transit_downgraded":"Le transit {net} à {city} est maintenant en {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 2d75e8e..cc61779 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin è sceso del {p}% mentre arrivava sul tuo conto.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin è salito del {p}% mentre arrivava sul tuo conto.", "interface.you_bought_out_bank_they_flew":"Hai liquidato {bank}.
Sono volati via in cerca di un’altra startup.", +"ip4.block_size":"Dimensione del blocco", +"ip4.blocks":"I tuoi blocchi", +"ip4.bought":"Comprato un {p} ({n} indirizzi) per {price}.", +"ip4.bought_on":"Comprato il {date}", +"ip4.business":"Usati dai clienti business", +"ip4.buy":"Compra {price}", +"ip4.cgnat_boxes":"Apparati CGNAT", +"ip4.cgnat_note":"Più case per indirizzo liberano spazio per i clienti, ma giochi e port forwarding ne soffrono: il {p} della bolletta di una casa dietro il CGNAT torna indietro in rimborsi.", +"ip4.cgnat_ratio":"CGNAT: case per indirizzo", +"ip4.costs_row":"Affitti IPv4 e CGNAT", +"ip4.free":"Liberi per nuovi clienti (prima le case passano dietro il CGNAT)", +"ip4.from_rir":"Dal RIR", +"ip4.give_back":"Restituiscilo", +"ip4.held":"Il RIR non trasferisce di nuovo quel blocco prima del {date}.", +"ip4.homes":"Case in banda larga", +"ip4.homes_cgnat":"{n}, il {p} dietro il CGNAT", +"ip4.in_use":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case dietro il CGNAT o prendi prima un altro blocco.", +"ip4.lease":"Affitta {price}/mese", +"ip4.lease_out":"Dai in affitto +{price}/mese", +"ip4.leased_in":"Preso in affitto un {p} ({n} indirizzi) per {price}/mese.", +"ip4.leased_in_mo":"In affitto · {price}/mese", +"ip4.leased_out":"Il tuo {p} è dato in affitto: +{price}/mese.", +"ip4.leased_out_mo":"Dato in affitto · +{price}/mese", +"ip4.leases_in":"Blocchi presi in affitto", +"ip4.leases_out":"Blocchi dati in affitto", +"ip4.market":"Mercato dei trasferimenti", +"ip4.market_note":"IPv4 costa circa {px} a indirizzo (i blocchi grandi un po' meno), in affitto {lin} a indirizzo al mese, e dato in affitto rende {lout} dopo la quota del broker. Una vendita paga il {p} del prezzo, e un blocco si può trasferire di nuovo solo due anni dopo l'ultimo trasferimento.", +"ip4.movable_from":"trasferibile dal {date}", +"ip4.n_addresses":{"one":"{n} indirizzo","other":"{n} indirizzi"}, +"ip4.n_homes_per_address":{"one":"{n} casa per indirizzo","other":"{n} case per indirizzo"}, +"ip4.no_grow":"{name} ({city}) voleva crescere a {bw}, ma non avevi indirizzi IPv4 liberi per farlo.", +"ip4.no_space":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case dietro il CGNAT.", +"ip4.note":"IPv6 è gratis e infinito. IPv4 è finito anni fa: i clienti business hanno bisogno di blocchi pubblici, e le case che non ci stanno condividono gli indirizzi dietro il CGNAT (il traffico IPv6 gli passa accanto).", +"ip4.off":"Con le regole di questa partita l'IPv4 abbonda.", +"ip4.offer_needs":"Serve un {p} di IPv4 ({n} indirizzi); solo {free} liberi.", +"ip4.preset_plenty":"IPv4 in abbondanza per tutti.", +"ip4.preset_scarce":"IPv4 scarseggia: compralo, affittalo o condividilo dietro il CGNAT.", +"ip4.really_sell":"Vendere davvero per {price}?", +"ip4.refunds":"Rimborsi ai gamer arrabbiati", +"ip4.section":"Spazio di indirizzi", +"ip4.sell":"Vendi {price}", +"ip4.sold":"Venduto il tuo {p} per {price}.", +"ip4.squeezed":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case per indirizzo. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.", +"ip4.take_back":"Riprendilo", +"ip4.toast_cgnat":"Il tuo IPv4 è pieno. Il {p} delle tue case ora condivide gli indirizzi dietro il CGNAT, e qualche gamer ha già scritto.", +"ip4.toast_out":"IPv4 esaurito. Nemmeno con {r} case per indirizzo il CGNAT basta per tutti: compra o affitta un blocco in banca.", +"ip4.too_many":"Hai {n} blocchi IPv4, il massimo che una rete può tenere. Vendi o restituisci qualche blocco piccolo per fare posto a uno più grande.", +"ip4.yours":"I tuoi indirizzi IPv4", "ix_downgrade.pni_downgraded":"Il PNI con {net} a {city} ora è {port}.", "ix_downgrade.port_downgraded_at_ix":"La porta su {ix} ora è da {port}.", "ix_downgrade.transit_downgraded":"Il transito {net} a {city} ora è {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index f65faba..5fc3410 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2638,6 +2638,54 @@ "interface.tubecoin_moved_down_p_on_the":"A TubeCoin caiu {p}% no caminho até sua conta.", "interface.tubecoin_moved_up_p_on_the":"A TubeCoin subiu {p}% no caminho até sua conta.", "interface.you_bought_out_bank_they_flew":"Você comprou a parte de {bank}.
Eles voaram em busca de outra startup.", +"ip4.block_size":"Tamanho do bloco", +"ip4.blocks":"Seus blocos", +"ip4.bought":"Você comprou um {p} ({n} endereços) por {price}.", +"ip4.bought_on":"Comprado em {date}", +"ip4.business":"Usados por clientes empresariais", +"ip4.buy":"Comprar {price}", +"ip4.cgnat_boxes":"Caixas de CGNAT", +"ip4.cgnat_note":"Mais casas por endereço liberam espaço para clientes, mas jogos e redirecionamento de portas sofrem: {p} da conta de uma casa atrás do CGNAT volta como reembolso.", +"ip4.cgnat_ratio":"CGNAT: casas por endereço", +"ip4.costs_row":"Aluguel de IPv4 e CGNAT", +"ip4.free":"Livres para novos clientes (as casas vão antes para trás do CGNAT)", +"ip4.from_rir":"Do RIR", +"ip4.give_back":"Devolver", +"ip4.held":"O RIR não transfere esse bloco de novo antes de {date}.", +"ip4.homes":"Casas com banda larga", +"ip4.homes_cgnat":"{n}, {p} atrás do CGNAT", +"ip4.in_use":"Seus clientes precisam desses endereços: coloque mais casas atrás do CGNAT ou arrume outro bloco antes.", +"ip4.lease":"Alugar {price}/mês", +"ip4.lease_out":"Alugar para terceiros +{price}/mês", +"ip4.leased_in":"Você alugou um {p} ({n} endereços) por {price}/mês.", +"ip4.leased_in_mo":"Alugado · {price}/mês", +"ip4.leased_out":"Seu {p} está alugado: +{price}/mês.", +"ip4.leased_out_mo":"Alugado para terceiros · +{price}/mês", +"ip4.leases_in":"Blocos alugados", +"ip4.leases_out":"Blocos alugados para terceiros", +"ip4.market":"Mercado de transferências", +"ip4.market_note":"IPv4 sai por cerca de {px} o endereço (blocos grandes, um pouco menos), aluga-se por {lin} o endereço por mês e, alugado para terceiros, rende {lout} depois da comissão do broker. Uma venda paga {p} do preço, e um bloco só pode ser transferido de novo dois anos depois da última transferência.", +"ip4.movable_from":"transferível a partir de {date}", +"ip4.n_addresses":{"one":"{n} endereço","other":"{n} endereços"}, +"ip4.n_homes_per_address":{"one":"{n} casa por endereço","other":"{n} casas por endereço"}, +"ip4.no_grow":"{name} ({city}) queria crescer para {bw}, mas você não tinha endereços IPv4 livres para isso.", +"ip4.no_space":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas atrás do CGNAT.", +"ip4.note":"IPv6 é grátis e infinito. IPv4 acabou há anos: clientes empresariais precisam de blocos públicos, e as casas que não cabem compartilham endereços atrás do CGNAT (o tráfego IPv6 passa por fora da caixa).", +"ip4.off":"Nas regras deste jogo, IPv4 não falta.", +"ip4.offer_needs":"Precisa de um {p} de IPv4 ({n} endereços); só {free} livres.", +"ip4.preset_plenty":"IPv4 de sobra para todo mundo.", +"ip4.preset_scarce":"IPv4 é escasso: compre, alugue ou compartilhe atrás do CGNAT.", +"ip4.really_sell":"Vender mesmo por {price}?", +"ip4.refunds":"Reembolsos para gamers irritados", +"ip4.section":"Espaço de endereços", +"ip4.sell":"Vender {price}", +"ip4.sold":"Seu {p} foi vendido por {price}.", +"ip4.squeezed":"Sem espaço: {p} das casas não cabem nem com {r} casas por endereço. As conexões caem e elas querem reembolso: compre ou alugue um bloco.", +"ip4.take_back":"Pegar de volta", +"ip4.toast_cgnat":"Seu IPv4 está cheio. {p} das suas casas agora compartilham endereços atrás do CGNAT, e alguns gamers já reclamaram.", +"ip4.toast_out":"Acabou o IPv4. Nem com {r} casas por endereço o CGNAT comporta todo mundo: compre ou alugue um bloco no banco.", +"ip4.too_many":"Você tem {n} blocos IPv4, o máximo que uma rede pode manter. Venda ou devolva blocos pequenos para abrir espaço para um maior.", +"ip4.yours":"Seus endereços IPv4", "ix_downgrade.pni_downgraded":"O PNI com {net} em {city} agora é {port}.", "ix_downgrade.port_downgraded_at_ix":"A porta em {ix} agora é de {port}.", "ix_downgrade.transit_downgraded":"O trânsito de {net} em {city} agora é {port}.", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 4b199a2..3a51abb 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -86,6 +86,9 @@ const API_DOMAINS={ pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'}, pieSpatChoice:{kind:'enum',values:[0,1]}, countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()}, + // Address space: an IPv4 prefix length the market sells, and the CGNAT ratios. + ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)}, + ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()}, scnId:{table:'SCN',kind:'id'}, // A traceroute target in the modal's own terms. }; diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 6d3f47b..cfb4e36 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -232,7 +232,7 @@ const API_CMD={ doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, /* ---------- customers ---------- */ accept:{args:[['id','entityId']], - doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, + doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, decline:{args:[['id','entityId']], doc:'Throw an offer away.'}, salesHire:{args:[['id','salesPersona']], @@ -282,6 +282,23 @@ const API_CMD={ repayLoan:{args:[['id','entityId']],confirm:'double', quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};}, doc:'Repay a loan early, or buy an equity investor out.'}, +/* ---------- address space (IPv4, rule ip4: On-call and BGP at 3 a.m.) ---------- */ + ip4Buy:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:ip4Cost(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Buy an IPv4 block of this prefix length (24 = 256 addresses up to 16 = 65,536) on the transfer market at today\'s price. It can be sold again two years after this transfer. A network holds at most 256 blocks, bought, leased in and from the registry together.'}, + ip4Lease:{args:[['len','ip4Len']],watch:['ip4'], + quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}), + doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'}, + ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'], + doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every home behind CGNAT.'}, + ip4Out:{args:[['id','entityId']],watch:['ip4'], + doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'}, + ip4Back:{args:[['id','entityId']],watch:['ip4'], + doc:'End the lease of a block you leased out; its addresses are yours to use again.'}, + ip4Return:{args:[['id','entityId']],watch:['ip4'], + doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'}, + ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'], + doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'}, /* ---------- security, China, incidents ---------- */ buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'], quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};}, @@ -453,6 +470,8 @@ const API_CMD={ const API_VIEW={ pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'}, + ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT and the transfer market.'}, + ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'}, pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'}, pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'}, pieCity:{args:[['v','cityId']],doc:'Pick the POP the Dishes tab works on.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index fb43b45..c3d1212 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -9,7 +9,7 @@ const API_STATE_DOC={ cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, - rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the later rules (sea, confs, broke, moods, pnis, and ip4 for scarce IPv4, off outside On-call and BGP at 3 a.m.), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, charter:{type:'string',doc:'The charter a normal game signed when it started: global | boutique | broker. chartSet is false until one is signed.'}, baronWon:{type:'number',doc:'The day a broker won Glass Baron, or 0.'}, chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, @@ -61,6 +61,7 @@ const API_STATE_DOC={ ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'}, popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'}, mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'}, demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index 0dce567..dfda734 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -6,17 +6,18 @@ // sea: cable ships sail out to subsea cuts, or (timer) a cut mends on its own clock. confs: conference season. // broke: deep in the red ends the game, or (rescue) a state loan keeps it going. moods: patient customers sour half as fast. // pnis: PNIs and their augments wait for the other network's team, or (instant) are up the moment they are ordered. -const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',mods:[]}; -const RULE_LATE=['sea','confs','broke','moods','pnis']; -const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant']}; +// ip4: IPv4 is scarce (#150, 33-address-space.js): customers need addresses, homes share them behind CGNAT. +const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',ip4:true,mods:[]}; +const RULE_LATE=['sea','confs','broke','moods','pnis','ip4']; +const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant'],ip4:[true,false]}; // i: icon, n: name, d: the one-line joke, x: what is different, in small print. const PRESETS={ - soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant'}, - freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder'}, + soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant',ip4:false}, + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',ip4:false}, oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a_real'),clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder'}, bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,money:'normal',gates:'ladder'}, - sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open'}, - puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open'}, + sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open',ip4:false}, + puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open',ip4:false}, }; const NORMAL_PRESETS=['soft','freeze','oncall','bgp']; // How often things break, against the classic game. Spicy outages also last half as long again. diff --git a/src/game/60-features/33-address-space.js b/src/game/60-features/33-address-space.js new file mode 100644 index 0000000..8d91812 --- /dev/null +++ b/src/game/60-features/33-address-space.js @@ -0,0 +1,89 @@ +/* ---------- Address space (#150): IPv6 is free for everyone, IPv4 ran out years ago ---------- + The network holds IPv4 blocks in real CIDR sizes (/24 to /16): its first allocation from the RIR, blocks bought on + the transfer market and blocks leased in by the month. Owned blocks can be leased out (a broker finds the tenant) or + sold, once two years have passed since they last moved (the RIRs' holding period, which also stops flipping). + Business customers on IP service take a public block each, sized by kind and port (a /29 for a small DIA port, a /23 + for a big hosting company); broadband homes take what is left, and the homes that do not fit share addresses behind + CGNAT at the player's ratio. CGNAT costs a little per Gbps it carries (IPv6 goes around the box) and some gamers want + their money back. An offer that needs more than is free, with every home already behind CGNAT, cannot be signed, and a + customer renewing bigger stays at its size when the bigger block is not free (clGrow). + Nothing is stored per customer: what each one needs follows from its kind and size, so growing customers and old saves + need no new fields. On in On-call and BGP at 3 a.m. (rule ip4), off in the gentler presets, sandbox and puzzles; + scenarios only when they opt in (S.scn.rules.ip4). No random draws: the market price is a function of the day. + The first allocation is a /21: one transit's worth of broadband levels off at about 1,300 homes in every start city, + so the first months fit with room for a few customers (gameplay rule F1). */ +// IP4_BLK: the most blocks a network holds; buying and leasing stop there, and a save keeps that many. +const IP4_START=21,IP4_MIN=16,IP4_MAX=24,IP4_HOLD=730,IP4_NAT=[8,16,32,64],IP4_NAT0=16,IP4_BLK=256; +// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries: the rest is IPv6. +const IP4_BB=10,IP4_V4=0.55,IP4_CGN=2; +// The market: dollars per address, flat for half a year, then +3% a year on a slow four-year swing. Leases are by the +// month (a broker keeps a cut of what yours earn), sales pay 92% of the price after the broker's fee. +const IP4_PX=38,IP4_FREE=180,IP4_YR=0.03,IP4_IN=0.5,IP4_OUT=0.4,IP4_SELL=0.92; +// Of the bill of a home behind CGNAT, the share that comes back as refunds (gamers, mostly): more homes per address, more +// grumbling. Homes squeezed past the ratio (port exhaustion) are worse. +const IP4_ANNOY={8:0.01,16:0.015,32:0.025,64:0.04},IP4_SQZ=0.15; +// Per kind of customer: addresses per Gbps of port, and the smallest block it takes. Circuits, waves and fiber carry no +// addresses of yours; downstream ISPs and universities bring their own (universities sit on legacy /16s); orbit +// terminals sit behind the satellite operator's own CGNAT. +const IP4_BIZ={cgame:[0.5,256],dia:[2,8],fabip:[2,8],game:[2,16],gpu:[0.5,64],host:[4,64],metav:[0.25,256],scrub:[2,8],stream:[1,32]}; +const ip4Sz=len=>2**(32-len),ip4LenOk=len=>Number.isInteger(len)&&len>=IP4_MIN&&len<=IP4_MAX; +const ip4Cidr=n=>'/'+(32-Math.ceil(Math.log2(Math.max(1,n)))),ip4N=n=>Math.round(n).toLocaleString(); +function ip4On(){return !!S&&!!S.ip4&&rule('ip4')===true&&(S.scn?scnRule('ip4'):S.mode==='normal');} +function ip4Need(b){const k=b&&IP4_BIZ[b.type];if(!k||!(b.bw>0))return 0;return Math.min(4096,2**Math.ceil(Math.log2(Math.max(k[1],b.bw*k[0]))));} +/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes; + cg: homes behind CGNAT; over: the share of homes that do not fit even at the ratio; free: what a new customer can have + with every home behind CGNAT. */ +function ip4Use(s=S){const I=s.ip4,r=I.nat;let own=0,inn=0,out=0,B=0,H=0; + for(const b of I.b){const n=ip4Sz(b.len);if(b.k==='in')inn+=n;else if(b.out)out+=n;else own+=n;} + for(const b of s.biz)B+=ip4Need(b); + for(const c in s.pops){const p=s.pops[c];if(p.bb)H+=p.bb.d*IP4_BB;} + H=Math.ceil(H);const T=own+inn,A=Math.max(0,T-B),min=Math.ceil(H/r);let cg=0,over=0; + if(A=min)cg=Math.min(H,Math.ceil((H-A)*r/(r-1)));else{cg=H;over=min?1-A/min:0;}} + return {T,own,inn,out,B,H,cg,over,free:T-B-min,r};} +const ip4Fits=o=>!ip4On()||ip4Need(o)<=Math.max(0,ip4Use().free); +// A customer renewing at bw: does the bigger block it needs fit what is free? +const ip4GrowOk=(b,bw)=>!ip4On()||ip4Need({type:b.type,bw})-ip4Need(b)<=Math.max(0,ip4Use().free); +const ip4Full=()=>S.ip4.b.length>=IP4_BLK; +// What you announce, as the AS box shows it: your blocks by prefix length, without the ones leased out to others. +const ip4Pfx=()=>{const c={};for(const b of S.ip4.b)if(!b.out)c[b.len]=(c[b.len]||0)+1;return Object.keys(c).sort((a,b)=>a-b).map(l=>`${c[l]} × /${l}`).join(', ');}; +// Would giving this block up (selling, leasing it out, handing it back) still leave room for everyone? +const ip4Spare=b=>ip4Use().free>=ip4Sz(b.len); +const ip4Held=b=>b.k!=='in'&&S.day-b.dMath.round(ip4Sz(len)*ip4Px()*(1-0.015*(IP4_MAX-len))/100)*100; +const ip4Value=len=>Math.round(ip4Cost(len)*IP4_SELL/100)*100; +const ip4InMo=len=>Math.round(ip4Sz(len)*IP4_IN*ip4Px()/IP4_PX),ip4OutMo=len=>Math.round(ip4Sz(len)*IP4_OUT*ip4Px()/IP4_PX); +// The month's IPv4 bill: leases in and out, CGNAT boxes, refunds (eye: what broadband earns a month). +function ip4Bill(eye){const u=ip4Use();let lin=0,lout=0;for(const b of S.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;} + const cgS=u.H?u.cg/u.H:0;return {u,lin,lout,box:u.cg/IP4_BB*IP4_V4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+u.over*IP4_SQZ)};} +// computeMoney: only what is there, so a network with nothing to pay keeps its money rows as they were. +function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(V.eyeballs||0),c=Math.round(b.lin+b.box+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;} +/* A new network gets its /21 from the RIR. An older save gets what it already uses registered to it and a quarter more to + grow into (about a month for a big, fast-growing network), rounded up to /24s in real CIDR blocks (a /21 at the + least), so nothing changes on load; those blocks move like any other two years on. + Their ids are fixed (rir0, rir1…), not uid(): a new game draws no id, so every id after it stays as it was. */ +function ip4Grant(s){const d=s.day||0,b=[],add=len=>b.push({id:'rir'+b.length,len,k:'rir',d});let need=0; + for(const x of s.biz||[])need+=ip4Need(x); + for(const c in s.pops||{}){const p=s.pops[c];if(p&&p.bb&&p.bb.d>0)need+=p.bb.d*IP4_BB;} + need=Math.max(ip4Sz(IP4_START),Math.ceil(need*1.25/256)*256); + while(need>=ip4Sz(IP4_MIN)&&b.length<200){add(IP4_MIN);need-=ip4Sz(IP4_MIN);} + for(let len=IP4_MIN+1;len<=IP4_MAX;len++)if(need>=ip4Sz(len)){add(len);need-=ip4Sz(len);} + return {b,nat:IP4_NAT0,w:0};} +const ip4New=()=>ip4Grant({}); +function ip4Fix(s){const I=s.ip4&&typeof s.ip4==='object'&&!Array.isArray(s.ip4)?s.ip4:null;if(!I){s.ip4=ip4Grant(s);return;} + const day=Math.max(0,num(s.day,0)),mo=v=>Math.round(Math.min(1e8,Math.max(0,num(v,0)))); + const b=(Array.isArray(I.b)?I.b:[]).filter(x=>x&&typeof x==='object'&&ip4LenOk(x.len)&&['rir','buy','in'].includes(x.k)).slice(0,IP4_BLK).map(x=>{ + const o={id:typeof x.id==='string'&&x.id&&x.id.length<=40?x.id:uid(),len:x.len,k:x.k,d:int(x.d,0,day,0)}; + if(x.k==='in')o.mo=mo(x.mo);else if(x.out===true){o.out=true;o.mo=mo(x.mo);}return o;}); + s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,w:int(I.w,0,3,0)};} +/* Once a day: say so when homes go behind CGNAT (a percent of them at least), and when even CGNAT cannot fit them all + (w: what was said). Each rearms only with room to spare again, so homes hovering at the limit hear it once. */ +function ip4Day(d){if(!ip4On())return;const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}]; + if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A>=u.H*1.05)I.w&=~1; + if(u.over>0){if(!(I.w&2)){I.w|=2;toast(tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}}else if(A>=Math.ceil(u.H/u.r)*1.1)I.w&=~2;} +// Renewals that wanted a bigger block than is free (clGrow, [customer, bandwidth]): they stay as they are, and hear why. +function ip4News(l=[]){for(const [b,bw] of l.slice(0,3))toast(tr('ip4.no_grow',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(bw)}),'',[{l:tr('ip4.section'),act:'ip4Open'}]);} +// The line under an offer that cannot be signed for want of addresses. +function ip4Why(o){if(ip4Fits(o))return '';const n=ip4Need(o); + return `
${tr('ip4.offer_needs',{p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))})} ${btn(tr('ip4.section'),'ip4Open',{},'ghost sm')}
`;} diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js index ff2efd0..9c68f86 100644 --- a/src/game/60-features/38-sales-desk.js +++ b/src/game/60-features/38-sales-desk.js @@ -65,13 +65,13 @@ function salesDay(d){const L=S.sales;if(!L)return; // With a rocket company, every other game is with the Founder, and in orbit (pieGolf, 99-pie-sales.js). const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia']; function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return; - const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl());if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name); const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40}; const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b)); toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');} // Declining an offer the CEO likes: about one in three, he already shook hands on it. -function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+slKey(o))>=0.33)return false; +function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false; const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;} // Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer. function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null; diff --git a/src/game/60-features/39-sales-auto.js b/src/game/60-features/39-sales-auto.js index 11f3b81..7251224 100644 --- a/src/game/60-features/39-sales-auto.js +++ b/src/game/60-features/39-sales-auto.js @@ -32,7 +32,7 @@ function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floo const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;}; opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o); if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;} - if(!A.on)continue; + if(!A.on||!ip4Fits(o))continue; if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))continue;ACT.accept({id:o.id});won(o);continue;} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 3559593..7903fdd 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, - ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, + ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null}; } diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 6b28350..4829518 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -374,10 +374,11 @@ function computeMoney(R2,PX=null){ C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}} const ids=linkIds();for(const b of S.biz){if(capPend(b)||BIZ_T[b.type].orbit)continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);} for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE; + ip4Money(C,V); if(PX)pieMoney(PX,R2,V); // The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js). {const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;if(PX)V.gov=pieGovMo();if(PX)R2.pie.gov={rdf:V.gov||0,sky:sky?GRANT_SKY_MO:0};} C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix+(V.orbit||0)); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); - R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0); + R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0); } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index e6c94b3..b18f5b9 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -112,6 +112,7 @@ function sanitize(s){ const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} specSanitize(s);mpSanitize(s); pieSanitize(s);pieIncFix(s); + ip4Fix(s); if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} function migrate(s){sanitize(s); diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js index 97a5d5d..2bba376 100644 --- a/src/game/80-simulation/75-customer-lifecycle.js +++ b/src/game/80-simulation/75-customer-lifecycle.js @@ -58,14 +58,16 @@ function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);} const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ '); -// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. -function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;} +// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. Not +// when the bigger IPv4 block it needs is not free (#150): out.v4 lists them for the day's news. +function clGrow(b,out){const T=BIZ_T[b.type];if(T.fiber)return false;const bw=(T.opts||[]).find(x=>x>b.bw)||b.bw*2; + if(!ip4GrowOk(b,bw)){if(out)out.v4.push([b,bw]);return false;}b.bw=bw;return true;} // Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says. function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))}; if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;} const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;} const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why'); - if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} + if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;} if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort(); const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null; if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}} @@ -75,7 +77,7 @@ function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clW /* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at the asked price. */ -function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); +function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[],v4:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0); const pat=rule('moods')==='patient'?0.5:1; for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue; if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;} @@ -86,7 +88,7 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l continue;} const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat*salesLeaveMul(b); if(clR(b,'leave')=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} + const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}} clRenew(b,clFair(b));clNote('ren');out.ren++;} clNews(out);clReferral(d);} // What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts. @@ -94,7 +96,7 @@ function clNews(out){ for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate; toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});} const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);}; - few(out.ok,'good');few(out.lost,''); + few(out.ok,'good');ip4News(out.v4);few(out.lost,''); if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');} const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});}; diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 2f008db..7c2a989 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -94,6 +94,7 @@ function dayPost(d){ scnTick(d); confTick(d); specDay(d); + ip4Day(d); // money trouble if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('day_tick.you_are_in_the_red_cancel'),'bad');} else S.neg=0; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index aa5e4c8..d683de8 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -4,7 +4,7 @@ Object.assign(ACT,{ if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p; toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, - accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');return;}const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, diff --git a/src/game/90-actions/54-address-space.js b/src/game/90-actions/54-address-space.js new file mode 100644 index 0000000..e2c934f --- /dev/null +++ b/src/game/90-actions/54-address-space.js @@ -0,0 +1,29 @@ +/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT ratio. Every block + change keeps room for the customers already signed, with every home behind CGNAT. */ +const ip4Re=()=>{after();renderBank();}; +function ip4Can(){if(ip4On())return true;toast(tr('ip4.off'),'bad');sfx('err');return false;} +const ip4Blk=id=>S.ip4.b.find(b=>b.id===id); +function ip4Busy(){toast(tr('ip4.in_use'),'bad');sfx('err');} +// No more blocks than a save keeps (IP4_BLK): a new one is refused with the way out. +function ip4Room(){if(!ip4Full())return true;toast(tr('ip4.too_many',{n:IP4_BLK}),'bad');sfx('err');return false;} +Object.assign(ACT,{ + ip4Open:()=>{if(!S||pzOn()||!ip4On())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankIp4');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});}, + // The size the market rows quote (a dropdown: v is the prefix length). + ip4Pick:({v})=>{const len=Number(v);if(ip4LenOk(len))UI.ip4Len=len;renderBank();}, + ip4Buy:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const c=ip4Cost(len);if(!spend(c))return; + S.ip4.b.push({id:uid(),len,k:'buy',d:S.day});toast(tr('ip4.bought',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(c)}),'good');sfx('coin');ip4Re();}, + ip4Lease:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const mo=ip4InMo(len); + S.ip4.b.push({id:uid(),len,k:'in',d:S.day,mo});toast(tr('ip4.leased_in',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(mo)}),'good');sfx('click');ip4Re();}, + ip4Sell:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return; + if(ip4Held(b)){toast(tr('ip4.held',{date:dateStr(b.d+IP4_HOLD)}),'bad');sfx('err');return;}if(!ip4Spare(b)){ip4Busy();return;} + if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;const v=ip4Value(b.len);S.ip4.b=S.ip4.b.filter(x=>x!==b);S.cash+=v; + toast(tr('ip4.sold',{p:'/'+b.len,price:fmt$(v)}),'good');sfx('coin');ip4Re();}, + ip4Out:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return;if(!ip4Spare(b)){ip4Busy();return;} + b.out=true;b.mo=ip4OutMo(b.len);toast(tr('ip4.leased_out',{p:'/'+b.len,price:fmt$(b.mo)}),'good');sfx('coin');ip4Re();}, + ip4Back:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||!b.out)return;delete b.out;delete b.mo;sfx('click');ip4Re();}, + ip4Return:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k!=='in')return;if(!ip4Spare(b)){ip4Busy();return;} + S.ip4.b=S.ip4.b.filter(x=>x!==b);sfx('click');ip4Re();}, + // Fewer homes per address needs more addresses: refused when the customers already signed would not fit. + ip4Nat:({v})=>{if(!ip4Can())return;const r=Number(v);if(!IP4_NAT.includes(r)||r===S.ip4.nat)return;const u=ip4Use(); + if(r
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); - h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)} + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${o.refN?`
${tr('lifecycle.referred_by',{name:esc(o.refN)})}
`:''}${spotWhy(o)}${ip4Why(o)}${bRisk(o)}${reqList(o)}
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${pieNocBtn()}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'':''}`,'routingOpen',{},'')}
`; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 43a2309..249a97f 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -140,7 +140,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${ip4Why(o)}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index b1e662f..b1ede29 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -9,7 +9,7 @@ function renderDash(){checkLayer();
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} -

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. @@ -28,7 +28,7 @@ function renderDash(){checkLayer(); const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); if(DT==='infra')h+=`

${tr('common.busiest_links')}

${ls.length?ls.map(({l,u})=>`
${CITY[l.a].name} ⇄ ${CITY[l.b].name} ${capName(l)} · ${linkLat(l).toFixed(1)} ms
${pct(u)}${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}
`).join(''):'

'+tr('common.no_links_yet')+'

'}

${tr('common.router_load')}

${rs.map(({c,u})=>`
${CITY[c].name} ${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}
${pct(u)}
`).join('')} -

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; +

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${(ip4On()&&ip4Pfx())||Math.max(1,Math.ceil(Object.keys(S.pops).length/3))+' × /22'} IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; if(DT==='pops')h+=popsSection(); if(DT==='lease')h+=leaseTab(); if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);} diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js index 9affb05..72566a4 100644 --- a/src/game/94-dashboard/70-bank.js +++ b/src/game/94-dashboard/70-bank.js @@ -29,6 +29,6 @@ function renderBank(){ ${B.equity?`
${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}
`:`
${tr('common.still_owed')}${fmt$(l.bal)}
${loanLine(l)}
`} ${covList(l)}${l.breach>=1?`
${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}
`:''}
${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash
`;} - h+=pieGovBank(); + h+=pieGovBank()+ip4Bank(); if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;} } diff --git a/src/game/94-dashboard/72-address-space.js b/src/game/94-dashboard/72-address-space.js new file mode 100644 index 0000000..149689c --- /dev/null +++ b/src/game/94-dashboard/72-address-space.js @@ -0,0 +1,22 @@ +/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it, the CGNAT ratio, your + blocks, and the transfer market. Phones: the boxes are full width, the dropdowns stack and every button row wraps. */ +const ip4Pc=x=>(x*100).toFixed(1).replace(/\.0$/,'')+'%'; +function ip4Bank(){if(!S||!ip4On())return '';const I=S.ip4,B=ip4Bill((R.rev&&R.rev.eyeballs)||0),u=B.u,len=ip4LenOk(UI.ip4Len)?UI.ip4Len:IP4_MAX,px=ip4Px(),full=ip4Full(); + const kv=(l,v,bad)=>`
${l}${v}
`,mo=v=>tr('common.price_mo',{price:fmt$(v)}); + let h=`

🔢 ${tr('ip4.section')}

${tr('ip4.note')}

`; + h+=`
${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}${kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H))}${kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0)}`; + if(u.over>0)h+=`
${tr('ip4.squeezed',{p:pct(u.over),r:u.r})}
`; + if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout)); + h+=` +

${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}

`; + h+=`
${tr('ip4.blocks')}
`; + for(const b of I.b){const n=ip4Sz(b.len),spare=u.free>=n,held=ip4Held(b),sure=UI.confirm===b.id; + const what=b.k==='in'?tr('ip4.leased_in_mo',{price:fmt$(b.mo||0)}):b.out?tr('ip4.leased_out_mo',{price:fmt$(b.mo||0)}):b.k==='buy'?tr('ip4.bought_on',{date:dateStr(b.d)}):tr('ip4.from_rir'); + const btns=b.k==='in'?btn(tr('ip4.give_back'),'ip4Return',{id:b.id},'ghost sm',!spare):b.out?btn(tr('ip4.take_back'),'ip4Back',{id:b.id},'ghost sm') + :btn(tr('ip4.lease_out',{price:fmt$(ip4OutMo(b.len))}),'ip4Out',{id:b.id},'sm',!spare)+btn(sure?tr('ip4.really_sell',{price:fmt$(ip4Value(b.len))}):tr('ip4.sell',{price:fmt$(ip4Value(b.len))}),'ip4Sell',{id:b.id},sure?'red sm':'ghost sm',held||!spare); + // Greyed for want of room: say so (a disabled button never gets to show ip4Busy's toast). + h+=`
/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}
${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}
${!spare&&!b.out?`
${tr('ip4.in_use')}
`:''}
${btns}
`;} + h+=`
${tr('ip4.market')}

${tr('ip4.market_note',{px:fmt$(px),lin:'$'+(IP4_IN*px/IP4_PX).toFixed(2),lout:'$'+(IP4_OUT*px/IP4_PX).toFixed(2),p:pct(IP4_SELL)})}

+ + ${full?`
${tr('ip4.too_many',{n:IP4_BLK})}
`:''}
${btn(tr('ip4.buy',{price:fmt$(ip4Cost(len))}),'ip4Buy',{len},'pink sm',full||S.cash
`; + return h;} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index e71afef..e582aae 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -43,7 +43,7 @@ function whatsNew(returning,force){ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]]; const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; // The chosen preset in one line: its joke, then what actually changes. -const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; +const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)} ${PRESETS[k].ip4===false?tr('ip4.preset_plenty'):tr('ip4.preset_scarce')}`; // The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js). const presetBtns=pr=>`
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

`; function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; diff --git a/src/i18n/en.js b/src/i18n/en.js index 0c4838e..c580cf8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2639,6 +2639,54 @@ "interface.tubecoin_moved_down_p_on_the":"TubeCoin moved down {p}% on the way to your account.", "interface.tubecoin_moved_up_p_on_the":"TubeCoin moved up {p}% on the way to your account.", "interface.you_bought_out_bank_they_flew":"You bought out {bank}.
They flew off to find another startup.", +"ip4.block_size":"Block size", +"ip4.blocks":"Your blocks", +"ip4.bought":"Bought a {p} ({n} addresses) for {price}.", +"ip4.bought_on":"Bought {date}", +"ip4.business":"Used by business customers", +"ip4.buy":"Buy {price}", +"ip4.cgnat_boxes":"CGNAT boxes", +"ip4.cgnat_note":"More homes per address frees space for customers, but games and port forwarding suffer: {p} of a CGNAT home's bill comes back as refunds.", +"ip4.cgnat_ratio":"CGNAT: homes sharing one address", +"ip4.costs_row":"IPv4 leases and CGNAT", +"ip4.free":"Free for new customers (homes move behind CGNAT first)", +"ip4.from_rir":"From the RIR", +"ip4.give_back":"Give it back", +"ip4.held":"The RIR won't transfer that block again before {date}.", +"ip4.homes":"Broadband homes", +"ip4.homes_cgnat":"{n}, {p} behind CGNAT", +"ip4.in_use":"Your customers need those addresses: put more homes behind CGNAT or get another block first.", +"ip4.lease":"Lease {price}/mo", +"ip4.lease_out":"Lease out +{price}/mo", +"ip4.leased_in":"Leased a {p} ({n} addresses) for {price}/mo.", +"ip4.leased_in_mo":"Leased in · {price}/mo", +"ip4.leased_out":"Your {p} is leased out: +{price}/mo.", +"ip4.leased_out_mo":"Leased out · +{price}/mo", +"ip4.leases_in":"Blocks leased in", +"ip4.leases_out":"Blocks leased out", +"ip4.market":"Transfer market", +"ip4.market_note":"IPv4 sells for about {px} an address (big blocks a little less), leases for {lin} an address a month, and earns {lout} leased out after the broker's cut. A sale pays {p} of the price, and a block can only move again two years after its last transfer.", +"ip4.movable_from":"can move again from {date}", +"ip4.n_addresses":{"one":"{n} address","other":"{n} addresses"}, +"ip4.n_homes_per_address":{"one":"{n} home per address","other":"{n} homes per address"}, +"ip4.no_grow":"{name} ({city}) wanted to grow to {bw}, but you had no IPv4 addresses free for it.", +"ip4.no_space":"{name} needs a {p} of IPv4 ({n} addresses), and only {free} are free. Buy or lease a block, or put more homes behind CGNAT.", +"ip4.note":"IPv6 is free and endless. IPv4 ran out years ago: business customers need public blocks of it, and homes that don't fit share addresses behind CGNAT (IPv6 traffic goes around the box).", +"ip4.off":"IPv4 is plentiful under this game's rules.", +"ip4.offer_needs":"Needs a {p} of IPv4 ({n} addresses); only {free} free.", +"ip4.preset_plenty":"Plenty of IPv4 for everyone.", +"ip4.preset_scarce":"IPv4 is scarce: buy it, lease it or share it behind CGNAT.", +"ip4.really_sell":"Really sell for {price}?", +"ip4.refunds":"Refunds to grumpy gamers", +"ip4.section":"Address space", +"ip4.sell":"Sell {price}", +"ip4.sold":"Sold your {p} for {price}.", +"ip4.squeezed":"Out of space: {p} of homes don't fit even at {r} homes per address. Their connections break and they want refunds: buy or lease a block.", +"ip4.take_back":"Take it back", +"ip4.toast_cgnat":"Your IPv4 is full. {p} of your homes now share addresses behind CGNAT, and a few gamers have already written in.", +"ip4.toast_out":"Out of IPv4. Even at {r} homes per address, CGNAT can't fit everyone: buy or lease a block at the bank.", +"ip4.too_many":"You hold {n} IPv4 blocks, the most one network can keep track of. Sell or give back small ones to make room for a bigger block.", +"ip4.yours":"Your IPv4 addresses", "ix_downgrade.pni_downgraded":"The PNI with {net} in {city} is now {port}.", "ix_downgrade.port_downgraded_at_ix":"Port at {ix} is now {port}.", "ix_downgrade.transit_downgraded":"{net} transit in {city} is now {port}.", diff --git a/tests/address-space.test.js b/tests/address-space.test.js new file mode 100644 index 0000000..92fafdf --- /dev/null +++ b/tests/address-space.test.js @@ -0,0 +1,442 @@ +// IPv4 address space (#150, src/game/60-features/33-address-space.js): business customers need public blocks, broadband +// homes share addresses behind CGNAT when they do not fit, blocks are bought, sold, leased in and leased out, and the +// whole thing is a rule (ip4): On-call and BGP at 3 a.m. only, scenarios when they opt in. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt on On-call, plenty of cash, nothing breaking, level 9 so every kind of customer can turn up. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});compute()"; +function game(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + return h; +} +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +const homes = (ev, g) => ev(`S.pops.fra.bb.d=${g};compute()`); +const biz = (ev, b) => ev(`S.biz.push(${lit({ id: b.id || 'b' + Math.random().toString(36).slice(2), city: 'fra', city2: null, reqs: [], name: 'X', type: 'host', bw: 10, rate: 60, mood: 100, since: 0, ...b })});compute()`); + +test('what each customer needs: a block by kind and size, nothing for circuits, fiber, downstream ISPs or orbit', (t) => { + const { ev, errors } = game(t); + const need = (type, bw) => ev(`ip4Need({type:${lit(type)},bw:${bw}})`); + assert.equal(need('dia', 1), 8, 'a small DIA port gets a /29'); + assert.equal(need('dia', 10), 32); + assert.equal(need('game', 5), 16); + assert.equal(need('host', 10), 64); + assert.equal(need('host', 80), 512, 'a big hosting company a /23'); + assert.equal(need('cgame', 3200), 2048); + assert.equal(need('metav', 6400), 2048); + assert.equal(need('host', 1e6), 4096, 'capped at a /20'); + for (const k of ['l2vpn', 'hyper', 'wwave', 'dfpair', 'isp', 'edu', 'provedor', 'event', 'pizza', 'flywifi']) assert.equal(need(k, 100), 0, k); + assert.equal(ev('ip4Cidr(8)'), '/29'); + assert.equal(ev('ip4Cidr(512)'), '/23'); + // Every IPv4 kind is a real kind of customer that pays by the Gbps. + assert.deepEqual(J(ev, 'Object.keys(IP4_BIZ).filter(k=>!BIZ_T[k]||!(BIZ_T[k].rate>0)||BIZ_T[k].l2||BIZ_T[k].fiber||BIZ_T[k].orbit)'), []); + assert.deepEqual(errors, []); +}); + +test('consumption: business first, homes take the rest, and the ones that do not fit go behind CGNAT', (t) => { + const { ev, errors } = game(t); + // A new network: one /21 from the RIR, held two years before it can move. + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.len,b.k,b.d])'), [[21, 'rir', 0]]); + assert.equal(ev('S.ip4.nat'), 16); + homes(ev, 50); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.T, u.B, u.H, u.cg, u.over, u.free], [2048, 0, 500, 0, 0, 2048 - 32], '500 homes all public; a new customer could push them all behind CGNAT'); + assert.equal(ev('R.cost.ip4'), undefined, 'nothing to pay while everyone has an address'); + biz(ev, { type: 'host', bw: 80 }); // a /23 + homes(ev, 150); + u = J(ev, 'ip4Use()'); + // 1,536 left for 1,500 homes: all public. 1,600 homes: (1600-1536)*16/15 rounded up go behind CGNAT. + assert.deepEqual([u.B, u.cg], [512, 0]); + homes(ev, 160); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, Math.ceil((1600 - 1536) * 16 / 15)); + assert.ok(u.H - u.cg + Math.ceil(u.cg / 16) <= 1536, 'public homes plus the CGNAT pool fit the space'); + const c = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.ok(c.box > 0 && c.refund > 0, 'CGNAT boxes and refunds cost money'); + assert.equal(ev('R.cost.ip4'), Math.round(c.box + c.refund)); + assert.ok(Math.abs(c.refund - ev('R.rev.eyeballs') * (u.cg / u.H) * 0.015) < 1e-6, 'refunds: 1.5% of the CGNAT share of what homes pay at 1:16'); + // A wider ratio frees addresses and annoys more gamers. + const free16 = u.free; + ev("ACT.ip4Nat({v:'64'})"); + assert.equal(ev('S.ip4.nat'), 64); + assert.ok(J(ev, 'ip4Use()').free > free16); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund > c.refund); + ev("ACT.ip4Nat({v:'16'})"); + // Business customers squeeze the homes: past the ratio, homes are squeezed out (port exhaustion) and it shows. + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 1e6, id: 'h3' }); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, u.H); + assert.ok(u.over > 0 && u.free < 0); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund >= ev('R.rev.eyeballs*ip4Use().over') * 0.15, 'squeezed homes want real money back'); + // Narrowing the ratio is refused when the signed customers would not fit. + ev("ACT.ip4Nat({v:'8'})"); + assert.equal(ev('S.ip4.nat'), 16); + assert.deepEqual(errors, []); +}); + +test('an offer that needs more IPv4 than is free cannot be signed, and says why; a block fixes it', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 50); + ev(`S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:[],exp:S.day+30},{id:'small',city:'fra',name:'Tiny DIA',type:'dia',bw:1,rate:600,reqs:[],exp:S.day+30})`); + assert.equal(ev("ip4Fits(S.offers[0])"), false, 'a /21 does not fit the starting /21 with homes on it'); + assert.equal(ev("ip4Fits(S.offers[1])"), true); + // The deals list and the city panel say why, with a way to the address space. + ev("UI.left='deals';UI.leftOpen=true;renderLeft();selectCity('fra');UI.tab='cust';renderPanel()"); + const left = dom.window.document.getElementById('leftBody').textContent; + assert.match(left, /Needs a \/21 of IPv4 \(2,048 addresses\); only 2,016 free\./); + assert.ok(dom.window.document.querySelector('#leftBody [data-act="ip4Open"]'), 'a button to the address space'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'not signed'); + assert.equal(ev('S.biz.length'), 0); + assert.match(dom.window.document.getElementById('toasts').textContent, /Pixel Palace needs a \/21 of IPv4/); + ev("ACT.accept({id:'small'})"); + assert.equal(ev('S.biz.length'), 1, 'a small one fits'); + // Buy a /21 and the big one signs. + const cash = ev('S.cash'); + ev("ACT.ip4Buy({len:21})"); + assert.equal(ev('S.cash'), cash - ev('ip4Cost(21)')); + assert.equal(ev('ip4Cost(21)'), Math.round(2048 * 38 * (1 - 0.015 * 3) / 100) * 100, 'about $38 an address, a little less for a bigger block'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 2); + assert.equal(J(ev, 'ip4Use()').B, 8 + 2048); + // The bank opens at the section. + ev("ACT.ip4Open()"); + assert.equal(dom.window.document.getElementById('bankBox').hidden, false); + assert.ok(dom.window.document.getElementById('bankIp4')); + assert.deepEqual(errors, []); +}); + +test('the sales desk and the CEO do not sign what does not fit', (t) => { + const { ev, errors } = game(t); + homes(ev, 50); + ev("ACT.salesHire({id:'shark'});closeModal();S.slAuto.on=true"); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + ev('slAutoDay(S.day)'); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'the shark leaves it'); + ev("ACT.salesFire({});ACT.salesFire({});closeModal();ACT.salesHire({id:'ceo'});closeModal()"); + assert.equal(ev("salesOverride(S.offers.find(o=>o.id==='big'))"), false, 'no handshake on addresses you do not have'); + assert.equal(ev("(()=>{const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));return t;})()"), 'gpu', 'the golf deal is the biggest that fits (a /23 for an AI data center, not a /21 for cloud gaming)'); + assert.deepEqual(errors, []); +}); + +test('buying, leasing in, leasing out and selling move the right money', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 20); + const rev0 = ev('R.revMo'), cost0 = ev('R.costMo'); + ev("ACT.ip4Lease({len:22})"); + const lin = ev("S.ip4.b.find(b=>b.k==='in').mo"); + assert.equal(lin, 512, 'a /22 leases for $0.50 an address a month'); + assert.equal(ev('R.costMo'), cost0 + lin); + assert.equal(ev('ip4Use().T'), 3072); + ev("ACT.ip4Buy({len:24})"); + const bought = ev("S.ip4.b.find(b=>b.k==='buy').id"); + ev(`ACT.ip4Out({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.find(b=>b.id===${lit(bought)}).mo`), Math.round(256 * 0.4)); + assert.equal(ev('R.revMo'), rev0 + Math.round(256 * 0.4), 'leased out: income every month'); + assert.equal(ev('R.rev.ip4'), Math.round(256 * 0.4)); + // A leased-out block cannot be sold; take it back first. A fresh block cannot move for two years. + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true); + ev(`ACT.ip4Back({id:${lit(bought)}})`); + assert.equal(ev('R.rev.ip4'), undefined); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.match(dom.window.document.getElementById('toasts').textContent, /won't transfer that block again/); + ev('S.day+=730'); + const cash = ev('S.cash'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true, 'the first click only asks'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), false); + assert.equal(ev('S.cash'), cash + ev('ip4Value(24)')); + assert.ok(ev('ip4Value(24)') < ev('ip4Cost(24)'), 'the broker keeps a cut'); + // Hand the leased block back: the fee stops. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id})"); + assert.equal(ev("S.ip4.b.some(b=>b.k==='in')"), false); + assert.equal(ev('R.cost.ip4'), undefined); + // Space in use cannot be given away: with customers on every address, leasing out or selling the /21 is refused. + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'host', bw: 40, id: 'h2' }); + const rir = ev("S.ip4.b.find(b=>b.k==='rir').id"); + ev(`ACT.ip4Out({id:${lit(rir)}})`); + assert.equal(ev(`!!S.ip4.b.find(b=>b.id===${lit(rir)}).out`), false); + assert.match(dom.window.document.getElementById('toasts').textContent, /Your customers need those addresses/); + assert.deepEqual(errors, []); +}); + +test('a list of blocks stops where a save keeps them: buying and leasing past it is refused, and a full save loads whole', (t) => { + const { ev, dom, errors } = load({ agent: true }); + t.after(() => dom.window.close()); + ev(BASE); + homes(ev, 20); + // The market's default size, clicked over and over (or an agent in a loop): bought and leased /24s. + ev('for(let i=0;i<150;i++)ACT.ip4Buy({len:24});for(let i=0;i<150;i++)ACT.ip4Lease({len:24})'); + assert.equal(ev('S.ip4.b.length'), ev('IP4_BLK'), 'stops at the most a save keeps'); + assert.equal(ev('IP4_BLK'), 256); + assert.match(dom.window.document.getElementById('toasts').textContent, /You hold 256 IPv4 blocks/); + const cash = ev('S.cash'), T = ev('ip4Use().T'), mo = ev('R.cost.ip4'); + ev('ACT.ip4Buy({len:16});ACT.ip4Lease({len:16})'); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.cash'), ev('ip4Use().T')], [256, cash, T], 'refused: no money spent, nothing added'); + // The bank says so and greys the market out; an agent's quote says why. + ev('ACT.ip4Open()'); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec.textContent, /the most one network can keep track of/); + assert.equal(sec.querySelector('[data-act="ip4Buy"]').disabled, true); + assert.equal(sec.querySelector('[data-act="ip4Lease"]').disabled, true); + assert.match(J(ev, 'API_CMD.ip4Buy.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + assert.match(J(ev, 'API_CMD.ip4Lease.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + // Saved and loaded: every block, every lease, the same space and bill. + const before = ev('JSON.stringify(S.ip4)'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + assert.deepEqual([ev('ip4Use().T'), ev('R.cost.ip4')], [T, mo]); + // Handing one back makes room for a bigger block. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id});ACT.ip4Buy({len:16})"); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.ip4.b[255].len')], [256, 16]); + assert.deepEqual(errors, []); +}); + +test('a customer renewing bigger stays at its size when the bigger block is not free, and says why', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 0); + // Eight 40G hosts (a /24 each) fill the /21; the ninth is refused at the door. + for (let i = 0; i < 9; i++) ev(`S.offers.push({id:'o${i}',city:'fra',name:'Host ${i}',type:'host',bw:40,rate:60,reqs:[],exp:S.day+30});ACT.accept({id:'o${i}'})`); + assert.equal(ev('S.biz.length'), 8); + assert.equal(J(ev, 'ip4Use()').free, 0); + // The next term of host 0 on a day its own rolls say: stay, and grow (to 80G, a /23). + const renew = () => J(ev, `(()=>{const b=S.biz[0];for(const x of S.biz)if(x!==b)x.te=1e6; + for(let k=Math.max(S.day,b.te)+1;k=(0.04+0.08*Math.min(1,clComp(b)/6))*salesLeaveMul(b)){S.day=k;document.getElementById('toasts').innerHTML='';clDay(k);compute(); + return {bw:b.bw,te:b.te,in:S.biz.includes(b),free:ip4Use().free,toasts:document.getElementById('toasts').textContent};}}return null;})()`); + let r = renew(); + assert.ok(r, 'a growing renewal turns up'); + assert.deepEqual([r.bw, r.in, r.free], [40, true, 0], 'renewed at the size it has: nobody runs on addresses you do not have'); + assert.ok(r.te > ev('S.day'), 'a new term'); + assert.match(r.toasts, /Host 0 \(Frankfurt\) wanted to grow to 80(\.0)? Gbps, but you had no IPv4 addresses free for it\./); + assert.match(r.toasts, /renewed/); + // The acquisition that would stay bigger goes through the same door. + assert.equal(ev('(()=>{const out={v4:[]};return clGrow(S.biz[0],out)===false&&out.v4.length===1&&S.biz[0].bw===40;})()'), true); + // A block bought, the next growing renewal grows. + ev('ACT.ip4Buy({len:24})'); + r = renew(); + assert.deepEqual([r.bw, r.free], [80, 0]); + assert.match(r.toasts, /renewed and grew to 80(\.0)? Gbps/); + // Without the rule, growth is as it always was. + ev("S.rules=makeRules('freeze');compute()"); + r = renew(); + assert.equal(r.bw, 160); + assert.doesNotMatch(r.toasts, /IPv4/); + assert.deepEqual(errors, []); +}); + +test('the address space says what its numbers mean: free counts homes behind CGNAT, blocks in use say why they stay', (t) => { + const { ev, dom, errors } = game(t); + ev('S.day=800'); + homes(ev, 50); + ev('ACT.ip4Open()'); + const sec = () => dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec().textContent, /Free for new customers \(homes move behind CGNAT first\)2,016/); + // The /21 is out of its holding period, but 500 homes use it: greyed out, and the row says why. + let row = sec().querySelector('[data-act="ip4Out"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, true); + assert.equal(row.querySelector('[data-act="ip4Sell"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // A leased-in /24 the customers need too: Give it back is greyed, with the reason. + ev("ACT.ip4Lease({len:24})"); + biz(ev, { type: 'host', bw: 80, id: 'h1' }); + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 80, id: 'h3' }); + biz(ev, { type: 'host', bw: 80, id: 'h4' }); + assert.equal(J(ev, 'ip4Use()').free, 224, 'fewer free than the /24 holds'); + ev('UI._bh=null;renderBank()'); + row = sec().querySelector('[data-act="ip4Return"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Return"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // With room to spare, no reason is shown and the buttons work. + ev("S.biz=[];compute();ACT.ip4Buy({len:24});UI._bh=null;renderBank()"); + row = [...sec().querySelectorAll('[data-act="ip4Out"]')].pop().closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, false); + assert.equal(row.querySelector('.why'), null); + assert.deepEqual(errors, []); +}); + +test('the AS box on the dashboard lists the blocks you announce, not a made-up count', (t) => { + const { ev, dom, errors } = game(t); + const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('.kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; + assert.match(asBox(), /1 × \/21 IPv4, 1 × \/32 IPv6/, 'the starting allocation'); + ev("ACT.ip4Lease({len:22});ACT.ip4Buy({len:24})"); + assert.match(asBox(), /1 × \/21, 1 × \/22, 1 × \/24 IPv4/, 'bought and leased-in blocks are announced too'); + ev("S.rules=makeRules('freeze');compute()"); + assert.match(asBox(), /1 × \/22 IPv4/, 'without the rule it stays as it always was'); + assert.deepEqual(errors, []); +}); + +test('the market price drifts gently with the day, and holds still without the market rule', (t) => { + const { ev, errors } = game(t); + assert.equal(ev('ip4Px(0)'), 38); + assert.equal(ev('ip4Px(180)'), 38, 'flat for half a year'); + const px = [400, 900, 1500, 2200].map((d) => ev(`ip4Px(${d})`)); + assert.ok(px.every((p) => p > 30 && p < 50), 'realistic: $30 to $50 an address: ' + px); + assert.ok(Math.abs(ev('ip4Px(546)') - ev('ip4Px(545)')) < 0.1, 'a gentle trend, not a jump'); + assert.ok(ev('ip4Cost(16)') / 65536 < ev('ip4Cost(24)') / 256, 'bigger blocks a little cheaper per address'); + ev("S.rules=makeRules('oncall',{market:false})"); + assert.equal(ev('ip4Px(1500)'), 38); + assert.deepEqual(errors, []); +}); + +test('the day says it once when homes go behind CGNAT, and when even CGNAT cannot fit them', (t) => { + const { ev, dom, errors } = game(t); + const said = () => dom.window.document.getElementById('toasts').textContent; + // A handful of homes over the edge (under a percent of them) is not news yet. + homes(ev, 205.3); + ev('ip4Day(S.day)'); + const few = J(ev, 'ip4Use()'); + assert.ok(few.cg > 0 && few.cg < few.H / 100, JSON.stringify(few)); + assert.equal(ev('S.ip4.w'), 0); + assert.doesNotMatch(said(), /IPv4/); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full\.\s*19% of your homes now share addresses behind CGNAT/); + assert.equal(ev('S.ip4.w'), 1); + ev("document.getElementById('toasts').innerHTML='';ip4Day(S.day)"); + assert.equal(said(), '', 'only once'); + // Homes hovering at the limit hear it once: dipping just under does not rearm it, real room again does. + homes(ev, 204); + ev('ip4Day(S.day)'); + assert.deepEqual([J(ev, 'ip4Use()').cg, ev('S.ip4.w')], [0, 1]); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.equal(said(), '', 'not again while hovering'); + homes(ev, 150); + ev('ip4Day(S.day)'); + assert.equal(ev('S.ip4.w'), 0, 'room to spare: it rearms'); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full/); + ev("document.getElementById('toasts').innerHTML=''"); + biz(ev, { type: 'host', bw: 1e6 }); + ev('ip4Day(S.day)'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Out of IPv4/); + assert.equal(ev('S.ip4.w'), 3); + ev("S.biz=[];S.pops.fra.bb.d=10;compute();ip4Day(S.day)"); + assert.equal(ev('S.ip4.w'), 0, 'fixed: the warnings rearm'); + assert.deepEqual(errors, []); +}); + +test('rule off means no effect: gentler presets, sandbox, puzzles and scenarios unless they opt in', (t) => { + const { ev, dom, errors } = game(t); + assert.deepEqual(J(ev, "['soft','freeze','oncall','bgp','sandbox','puzzle'].map(p=>makeRules(p).ip4)"), [false, false, null, null, false, false], 'On-call and BGP keep the default (on), written nowhere'); + assert.equal(ev('RULE_DEF.ip4'), true); + ev("S.rules=makeRules('freeze');S.pops.fra.bb.d=500;compute()"); + assert.equal(ev('ip4On()'), false); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + assert.equal(ev("ip4Why(S.offers[0])"), ''); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 1, 'signed: IPv4 is plentiful here'); + assert.equal(ev('R.cost.ip4'), undefined); + ev("ACT.ip4Buy({len:24})"); + assert.equal(ev('S.ip4.b.length'), 1, 'the market is closed'); + ev("ACT.bank()"); + assert.equal(dom.window.document.getElementById('bankIp4'), null, 'no address space in the bank'); + ev("ACT.bankClose()"); + // Sandbox and scenarios. + ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), false, 'sandbox'); + ev("beginGame('S','fra',{mode:'normal',preset:'oncall',scn:SCN.find(x=>x.city==='fra')||SCN[0]});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev("S.mode"), 'scenario'); + assert.equal(ev('ip4On()'), false, 'scenarios run On-call but stay as they were'); + ev('S.scn.rules.ip4=true'); + assert.equal(ev('ip4On()'), true, 'unless they opt in'); + ev("beginGame('B','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), true, 'BGP at 3 a.m.'); + assert.deepEqual(errors, []); +}); + +test('old saves: what they already use is registered to them, so nothing changes on load', (t) => { + const { ev, errors } = game(t); + homes(ev, 300); + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'dia', bw: 10, id: 'd1' }); + biz(ev, { type: 'l2vpn', bw: 10, id: 'l1' }); + // The same network without the rule, for its money. + ev("window.__r=S.rules;S.rules=makeRules('freeze');compute();window.__m=[R.revMo,R.costMo];S.rules=__r"); + ev('S.day=400;delete S.ip4;S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + const u = J(ev, 'ip4Use()'); + assert.equal(u.cg, 0, 'no home behind CGNAT'); + const want = (u.B + u.H) * 1.25; + assert.ok(u.T >= want && u.T - want < 256, 'what they use and a quarter more to grow into, rounded up to whole /24s: ' + JSON.stringify(u)); + assert.ok(J(ev, 'S.ip4.b').every((b) => b.k === 'rir' && b.d === 400 && b.len >= 16 && b.len <= 24)); + assert.deepEqual([ev('R.revMo'), ev('R.costMo')], J(ev, '__m'), 'the same money as before the feature'); + // A tiny old save still gets the /21 a new one starts with. + ev("S.biz=[];S.pops.fra.bb.d=1;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>b.len)'), [21]); + // A big old network: whole /16s. + ev("S.pops.fra.bb.d=20000;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + const big = J(ev, 'ip4Use()'); + assert.ok(big.T >= 200000 && big.cg === 0 && J(ev, 'S.ip4.b.filter(b=>b.len===16).length') === 3); + assert.deepEqual(errors, []); +}); + +test('the big network loads with its usage granted: routing and money as before', (t) => { + const { ev, dom, errors } = load({ seed: 3 }); + t.after(() => dom.window.close()); + const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); + const on = ev('ip4On()'); + const digest = 'JSON.stringify([R.served,R.revMo,R.costMo,R.cost,R.rev])'; + const a = ev(digest); + ev("window.__r=S.rules;S.rules=Object.assign({},S.rules,{ip4:false});compute()"); + assert.equal(ev(digest), a, 'the grant covers it all (rule ' + (on ? 'on' : 'off') + ')'); + assert.equal(J(ev, 'S.ip4.b.length') > 0, true); + assert.deepEqual(errors, []); +}); + +test('saves: garbage is repaired, and the state round-trips', (t) => { + const { ev, errors } = game(t); + ev("ACT.ip4Lease({len:23});ACT.ip4Nat({v:'32'})"); + const before = ev('JSON.stringify(S.ip4)'); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + ev(`S.ip4={b:[{id:'a',len:12,k:'rir',d:0},{id:'b',len:24,k:'stolen',d:0},{id:'c',len:24,k:'buy',d:-5,out:'yes',mo:5},{id:'d',len:23,k:'in',d:1e9,mo:-3},null,{id:'e',len:24,k:'rir',d:0,out:true,mo:'x'}],nat:7,w:99};S=sanitize(JSON.parse(JSON.stringify(S)))`); + assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, w: 3 }); + ev("S.ip4='nope';S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.ok(J(ev, 'S.ip4.b.length') >= 1, 'a broken field is granted afresh'); + assert.deepEqual(errors, []); +}); + +test('the address space works on a phone: one column, wrapping buttons, the dropdowns stacked', (t) => { + const { ev, dom, errors } = game(t); + ev("window.innerWidth=360;window.innerHeight=740;S.pops.fra.bb.d=250;compute();ACT.ip4Lease({len:24});ACT.ip4Open()"); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.ok(sec, 'the section is in the bank'); + assert.equal(sec.querySelectorAll('select').length, 2, 'the CGNAT ratio and the block size'); + for (const s of sec.querySelectorAll('select')) assert.ok(s.closest('.ops-sel'), 'each dropdown in a stacking label'); + for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); + assert.match(sec.textContent, /2,500, \d+% behind CGNAT/); + // The dropdown picks the size the buttons quote. + ev("ACT.ip4Pick({v:'18'})"); + assert.ok(dom.window.document.querySelector('#bankCard [data-act="ip4Buy"]').dataset.args.includes('"len":18')); + assert.deepEqual(errors, []); +}); + +test('no raw labels in the address space, in every language', (t) => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + ev(BASE); + ev("S.pops.fra.bb.d=300;compute();ACT.ip4Lease({len:24});ACT.ip4Buy({len:24});S.ip4.b[2].out=true;S.ip4.b[2].mo=99;S.biz.push({id:'z',city:'fra',city2:null,reqs:[],name:'Z',type:'host',bw:1e6,rate:1,mood:100,since:0});compute();ip4Day(S.day);ACT.ip4Open()"); + ev("S.offers.push({id:'o',city:'fra',name:'O',type:'host',bw:80,rate:60,reqs:[],exp:S.day+30});UI.left='deals';renderLeft()"); + ev("for(let i=S.ip4.b.length;i 2, lang + ': the full list and the blocks in use say why'); + const txt = dom.window.document.getElementById('bankCard').textContent + dom.window.document.getElementById('leftBody').textContent + dom.window.document.getElementById('toasts').textContent; + assert.doesNotMatch(txt, /\bip4\.[a-z_]+|\{[a-z]+\}|undefined|NaN/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 91e9080..7d1f3e3 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -256,7 +256,8 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'], - ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']]; + ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'], + ['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()']]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); // and in play: no chaos and no market means a quiet year const g = load(); @@ -372,6 +373,23 @@ test('F1: new players get a gentle start: nothing breaks for 45 days, no sold-ou assert.deepEqual(g.errors, []); }); +test('F1: the first IPv4 block covers the start: no CGNAT, no IPv4 bill and no IPv4 warning before day 50', () => { + // The F2 reference build, signing every offer that fits, in the F2 cities and the fastest-growing big homes (Asia). + const bad = []; + for (const city of ['fra', 'nyc', 'sin', 'jnb', 'tok', 'del']) { + const g = load(); + g.ev(`beginGame('Ref','${city}',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()`); + g.ev(`(()=>{const c='${city}',n=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0]; + ACT.launchBB({city:c});ACT.buyTransit({city:c,net:n.id,tier:1});if(ixName(c)){ACT.buyIx({city:c,tier:1,signed:true});ACT.rs({city:c});}})()`); + assert.equal(g.ev('ip4On()'), true, 'On-call has scarce IPv4'); + const hit = g.ev(`(()=>{for(let d=0;d<50;d++){for(const o of S.offers.slice())if(bHas(o)&&ip4Fits(o))ACT.accept({id:o.id});dayTick(); + const u=ip4Use();if(u.cg>0||S.ip4.w||R.cost.ip4)return 'day '+S.day+': '+u.cg+' of '+u.H+' homes behind CGNAT, bill '+(R.cost.ip4||0);}return '';})()`); + if (hit) bad.push(`${city}: ${hit}`); + assert.deepEqual(g.errors, []); + } + fail('F1', bad, 'size the first allocation (IP4_START, src/game/60-features/33-address-space.js) so the start fits'); +}); + test('F2: a simple build in a start city makes money within three months on On-call', () => { // Reference build: launch broadband, the cheapest 100G transit in town, and a port with a route server where there is an exchange. const bad = []; diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 91cce81..71230db 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -227,7 +227,7 @@ test('a dry run prices every command that has a price, and changes nothing', () fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, - pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, + pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); assert.deepEqual(missing, [], 'every priced command with arguments has a sample here'); diff --git a/tests/sales-desk.test.js b/tests/sales-desk.test.js index 1a3190b..d633a6b 100644 --- a/tests/sales-desk.test.js +++ b/tests/sales-desk.test.js @@ -80,6 +80,8 @@ test('the shark: bigger deals at a quarter more, oversold promises, no nerds, a test('the CEO: golf deals at 30% off, the odd declined offer signed anyway, opinions; all from hashes, not Math.random', () => { const { ev, errors } = load(); ev(start); + // Room for every deal he signs (#150: nobody signs what the network has no IPv4 addresses for), so this counts handshakes. + ev("S.ip4.b.push({id:'room',len:16,k:'buy',d:0})"); ev("ACT.salesHire({id:'ceo'})"); ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};'); const n0 = ev('S.biz.length'); From 8e1f2d66a5ffe42945b7cd4e5182beec9939f200 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:06:30 +0100 Subject: [PATCH 6/8] Express fiber: light a wave through a city without its router (#58) An express lightpath runs from A to C over your own or IRU dark fibers A-B, B-C (up to six) and passes B through its ROADM as light: ports only at its two ends, no hop in B, the fibers' latency added up. It takes one channel slot on every fiber it rides, needs a ROADM line system on each, and an optic that makes the whole run between regen sites. Routing, the route worker, traceroute, diverse paths and saves see it as a link A-C. A cut, a build, an amp or ROADM failure or a line system swap on any fiber under it darkens it; backhoes and the chaos monkey still find fibers that only carry expresses. "Express to..." on a fiber and an Express tab in the link window plan one, with reach, slots per fiber and the price. The intern's optics order leaves fibers that only carry expresses bare, decom never hands one back, and the build standard keeps a fiber's line system while an express on it carries traffic. --- CHANGELOG.md | 1 + site/i18n/de.js | 40 ++ site/i18n/es.js | 40 ++ site/i18n/fr.js | 40 ++ site/i18n/it.js | 40 ++ site/i18n/pt.js | 40 ++ src/agent/20-commands.js | 10 +- src/agent/30-docs.js | 2 +- src/game/10-catalog/40-ports.js | 4 +- src/game/10-catalog/60-reach-and-subsea.js | 6 +- src/game/60-features/20-scenarios.js | 2 +- src/game/60-features/50-traceroute.js | 2 +- src/game/60-features/95-standing-orders.js | 5 +- src/game/60-features/96-pop-standard.js | 5 +- src/game/80-simulation/30-compute.js | 7 +- src/game/80-simulation/40-billing.js | 4 +- src/game/80-simulation/50-sanitize.js | 3 +- src/game/80-simulation/60-requirements.js | 6 +- src/game/80-simulation/65-express.js | 87 ++++ .../80-simulation/80-geography-and-latency.js | 2 +- src/game/85-incidents/20-failures.js | 15 +- src/game/85-incidents/40-chaos-monkey.js | 4 +- src/game/90-actions/50-customers.js | 2 +- src/game/90-actions/60-links.js | 4 +- src/game/90-actions/87-express.js | 22 + src/game/90-actions/87-fiber-and-hardware.js | 8 +- src/game/90-actions/88-optic-counts.js | 2 +- src/game/90-actions/90-action-helpers.js | 6 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/60-decommission.js | 3 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/93-ui/72-express.js | 48 +++ src/game/94-dashboard/50-lease-swaps.js | 4 +- src/game/95-modals/70-link-modal.js | 7 +- src/game/96-map/50-link-geometry.js | 2 + src/game/96-map/51-express-geometry.js | 5 + src/game/96-map/55-link-look.js | 10 +- src/i18n/en.js | 40 ++ src/styles/40-modal.css | 2 + tests/express-fiber.test.js | 398 ++++++++++++++++++ tests/mcp-commands.test.js | 2 +- 41 files changed, 883 insertions(+), 53 deletions(-) create mode 100644 src/game/80-simulation/65-express.js create mode 100644 src/game/90-actions/87-express.js create mode 100644 src/game/93-ui/72-express.js create mode 100644 src/game/96-map/51-express-geometry.js create mode 100644 tests/express-fiber.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e5f8d8e..639dbf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project are documented here. The project follows - Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). +- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). diff --git a/site/i18n/de.js b/site/i18n/de.js index a152ee3..bccdbe8 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2020,6 +2020,46 @@ "exchanges.20_peering_sessions_n":"20+ Peering-Sessions ({n})", "exchanges.pops_on_3_continents":"POPs auf 3+ Kontinenten", "exchanges.serve_1_5_tbps_v":"1,5 Tbps ausliefern ({v})", +"express.already":{"one":"Auf diesem Weg läuft schon ein Express mit {n} Kanal: Das hier kommt dazu.","other":"Auf diesem Weg läuft schon ein Express mit {n} Kanälen: Das hier kommt dazu."}, +"express.cannot":"{optic} geht auf diesem Express nicht.
{why}", +"express.cap":"{cap} Express", +"express.city_via":"Express über {via}", +"express.dark_building":{"one":"{span} wird noch gebaut: noch {n} Tag.","other":"{span} wird noch gebaut: noch {n} Tage."}, +"express.dark_cut":"{span} ist gekappt.", +"express.dark_gone":"Eine der Glasfasern darunter gibt es nicht mehr.", +"express.dark_reach":"Keine ihrer Optiken schafft diese Strecke.", +"express.dark_system":"Auf {span} ist das Line System down.", +"express.express_to":"Express nach …", +"express.eyebrow":"Express-Lightpath · {km} km", +"express.fiber_busy":{"one":"Über diese Glasfaser läuft ein Express-Lightpath.
Bau ihn zuerst ab: Öffne ihn im Express-Abschnitt dieser Glasfaser.","other":"Über diese Glasfaser laufen {n} Express-Lightpaths.
Bau sie zuerst ab: Öffne sie im Express-Abschnitt dieser Glasfaser."}, +"express.fiber_full":"{a} ⇄ {b} hat keinen freien Kanal-Slot mehr ({max} im Line System).", +"express.free_slots":"{n} von {max} Slots frei", +"express.its_fibers":"Die Glasfasern darunter", +"express.last_channel":"Das ist der letzte Kanal des Express. Wenn du ihn loswerden willst, bau den Express ab.", +"express.lead":"Schick eine Wave am anderen Ende direkt durch den ROADM auf deine nächste Glasfaser: keine Router-Ports in der Stadt dazwischen, weniger Latenz, ein Kanal-Slot auf jeder Glasfaser, über die sie läuft.", +"express.lit":"Express leuchtet: {a} ⇄ {b}.
{optic} läuft direkt durch {via}: Kein Router dort bekommt sie zu sehen.", +"express.modal_lead":"Schick eine Wave von {a} nach {b} durch die ROADMs unterwegs: Die Städte dazwischen sehen sie auf keinem Router.", +"express.modal_note":"Der erste Kanal zahlt außerdem {price} pro Stadt unterwegs, damit er dort durch den ROADM gepatcht wird. Optiken aus dem Ersatzteilregal sind gratis; jeder Regen-Standort unterwegs braucht eine Karte.", +"express.n_carry_expresses":{"one":"{n} trägt einen Express","other":"{n} tragen Express-Lightpaths"}, +"express.n_channels":{"one":"{n} Kanal","other":"{n} Kanäle"}, +"express.needs_roadm":"Jede Glasfaser unter einem Express braucht ein ROADMaster-Line-System (oben unter Line System upgraden).", +"express.no_such_path":"Diese Glasfasern führen nicht mehr von der einen Stadt zur anderen.", +"express.one_more":"Noch eine {optic} auf dem Express {a} ⇄ {b}: jetzt {n} Kanäle.", +"express.optical_run":"Längste Strecke ohne Regen", +"express.out_of_reach":"außer Reichweite", +"express.passes":"Läuft als Licht durch den ROADM in {via}: Dort kein Router-Port, kein Hop im Traceroute.", +"express.plan":"Planen", +"express.riding_here":"Auf dieser Glasfaser", +"express.riding_note":"Bau sie ab, bevor du die Glasfaser aufgibst. Ein Schnitt oder ein Line-System-Tausch hier macht sie auch dunkel.", +"express.runs_at":"läuft mit {g}", +"express.slot_note":"Jeder Kanal belegt einen Slot auf jeder dieser Glasfasern. Ein Schnitt, ein Bau oder ein Line-System-Tausch auf einer davon macht den Express dunkel.", +"express.tab":"Express", +"express.tear_down":"Express abbauen", +"express.tear_down_note":"Seine Optiken kommen ins Ersatzteilregal.", +"express.title":"Express-Lightpaths", +"express.too_far":"Zu weit: Das Licht läuft {run} km ohne Regen-Standort, und diese Optik schafft selbst im langsamsten Modus nur {max} km. Bau Regen-Standorte auf den Glasfasern.", +"express.trace_hop":"Express-Lightpath, durchquert {via} nur als Licht", +"express.via_km":"über {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Eine Hitzewelle mit 45 °C in {city}: Das Stromnetz hat Last abgeworfen, die Kältemaschinen haben aufgegeben, und der Generator bei {dc} auch.", "failures.a_b_is_down_same_cable":"{a}–{b} ist down. Gleiches Kabel, neuer Anker. Der Reparaturtrupp hat eine Stempelkarte angelegt.", "failures.a_backhoe_cut_the_metro_ring":"Ein Bagger hat den Metro-Ring zwischen deinen beiden Standorten in {city} gekappt. Wie sich herausstellt, liefen beide Glasfaserwege durch dieselbe Straße.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 1f8b28a..9ec154f 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sesiones de peering ({n})", "exchanges.pops_on_3_continents":"POPs en 3+ continentes", "exchanges.serve_1_5_tbps_v":"sirve 1,5 Tbps ({v})", +"express.already":{"one":"Ya tienes un exprés por este camino con {n} canal: esto añade otro.","other":"Ya tienes un exprés por este camino con {n} canales: esto añade otro."}, +"express.cannot":"No se puede encender {optic} en este exprés.
{why}", +"express.cap":"{cap} exprés", +"express.city_via":"exprés por {via}", +"express.dark_building":{"one":"{span} todavía se está construyendo: queda {n} día.","other":"{span} todavía se está construyendo: quedan {n} días."}, +"express.dark_cut":"{span} está cortada.", +"express.dark_gone":"Una de las fibras por debajo ya no existe.", +"express.dark_reach":"Ninguna de sus ópticas llega tan lejos.", +"express.dark_system":"{span} tiene el sistema de línea caído.", +"express.express_to":"Exprés a…", +"express.eyebrow":"Lightpath exprés · {km} km", +"express.fiber_busy":{"one":"Un lightpath exprés va por esta fibra.
Desmóntalo primero: ábrelo desde la sección Exprés de esta fibra.","other":"{n} lightpaths exprés van por esta fibra.
Desmóntalos primero: ábrelos desde la sección Exprés de esta fibra."}, +"express.fiber_full":"{a} ⇄ {b} no tiene ningún hueco de canal libre ({max} en su sistema de línea).", +"express.free_slots":"{n} de {max} huecos libres", +"express.its_fibers":"Las fibras por las que va", +"express.last_channel":"Es el último canal del exprés. Para quitarlo, desmonta el exprés.", +"express.lead":"Manda una onda directo por el ROADM del otro extremo a tu siguiente fibra: sin puertos de router en la ciudad de en medio, menos latencia, un hueco de canal en cada fibra que recorre.", +"express.lit":"Exprés encendido: {a} ⇄ {b}.
{optic} pasa directo por {via}: ningún router de allí la ve.", +"express.modal_lead":"Enciende una onda de {a} a {b} a través de los ROADMs del camino: las ciudades de en medio nunca la ven en un router.", +"express.modal_note":"El primer canal paga además {price} por cada ciudad por la que pasa, para cruzarlo por el ROADM de allí. Las ópticas del estante de repuestos salen gratis; cada sitio regenerador del camino necesita una tarjeta.", +"express.n_carry_expresses":{"one":"{n} lleva un exprés","other":"{n} llevan lightpaths exprés"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canales"}, +"express.needs_roadm":"Cada fibra por la que va un exprés necesita un sistema de línea ROADMaster (mejóralo arriba, en Sistema de línea).", +"express.no_such_path":"Esas fibras ya no enlazan una ciudad con la otra.", +"express.one_more":"Otra {optic} en el exprés {a} ⇄ {b}: ahora {n} canales.", +"express.optical_run":"Tramo más largo sin regenerar", +"express.out_of_reach":"fuera de alcance", +"express.passes":"Pasa por {via} como luz, a través del ROADM: allí ni puerto de router ni salto en un traceroute.", +"express.plan":"Planear", +"express.riding_here":"Por esta fibra", +"express.riding_note":"Desmóntalos antes de dejar la fibra. Un corte o un cambio de sistema de línea aquí también los apaga.", +"express.runs_at":"va a {g}", +"express.slot_note":"Cada canal ocupa un hueco en cada una de estas fibras. Un corte, una obra o un cambio de sistema de línea en cualquiera de ellas apaga el exprés.", +"express.tab":"Exprés", +"express.tear_down":"Desmontar el exprés", +"express.tear_down_note":"Sus ópticas vuelven al estante de repuestos.", +"express.title":"Lightpaths exprés", +"express.too_far":"Demasiado lejos: la luz recorre {run} km sin sitio regenerador y esta óptica llega a {max} km en su modo más lento. Añade sitios regeneradores en las fibras.", +"express.trace_hop":"lightpath exprés, cruza {via} solo como luz", +"express.via_km":"por {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Una ola de calor de 45 °C en {city}: la red recortó carga, los enfriadores se rindieron y también el generador de {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} está caído. Mismo cable, ancla nueva. El equipo de reparación ya tiene tarjeta de fidelidad.", "failures.a_backhoe_cut_the_metro_ring":"Una retroexcavadora cortó el anillo metropolitano entre tus dos sedes en {city}. Resulta que ambas rutas de fibra pasaban por la misma calle.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 7729036..ec461d3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessions de peering ({n})", "exchanges.pops_on_3_continents":"POP sur 3+ continents", "exchanges.serve_1_5_tbps_v":"servir 1,5 Tbps ({v})", +"express.already":{"one":"Tu as déjà un express sur ce chemin avec {n} canal : ceci en ajoute un.","other":"Tu as déjà un express sur ce chemin avec {n} canaux : ceci en ajoute un."}, +"express.cannot":"Impossible d’allumer {optic} sur cet express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} est encore en construction : encore {n} jour.","other":"{span} est encore en construction : encore {n} jours."}, +"express.dark_cut":"{span} est coupée.", +"express.dark_gone":"Une des fibres en dessous n’existe plus.", +"express.dark_reach":"Aucune de ses optiques ne porte aussi loin.", +"express.dark_system":"{span} a son système de ligne en panne.", +"express.express_to":"Express vers…", +"express.eyebrow":"Lightpath express · {km} km", +"express.fiber_busy":{"one":"Un lightpath express passe par cette fibre.
Démonte-le d’abord : ouvre-le depuis la section Express de cette fibre.","other":"{n} lightpaths express passent par cette fibre.
Démonte-les d’abord : ouvre-les depuis la section Express de cette fibre."}, +"express.fiber_full":"{a} ⇄ {b} n’a plus d’emplacement de canal libre ({max} sur son système de ligne).", +"express.free_slots":"{n} emplacements libres sur {max}", +"express.its_fibers":"Les fibres qu’il emprunte", +"express.last_channel":"C’est le dernier canal de l’express. Pour l’arrêter, démonte l’express.", +"express.lead":"Envoie une onde tout droit à travers le ROADM du bout opposé, sur ta fibre suivante : aucun port de routeur dans la ville du milieu, moins de latence, un emplacement de canal sur chaque fibre empruntée.", +"express.lit":"Express allumé : {a} ⇄ {b}.
{optic} traverse {via} tout droit : aucun routeur là-bas ne la voit.", +"express.modal_lead":"Allume une onde de {a} à {b} à travers les ROADM du chemin : les villes du milieu ne la voient jamais sur un routeur.", +"express.modal_note":"Le premier canal paie aussi {price} pour chaque ville traversée, pour le brasser dans le ROADM sur place. Les optiques de l’étagère de rechange sont gratuites ; chaque site de régénération du chemin demande une carte.", +"express.n_carry_expresses":{"one":"{n} porte un express","other":"{n} portent des lightpaths express"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canaux"}, +"express.needs_roadm":"Chaque fibre empruntée par un express a besoin d’un système de ligne ROADMaster (mets-le à niveau plus haut, dans Système de ligne).", +"express.no_such_path":"Ces fibres ne relient plus une ville à l’autre.", +"express.one_more":"Une {optic} de plus sur l’express {a} ⇄ {b} : {n} canaux maintenant.", +"express.optical_run":"Plus longue portée sans régénération", +"express.out_of_reach":"hors de portée", +"express.passes":"Traverse {via} sous forme de lumière, par le ROADM : aucun port de routeur là-bas, aucun saut dans un traceroute.", +"express.plan":"Préparer", +"express.riding_here":"Sur cette fibre", +"express.riding_note":"Démonte-les avant d’abandonner la fibre. Une coupure ou un changement de système de ligne ici les éteint aussi.", +"express.runs_at":"tourne à {g}", +"express.slot_note":"Chaque canal prend un emplacement sur chacune de ces fibres. Une coupure, un chantier ou un changement de système de ligne sur l’une d’elles éteint l’express.", +"express.tab":"Express", +"express.tear_down":"Démonter l’express", +"express.tear_down_note":"Ses optiques retournent sur l’étagère de rechange.", +"express.title":"Lightpaths express", +"express.too_far":"Trop loin : la lumière parcourt {run} km sans site de régénération et cette optique porte à {max} km dans son mode le plus lent. Ajoute des sites de régénération sur les fibres.", +"express.trace_hop":"lightpath express, traverse {via} sous forme de lumière", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Canicule à 45 °C à {city} : le réseau a délesté, les groupes froids ont lâché, et le groupe électrogène de {dc} aussi.", "failures.a_b_is_down_same_cable":"{a}–{b} est en panne. Même câble, nouvelle ancre. L’équipe de réparation a créé une carte de fidélité.", "failures.a_backhoe_cut_the_metro_ring":"Une pelleteuse a coupé l’anneau métropolitain entre tes deux sites à {city}. En fait, les deux chemins de fibre passaient par la même rue.", diff --git a/site/i18n/it.js b/site/i18n/it.js index cc61779..06d88d6 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessioni di peering ({n})", "exchanges.pops_on_3_continents":"POP in 3+ continenti", "exchanges.serve_1_5_tbps_v":"servire 1,5 Tbps ({v})", +"express.already":{"one":"Su questo percorso hai già un express con {n} canale: così ne aggiungi un altro.","other":"Su questo percorso hai già un express con {n} canali: così ne aggiungi un altro."}, +"express.cannot":"Impossibile accendere {optic} su questo express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} è ancora in costruzione: manca {n} giorno.","other":"{span} è ancora in costruzione: mancano {n} giorni."}, +"express.dark_cut":"{span} è tranciata.", +"express.dark_gone":"Una delle fibre sotto non c’è più.", +"express.dark_reach":"Nessuna delle sue ottiche arriva così lontano.", +"express.dark_system":"{span} ha il line system giù.", +"express.express_to":"Express verso…", +"express.eyebrow":"Lightpath express · {km} km", +"express.fiber_busy":{"one":"Su questa fibra passa un lightpath express.
Smontalo prima: aprilo dalla sezione Express di questa fibra.","other":"Su questa fibra passano {n} lightpath express.
Smontali prima: aprili dalla sezione Express di questa fibra."}, +"express.fiber_full":"{a} ⇄ {b} non ha più slot di canale liberi ({max} sul suo line system).", +"express.free_slots":"{n} slot liberi su {max}", +"express.its_fibers":"Le fibre su cui viaggia", +"express.last_channel":"È l’ultimo canale dell’express. Per fermarlo, smonta l’express.", +"express.lead":"Manda una wave dritta attraverso il ROADM all’altro capo, sulla tua fibra successiva: niente porte router nella città in mezzo, meno latenza, uno slot di canale su ogni fibra che percorre.", +"express.lit":"Express acceso: {a} ⇄ {b}.
{optic} passa dritta per {via}: nessun router lì la vede.", +"express.modal_lead":"Accendi una wave da {a} a {b} attraverso i ROADM lungo la strada: le città in mezzo non la vedono mai su un router.", +"express.modal_note":"Il primo canale paga anche {price} per ogni città che attraversa, per farlo passare nel ROADM lì. Le ottiche dallo scaffale dei ricambi sono gratis; ogni sito di rigenerazione lungo la strada vuole una scheda.", +"express.n_carry_expresses":{"one":"{n} porta un express","other":"{n} portano lightpath express"}, +"express.n_channels":{"one":"{n} canale","other":"{n} canali"}, +"express.needs_roadm":"Ogni fibra su cui viaggia un express ha bisogno di un line system ROADMaster (aggiornalo qui sopra, in Sistema di linea).", +"express.no_such_path":"Quelle fibre non collegano più una città all’altra.", +"express.one_more":"Un’altra {optic} sull’express {a} ⇄ {b}: ora {n} canali.", +"express.optical_run":"Tratta più lunga senza rigenerazione", +"express.out_of_reach":"fuori portata", +"express.passes":"Attraversa {via} come luce, dentro il ROADM: lì niente porta router, niente hop in un traceroute.", +"express.plan":"Pianifica", +"express.riding_here":"Su questa fibra", +"express.riding_note":"Smontali prima di abbandonare la fibra. Un taglio o un cambio di line system qui spegne anche loro.", +"express.runs_at":"va a {g}", +"express.slot_note":"Ogni canale occupa uno slot su ciascuna di queste fibre. Un taglio, un cantiere o un cambio di line system su una qualsiasi di esse spegne l’express.", +"express.tab":"Express", +"express.tear_down":"Smonta l’express", +"express.tear_down_note":"Le sue ottiche tornano sullo scaffale dei ricambi.", +"express.title":"Lightpath express", +"express.too_far":"Troppo lontano: la luce percorre {run} km senza un sito di rigenerazione e questa ottica arriva a {max} km nella modalità più lenta. Aggiungi siti di rigenerazione sulle fibre.", +"express.trace_hop":"lightpath express, attraversa {via} solo come luce", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Ondata di caldo a 45 °C a {city}: la rete ha staccato carichi, i chiller si sono arresi e anche il generatore di {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} è giù. Stesso cavo, ancora nuova. La squadra di riparazione ha aperto una tessera fedeltà.", "failures.a_backhoe_cut_the_metro_ring":"Una ruspa ha tagliato il ring metropolitano tra i tuoi due siti a {city}. A quanto pare entrambe le tratte in fibra passavano per la stessa strada.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 5fc3410..4714044 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2018,6 +2018,46 @@ "exchanges.20_peering_sessions_n":"20+ sessões de peering ({n})", "exchanges.pops_on_3_continents":"POPs em 3+ continentes", "exchanges.serve_1_5_tbps_v":"entregar 1,5 Tbps ({v})", +"express.already":{"one":"Você já tem um expresso neste caminho com {n} canal: isto adiciona mais um.","other":"Você já tem um expresso neste caminho com {n} canais: isto adiciona mais um."}, +"express.cannot":"Não dá para acender {optic} neste expresso.
{why}", +"express.cap":"{cap} expresso", +"express.city_via":"expresso via {via}", +"express.dark_building":{"one":"{span} ainda está em construção: falta {n} dia.","other":"{span} ainda está em construção: faltam {n} dias."}, +"express.dark_cut":"{span} está cortada.", +"express.dark_gone":"Uma das fibras por baixo não existe mais.", +"express.dark_reach":"Nenhuma das suas ópticas alcança essa distância.", +"express.dark_system":"{span} está com o line system fora do ar.", +"express.express_to":"Expresso para…", +"express.eyebrow":"Lightpath expresso · {km} km", +"express.fiber_busy":{"one":"Um lightpath expresso passa por esta fibra.
Desmonte-o primeiro: abra-o na seção Expresso desta fibra.","other":"{n} lightpaths expressos passam por esta fibra.
Desmonte-os primeiro: abra-os na seção Expresso desta fibra."}, +"express.fiber_full":"{a} ⇄ {b} não tem mais slot de canal livre ({max} no seu line system).", +"express.free_slots":"{n} de {max} slots livres", +"express.its_fibers":"As fibras por onde ele passa", +"express.last_channel":"Esse é o último canal do expresso. Para parar, desmonte o expresso.", +"express.lead":"Mande uma onda direto pelo ROADM da outra ponta para a sua próxima fibra: sem portas de router na cidade do meio, menos latência, um slot de canal em cada fibra que ela percorre.", +"express.lit":"Expresso aceso: {a} ⇄ {b}.
{optic} passa direto por {via}: nenhum router lá a vê.", +"express.modal_lead":"Acenda uma onda de {a} a {b} pelos ROADMs do caminho: as cidades do meio nunca a veem num router.", +"express.modal_note":"O primeiro canal também paga {price} por cidade que atravessa, para passá-lo pelo ROADM de lá. Ópticas da prateleira de reservas saem de graça; cada site de regeneração no caminho precisa de uma placa.", +"express.n_carry_expresses":{"one":"{n} leva um expresso","other":"{n} levam lightpaths expressos"}, +"express.n_channels":{"one":"{n} canal","other":"{n} canais"}, +"express.needs_roadm":"Cada fibra por onde um expresso passa precisa de um line system ROADMaster (faça o upgrade acima, em Sistema de linha).", +"express.no_such_path":"Essas fibras não ligam mais uma cidade à outra.", +"express.one_more":"Mais uma {optic} no expresso {a} ⇄ {b}: agora {n} canais.", +"express.optical_run":"Maior trecho sem regeneração", +"express.out_of_reach":"fora de alcance", +"express.passes":"Atravessa {via} como luz, pelo ROADM: lá não usa porta de router nem aparece como salto no traceroute.", +"express.plan":"Planejar", +"express.riding_here":"Nesta fibra", +"express.riding_note":"Desmonte-os antes de abrir mão da fibra. Um corte ou uma troca do line system aqui também os apaga.", +"express.runs_at":"roda a {g}", +"express.slot_note":"Cada canal ocupa um slot em cada uma destas fibras. Um corte, uma obra ou uma troca do line system em qualquer uma delas apaga o expresso.", +"express.tab":"Expresso", +"express.tear_down":"Desmontar o expresso", +"express.tear_down_note":"As ópticas dele voltam para a prateleira de reservas.", +"express.title":"Lightpaths expressos", +"express.too_far":"Longe demais: a luz percorre {run} km sem site de regeneração e esta óptica alcança {max} km no modo mais lento. Adicione sites de regeneração nas fibras.", +"express.trace_hop":"lightpath expresso, passa por {via} só como luz", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"Onda de calor de 45 °C em {city}: a rede cortou carga, os chillers desistiram e o gerador do {dc} também.", "failures.a_b_is_down_same_cable":"{a}–{b} caiu. Mesmo cabo, âncora nova. A equipe de reparo criou um cartão fidelidade.", "failures.a_backhoe_cut_the_metro_ring":"Uma retroescavadeira cortou o anel metropolitano entre seus dois sites em {city}. Pelo visto, as duas rotas de fibra passavam pela mesma rua.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index cfb4e36..8ea9a36 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -123,7 +123,7 @@ const API_CMD={ quote:a=>{const A=a.a,B=a.b,tier=a.tier; if(!S.pops[A])return {blocked:[linkFromWhy(A)]}; if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; - const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; const blocked=[],so=soldOut(A,B,tier,wr.cab); @@ -230,6 +230,13 @@ const API_CMD={ setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'], quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:opticCountCost(l,a.o,a.n)}:{};}, doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, + xpBuild:{args:[['a','cityId'],['b','cityId'],['via','string'],['o','opticId']], + quote:a=>{const sp=xpParse(a.a,a.b,a.via);if(!sp||!OPT[a.o])return {setup:0,blocked:[tr('express.no_such_path')]};const old=xpFind(a.a,a.b,sp.map(s=>s.id)); + return {setup:xpCost(sp,a.o,!old),blocked:[xpWhy(a.a,a.b,sp,a.o)].filter(Boolean)};}, + doc:'Light an express lightpath from a to b straight through the ROADMs of the cities between: via is the ids of your ROADM dark fibers (land, own or IRU) in order from a, comma-separated, 2 to 6 of them. One optic, one channel slot on every fiber, ports only at a and b, and the light must reach the whole run between regen sites. The same path again adds a channel to that express. Give one up with rmLink.'}, + xpCh:{args:[['id','entityId'],['o','opticId'],['d','step']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id),sp=l&&l.kind==='xp'&&xpSpans(l);if(!sp||!OPT[a.o]||a.d<0)return {setup:0};return {setup:xpCost(sp,a.o,false),blocked:[xpWhy(l.a,l.b,sp,a.o)].filter(Boolean)};}, + doc:'Add (d:1) or unplug (d:-1) one channel of an optic on an express lightpath; unplugged optics go on the spares shelf. The last channel stays: rmLink gives the express up.'}, /* ---------- customers ---------- */ accept:{args:[['id','entityId']], doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, @@ -574,6 +581,7 @@ const API_BOUND={ via:{command:'buildLink',arg:'cable'}, route:{command:'buildLink',arg:'route'}, dfMode:{command:'orderDf',note:'opens the dark-fiber modal',arg:'a/b'}, + xpOpen:{command:'xpBuild',note:'opens the link window on its Express tab: the ways your ROADM fibers chain from a to b (via, fiber ids comma-separated, puts that path first)',arg:'a/b/via'}, dfSrc:{command:'orderDf',arg:'source'}, dfSys:{command:'orderDf',arg:'system'}, seaDesign:{command:'orderCable',arg:'design'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index c3d1212..12d573e 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -20,7 +20,7 @@ const API_STATE_DOC={ auV:{type:'integer',doc:'Australia content level gate.'}, seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc) and express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics), each with an entity id.'}, transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, rs:{type:'map',doc:'Route-server sessions by exchange city.'}, diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 8712607..a8cf7d0 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -15,7 +15,7 @@ const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c); in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */ const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;}; function portsUsed(c,g){let u=0; - for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} + for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'&&l.kind!=='xp'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} // A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours. for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1); for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); @@ -33,5 +33,5 @@ const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,''); function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return ''; if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn}); if([...S.transit,...S.pni,...(S.nni||[])].some(t=>t.city===c&&!t.pz&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); - if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='df'&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); + if(S.links.some(l=>(l.a===c||l.b===c)&&(l.kind==='df'||l.kind==='xp')&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); if(portsUsed(c,g)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c,g)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';} diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index d4f368f..4f0835e 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -69,9 +69,9 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; const dfCap0=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):l.kind==='xp'?xpG(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); -const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; -const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; +const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; +const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index e6e4956..17cebc0 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,7 +2,7 @@ gives the same world. Free play keeps using the browser's Math.random. */ const _rand=Math.random; Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();}; -const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; +const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)P.dist[e.city]!==undefined); lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index ce0dffb..3277d96 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -204,8 +204,9 @@ const OPS_RUN={ optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o); for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue; let cap=dfCap(l);const load=(R.load&&R.load[l.id])||0; - // New fiber gets its first channel; lit fiber gets more while it runs hot. - for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length:load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)<=0)break; + // New fiber gets its first channel; lit fiber gets more while it runs hot. A fiber that only carries expresses is + // not new: it was left bare so the city in the middle needs no router ports. + for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length&&!xpSlots(l):load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)<=0)break; const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1; // More of what is already lit, or else the most Gbps per dollar that reaches. Told to go big (#262), the intern // picks the most Gbps per channel it can afford for a new kind of optic, but never swaps what is already lit. diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index ae8aa3e..425caa5 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -182,7 +182,10 @@ function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen // ex: fibers already going dark today (id → whether they carry traffic): they carry nothing for this one, and one whose // traffic leans on its parallel links keeps them lit. const bstdBusy=l=>((R.load&&R.load[l.id])||0)>Math.max(1,capOf(l)*0.1); -function bstdDarkOk(l,ex){const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; +// Express lightpaths (#58) ride the fiber's glass: its own load says nothing about them, and its parallel links do not +// carry them, so an express with any traffic at all keeps the fiber lit (the line system waits, as for a busy fiber). +const bstdXpBusy=l=>xpSlots(l)>0&&xpOver(l.id).some(x=>((R.load&&R.load[x.id])||0)>1e-6); +function bstdDarkOk(l,ex){if(bstdXpBusy(l))return false;const P=pairLinks(l.a,l.b).filter(x=>x!==l);if(ex&&P.some(x=>ex.get(x.id)))return false;if(!bstdBusy(l))return true; return P.filter(x=>!linkDown(x)&&!x.standby&&!(ex&&ex.has(x.id))).reduce((a,x)=>a+Math.max(0,capOf(x)-((R.load&&R.load[x.id])||0)),0)>=((R.load&&R.load[l.id])||0);} // Do the plan's jobs in order. can(j): may it be paid for (budget, floor, cash); pay(j): run it, true if it took. // one: at most one fiber goes dark (the intern's shift); max: at most that many jobs tried, done or failed, so a shift's diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 4829518..1a4cf12 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -140,11 +140,12 @@ function compute(){RW.gen++; const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id); // disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer. const LA=[];for(const l of live){const ai=CIDX[l.a],bi=CIDX[l.b];(LA[ai]||(LA[ai]=[])).push([bi,l]);(LA[bi]||(LA[bi]=[])).push([ai,l]);} - const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); + // An express runs in the trenches of every fiber it rides: one backhoe in any of them takes it out. + const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id),hitR=(s,l)=>l.kind==='xp'?xpRisk(l).some(r=>s.has(r)):s.has(srlg(l)); const bfsI=(a,b,skip)=>{const prev=[],seen=new Uint8Array(NC),q=[a];seen[a]=1; - for(let h=0;h{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));}; + const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.flatMap(l=>l.kind==='xp'?xpRisk(l):[srlg(l)])));}; 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(PX&&m==='fast')return pieFast(PX,fastSP,A,B,b,wLat); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index b7dae0d..87d5139 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -2,7 +2,9 @@ // sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} -function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);} +// Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides). +function linkCut(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))));} +function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l));} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} // Monthly price of one connection; compute() sums these, the connections overview lists them. diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index b18f5b9..ed6494c 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,8 +21,9 @@ function sanitize(s){ if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); + xpSanitize(s); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ {const pm=s.pairMet,lo={};for(const l of s.links){if(l.metric!==undefined){const k=edgeKey(l),m=own(MET,l.metric)?l.metric:'normal';if(!lo[k]||MET[m].f{const ok=REQS[k].ok(o),lab=typeo function diversePaths(a,b){ const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c); return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));} -function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); +function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?['fab:'+l.prov]:l.kind==='xp'?xpRisk(l):[l.trench||l.id]; const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);} const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}} if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;}; - const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));} + const p1=bfs(live);if(!p1)return false;const used=new Set(p1.flatMap(srlg));return !!bfs(live.filter(l=>!srlg(l).some(r=>used.has(r))));} // Check buildable geography, not today's POPs, capacity or outages. Parallel land // routes can use separate trenches; all segments of one cable share its risk. let diversityMap=null; @@ -75,7 +75,7 @@ function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.lin function soldSlots(l,u){return u?u.sold.get(l.id)||0:S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);} // Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build // a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices. -const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u),pairFree=(l,u)=>!!l.own&&(u?u.dfp.get(l.id)||0:S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length)<2&&!(u?u.pairs.has(l.id):S.biz.some(b=>(b.type==='pairs'||b.type==='capfib')&&b.link===l.id)); +const freeCh=(l,u)=>chMax(l)-(l.ch||[]).length-soldSlots(l,u)-xpSlots(l),pairFree=(l,u)=>!!l.own&&(u?u.dfp.get(l.id)||0:S.biz.filter(b=>b.type==='dfpair'&&b.link===l.id).length)<2&&!(u?u.pairs.has(l.id):S.biz.some(b=>(b.type==='pairs'||b.type==='capfib')&&b.link===l.id)); const wwWhat=(l,n)=>trn('requirements.n_400g_alien_wave_on_your',n,{a:CITY[l.a].name,b:CITY[l.b].name}); function fiberOffer(t,l,nm,cut=1){ if(t==='wwave'){const slots=1+Math.floor(Math.random()*Math.min(4,freeCh(l))); diff --git a/src/game/80-simulation/65-express.js b/src/game/80-simulation/65-express.js new file mode 100644 index 0000000..d10ac7b --- /dev/null +++ b/src/game/80-simulation/65-express.js @@ -0,0 +1,87 @@ +/* Express lightpaths (#58): a wave from A to C over your own (or leased) dark fibers A–B, B–C… that passes B through its + ROADM as light, so B's routers never see it: no ports there, no hop, a little less latency. It is a link of its own + (kind 'xp') between A and C: via lists the fibers it rides in order from a, ch its optics. Every channel takes one + slot on each of those fibers, and the light has to make the whole run between regen sites in one go. */ +const XP_HOPS=6,XP_PASS=5000,XP_BUDGET=4000,XP_CH=64; +// The fibers an express can ride: dark fiber on land with a ROADMaster (your own build or an IRU). Subsea line +// systems end at the landing station, so a wave never runs through one into the land network. +const xpSpanOk=s=>!!s&&s.kind==='df'&&!s.sub&&isRdm(s.sys); +/* What the expresses take on each fiber, and the links by id, kept while S.links and every express's optics and path + are the same: the map, compute() and the free-channel checks ask often, and most networks have no express at all. */ +const XPX={L:null,n:-1,xs:[],m:null,ids:null}; +function xpIdx(){const L=S.links;let ok=XPX.L===L&&XPX.n===L.length; + if(ok)for(const x of XPX.xs)if((x[0].ch||[]).length!==x[1]||x[0].via!==x[2]){ok=false;break;} + if(!ok){const m=new Map(),xs=[];for(const l of L)if(l.kind==='xp'){const n=(l.ch||[]).length;xs.push([l,n,l.via]);for(const id of l.via||[])m.set(id,(m.get(id)||0)+n);} + XPX.L=L;XPX.n=L.length;XPX.xs=xs;XPX.m=m;XPX.ids=null;} + return XPX;} +function xpLink(id){const X=xpIdx();if(!X.ids){X.ids=new Map();for(const l of S.links)if(!X.ids.has(l.id))X.ids.set(l.id,l);}return X.ids.get(id);} +// Channel slots express channels take on fiber l. +function xpSlots(l){return xpIdx().m.get(l.id)||0;} +// The expresses riding fiber id, and a list of links with every express that rides one of them added. +const xpOver=id=>xpIdx().xs.filter(x=>(x[0].via||[]).includes(id)).map(x=>x[0]); +function xpWith(ls){const ids=new Set(ls.map(l=>l.id)),out=ls.slice();for(const [x] of xpIdx().xs)if(!ids.has(x.id)&&(x.via||[]).some(id=>ids.has(id))){out.push(x);ids.add(x.id);}return out;} +// The fibers of an express, in order (null when one is gone). +function xpSpans(l){const v=l.via;if(!Array.isArray(v)||!v.length)return null;const out=[];for(const id of v){const s=xpLink(id);if(!xpSpanOk(s))return null;out.push(s);}return out;} +// The cities a chain of fibers passes from a, end included; null when they do not chain or come back to a city. +function xpCities(a,sp){const cs=[a];let c=a;for(const s of sp){const n=s.a===c?s.b:s.b===c?s.a:null;if(!n||cs.includes(n))return null;cs.push(n);c=n;}return cs;} +// Free slots on a fiber for one more express channel: what its line system holds, less lit, sold and express channels. +const xpFree=s=>chMax(s)-(s.ch||[]).length-soldSlots(s)-xpSlots(s); +/* The longest stretch the light runs without being regenerated. Regen sites split each fiber into equal spans, as for + its own channels; through a city the light goes on, so the last span of one fiber and the first of the next add up. */ +function xpRunKm(sp){let cur=0,mx=0;for(const s of sp){const r=s.regen|0,p=s.km/(r+1);if(!r){cur+=s.km;continue;}cur+=p;if(cur>mx)mx=cur;if(p>mx)mx=p;cur=p;}return Math.ceil(Math.max(mx,cur));} +// What optic o carries over that run (0: out of reach), cached like every channel (optG). +const xpOptG=(o,run)=>OPT[o]?optG(o,{km:run}):0; +function xpG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);let g=0;for(const o of l.ch||[])g+=xpOptG(o,run);return g;} +// The fastest single channel, as a scenario's fast path asks of every hop. +function xpHopG(l){const sp=xpSpans(l);if(!sp)return 0;const run=xpRunKm(sp);return Math.max(0,...(l.ch||[]).map(o=>xpOptG(o,run)));} +// Dark when a fiber under it is cut, still being built or has its line system down, or nothing lit reaches. +function xpDown(l){const sp=xpSpans(l);if(!sp)return true;const d=S.day;for(const s of sp)if(linkCut(s)||s.ready>d||s.eqDown>d)return true;return xpG(l)<=0;} +// The cities an express passes without touching a router, for its labels. +function xpVia(l){const sp=xpSpans(l),cs=sp&&xpCities(l.a,sp);return cs?cs.slice(1,-1).map(c=>CITY[c].name).join(', '):'';} +// A fiber that carries only expresses is dark as a link of its own, but there is light in it: a backhoe or a monkey +// that cuts fibers still finds it. Fibers only: linkDown() of an express asks xpDown(), never this. +const xpBare=l=>l.kind==='df'&&!l.sub&&xpSlots(l)>0&&linkDown(l)&&!linkCut(l)&&!(l.ready>S.day)&&!(l.eqDown>S.day); +// The light runs the whole way in glass: the fibers' own latency added up, and no router in between. +function xpLat(l){const sp=xpSpans(l);return sp?sp.reduce((a,s)=>a+linkLat(s),0):l.km*1.1/200;} +// What one backhoe can take out: every trench the express runs in (diverse paths and redundancy checks). +function xpRisk(l){const sp=xpSpans(l);return sp?sp.map(s=>s.trench||s.id):[l.id];} +// The furthest any optic reaches at its slowest setting: a longer run is never worth listing. +let XP_REACH=0;const xpReachMax=()=>XP_REACH||(XP_REACH=Math.max(...Object.values(OPT).map(O=>O.modes.at(-1)[1]))); +/* Ways to chain ROADM fibers from city a: to b (every path, shortest first, k of them) or, with b null, the shortest + path to each city two or more fibers away. first: the path starts on that fiber. The search is bounded: a few dozen + fibers is a big optical network, and XP_HOPS and XP_BUDGET keep it small on the biggest. */ +function xpPaths(a,b,first,k=3){const adj=new Map();for(const s of S.links)if(xpSpanOk(s))for(const c of [s.a,s.b]){let L=adj.get(c);if(!L)adj.set(c,L=[]);L.push(s);} + if(!adj.has(a))return [];for(const L of adj.values())L.sort((x,y)=>x.km-y.km); + const out=[],best=new Map(),seen=new Set([a]),path=[];let budget=XP_BUDGET; + const go=(c,km)=>{for(const s of adj.get(c)||[]){if(--budget<0)return;if(!path.length&&first&&s!==first)continue;const n=s.a===c?s.b:s.a;if(seen.has(n))continue; + const d=km+s.km;path.push(s);seen.add(n); + if(path.length>=2){if(b==null){const o=best.get(n);if(!o||dx.km-y.km||x.sp.length-y.sp.length).slice(0,k);} +// The express already lit on this path, either way round. +function xpFind(a,b,ids){const k=ids.join(','),r=ids.slice().reverse().join(',');return xpIdx().xs.map(x=>x[0]).find(x=>(x.a===a&&x.b===b&&(x.via||[]).join(',')===k)||(x.a===b&&x.b===a&&(x.via||[]).join(',')===r))||null;} +// A typed order's path: fiber ids, comma-separated, chaining from a to b (null when it does not). +function xpParse(a,b,via){if(!isCity(a)||!isCity(b)||a===b||!S.pops[a]||!S.pops[b]||typeof via!=='string')return null;const ids=via.split(','); + if(ids.length<2||ids.length>XP_HOPS||new Set(ids).size!==ids.length)return null;const sp=ids.map(id=>S.links.find(x=>x.id===id)); + if(!sp.every(xpSpanOk))return null;const cs=xpCities(a,sp);return cs&&cs[cs.length-1]===b?sp:null;} +// Why one more channel of optic o cannot run from a to b over these fibers ('' when it can). +function xpWhy(a,b,sp,o){const O=OPT[o];if(!O)return '';if(!techOk('opt',o,O.lvl))return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl}); + const run=xpRunKm(sp);if(!xpOptG(o,run))return tr('express.too_far',{run:run.toLocaleString(),max:O.modes.at(-1)[1].toLocaleString()}); + for(const s of sp)if(xpFree(s)<1)return tr('express.fiber_full',{a:CITY[s.a].name,b:CITY[s.b].name,max:chMax(s)}); + for(const c of [a,b]){const p=S.pops[c];if(!p)return linkFromWhy(c);if(RG[p.rgen||0].clsa+(s.regen|0),0);return Math.round(optCost(o)*(spareN(o)>0?r:1+r))+(fresh?XP_PASS*(sp.length-1):0);} +// Taking a regen site off fiber l (to n sites) must leave every express on it in reach. +function xpRegenBad(l,n){return xpOver(l.id).some(x=>{const sp=xpSpans(x);if(!sp)return false;const run=xpRunKm(sp.map(s=>s===l?{km:s.km,regen:n}:s));return (x.ch||[]).some(o=>!xpOptG(o,run));});} +/* Saves: an express must ride fibers that are still there, chain from a to b and carry real optics; anything else is + dropped and its optics go back on the shelf. km is worked out again from the fibers. */ +function xpSanitize(s){const ids=new Map();for(const l of s.links)if(!ids.has(l.id))ids.set(l.id,l);const drop=new Set(); + for(const l of s.links){if(l.kind!=='xp')continue;const via=Array.isArray(l.via)?l.via.map(String):[],sp=via.map(id=>ids.get(id)),ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)).slice(0,XP_CH):[]; + let ok=via.length>=2&&via.length<=XP_HOPS&&new Set(via).size===via.length&&sp.every(xpSpanOk)&&ch.length>0; + if(ok){const cs=xpCities(l.a,sp);ok=!!cs&&cs[cs.length-1]===l.b;} + if(!ok){drop.add(l);if(ch.length){if(!s.spares||typeof s.spares!=='object'||Array.isArray(s.spares))s.spares={};for(const o of ch)s.spares[o]=(Math.floor(+s.spares[o])||0)+1;}continue;} + for(const k of ['cable','trench','seat','own','list','regen','sys','ready','eqDown','chFail','pairs','tier','premium','border','mult','prov','vt','spares','sub'])delete l[k]; + l.via=via;l.ch=ch;l.km=Math.max(1,Math.round(sp.reduce((a,x)=>a+num(x.km,0),0)));l.mo=0;} + if(drop.size)s.links=s.links.filter(l=>!drop.has(l));} diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index 72c8f0f..f48a5fd 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -30,7 +30,7 @@ const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg&&CITY[a].cc! function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);} function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two'); const r=[];if(landX(a,b))r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');} -function linkLat(l){const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} +function linkLat(l){if(l.kind==='xp')return xpLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} /* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York). diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 9266616..b4e3650 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -4,15 +4,18 @@ const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair( const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); function fireFailure(only){ const opts=[]; - const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; - if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);} + const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; + // A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it. + const bare=S.links.filter(xpBare),dug=live.concat(bare); + if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);} if(Object.keys(S.pops).length)opts.push(['crash',3],['power',2]); if(Object.values(S.pops).some(p=>p.site2))opts.push(['ring',1.2]); if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]); if(Object.keys(S.ixp).length)opts.push(['ixloop',2]); if(S.transit.length&&S.day>60)opts.push(['leak',2]); if(fabsUsed.length)opts.push(['fabric',1.5]); - const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l));if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]); + // Amp huts and ROADMs carry every channel in the glass, the expresses' too; an optic of its own needs a channel of its own. + const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l)),amps=lit.concat(bare);if(amps.length)opts.push(['amp',1.5+amps.length*0.3]);if(lit.length)opts.push(['optic',1.5+lit.length*0.3]); // Two vendors' idea of the same protocol: the higher the backbone runs, the more often they disagree. const iop=coreIopRisk()?coreIopLinks(live):[];if(iop.length)opts.push(['interop',3*coreIopRisk()]); opts.push(['funny',4]); @@ -20,7 +23,7 @@ function fireFailure(only){ let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0]; for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}} if(only)type=only; - if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);} + if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(amps.length)f.push('roadmff');type=pick(f);} const before=R.served; if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`${m[0]}
${m[1]}`,'goal');sfx('alert');return;} if(type==='ring'){const cs=Object.keys(S.pops).filter(c=>S.pops[c].site2),c=pick(cs),pp=S.pops[c],dur=2+Math.floor(Math.random()*3);pp.ringcut=S.day+dur; @@ -75,7 +78,7 @@ function fireFailure(only){ }else if(type==='rpki'){ S.ev.rpki={until:S.day+3,nets:NETS.map(n=>n.id).filter(()=>Math.random()<0.5)};addInc({type,ref:'rpki',until:S.day+3,msg:tr('failures.your_roa_expired_over_the_weekend'),cost:1000,fix:tr('failures.renew_the_roa')}); }else if(type==='amp'||type==='roadmff'){ - const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur; + if(!amps.length)return;const l=pick(amps),A=CITY[l.a].name,B=CITY[l.b].name,dur=type==='roadmff'?1:(l.spares?1:2+Math.floor(Math.random()*3));l.eqDown=S.day+dur; const msg=type==='roadmff'?tr('failures.you_fat_fingered_the_channel_plan',{a:A,b:B}):pick([tr('failures.an_in_line_amplifier_hut_between',{a:A,b:B}),tr('failures.someone_stole_the_copper_grounding',{a:A,b:B}),tr('failures.a_firmware_bug_in_the_sys',{sys:DF_SYS[l.sys].n,a:A}),tr('failures.lightning_hit_an_amp_site_on',{a:A,b:B})]); addInc({type,ref:l.id,until:l.eqDown,msg:msg+(type==='amp'&&l.spares?' '+tr('failures.your_spares_kit_gets_it_back'):''),cost:type==='amp'&&!l.spares?AMP_COST:0,fix:tr('failures.truck_a_spare_amp_out')}); }else if(type==='optic'){ @@ -83,7 +86,7 @@ function fireFailure(only){ addInc({type,ref:l.id,until:S.day+dur,msg:pick([tr('failures.a_optic_on_a_b_overheated',{optic:OPT[o].n,a:A,b:B}),tr('failures.the_laser_in_a_optic_on',{optic:OPT[o].n,a:A,b:B}),tr('failures.a_optic_on_a_b_started',{optic:OPT[o].n,a:A,b:B})])+(l.spares?' '+tr('failures.swapped_from_your_spares_kit_by'):''),cost:l.spares?0:OPT[o].cost,fix:tr('failures.buy_a_replacement')}); }else if(type==='cut'){ const mon=cal(S.day).m,monsoon=mon>=5&&mon<=8,tw=x=>(x.sub&&(x.a==='tpe'||x.b==='tpe'||(x.cable&&CAB[x.cable].anchor)))||(scnRule('anchors')&&anchorProne(x)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india); - const pool=only&&scnRule('anchors')?live.filter(anchorProne):live;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=(10+Math.floor(Math.random()*8))*(wetCut(l)?2:1),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); + const pool=only&&scnRule('anchors')?dug.filter(anchorProne):dug;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=(10+Math.floor(Math.random()*8))*(wetCut(l)?2:1),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1; const en=wetCut(l)?N_('failures.the_wet_season_washed_out_the'):l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]); addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en); diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 513979b..668478e 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -22,7 +22,7 @@ function mkTick(d){const M=S.monkey;if(!M)return; if(!mkElig()){if(M.on)mkLeave('quiet');return;} // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; - if(!M.on){if(dl.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;} if(d>=M.until){mkLeave();return;} if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); @@ -30,7 +30,7 @@ function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint( Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} -function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return; +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l)));if(!live.length)return; // Weak spots first: a sample keeps this cheap on big networks. const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index d683de8..19aa159 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -5,7 +5,7 @@ Object.assign(ACT,{ toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();}, unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();}, accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');return;}const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} - if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, // instead of a new customer for every few waves (a big fiber business otherwise fills the save with tiny contracts). diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 9848304..cf98a50 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -3,7 +3,7 @@ Object.assign(ACT,{ decomOpen:({city})=>{UI.decom=new Set(city&&S.pops[city]?[city]:[]);decomModal();}, decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, - rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');} + rmLink:({id})=>{{const n=xpOver(id).length;if(n){toast(trn('express.fiber_busy',n),'bad');sfx('err');UI.confirm=null;renderPanel();return;}}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');} const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();}, // The chaos monkey takes a banana and goes home early (no bonus). mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();}, @@ -14,7 +14,7 @@ Object.assign(ACT,{ myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, - buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} diff --git a/src/game/90-actions/87-express.js b/src/game/90-actions/87-express.js new file mode 100644 index 0000000..2ab83e9 --- /dev/null +++ b/src/game/90-actions/87-express.js @@ -0,0 +1,22 @@ +// Express lightpaths (#58, 65-express.js): light a wave from a to b over a chain of your ROADM fibers, or one more +// channel on it; giving one up is rmLink, like any link. Every check is made here: tools and the NOC window send raw args. +Object.assign(ACT,{ + // The link window on its Express tab, from a fiber's panel or the tab itself. via: the path a fiber's panel offered, + // listed first even when shorter ones exist (the window checks it with xpParse). + xpOpen:({a,b,via})=>{if(!isCity(a)||!isCity(b)||a===b||!S.pops[a])return;UI.lmode='xp';UI.xpPath=typeof via==='string'?via.slice(0,400):null;openLinkModal(a,b);}, + // via: the fibers' ids in order from a, comma-separated. The same path again adds a channel to the express already there. + xpBuild:({a,b,via,o})=>{const sp=xpParse(a,b,via);if(!sp||!OPT[o]){toast(tr('express.no_such_path'),'bad');sfx('err');return;} + const ids=sp.map(s=>s.id),old=xpFind(a,b,ids),why=xpWhy(a,b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(old&&(old.ch=old.ch||[]).length>=XP_CH)return;if(!portGate(a,chPorts(o,a))||!portGate(b,chPorts(o,b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,!old)))return;if(spare)S.spares[o]--; + let l=old;if(l)l.ch.push(o);else{l={id:uid(),a,b,kind:'xp',via:ids,ch:[o],km:Math.round(sp.reduce((x,s)=>x+s.km,0)),mo:0,cut:0,day:S.day};S.links.push(l);} + closeModal();UI.sel={type:'link',id:l.id};UI.confirm=null; + toast(old?tr('express.one_more',{optic:OPT[o].n,a:CITY[l.a].name,b:CITY[l.b].name,n:l.ch.length}):tr('express.lit',{optic:OPT[o].n,a:CITY[a].name,b:CITY[b].name,via:esc(xpVia(l))}),'good');sfx('build');after();}, + // One channel more (d:1) or less (d:-1) on an express; an unplugged optic goes on the spares shelf. The last one stays: + // giving the express up is the link's own button. + xpCh:({id,o,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='xp'||!OPT[o]||(d!==1&&d!==-1))return;l.ch=l.ch||[];const mid=[(CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20]; + if(d<0){const i=l.ch.lastIndexOf(o);if(i<0)return;if(l.ch.length<2){toast(tr('express.last_channel'),'bad');sfx('err');return;} + l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater(mid[0],mid[1],tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();return;} + const sp=xpSpans(l);if(!sp||l.ch.length>=XP_CH)return;const why=xpWhy(l.a,l.b,sp,o);if(why){toast(tr('express.cannot',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + if(!portGate(l.a,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))return;const spare=spareN(o)>0;if(!spend(xpCost(sp,o,false)))return;if(spare)S.spares[o]--; + l.ch.push(o);floater(mid[0],mid[1],`+${OPT[o].n}`,'#FF4F9A');after();}, +}); diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index 7eb2919..75b81db 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -18,19 +18,19 @@ Object.assign(ACT,{ const own=UI.dfSrc==='build'&&!sc,sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite';if(glassLvl()<2)return; const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} - const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid(); + const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid(); const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false}; S.links.push(l);closeModal();UI.sel={type:'link',id}; toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();}, regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; - if(d<0&&(l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} + if(d<0&&((l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))||xpRegenBad(l,n))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} if(d>0&&!spend(REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH)))return;l.regen=n;toast(d>0?tr('fiber_and_hardware.regen_site_n_is_up_optical',{n,a:CITY[l.a].name,b:CITY[l.b].name,km:spanKm(l).toLocaleString()}):tr('fiber_and_hardware.regen_site_removed'),'good');sfx('build');after();}, addCh:({id,o})=>{const l=S.links.find(x=>x.id===id),O=OPT[o];if(!l||!O||l.kind!=='df')return;const why=chWhy(l,o);if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:O.n,why:esc(why)}),'bad');sfx('err');return;}if(!portGate(l.a,chPorts(o,l.a))||!portGate(l.b,chPorts(o,l.b)))return;const sp=spareN(o)>0;if(!spend(chCost(l,o)))return;if(sp)S.spares[o]--;(l.ch=l.ch||[]).push(o);floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,`+${O.n}`,'#FF4F9A');after();}, - rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o])return;const i=(l.ch||[]).lastIndexOf(o);if(i<0)return;l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();}, + rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o]||l.kind==='xp')return;const i=(l.ch||[]).lastIndexOf(o);if(i<0)return;l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();}, hwLock:()=>{if(hwLock())return;const c=hwLockCost();if(!spend(c))return;S.hw=S.hw||{};S.hw.lock={until:S.day+HW_LOCK_DAYS,mul:hwTrend(S.day)};toast(tr('fiber_and_hardware.prices_locked_until_date_your_vendor',{date:dateStr(S.hw.lock.until)}),'good');after();}, buySpare:({o})=>{if(!OPT[o]||!techOk('opt',o,OPT[o].lvl)||spareN(o)>=64)return;if(!spend(optCost(o)))return;S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;sfx('build');after();}, sellSpare:({o})=>{if(!OPT[o]||spareN(o)<1)return;S.spares[o]--;const v=spareValue(o);S.cash+=v;toast(tr('fiber_and_hardware.sold_a_spare_optic_on_ebuy',{optic:OPT[o].n,price:fmt$(v),p:pct(SPARE_RESALE)}),'good');sfx('coin');after();}, - addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l){const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l)+xpSlots(l){const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||!techOk('sys',to,DF_SYS[to].lvl))return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();}, spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();}, // Your own subsea cable: book a second lay ship before laying starts; it lays from the other end (50-cable-ships.js). diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js index 6215bd5..8a4db1c 100644 --- a/src/game/90-actions/88-optic-counts.js +++ b/src/game/90-actions/88-optic-counts.js @@ -12,7 +12,7 @@ Object.assign(ACT,{ if(d>0){ const why=chWhy(l,o); if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} - const free=chMax(l)-(l.ch||[]).length-soldSlots(l); + const free=chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l); if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;} if(!portGate(l.a,d*chPorts(o,l.a))||!portGate(l.b,d*chPorts(o,l.b))||!spend(opticCountCost(l,o,n)))return; const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp; diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 735a4da..31b06aa 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -1,6 +1,6 @@ // Overland routes already dug between two cities, in the order they were built (#77). The first is the // main route; every other one was a diverse route and keeps that price when you add waves to it. -function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind==='vxc'||l.cable||l.sub)continue;const k=l.trench||l.id;let t=out.find(x=>x.k===k);if(!t)out.push(t={k,n:0,caps:[]});t.n++;t.caps.push(capName(l));}return out;} +function landTrenches(a,b){const out=[];for(const l of pairLinks(a,b)){if(l.kind==='vxc'||l.kind==='xp'||l.cable||l.sub)continue;const k=l.trench||l.id;let t=out.find(x=>x.k===k);if(!t)out.push(t={k,n:0,caps:[]});t.n++;t.caps.push(capName(l));}return out;} // Which route a new wave joins: null = a new diverse route. 'same' is the old two-way choice (the main route). function routeJoin(a,b){const ts=landTrenches(a,b),r=UI.route||'';if(r==='same')return ts[0]||null;if(r.startsWith('t:'))return ts.find(t=>t.k===r.slice(2))||null;return null;} function pairLinks(a,b){return S.links.filter(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} @@ -32,12 +32,12 @@ function optCost(o){return Math.round(OPT[o].cost*techMul(OPT[o].lvl)*hwMul('opt // Line systems upgrade in place: Rainbow → ROADMaster → C+L. Every lit pair gets the new gear. const sysNext=l=>l.sys==='lite'?'roadm':l.sys==='roadm'?'cl':null,sysUpCost=l=>{const t=sysNext(l);return t?sysCost(t)*(t==='cl'&&l.own?Math.max(1,l.pairs|0):1):0;}; function pairBtn(l){if(!l.own||!isRdm(l.sys)||l.ready>S.day)return '';const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return `${tr('action_helpers.n_fiber_pairs_lit_the_trench',{n})}`; - const full=(l.ch||[]).length+soldSlots(l)>=chMax(l),c=pairCost(l);return btn(l.sub?tr('action_helpers.light_fiber_pair_n_price',{n:n+1,price:fmt$(c)}):tr('action_helpers.light_fiber_pair_n_price_mo',{n:n+1,price:fmt$(c),mo:fmt$(ampCount(l.km)*AMP_MO)}),'addPair',{id:l.id},full?'pink sm':'ghost sm',!full||S.cash=chMax(l),c=pairCost(l);return btn(l.sub?tr('action_helpers.light_fiber_pair_n_price',{n:n+1,price:fmt$(c)}):tr('action_helpers.light_fiber_pair_n_price_mo',{n:n+1,price:fmt$(c),mo:fmt$(ampCount(l.km)*AMP_MO)}),'addPair',{id:l.id},full?'pink sm':'ghost sm',!full||S.cash(OPT[x].sys!=='roadm'||isRdm(l.sys))&&optMode(x,withSubUps(l))).map(x=>OPT[x].n);if(alt.length)return tr('action_helpers.upgrades_cannot_stretch_this_optic',{...v,optics:alt.join(', ')});} return tr('action_helpers.this_channel_reaches_max_km_on',v);}return tr('action_helpers.too_far_even_at_its_slowest',{span:spanKm(l).toLocaleString(),max:mx.toLocaleString()});} - if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); + if((l.ch||[]).length+soldSlots(l)+xpSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].cls

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

`; if(!ls.length)h+=`

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); - h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} h+=``; if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; } diff --git a/src/game/93-ui/60-decommission.js b/src/game/93-ui/60-decommission.js index d8df5df..6b3024a 100644 --- a/src/game/93-ui/60-decommission.js +++ b/src/game/93-ui/60-decommission.js @@ -1,7 +1,8 @@ /* Decommissioning POPs. Customers that touch a decommissioned city, or ride a removed link, are let go with an early-termination penalty of three months of their contract. */ const DECOM_MONTHS=3; -function decomImpact(cities){const set=new Set(cities),links=S.links.filter(l=>set.has(l.a)||set.has(l.b)),lids=new Set(links.map(l=>l.id)); +// An express riding a fiber that goes is decommissioned with it. +function decomImpact(cities){const set=new Set(cities),links=xpWith(S.links.filter(l=>set.has(l.a)||set.has(l.b))),lids=new Set(links.map(l=>l.id)); const biz=S.biz.filter(b=>bCities(b).some(c=>set.has(c))||(b.link&&lids.has(b.link))); const pen=b=>Math.max(2000,Math.round(b.fee?b.fee*0.5:b.bw*b.rate*DECOM_MONTHS)); return {links,biz,pen,fee:biz.reduce((a,b)=>a+pen(b),0),eye:cities.reduce((a,c)=>a+(R.cityEye[c]||0),0)};} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 249a97f..200de31 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -117,7 +117,7 @@ function dfPanel(l){ if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; - h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${fmtG(load)} / ${fmtG(cap)}
+ h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${xpSlots(l)?` · ${trn('express.n_carry_expresses',xpSlots(l))}`:''}${fmtG(load)} / ${fmtG(cap)}
${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); @@ -134,6 +134,7 @@ function dfPanel(l){ const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH); h+=`

${tr('common.line_system')}

${esc(sysD.n)}${tr('link_panels.n_amplifiers',{n:amps})}
${tr('common.regen_sites')}${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}

${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}

${l.seat?`

${tr('broker.seat_regen_note')}

`:''}${l.sub&&l.own&&!l.seat?`

${tr('link_panels.no_regen_sites_in_the_middle')}

`:`
${rg`}

${esc(sysD.blurb)}

${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return !techOk('sys',t,T.lvl)?demoBtn('sys',t,T.lvl,tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'sm'):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash

${tr('link_panels.spare_optics_and_amplifier_cards_on')}

`; + h+=xpDfSection(l); {const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`

${tr('common.redundancy')}

${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}

${sib.map(x=>`
${esc(capName(x))} ${linkDown(x)?''+tr('common.cut')+'':''}${x.standby?' '+tr('common.standby')+'':''}
${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')}
${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}
`;} h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):(l.own?tr('link_panels.abandon_the_fiber'):tr('link_panels.cancel_the_iru')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`

${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}

`:''}
`; return h; @@ -146,6 +147,7 @@ function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} if(l.kind==='vxc')return vxcPanel(l); if(l.kind==='df')return dfPanel(l); + if(l.kind==='xp')return xpPanel(l); const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); let h=`
${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; if(cut)h+=`

${tr('common.cut_2e50')}

${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}

${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; diff --git a/src/game/93-ui/72-express.js b/src/game/93-ui/72-express.js new file mode 100644 index 0000000..86633fd --- /dev/null +++ b/src/game/93-ui/72-express.js @@ -0,0 +1,48 @@ +/* Express lightpaths (#58): the panel of one, the section on a dark fiber's panel (what rides it, where it chains on) + and the Express tab of the link window (70-link-modal.js). The rules are in 80-simulation/65-express.js. */ +const xpSpanName=s=>`${CITY[s.a].name} ⇄ ${CITY[s.b].name}`; +// Why an express is dark today, fiber by fiber. +function xpDarkWhy(l){const sp=xpSpans(l);if(!sp)return [tr('express.dark_gone')];const d=S.day,out=[]; + for(const s of sp){const n=xpSpanName(s);if(linkCut(s))out.push(tr('express.dark_cut',{span:n}));else if(s.ready>d)out.push(trn('express.dark_building',s.ready-d,{span:n}));else if(s.eqDown>d)out.push(tr('express.dark_system',{span:n}));} + if(!out.length)out.push(tr('express.dark_reach'));return out;} +// One fiber of a path: whose it is, how long, the slots left for express channels. +const xpSpanMeta=s=>`${s.own?tr('common.own_dark_fiber'):tr('common.leased_iru')} · ${Math.round(s.km).toLocaleString()} km · ${tr('express.free_slots',{n:Math.max(0,xpFree(s)),max:chMax(s)})}`; +// An optic's settings over a run, as the fiber panel lists them. +const xpModes=(o,run)=>OPT[o].modes.map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')+` · ${xpOptG(o,run)?tr('express.runs_at',{g:fmtG(xpOptG(o,run))}):tr('express.out_of_reach')}`; +function xpPanel(l){const sp=xpSpans(l),load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,down=linkDown(l),A=CITY[l.a].name,B=CITY[l.b].name,run=sp?xpRunKm(sp):0,ch=l.ch||[]; + let h=`
${tr('express.eyebrow',{km:Math.round(l.km).toLocaleString()})}

${A} ⇄ ${B}

`; + if(down)h+=`

${tr('common.dark_6bf5')}

${xpDarkWhy(l).map(t=>`

${t}

`).join('')}
`; + h+=`

${tr('common.capacity')}

${trn('express.n_channels',ch.length)}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${tr('express.optical_run')}${run.toLocaleString()} km
+

${tr('express.passes',{via:esc(xpVia(l))})}

`; + if(sp)h+=`

${tr('express.its_fibers')}

${sp.map(s=>`
${xpSpanName(s)} ${linkCut(s)?''+tr('common.cut')+'':''}
${xpSpanMeta(s)}
${btn(tr('common.open'),'selLink',{id:s.id},'ghost sm')}
`).join('')}

${tr('express.slot_note')}

`; + if(sp){h+=`

${tr('common.optics')}

`; + for(const k of Object.keys(OPT)){const O=OPT[k],n=ch.filter(x=>x===k).length;if(!n&&!techOk('opt',k,O.lvl))continue;const why=xpWhy(l.a,l.b,sp,k),c=xpCost(sp,k,false),spn=spareN(k); + h+=`
${O.n}
${xpModes(k,run)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${spn?` · ${trn('link_panels.n_spare_on_the_shelf',spn)}`:''}
${why?`
${esc(why)}
`:''}
${n&&ch.length>1?btn('−','xpCh',{id:l.id,o:k,d:-1},'ghost sm'):''}${btn(`+ ${spn?tr('link_panels.spare_price',{price:fmt$(c)}):fmt$(c)}`,'xpCh',{id:l.id,o:k,d:1},'sm',!!why||S.cash`;} + h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`;} + h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):tr('express.tear_down'),'rmLink',{id:l.id},'ghost sm')}

${tr('express.tear_down_note')}

`; + return h;} +// Where an express can go from this fiber: through either end and on over your other ROADM fibers. +function xpTargets(l){const out=[];for(const [x,y] of [[l.a,l.b],[l.b,l.a]])for(const p of xpPaths(x,null,l,6))if(xpRunKm(p.sp)<=xpReachMax())out.push({from:x,...p}); + return out.sort((p,q)=>p.km-q.km).slice(0,6);} +// On a dark fiber's panel: the expresses riding it, and where one could go from here. +function xpDfSection(l){if(l.sub)return '';const on=xpOver(l.id),rdm=isRdm(l.sys),tg=rdm?xpTargets(l):[]; + // Without a ROADMaster the hint is only worth showing where another fiber of yours meets this one. + const near=!rdm&&S.links.some(x=>x!==l&&x.kind==='df'&&!x.sub&&[x.a,x.b].some(c=>c===l.a||c===l.b)); + if(!on.length&&!tg.length&&!near)return ''; + let h=`

${tr('express.title')}

${tr('express.lead')}

`; + if(!rdm)h+=`

${tr('express.needs_roadm')}

`; + if(on.length)h+=`

${tr('express.riding_here')}

`+on.map(x=>`
${CITY[x.a].name} ⇄ ${CITY[x.b].name} ${linkDown(x)?''+tr('common.dark')+'':''}
${capName(x)} · ${trn('express.n_channels',(x.ch||[]).length)} · ${tr('express.city_via',{via:esc(xpVia(x))})}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')+`

${tr('express.riding_note')}

`; + if(tg.length)h+=`

${tr('express.express_to')}

`+tg.map(t=>{const cs=xpCities(t.from,t.sp);return `
${CITY[t.from].name} → ${CITY[t.to].name}
${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(t.km).toLocaleString()})}
${btn(tr('express.plan'),'xpOpen',{a:t.from,b:t.to,via:t.sp.map(s=>s.id).join(',')},'pink sm')}
`;}).join(''); + return h+`
`;} +// The link window's Express tab: the ways your fibers chain from a to b, shortest first, an optic per button. Optic +// names are long: they go above the reason, not in the narrow column a wave's '400G' fits in. +function xpModalBody(a,b,routes){let h=`

${tr('express.modal_lead',{a:CITY[a].name,b:CITY[b].name})}

`; + for(const r of routes){const sp=r.sp,ids=sp.map(s=>s.id),cs=xpCities(a,sp),run=xpRunKm(sp),old=xpFind(a,b,ids),lat=sp.reduce((x,s)=>x+linkLat(s),0); + h+=`

${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(r.km).toLocaleString()})}

+ ${sp.map(s=>`
${xpSpanName(s)} · ${xpSpanMeta(s)}
`).join('')} +
${tr('express.optical_run')}${run.toLocaleString()} km
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:lat.toFixed(1)})}
+ ${old?`

${trn('express.already',(old.ch||[]).length)}

`:''} +
${Object.keys(OPT).filter(k=>techOk('opt',k,OPT[k].lvl)).map(k=>{const O=OPT[k],why=xpWhy(a,b,sp,k),c=xpCost(sp,k,!old),g=xpOptG(k,run); + return ``;}).join('')}
`;} + return h+`

${tr('express.modal_note',{price:fmt$(XP_PASS)})}

`;} diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index eb74159..c5e56ab 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -6,11 +6,11 @@ function swapOptics(km,cap,sub,sys){for(let r=0;r<=(sub?0:REGEN_MAX);r++){const const leaseCap=ls=>ls.reduce((s,l)=>s+(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?(l.ch||[]).reduce((t,o)=>t+optG(o,l),0):LT[l.tier].g),0); const swapOpt=(k,up,omo,days,mo)=>{const save=mo-omo;return {k,up,omo,days,save,pay:save>0?Math.ceil(up/save):0};}; // Lighting leased capacity on a fiber you already have (#72 review): needs free channels, and optics cost money. -function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L);let b=null; +function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L)-xpSlots(L);let b=null; for(const o in OPT){const O=OPT[o];if(O.lvl>glassLvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls); const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;} // Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear. diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index a7b5c25..daf9830 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -1,14 +1,17 @@ function openLinkModal(a,b){ {const nt=noTalk(a,b);if(nt){openModal(`

${tr('common.not_happening')}

${tr(nt)}

`);return;}} if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`

${tr('link_modal.not_without_a_license')}

${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}

`);return;} - let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'); + let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'); if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(border)route+=`

${tr('link_modal.cross_border_circuits_into_mainland')}

${a==='hkg'||b==='hkg'?`
${btn(tr('common.regular_crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('link_modal.premium_crossing_60_3_loss'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}
`:`

${tr('link_modal.premium_crossings_are_only_sold_in')}

`}`; if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`

${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}

${ts.length>1?ts.map((t,i)=>btn(`${i?tr('link_modal.diverse_route_n',{n:i}):tr('common.main_route')} ${esc(t.caps.join(', '))}${i?' · +40%':''}`,'route',{r:'t:'+t.k},jn&&jn.k===t.k?'pink':'ghost')).join('')+btn(tr('link_modal.new_diverse_route_40_survives_cuts'),'route',{r:'diverse'},!jn?'pink':'ghost'):btn(tr('link_modal.diverse_route_40_survives_cuts_alone'),'route',{r:'diverse'},!jn?'pink':'ghost')+btn(tr('link_modal.same_trench_cheaper_one_backhoe_cuts'),'route',{r:'same'},jn?'pink':'ghost')}
${ts.length>1?`

${tr('link_modal.waves_on_the_same_route_share')}

`:''}`;} - const mode=UI.lmode==='df'?'df':'wave',tabs=`
${btn(tr('link_modal.lease_a_wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('common.dark_fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}
`; + // Express (#58): only where your ROADM fibers already chain from a to b. The path a fiber's panel offered comes first. + const xp1=UI.xpPath?xpParse(a,b,UI.xpPath):null,xr0=xpPaths(a,b),xr=xp1&&!xr0.some(r=>r.sp.length===xp1.length&&r.sp.every((s,i)=>s===xp1[i]))?[{to:b,sp:xp1,km:xp1.reduce((x,s)=>x+s.km,0)},...xr0.slice(0,2)]:xr0; + const mode=UI.lmode==='df'?'df':UI.lmode==='xp'&&xr.length?'xp':'wave',tabs=`
${btn(tr('link_modal.lease_a_wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('common.dark_fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}${xr.length?btn(tr('express.tab'),'xpOpen',xp1?{a,b,via:UI.xpPath}:{a,b},mode==='xp'?'pink':'ghost'):''}
`; const head=`
${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km

${CITY[a].name} → ${CITY[b].name}

${tabs}`; if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;} + if(mode==='xp'){openModal(head+xpModalBody(a,b,xr));return;} if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${cabOpen()&&!ownCabWhy(a,b)?ownCabTeaser(a,b):''}`);return;} if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`

${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}

`);return;} if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`

${landWhy(a,b)}

`; diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index b792d3b..b7f2a4c 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -14,6 +14,8 @@ function linkGeom(l,pl){const i=lineIdx(l,pl);const key=l.id+'|'+i+'|'+(l.cable| if(!pts&&l.kind==='df'&&l.own&&l.sub){const k=pairLinks(l.a,l.b).filter(x=>x.kind==='df'&&x.own&&x.sub).indexOf(l),c0=cablesFor(l.a,l.b).slice().sort((x,y)=>x.km-y.km)[0],cp=c0&&cablePair(c0.cid,l.a,l.b); if(cp)pts=besideLine(cp.pts,2+k*1.5); else{const g=bezGeom(l,k);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));}} + // An express follows the fibers it rides, a little to one side, so it shows passing the cities on the way. + if(!pts&&l.kind==='xp')pts=xpGeom(l); if(!pts){const g=bezGeom(l);pts=[];for(let j=0;j<=20;j++)pts.push(qpt(g,j/20));} const cum=[0];let L=0;for(let j=1;j{let q=linkGeom(s).pts;if(s.a!==cs[i])q=q.slice().reverse();for(let j=pts.length?1:0;j1?besideLine(pts,4):null;} diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js index 32c636c..b0d354d 100644 --- a/src/game/96-map/55-link-look.js +++ b/src/game/96-map/55-link-look.js @@ -1,13 +1,13 @@ /* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in 58-webgl-links.js), so they cannot drift apart. */ // Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable, -// 7 a link being dragged out. -const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12]]; +// 7 a link being dragged out, 8 an express lightpath. +const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12],[14,5]]; // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; - const 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',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); - return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), - col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0, + const 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',xp=l.kind==='xp',bld=df&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx||xp?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills // The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the // links and with the day's routing (R), not with the camera, so it is kept until one of those changes. diff --git a/src/i18n/en.js b/src/i18n/en.js index c580cf8..46cf379 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2019,6 +2019,46 @@ "exchanges.20_peering_sessions_n":"20+ peering sessions ({n})", "exchanges.pops_on_3_continents":"POPs on 3+ continents", "exchanges.serve_1_5_tbps_v":"serve 1.5 Tbps ({v})", +"express.already":{"one":"You already run an express on this path with {n} channel: this adds another.","other":"You already run an express on this path with {n} channels: this adds another."}, +"express.cannot":"Can't light {optic} on this express.
{why}", +"express.cap":"{cap} express", +"express.city_via":"express via {via}", +"express.dark_building":{"one":"{span} is still being built: {n} day left.","other":"{span} is still being built: {n} days left."}, +"express.dark_cut":"{span} is cut.", +"express.dark_gone":"One of the fibers under it is gone.", +"express.dark_reach":"None of its optics reach over this run.", +"express.dark_system":"{span} has its line system down.", +"express.express_to":"Express to…", +"express.eyebrow":"Express lightpath · {km} km", +"express.fiber_busy":{"one":"An express lightpath rides this fiber.
Tear it down first: open it from this fiber's Express section.","other":"{n} express lightpaths ride this fiber.
Tear them down first: open them from this fiber's Express section."}, +"express.fiber_full":"{a} ⇄ {b} has no free channel slot ({max} on its line system).", +"express.free_slots":"{n} of {max} slots free", +"express.its_fibers":"The fibers it rides", +"express.last_channel":"That is the express's last channel. To stop it, tear the express down.", +"express.lead":"Send a wave straight through the ROADM at the far end onto your next fiber: no router ports in the city between, less latency, one channel slot on every fiber it rides.", +"express.lit":"Express lit: {a} ⇄ {b}.
{optic} goes straight through {via}: no router there sees it.", +"express.modal_lead":"Light a wave from {a} to {b} through the ROADMs on the way: the cities between never see it on a router.", +"express.modal_note":"The first channel also pays {price} for every city it passes, to patch it through the ROADM there. Optics from the spares shelf are free; every regen site on the way needs a card.", +"express.n_carry_expresses":{"one":"{n} carries an express","other":"{n} carry expresses"}, +"express.n_channels":{"one":"{n} channel","other":"{n} channels"}, +"express.needs_roadm":"Every fiber an express rides needs a ROADMaster line system (upgrade it under Line system above).", +"express.no_such_path":"Those fibers no longer chain from one city to the other.", +"express.one_more":"Another {optic} on the {a} ⇄ {b} express: {n} channels now.", +"express.optical_run":"Longest run without a regen", +"express.out_of_reach":"out of reach", +"express.passes":"Passes {via} as light, through the ROADM: no router port there, no hop in a traceroute.", +"express.plan":"Plan", +"express.riding_here":"Riding this fiber", +"express.riding_note":"Tear these down before you give up the fiber. A cut or a line system swap here darkens them too.", +"express.runs_at":"runs at {g}", +"express.slot_note":"Each channel takes one slot on every one of these fibers. A cut, a build or a line system swap on any of them darkens the express.", +"express.tab":"Express", +"express.tear_down":"Tear down the express", +"express.tear_down_note":"Its optics go back on the spares shelf.", +"express.title":"Express lightpaths", +"express.too_far":"Too far: the light runs {run} km without a regen site and this optic reaches {max} km at its slowest. Add regen sites on the fibers.", +"express.trace_hop":"express lightpath, optically past {via}", +"express.via_km":"via {via} · {km} km", "failures.a_45_c_heatwave_in_city":"A 45 °C heatwave in {city}: the grid shed load, the chillers gave up and so did the generator at {dc}.", "failures.a_b_is_down_same_cable":"{a}–{b} is down. Same cable, new anchor. The repair crew has started a loyalty card.", "failures.a_backhoe_cut_the_metro_ring":"A backhoe cut the metro ring between your two sites in {city}. Turns out both fiber routes ran down the same street.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index c07d336..71e682c 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -157,6 +157,8 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px} .tierbtn .grow{flex:1} .tierbtn .pr{font-family:var(--display);font-weight:800;font-size:18px} +/* A name too long for .sz (an optic on the Express tab) goes on its own line above the reason. */ +.tierbtn .onm{display:block;font-family:var(--display);font-weight:800;font-size:17px;line-height:1.15;margin-bottom:2px}.tierbtn .onm~.meta{display:block} .gl dt{font-family:var(--display);font-weight:800;font-size:16px;margin-top:10px} .gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px} .kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)} diff --git a/tests/express-fiber.test.js b/tests/express-fiber.test.js new file mode 100644 index 0000000..4847cf5 --- /dev/null +++ b/tests/express-fiber.test.js @@ -0,0 +1,398 @@ +// Express lightpaths (#58): a wave from Frankfurt to Paris over your own dark fibers Frankfurt–Brussels and +// Brussels–Paris that passes Brussels as light, through its ROADM. Routing sees a Frankfurt–Paris edge; Brussels' +// router never sees the traffic. Change Freeze, no random failures: nothing here depends on luck. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Three POPs on routers that take 400G optics, broadband in Paris, transit in Frankfurt, and two ROADM fibers +// (s1 Frankfurt–Brussels, s2 Brussels–Paris), finished and dark. df(a,b,extra) lays another one. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=8;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');closeModal();" + + "for(const c of ['bru','par'])ACT.buildPop({city:c});for(const c of ['fra','bru','par'])S.pops[c].rgen=1;ACT.launchBB({city:'par'});ACT.buyTransit({city:'fra',net:'cog',tier:2});" + + "window.df=(a,b,o={})=>{const id=uid();S.links.push(Object.assign({id,a,b,kind:'df',own:true,sys:'roadm',ch:[],km:kmBetween(a,b),sub:false,cable:null,mo:100,trench:id,cut:0,day:S.day,ready:S.day,spares:false,pairs:1},o));return id;};" + + "window.L=id=>S.links.find(l=>l.id===id);"; +const SPANS = "window.s1=df('fra','bru');window.s2=df('bru','par');compute();"; +const BUILD = "ACT.xpBuild({a:'fra',b:'par',via:s1+','+s2,o:'zr4'});window.x=(S.links.find(l=>l.kind==='xp')||{}).id;compute();"; +function game(t, extra = SPANS, opts = {}) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE + extra); + return h; +} +const xps = (ev) => ev("S.links.filter(l=>l.kind==='xp').length"); + +test('an express is a Frankfurt–Paris edge: traffic rides it, ports at both ends, and Brussels never sees it', (t) => { + const { ev, errors } = game(t); + assert.equal(ev("JSON.stringify(xpPaths('fra','par').map(p=>p.sp.map(s=>s.id)))"), ev('JSON.stringify([[s1,s2]])'), 'the two fibers chain'); + const ports = () => JSON.parse(ev("JSON.stringify(['fra','bru','par'].map(c=>portsUsed(c)))")); + const p0 = ports(), cash = ev('S.cash'); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.deepEqual(JSON.parse(ev('JSON.stringify(L(x))')), { id: ev('x'), a: 'fra', b: 'par', kind: 'xp', via: [ev('s1'), ev('s2')], ch: ['zr4'], km: ev('L(s1).km+L(s2).km'), mo: 0, cut: 0, day: ev('S.day') }); + assert.equal(cash - ev('S.cash'), ev("optCost('zr4')+XP_PASS"), 'the optic, and patching it through Brussels'); + const p1 = ports(); + assert.equal(p1[0] - p0[0], ev("chPorts('zr4','fra')"), 'a port in Frankfurt'); + assert.equal(p1[2] - p0[2], ev("chPorts('zr4','par')"), 'a port in Paris'); + assert.equal(p1[1], p0[1], 'none in Brussels'); + assert.equal(ev('capOf(L(x))'), 400); + assert.ok(ev('R.load[x]') > 1, 'Paris reaches its transit over the express'); + assert.ok(!ev('R.nodeLoad.bru'), "Brussels' router carries nothing"); + assert.equal(ev('linkLat(L(x))'), ev('linkLat(L(s1))+linkLat(L(s2))'), 'the latency of the fibers it rides, with no router in between'); + // With channels of their own on both fibers there is a path through Brussels too: the express is one hop shorter. + ev("L(s1).ch=['zr4'];L(s2).ch=['zr4'];compute()"); + assert.ok(ev('R.load[x]') > 1); + assert.equal(ev('(R.load[s1]||0)+(R.load[s2]||0)'), 0, 'the hop through Brussels stays idle'); + assert.ok(!ev('R.nodeLoad.bru')); + // Without the express the same traffic goes through Brussels' router. + ev('L(x).standby=true;S.pairMet[edgeKey(L(x))]="backup";compute()'); + assert.ok(ev('R.nodeLoad.bru') > 1, 'the router in Brussels works when the light does not pass it'); + assert.deepEqual(errors, []); +}); + +test('a cut, a build or a line system swap on any fiber darkens the express; a fiber under one stays', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev('linkDown(L(x))'), false); + ev('L(s2).cut=S.day+5;compute()'); + assert.equal(ev('linkDown(L(x))'), true, 'a cut fiber'); + assert.equal(ev('R.load[x]||0'), 0); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /Brussels ⇄ Paris is cut/); + assert.equal(ev('(o=>o.dark&&!o.cut&&o.dash===8)(linkLook([L(x)],S.day))'), true, 'drawn dark, no backhoe of its own'); + ev('L(s2).cut=0;L(s2).ready=S.day+10;compute()'); + assert.equal(ev('linkDown(L(x))'), true, 'a fiber still being built'); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /Brussels ⇄ Paris is still being built: 10 days left\./); + ev('L(s2).ready=S.day+1'); + assert.match(ev("xpDarkWhy(L(x)).join(' ')"), /still being built: 1 day left\./, 'one day, not one days'); + ev('L(s2).ready=S.day;compute()'); + assert.equal(ev('linkDown(L(x))'), false); + ev('ACT.upSys({id:s1})'); + assert.equal(ev("L(s1).sys"), 'cl'); + assert.equal(ev('linkDown(L(x))'), true, 'the line system swap takes the express down for the day'); + ev('S.day++;compute()'); + assert.equal(ev('linkDown(L(x))'), false, 'and it is back the next day, on the new line system'); + // A fiber under an express cannot be given up; the express can, and its optic goes on the shelf. + ev('ACT.rmLink({id:s1});ACT.rmLink({id:s1})'); + assert.ok(ev('!!L(s1)'), 'the fiber is still there'); + assert.match(ev('S.log[0].t'), /express lightpath rides this fiber/); + const sp = ev("spareN('zr4')"); + ev('ACT.rmLink({id:x});ACT.rmLink({id:x})'); + assert.equal(xps(ev), 0); + assert.equal(ev("spareN('zr4')"), sp + 1); + ev('ACT.rmLink({id:s1});ACT.rmLink({id:s1})'); + assert.ok(!ev('L(s1)'), 'then the fiber goes'); + assert.deepEqual(errors, []); +}); + +test('a backhoe or the chaos monkey still finds a fiber that only carries expresses, never the express itself', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev('linkDown(L(s1))&&linkDown(L(s2))'), true, 'dark as links of their own: no channels of their own'); + assert.equal(ev('xpBare(L(s1))&&xpBare(L(s2))'), true); + ev("fireFailure('cut');compute()"); + assert.equal(ev("S.links.filter(l=>l.cut>S.day).map(l=>l.kind).join()"), 'df', 'one fiber cut, not the express'); + assert.equal(ev('linkDown(L(x))'), true); + assert.equal(ev("S.inc.filter(i=>i.type==='cut').length"), 1); + ev("for(const l of S.links)l.cut=0;S.inc=[];compute();mkSnip()"); + assert.equal(ev("S.links.filter(l=>l.cut>S.day).map(l=>l.kind).join()"), 'df', 'the monkey snips a fiber too'); + assert.deepEqual(errors, []); +}); + +test("the intern's decom order counts an express as a link between its cities, and never hands one back", (t) => { + const { ev, errors } = game(t); + ev(BUILD + "UI.pending={a:'fra',b:'par'};UI.route='diverse';ACT.buildLink({tier:1});compute()"); + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.decom=true;S.ops.cap.decom=0;compute();opsDay(S.day)"); + assert.equal(ev("S.links.filter(l=>l.kind==='wave').length"), 1, 'kept as the spare: its trench is not one the express runs in'); + ev("S.ops.p.decom={keep:false};S.day++;compute();opsDay(S.day)"); + assert.equal(ev("S.links.map(l=>l.kind).join()"), 'df,df,xp', 'the express carries the pair with room to spare: the wave goes back'); + assert.deepEqual(errors, []); +}); + +test('decommissioning the city in the middle takes its fibers and the expresses riding them', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.equal(ev("decomImpact(['bru']).links.length"), 3, 'both fibers and the express'); + const sp = ev("spareN('zr4')"); + ev("decommission(['bru']);compute()"); + assert.equal(ev('S.links.length'), 0); + assert.equal(ev("spareN('zr4')"), sp + 1, 'the express optic is on the shelf'); + assert.deepEqual(errors, []); +}); + +test('reach: the light must make the whole run between regen sites, through Brussels too', (t) => { + const { ev, errors } = game(t, "window.s1=df('fra','bru',{km:2000});window.s2=df('bru','par',{km:2000});compute();"); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 4000, 'no regen anywhere: one 4,000 km run'); + assert.match(ev("xpWhy('fra','par',[L(s1),L(s2)],'zr4')"), /Too far: the light runs 4,000 km/); + ev(BUILD); + assert.equal(xps(ev), 0, 'refused'); + ev('ACT.regen({id:s1,d:1})'); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 3000, 'the last 1,000 km of the first fiber and all of the second'); + const cash = ev('S.cash'); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.equal(cash - ev('S.cash'), ev("Math.round(optCost('zr4')*1.5)+XP_PASS"), 'a regen card at the one regen site'); + assert.equal(ev('capOf(L(x))'), 200, 'a 400ZR+ at 3,000 km runs its slow setting'); + ev('ACT.regen({id:s1,d:-1})'); + assert.equal(ev('L(s1).regen'), 1, 'the express needs that regen site: it stays'); + ev('L(s1).regen=2;L(s2).regen=2;compute()'); + assert.equal(ev('xpRunKm([L(s1),L(s2)])'), 1334); + assert.equal(ev('capOf(L(x))'), 400, 'short runs everywhere: full rate'); + assert.deepEqual(errors, []); +}); + +test('slots: lit channels, sold alien waves and express channels share every line system', (t) => { + const { ev, errors } = game(t); + ev("L(s1).ch=Array(10).fill('zr4');S.biz.push({id:uid(),city:'fra',city2:'bru',link:s1,slots:53,type:'wwave',name:'Alien Co',bw:1,rate:1000,reqs:[],mood:100,since:S.day});for(const c of ['fra','bru','par'])S.pops[c].routers=4;compute()"); + assert.equal(ev('freeCh(L(s1))'), 1); + ev(BUILD); + assert.equal(xps(ev), 1); + assert.equal(ev('xpSlots(L(s1))'), 1); + assert.equal(ev('xpSlots(L(s2))'), 1); + assert.equal(ev('freeCh(L(s1))'), 0, 'the sold waves and the express take the last slots'); + assert.equal(ev('freeCh(L(s2))'), 63); + assert.match(ev("chWhy(L(s1),'zr4')"), /is full/, 'no more channels of its own either'); + assert.match(ev("xpWhy('fra','par',[L(s1),L(s2)],'zr4')"), /Frankfurt ⇄ Brussels has no free channel slot/); + ev("ACT.xpCh({id:x,o:'zr4',d:1})"); + assert.equal(ev('L(x).ch.length'), 1, 'refused'); + // A full pair lets you light the next one, and the express grows into it. + ev('ACT.addPair({id:s1})'); + assert.equal(ev('L(s1).pairs'), 2); + ev("ACT.xpCh({id:x,o:'zr4',d:1})"); + assert.equal(ev('L(x).ch.length'), 2); + assert.equal(ev('xpSlots(L(s2))'), 2); + assert.equal(ev('capOf(L(x))'), 800); + // The intern lights optics on hot fibers: never into the slots expresses and alien waves hold. + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();S.ops.on.optics=true;S.ops.cap.optics=0;compute();for(const l of S.links)if(l.kind==='df')R.load[l.id]=1e6;opsDay(S.day)"); + assert.equal(ev("S.links.filter(l=>l.kind==='df').every(l=>(l.ch||[]).length+soldSlots(l)+xpSlots(l)<=chMax(l))"), true); + assert.ok(ev('L(s1).ch.length') > 10, 'the intern did light the hot fiber with room'); + assert.equal(ev('L(s2).ch.length'), 0, 'a fiber that only carries the express is not new fiber: it stays bare'); + // Unplugging: never the last channel. + ev("ACT.xpCh({id:x,o:'zr4',d:-1})"); + assert.equal(ev('L(x).ch.length'), 1); + ev("ACT.xpCh({id:x,o:'zr4',d:-1})"); + assert.equal(ev('L(x).ch.length'), 1, 'the last channel stays'); + ev("ACT.rmCh({id:x,o:'zr4'})"); + assert.equal(ev('L(x).ch.length'), 1, "a fiber's unplug button does not work on an express"); + assert.deepEqual(errors, []); +}); + +test('saves: an express survives a round trip; one whose fibers are gone is dropped and its optics go on the shelf', (t) => { + const { ev, errors } = game(t); + // A save from before expresses existed loads as it always did. + const old = ev('JSON.stringify(S)'); + ev(`S=migrate(JSON.parse(${JSON.stringify(old)}));compute()`); + assert.equal(ev('S.links.length'), 2); + assert.equal(ev('freeCh(L(s1))'), 64); + ev(BUILD); + ev('S=sanitize(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev("L(x).kind"), 'xp', 'still an express, not a wave'); + assert.equal(ev("L(x).via.join(',')"), ev("s1+','+s2")); + assert.ok(ev('R.load[x]') > 1); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(xps(ev), 1); + const sp = ev("spareN('zr4')"); + // Its second fiber gone (a hand-edited file): dropped, the optic back on the shelf. + ev('{const o=JSON.parse(JSON.stringify(S));o.links=o.links.filter(l=>l.id!==s2);S=sanitize(o);compute();}'); + assert.equal(xps(ev), 0); + assert.equal(ev("spareN('zr4')"), sp + 1); + // Fibers that do not chain from a, a fiber without a ROADM, no optic: all dropped. + for (const bad of ["x.via=[s2,s1]", "o.links.find(l=>l.id===s1).sys='lite'", "x.ch=['nope']", "x.via=[s1]", "x.b='ams'"]) { + ev(`{S=migrate(JSON.parse(${JSON.stringify(old)}));${BUILD}const o=JSON.parse(JSON.stringify(S)),x=o.links.find(l=>l.kind==='xp');${bad};S=sanitize(o);compute();}`); + assert.equal(xps(ev), 0, bad); + } + assert.deepEqual(errors, []); +}); + +test('the route worker routes an express as the page does; traceroute skips Brussels; diverse paths count its trenches', (t) => { + const h = game(t); + const { ev, errors } = h; + h.dom.window.structuredClone = globalThis.structuredClone; + ev(BUILD + "L(s1).ch=['zr4'];L(s2).ch=['zr4'];compute()"); + const SIG = "JSON.stringify({load:R.load,served:R.served,node:R.nodeLoad,ef:Object.keys(R.ef).sort().map(k=>[k,R.ef[k]])})"; + ev('window.__got=null;window.postMessage=(m)=>{window.__got=m;};'); + ev('{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}'); + ev('R=rwUnpack(structuredClone(__got.R),__got.ef)'); + const fromWorker = ev(SIG); + assert.ok(ev('R.load[x]') > 1, 'the worker routed over the express'); + ev('R=__R0;S=JSON.parse(__S0);compute()'); + assert.equal(ev(SIG), fromWorker); + const tr = ev("traceroute('par',{city:'fra'}).text"); + assert.match(tr, /express lightpath, optically past Brussels/); + assert.doesNotMatch(tr, /cr1\.bru\./, 'no hop in Brussels'); + // The express runs in the trenches of the fibers it rides: with them it is no second path. + assert.equal(ev("diversePaths('fra','par')"), false); + ev("S.biz.push({id:'div1',city:'fra',city2:'par',type:'ai',name:'Skynot Compute',bw:400,rate:10,reqs:['diverse'],mood:100,since:S.day});compute()"); + assert.equal(ev("R.div['div1']"), false, 'compute() agrees'); + ev("UI.pending={a:'fra',b:'par'};UI.route='diverse';ACT.buildLink({tier:1});compute()"); + assert.equal(ev("diversePaths('fra','par')"), true, 'a wave in a trench of its own is'); + assert.equal(ev("R.div['div1']"), true); + assert.deepEqual(errors, []); +}); + +test('on a phone: the fiber offers an express, the link window has an Express tab, the express has its panel, the map draws it', (t) => { + const h = load(); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev('window.innerWidth=360;window.innerHeight=740;' + BASE + SPANS); + assert.equal(ev('isPhone()'), true); + ev('selectLink(s1)'); + const panel = ev("$('panel').innerHTML"); + assert.match(panel, /Express lightpaths/); + assert.match(panel, /data-act="xpOpen"/); + ev("ACT.xpOpen({a:'fra',b:'par'})"); + const modal = ev("$('modal').innerHTML"), text = ev("$('modal').textContent"); + assert.match(modal, /data-act="xpBuild"/); + assert.match(text, /via Brussels · 581 km/); + // Optic names are long ('Sienna WaveMagic 1.6T'): never in the 70px column a wave's '400G' fits in. + assert.equal(ev(`[...$('modal').querySelectorAll('[data-act="xpBuild"]')].filter(b=>b.querySelector('.sz')||!b.querySelector('.grow .onm+.meta')).length`), 0); + assert.equal(ev(`$('modal').querySelector('[data-act="xpBuild"] .onm').textContent`), ev('OPT.zr4.n')); + assert.doesNotMatch(text, /express\.[a-z_]{3,}|undefined|NaN/); + // The other tabs are one tap away, and the Express tab only shows where fibers chain. + ev("ACT.dfMode({m:'wave'})"); + assert.match(ev("$('modal').innerHTML"), /data-act="xpOpen"/); + ev("closeModal();UI.lmode='xp';openLinkModal('fra','ams')"); + assert.doesNotMatch(ev("$('modal').innerHTML"), /data-act="xpOpen"|data-act="xpBuild"/); + ev('closeModal();' + BUILD + 'selectLink(s1)'); + assert.match(ev("$('panel').textContent"), /0 of 64 channels lit · 1 carries an express/, 'the slot the express takes, next to the lit ones'); + // Without a ROADMaster the hint points at the Line system section, which comes before it. + ev("L(s1).sys='lite';selectLink(s1)"); + const lp = ev("$('panel').innerHTML"), hint = lp.indexOf('upgrade it under Line system above'); + assert.ok(hint > 0 && lp.indexOf('

Line system

') < hint, 'the upgrade is above the hint'); + ev("L(s1).sys='roadm';selectLink(x)"); + const xp = ev("$('panel').textContent"); + assert.match(xp, /Express lightpath · 581 km/); + assert.match(xp, /Tear down the express/); + assert.doesNotMatch(xp, /express\.[a-z_]{3,}|undefined|NaN/); + assert.match(ev('capName(L(x))'), /400G express/); + // Drawn along its fibers, a little to one side: it passes Brussels without landing there. + const g = JSON.parse(ev("JSON.stringify(linkGeom(L(x)).pts)")), B = JSON.parse(ev("JSON.stringify([CITY.bru.x,CITY.bru.y])")); + const near = Math.min(...g.map(([x, y]) => Math.hypot(x - B[0], y - B[1]))); + assert.ok(near > 1 && near < 12, 'beside Brussels: ' + near); + ev('UI.started=true;UI.pitched=true;for(const z of [0.6,1.5,3]){cam.z=z;draw(performance.now());}'); + assert.deepEqual(errors, []); +}); + +test('in German, every express screen is translated', (t) => { + const h = load({ lang: 'de' }); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev('window.innerWidth=360;' + BASE + SPANS + BUILD + 'selectLink(s1)'); + assert.match(ev("$('panel').textContent"), /Express-Lightpaths/); + ev("ACT.xpOpen({a:'fra',b:'par'})"); + assert.doesNotMatch(ev("$('modal').textContent"), /express\.[a-z_]{3,}|undefined|NaN/); + ev('closeModal();selectLink(x)'); + assert.match(ev("$('panel').textContent"), /Express abbauen/); + assert.deepEqual(errors, []); +}); + +test('amp huts, ROADM slips and backhoes find fibers that only carry expresses, forced or at random', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + ev("fireFailure('amp');compute()"); + assert.equal(ev('[s1,s2].filter(id=>L(id).eqDown>S.day).length'), 1, 'an amp hut on one of the fibers goes'); + assert.equal(ev('linkDown(L(x))'), true, 'and the express with it'); + assert.equal(ev('S.inc.at(-1).type'), 'amp'); + assert.equal(ev('S.inc.at(-1).cost'), ev('AMP_COST'), 'no spares kit: a truck and a new amp'); + ev("for(const l of S.links)l.eqDown=0;S.inc=[];compute();fireFailure('roadmff');compute()"); + assert.equal(ev('[s1,s2].filter(id=>L(id).eqDown>S.day).length'), 1, 'a fat-fingered channel plan too'); + // The glass under the express is the only glass here: the dice still find it (seeded, so always the same draws). + ev(`window.__n={};for(let i=0;i<400;i++){for(const l of S.links){l.cut=0;l.eqDown=0;}for(const p of Object.values(S.pops)){p.down=0;p.rdown=0;}for(const x of S.transit)x.down=0;S.inc=[];compute(); + fireFailure();for(const c of S.inc)if([s1,s2].includes(c.ref))__n[c.type]=(__n[c.type]||0)+1;if(S.links.some(l=>l.kind==='xp'&&(l.cut>S.day||l.eqDown>S.day)))__n.xp=(__n.xp||0)+1;}`); + const n = JSON.parse(ev('JSON.stringify(__n)')); + assert.ok(n.cut > 0, 'a backhoe: ' + JSON.stringify(n)); + assert.ok(n.amp > 0, 'an amp hut: ' + JSON.stringify(n)); + assert.ok(!n.xp, 'never the express itself'); + assert.deepEqual(errors, []); +}); + +test('the chaos monkey counts fibers that only carry expresses when it decides whether to visit', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;window.s1=df('fra','bru');window.s2=df('bru','par');window.s3=df('bru','ams');compute();"); + ev(BUILD + "ACT.xpBuild({a:'fra',b:'ams',via:s1+','+s3,o:'zr4'});compute()"); + assert.equal(ev('xps=S.links.filter(l=>l.kind==="xp").length'), 2); + assert.equal(ev('[s1,s2,s3].every(id=>xpBare(L(id)))'), true); + ev("S.rules=makeRules('oncall');S.monkey={next:S.day};mkTick(S.day)"); + assert.equal(ev('!!S.monkey.on'), true, 'three fibers in the ground: enough network for a visit'); + assert.deepEqual(errors, []); +}); + +test("the intern's optics order leaves fibers that only carry expresses bare: no ports in the city they bypass", (t) => { + const { ev, errors } = game(t, SPANS + "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;window.s3=df('fra','ams');compute();"); + ev(BUILD); + const ports = () => JSON.parse(ev("JSON.stringify(['bru','par'].map(c=>portsUsed(c)))")); + const p0 = ports(); + ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.optics=true;S.ops.cap.optics=0;compute();opsDay(S.day)"); + assert.equal(ev('L(s1).ch.length+L(s2).ch.length'), 0, 'both fibers under the express stay bare'); + assert.deepEqual(ports(), p0, 'no router port in Brussels, none more in Paris'); + assert.ok(ev('L(s3).ch.length') > 0, 'new fiber with nothing on it still gets its first channel'); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('L(s1).ch.length+L(s2).ch.length'), 0, 'and on the next shift'); + assert.deepEqual(errors, []); +}); + +test('an express is no link between its ends for a new wave: the first one pays the usual price and gets no route question', (t) => { + const wave = (extra) => { + const { ev, errors } = game(t, SPANS + extra, { agent: true }); + const quote = ev("API_CMD.buildLink.quote({a:'fra',b:'par',tier:1}).monthly"); + ev("UI.lmode='wave';openLinkModal('fra','par')"); + const modal = ev("$('modal').innerHTML"); + ev("UI.route='same';ACT.buildLink({tier:1});compute()"); + const w = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='wave'))")); + assert.deepEqual(errors, []); + return { quote, modal, mo: w.mo, mult: w.mult }; + }; + const plain = wave(''), xp = wave(BUILD); + assert.ok(plain.mo > 0); + assert.equal(xp.mo, plain.mo, 'the same monthly price as without the express'); + assert.equal(xp.mult, plain.mult); + assert.equal(xp.quote, plain.quote, 'and the same quote for tools'); + assert.doesNotMatch(xp.modal, /data-act="route"/, 'no same-trench or diverse choice: there is no wave here yet'); +}); + +test("a fiber's 'Express to…' opens the window on the path it offered, even with shorter ones elsewhere", (t) => { + // Frankfurt to Paris: via Bettembourg, via Brussels, via Düsseldorf and Brussels are all shorter than via Amsterdam. + const { ev, errors } = game(t, SPANS + "ACT.buildPop({city:'ams'});for(const c of ['bet','dus']){ACT.buildPop({city:c});S.pops[c].rgen=1;}S.pops.ams.rgen=1;" + + "df('fra','bet');df('bet','par');df('fra','dus');df('dus','bru');window.fa=df('fra','ams');df('ams','par');compute();"); + ev('selectLink(fa)'); + const plans = JSON.parse(ev(`JSON.stringify([...$('panel').querySelectorAll('[data-act="xpOpen"]')].map(b=>JSON.parse(b.dataset.args)))`)); + const offer = plans.find((p) => p.a === 'fra' && p.b === 'par'); + assert.ok(offer, 'the fiber offers Frankfurt → Paris: ' + JSON.stringify(plans)); + assert.equal(offer.via.split(',')[0], ev('fa'), 'starting on this fiber'); + assert.equal(ev(`xpPaths('fra','par').some(r=>r.sp[0].id===fa)`), false, 'not among the three shortest'); + ev(`ACT.xpOpen(${JSON.stringify(offer)})`); + const heads = () => JSON.parse(ev(`JSON.stringify([...$('modal').querySelectorAll('h4')].map(h=>h.textContent))`)); + assert.match(heads()[0], /^via Amsterdam · /, 'the offered path comes first: ' + heads().join(' | ')); + assert.ok(ev(`[...$('modal').querySelectorAll('[data-act="xpBuild"]')].some(b=>JSON.parse(b.dataset.args).via===${JSON.stringify(offer.via)}&&!b.disabled)`), 'and it can be lit from here'); + // Switching tabs and back keeps it; the Express tab of a fresh window shows the shortest three. + ev("ACT.dfMode({m:'wave'})"); + ev(`ACT.xpOpen(JSON.parse($('modal').querySelector('[data-act="xpOpen"]').dataset.args))`); + assert.match(heads()[0], /^via Amsterdam · /); + ev("closeModal();ACT.xpOpen({a:'fra',b:'par'})"); + assert.ok(!heads().some((h) => /Amsterdam/.test(h)), heads().join(' | ')); + ev(`ACT.xpBuild({a:'fra',b:'par',via:${JSON.stringify(offer.via)},o:'zr4'});compute()`); + assert.equal(ev("S.links.filter(l=>l.kind==='xp').map(l=>l.via[0]).join()"), ev('fa')); + assert.deepEqual(errors, []); +}); + +test('the build standard keeps a fiber lit while an express on it carries traffic, and swaps it once the express is idle', (t) => { + const { ev, errors } = game(t); + ev(BUILD); + assert.ok(ev('R.load[x]') > 1, 'Paris rides the express'); + assert.equal(ev('(R.load[s1]||0)+(R.load[s2]||0)'), 0, 'the fibers carry nothing of their own'); + ev("S.popStd=bstdPut(Object.assign(bstd(),{sys:'cl'}));compute()"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false).held)')).sort(), ['bru|par', 'fra|bru'], 'both fibers wait'); + ev('ACT.bstdApply()'); + assert.equal(ev("L(s1).sys+','+L(s2).sys"), 'roadm,roadm', 'no line system swap under a busy express'); + assert.equal(ev('xpDown(L(x))'), false, 'the express stays up'); + // Idle (Paris has no users left), the express no longer holds its fibers back. + ev('S.pops.par.bb=null;compute()'); + assert.equal(ev('R.load[x]||0'), 0); + ev('ACT.bstdApply()'); + assert.equal(ev("L(s1).sys+','+L(s2).sys"), 'cl,cl', 'both fibers move up to C+L'); + assert.deepEqual(errors, []); +}); + +test('in Spanish, every express label says exprés', () => { + const es = require('fs').readFileSync(require('path').join(__dirname, '..', 'site', 'i18n', 'es.js'), 'utf8'); + const lines = es.split('\n').filter((l) => l.startsWith('"express.')); + assert.ok(lines.length > 30); + assert.deepEqual(lines.filter((l) => /\bexpress\b/i.test(l.slice(l.indexOf(':')))), []); +}); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 71230db..50bf647 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -223,7 +223,7 @@ test('a dry run prices every command that has a price, and changes nothing', () rmLink: { id: wave }, buyNni: { city: 'fra', prov: fab, tier: 0 }, lagNni: { city: 'fra', prov: fab, d: 1 }, buyVxc: { a: 'fra', b: 'ams', prov: fab, t: 0 }, upVxc: { id: wave, t: 1 }, orderDf: { a: 'fra', b: 'ams', source: 'lease', system: 'lite' }, orderCable: { a: 'lis', b: 'nyc' }, subUpgrade: { id: df, k: 'terminal' }, crews: { id: df }, addCh: { id: df, o: 'zr4' }, addPair: { id: df }, upSys: { id: df }, regen: { id: df, d: 1 }, buySpare: { o: 'zr4' }, sellSpare: { o: 'zr4' }, - setChCount: { id: df, o: 'zr4', n: 2 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, + setChCount: { id: df, o: 'zr4', n: 2 }, xpBuild: { a: 'fra', b: 'par', via: df + ',' + df, o: 'zr4' }, xpCh: { id: df, o: 'zr4', d: 1 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, From e1ae8e0164cbda1bbe662aacea51ddfc7e78189d Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:12:23 +0100 Subject: [PATCH 7/8] Satellite teleports: GEO and MEO circuits for islands and remote towns (#83) The early and mid-game satellite option, before Pie in the Sky. Build a teleport at a POP that a satellite sees, then rent capacity from it to a remote POP: GEO (Intelsplat, Kacophony) needs no capex but costs a lot a month per Gbps, 1-10 Gbps at about 600 ms; MEO (O3bservant) needs tracking antennas at the teleport and gives multi-Gbps at about 130 ms where both ends are under its ring, at least 5 degrees up. Coverage follows each bird's footprint by ocean region. Latency feeds the latency model: users who ride a satellite notice, in proportion to the share. A circuit beside a cable goes on standby, whichever came first, and carries only what the cable cannot: the classic single-cable island backup. Satellites are not subsea links for covenants, scenario goals or subsidies (Pitcairn's UK grant needs a cable). Express fiber and the build standard leave satellite circuits alone. --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 1 + site/i18n/de.js | 70 +++ site/i18n/es.js | 70 +++ site/i18n/fr.js | 70 +++ site/i18n/it.js | 70 +++ site/i18n/pt.js | 70 +++ src/agent/10-domains.js | 2 + src/agent/20-commands.js | 19 +- src/agent/30-docs.js | 5 +- src/agent/40-read.js | 2 +- src/game/10-catalog/60-reach-and-subsea.js | 6 +- src/game/10-catalog/75-satellites.js | 61 +++ src/game/60-features/10-banks.js | 4 +- src/game/60-features/20-scenarios.js | 4 +- src/game/60-features/45-teleports.js | 73 +++ src/game/60-features/50-traceroute.js | 2 +- src/game/60-features/85-pitcairn.js | 11 +- src/game/60-features/95-standing-orders.js | 2 +- src/game/60-features/96-pop-standard.js | 2 +- src/game/60-features/99-pie-subsidies.js | 2 +- src/game/80-simulation/10-dijkstra.js | 2 +- src/game/80-simulation/30-compute.js | 21 +- src/game/80-simulation/40-billing.js | 2 +- src/game/80-simulation/50-sanitize.js | 3 +- .../80-simulation/80-geography-and-latency.js | 2 +- src/game/85-incidents/20-failures.js | 2 +- src/game/85-incidents/40-chaos-monkey.js | 4 +- src/game/88-days/10-day-tick.js | 2 +- src/game/90-actions/10-interface.js | 2 +- src/game/90-actions/60-links.js | 6 +- src/game/90-actions/86-specialist.js | 2 +- src/game/90-actions/87-fiber-and-hardware.js | 4 +- src/game/90-actions/87-teleports.js | 27 ++ src/game/93-ui/50-city-panel.js | 7 +- src/game/93-ui/70-link-panels.js | 1 + src/game/93-ui/72-teleport-panels.js | 60 +++ src/game/94-dashboard/50-lease-swaps.js | 2 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/94-dashboard/70-bank.js | 2 +- src/game/95-modals/70-link-modal.js | 2 +- src/game/96-map/55-link-look.js | 4 +- src/i18n/en.js | 70 +++ tests/gameplay-rules.test.js | 6 +- tests/mcp-commands.test.js | 1 + tests/satellites.test.js | 445 ++++++++++++++++++ 46 files changed, 1176 insertions(+), 55 deletions(-) create mode 100644 src/game/10-catalog/75-satellites.js create mode 100644 src/game/60-features/45-teleports.js create mode 100644 src/game/90-actions/87-teleports.js create mode 100644 src/game/93-ui/72-teleport-panels.js create mode 100644 tests/satellites.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 6f149f4..619584b 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -24,7 +24,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. | | W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. | -| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, or reach it through a pie dish; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | +| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | | W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. | | W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. | @@ -33,7 +33,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | | N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. | -| N2 | Names are puns: no network, cable, exchange, data center, router, optic, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | +| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | | N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. | | N4 | No upstream cycles. | Cones must be trees, not loops. | | N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 639dbf4..af60927 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. - Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). - Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) +- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order. - Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. - Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. - IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). diff --git a/site/i18n/de.js b/site/i18n/de.js index bccdbe8..8e8c786 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3927,6 +3927,7 @@ "pie_traffic.via_dishes":"hoch in {up}, runter in {down}", "pitcairn.uk_grant_mo":"Zuschuss aus UK {mo}/Monat", "pitcairn.uk_grant_mo_once_islanders":"Zuschuss aus UK {mo}/Monat, sobald die Inselbewohner online sind", +"pitcairn.uk_grant_needs_a_cable":"Zuschuss aus UK {mo}/Monat nur mit Kabel: gemietete Satellitenkapazität zählt nicht", "pitcairn.uk_sky_grant_mo":"Satelliten-Zuschuss aus UK {mo}/Monat (Glasfaser bekommt {full})", "pni_all.additional_per_month":"Zusätzliche Kosten pro Monat", "pni_all.all_at_port":"Mit allen Netzen peeren · {port}", @@ -4534,6 +4535,75 @@ "sales.w_last":"Letzte Woche: {name} {list}.", "sales.w_now":"Diese Woche: {name} {list}.", "sales.w_signed":{"one":"hat einen Kunden gewonnen ({rev}/Monat)","other":"hat {n} Kunden gewonnen ({rev}/Monat)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Ein Teleport ist ein Satelliten-Gateway: große Schüsseln an diesem POP, die Kapazität auf fremden Satelliten mieten, für kleine Inseln und abgelegene Orte, die kein Kabel erreicht, oder die an einem Kabel und einem Stoßgebet hängen.", +"satellites.add_tracking_antennas_cost_mo":"MEO-Nachführantennen {cost} + {mo}/Monat", +"satellites.being_commissioned":"Wird in Betrieb genommen", +"satellites.build_a_teleport_cost_mo":"Teleport bauen {cost} + {mo}/Monat", +"satellites.by_satellite":"Per Satellit", +"satellites.cancel_n_circuits_first":{"one":"Kündige zuerst seine Satellitenverbindung.","other":"Kündige zuerst seine {n} Satellitenverbindungen."}, +"satellites.choose":"Wählen", +"satellites.circuit_ordered":{"one":"{cap} auf {bird} bestellt. {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tag.","other":"{cap} auf {bird} bestellt. {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tagen."}, +"satellites.close_the_teleport":"Teleport schließen", +"satellites.costs_row":"Teleports und Satelliten", +"satellites.geo_dishes":"GEO-Schüsseln", +"satellites.geo_dishes_and_meo_tracking":"GEO-Schüsseln und MEO-Nachführantennen", +"satellites.geo_users_notice":"Aus 36.000 km Höhe dauert die Runde etwa 600 ms: Videocalls und Games ruckeln, und die Nutzer werten {p} des Service als schlecht.", +"satellites.grow_to":"Auf {cap} vergrößern", +"satellites.in_view_list":"In Sicht: {list}.", +"satellites.it_waits_on_standby":"Zwischen den beiden hast du schon einen Link: Der Satellit wartet im Standby und trägt Traffic nur, wenn dieser Link ausfällt.", +"satellites.its_blurb":"Klassische C- und Ku-Band-Strahlen, die einen ganzen Ozean abdecken. Zuverlässig, überall, und so bepreist.", +"satellites.kac_blurb":"Ka-Band-Spotbeams über dem Westpazifik: das billigste Gbps im Orbit, wenn deine Insel unter einem Beam liegt.", +"satellites.meo_comes_at_level":"Der MEO-Ring (etwa 130 ms hin und zurück) kommt auf Level {lv}.", +"satellites.meo_ring_misses_city":"Der MEO-Ring sieht {city} nicht: Er deckt {lat}° beiderseits des Äquators ab.", +"satellites.meo_users_notice":"Viel näher am Boden, etwa 130 ms hin und zurück: Die Nutzer merken kaum etwas ({p} des Service gilt als schlecht).", +"satellites.more_islands_and_towns":"Weitere Inseln und Orte in Sicht", +"satellites.ms_one_way_rtt":"{ms} ms pro Richtung, {rtt} ms hin und zurück", +"satellites.ms_round_trip":"{ms} ms hin und zurück", +"satellites.n_birds_see_both":{"one":"{n} Satellit sieht beide","other":"{n} Satelliten sehen beide"}, +"satellites.n_circuits_go_on_standby":{"one":"Deine Satellitenverbindung zwischen {a} und {b} geht neben dem neuen Link in Standby: Sie trägt Traffic nur, wenn dieser Link ausfällt.","other":"Deine {n} Satellitenverbindungen zwischen {a} und {b} gehen neben dem neuen Link in Standby: Sie tragen Traffic nur, wenn dieser Link ausfällt."}, +"satellites.n_places_in_reach":{"one":"{n} Insel oder abgelegener Ort in Reichweite auf deinem Level.","other":"{n} Inseln und abgelegene Orte in Reichweite auf deinem Level."}, +"satellites.needs_tracking_antennas":"Der MEO-Ring braucht Nachführantennen an deinem Teleport in {city}.", +"satellites.new_pop_cost":"neuer POP {cost}", +"satellites.no_bird_sees_both":"Kein Satellit im Angebot sieht {a} und {b} zugleich.", +"satellites.no_bird_sees_this_city":"Kein Satellit im Angebot sieht diese Stadt.", +"satellites.no_cable_needed_a_pop_here":"Kein Kabel nötig: Eine Satellitenverbindung von einem deiner Teleports bringt einen POP in {city} online.", +"satellites.no_pop_in_city":"Du hast keinen POP in {city}.", +"satellites.no_pop_there_yet":"Noch kein POP in {city}: Der wird gleich mitgebaut ({cost}).", +"satellites.no_such_circuit":"Diese Satellitenverbindung gibt es nicht.", +"satellites.no_teleport_in_city":"Du hast keinen Teleport in {city}.", +"satellites.no_teleport_reaches_city":"Keiner deiner Teleports erreicht {city}. Bau einen an einem POP, dessen Satelliten die Stadt sehen.", +"satellites.not_remote":"{city} ist ein zu großer Markt für Satellitenkapazität: Die ist für kleine Inseln und abgelegene Orte da.", +"satellites.nothing_in_view_from_here":"Von hier ist keine Insel und kein abgelegener Ort in Sicht.", +"satellites.on_standby_beside_your_link":"Er wartet im Standby neben deinem Link zwischen den beiden und trägt Traffic nur, wenn dieser Link ausfällt.", +"satellites.orbit_unlocks_at_level":"{orb}-Satelliten gibt es ab Level {lv}.", +"satellites.out_of_footprint":"{bird} sieht nicht {a} und {b} zugleich.", +"satellites.pointing_dishes_and_testing":"Schüsseln ausrichten und testen", +"satellites.radio_path":"Funkweg, hoch und runter", +"satellites.reachable_from_your_teleports":"Deine Teleports erreichen {city} per Satellit:", +"satellites.really_close_it":"Wirklich schließen?", +"satellites.rent":"Miete", +"satellites.rent_satellite_capacity":"Satellitenkapazität mieten", +"satellites.satellite_capacity":"Satellitenkapazität", +"satellites.satellites":"Satelliten", +"satellites.sea_americas":"Amerika", +"satellites.sea_atlantic":"Atlantik", +"satellites.sea_indian":"Indischer Ozean", +"satellites.sea_pacific":"Pazifik", +"satellites.sea_tropics":"bis 50° um den Äquator", +"satellites.sea_west_pacific":"Westpazifik", +"satellites.sesa_blurb":"Ein Ring aus Satelliten 8.000 km über dem Äquator, für die anderen drei Milliarden. Sesam, öffne dich: etwa 130 ms hin und zurück.", +"satellites.shrink_to":"Auf {cap} verkleinern", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"Der Teleport in {city} ist geschlossen.", +"satellites.teleport_up_in_city":"Teleport in {city} läuft. Große Schüsseln auf dem Dach, ab in den Himmel: Miete von hier Kapazität zu den Inseln in Sicht.", +"satellites.teleports_unlock_at_level":"Teleports gibt es ab Level {lv}.", +"satellites.tracking_antennas_up":"Nachführantennen in {city} laufen. Sie folgen dem MEO-Ring über den Himmel.", +"satellites.up_in_n_days":{"one":"läuft in {n} Tag","other":"läuft in {n} Tagen"}, +"satellites.users_notice_geo_meo":"Die Nutzer merken die Verzögerung: Breitband über GEO zählt als halber Service, über MEO fast als ganzer. Ein Kabel gewinnt immer, deine Router schicken Traffic also nur nach oben, wenn es keinen anderen Weg gibt.", +"satellites.users_ride_a_satellite":"Nutzer hängen am Satelliten", +"satellites.via_bird":"über {bird}", +"satellites.who_a_satellite_serves":"Satelliten bedienen kleine Inseln und abgelegene Orte, die derselbe Satellit sieht wie dein Teleport. Wähle das Ziel.", +"satellites.your_pops_in_view":"Deine POPs in Sicht", "save.cash_in_the_bank":"{cash} auf der Bank", "save.import_failed_err":"Import fehlgeschlagen.
{err}", "save.load_name":"{name} laden?", diff --git a/site/i18n/es.js b/site/i18n/es.js index 9ec154f..a416061 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"sube en {up}, baja en {down}", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", +"pitcairn.uk_grant_needs_a_cable":"Subvención británica {mo}/mes solo con cable: la capacidad satelital alquilada no cuenta", "pitcairn.uk_sky_grant_mo":"Subvención británica por satélite {mo}/mes (la fibra recibe {full})", "pni_all.additional_per_month":"Coste mensual adicional", "pni_all.all_at_port":"Peering con todas las redes · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La semana pasada {name} {list}.", "sales.w_now":"Esta semana {name} {list}.", "sales.w_signed":{"one":"firmó un cliente ({rev}/mes)","other":"firmó {n} clientes ({rev}/mes)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un teleport es una pasarela satelital: antenas grandes en este POP que alquilan capacidad en satélites ajenos, para islas pequeñas y pueblos remotos a los que no llega ningún cable, o que cuelgan de un solo cable y una plegaria.", +"satellites.add_tracking_antennas_cost_mo":"Antenas de seguimiento MEO {cost} + {mo}/mes", +"satellites.being_commissioned":"En puesta en servicio", +"satellites.build_a_teleport_cost_mo":"Construir un teleport {cost} + {mo}/mes", +"satellites.by_satellite":"Por satélite", +"satellites.cancel_n_circuits_first":{"one":"Primero cancela su circuito satelital.","other":"Primero cancela sus {n} circuitos satelitales."}, +"satellites.choose":"Elegir", +"satellites.circuit_ordered":{"one":"{cap} en {bird} pedidos. {a} ⇄ {b} se está apuntando y probando: listo en {n} día.","other":"{cap} en {bird} pedidos. {a} ⇄ {b} se está apuntando y probando: listo en {n} días."}, +"satellites.close_the_teleport":"Cerrar el teleport", +"satellites.costs_row":"Teleports y satélites", +"satellites.geo_dishes":"Antenas GEO", +"satellites.geo_dishes_and_meo_tracking":"Antenas GEO y antenas de seguimiento MEO", +"satellites.geo_users_notice":"Desde 36.000 km de altura la ida y vuelta tarda unos 600 ms: las videollamadas y los juegos se traban, y los usuarios cuentan {p} del servicio como malo.", +"satellites.grow_to":"Ampliar a {cap}", +"satellites.in_view_list":"A la vista: {list}.", +"satellites.it_waits_on_standby":"Ya tienes un enlace entre estas dos: el satélite espera en reserva y solo lleva tráfico cuando ese enlace cae.", +"satellites.its_blurb":"Haces de banda C y Ku de toda la vida que cubren un océano entero. Fiables, en todas partes, y con precio a juego.", +"satellites.kac_blurb":"Haces puntuales en banda Ka sobre el Pacífico occidental: el Gbps más barato en órbita, si tu isla queda bajo un haz.", +"satellites.meo_comes_at_level":"El anillo MEO (unos 130 ms de ida y vuelta) llega en el nivel {lv}.", +"satellites.meo_ring_misses_city":"El anillo MEO no ve {city}: cubre {lat}° a cada lado del ecuador.", +"satellites.meo_users_notice":"Mucho más cerca del suelo, unos 130 ms de ida y vuelta: los usuarios apenas lo notan ({p} del servicio cuenta como malo).", +"satellites.more_islands_and_towns":"Más islas y pueblos a la vista", +"satellites.ms_one_way_rtt":"{ms} ms de ida, {rtt} ms de ida y vuelta", +"satellites.ms_round_trip":"{ms} ms de ida y vuelta", +"satellites.n_birds_see_both":{"one":"{n} satélite ve los dos","other":"{n} satélites ven los dos"}, +"satellites.n_circuits_go_on_standby":{"one":"Tu circuito satelital entre {a} y {b} pasa a reserva junto al nuevo enlace: solo lleva tráfico cuando ese enlace cae.","other":"Tus {n} circuitos satelitales entre {a} y {b} pasan a reserva junto al nuevo enlace: solo llevan tráfico cuando ese enlace cae."}, +"satellites.n_places_in_reach":{"one":"{n} isla o pueblo remoto a tu alcance en tu nivel.","other":"{n} islas y pueblos remotos a tu alcance en tu nivel."}, +"satellites.needs_tracking_antennas":"El anillo MEO necesita antenas de seguimiento en tu teleport de {city}.", +"satellites.new_pop_cost":"POP nuevo {cost}", +"satellites.no_bird_sees_both":"Ningún satélite a la venta ve a la vez {a} y {b}.", +"satellites.no_bird_sees_this_city":"Ningún satélite a la venta ve esta ciudad.", +"satellites.no_cable_needed_a_pop_here":"Sin cable: un circuito satelital desde uno de tus teleports pone en línea un POP en {city}.", +"satellites.no_pop_in_city":"No tienes POP en {city}.", +"satellites.no_pop_there_yet":"Aún no hay POP en {city}: esto también construye uno ({cost}).", +"satellites.no_such_circuit":"Ese circuito satelital no existe.", +"satellites.no_teleport_in_city":"No tienes teleport en {city}.", +"satellites.no_teleport_reaches_city":"Ninguno de tus teleports llega a {city}. Construye uno en un POP cuyos satélites la vean.", +"satellites.not_remote":"{city} es un mercado demasiado grande para capacidad satelital: es para islas pequeñas y pueblos remotos.", +"satellites.nothing_in_view_from_here":"Desde aquí no hay ninguna isla ni pueblo remoto a la vista.", +"satellites.on_standby_beside_your_link":"Espera en reserva junto a tu enlace entre las dos y solo lleva tráfico cuando ese enlace cae.", +"satellites.orbit_unlocks_at_level":"Los satélites {orb} se desbloquean en el nivel {lv}.", +"satellites.out_of_footprint":"{bird} no ve a la vez {a} y {b}.", +"satellites.pointing_dishes_and_testing":"Apuntando antenas y probando", +"satellites.radio_path":"Trayecto de radio, subida y bajada", +"satellites.reachable_from_your_teleports":"Tus teleports llegan a {city} por satélite:", +"satellites.really_close_it":"¿Cerrarlo de verdad?", +"satellites.rent":"Alquiler", +"satellites.rent_satellite_capacity":"Alquilar capacidad satelital", +"satellites.satellite_capacity":"Capacidad satelital", +"satellites.satellites":"Satélites", +"satellites.sea_americas":"Américas", +"satellites.sea_atlantic":"Atlántico", +"satellites.sea_indian":"Océano Índico", +"satellites.sea_pacific":"Pacífico", +"satellites.sea_tropics":"hasta 50° del ecuador", +"satellites.sea_west_pacific":"Pacífico occidental", +"satellites.sesa_blurb":"Un anillo de satélites a 8.000 km sobre el ecuador, para los otros tres mil millones. Ábrete, sésamo: unos 130 ms de ida y vuelta.", +"satellites.shrink_to":"Reducir a {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"El teleport de {city} está cerrado.", +"satellites.teleport_up_in_city":"Teleport en marcha en {city}. Antenas enormes en la azotea, apuntando al cielo: alquila desde aquí capacidad hacia las islas a la vista.", +"satellites.teleports_unlock_at_level":"Los teleports se desbloquean en el nivel {lv}.", +"satellites.tracking_antennas_up":"Antenas de seguimiento en marcha en {city}. Siguen el anillo MEO por el cielo.", +"satellites.up_in_n_days":{"one":"listo en {n} día","other":"listo en {n} días"}, +"satellites.users_notice_geo_meo":"Los usuarios notan el retardo: la banda ancha por GEO cuenta como medio servicio, por MEO casi como el servicio entero. Un cable siempre gana, así que tus routers solo mandan tráfico arriba cuando no hay otro camino.", +"satellites.users_ride_a_satellite":"usuarios vía satélite", +"satellites.via_bird":"vía {bird}", +"satellites.who_a_satellite_serves":"Los satélites sirven a islas pequeñas y pueblos remotos que ve el mismo satélite que tu teleport. Elige el destino.", +"satellites.your_pops_in_view":"Tus POP a la vista", "save.cash_in_the_bank":"{cash} en el banco", "save.import_failed_err":"Falló la importación.
{err}", "save.load_name":"¿Cargar {name}?", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index ec461d3..6ca08cf 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"monte à {up}, descend à {down}", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pitcairn.uk_grant_needs_a_cable":"Subvention britannique {mo}/mois seulement avec un câble : la capacité satellite louée ne compte pas", "pitcairn.uk_sky_grant_mo":"Subvention britannique satellite {mo}/mois (la fibre touche {full})", "pni_all.additional_per_month":"Coût mensuel supplémentaire", "pni_all.all_at_port":"Peering avec tous les réseaux · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La semaine dernière, {name} {list}.", "sales.w_now":"Cette semaine, {name} {list}.", "sales.w_signed":{"one":"a signé un client ({rev}/mois)","other":"a signé {n} clients ({rev}/mois)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un téléport est une passerelle satellite : de grandes paraboles sur ce POP qui louent de la capacité sur les satellites des autres, vers les petites îles et les villes isolées qu’aucun câble ne dessert, ou qui ne tiennent qu’à un câble et une prière.", +"satellites.add_tracking_antennas_cost_mo":"Antennes de poursuite MEO {cost} + {mo}/mois", +"satellites.being_commissioned":"Mise en service", +"satellites.build_a_teleport_cost_mo":"Construire un téléport {cost} + {mo}/mois", +"satellites.by_satellite":"Par satellite", +"satellites.cancel_n_circuits_first":{"one":"Résilie d’abord son circuit satellite.","other":"Résilie d’abord ses {n} circuits satellite."}, +"satellites.choose":"Choisir", +"satellites.circuit_ordered":{"one":"{cap} sur {bird} commandé. {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jour.","other":"{cap} sur {bird} commandé. {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jours."}, +"satellites.close_the_teleport":"Fermer le téléport", +"satellites.costs_row":"Téléports et satellites", +"satellites.geo_dishes":"Paraboles GEO", +"satellites.geo_dishes_and_meo_tracking":"Paraboles GEO et antennes de poursuite MEO", +"satellites.geo_users_notice":"Depuis 36 000 km d’altitude, l’aller-retour prend environ 600 ms : visios et jeux saccadent, et les utilisateurs comptent {p} du service comme mauvais.", +"satellites.grow_to":"Passer à {cap}", +"satellites.in_view_list":"En vue : {list}.", +"satellites.it_waits_on_standby":"Tu as déjà un lien entre ces deux villes : le satellite attend en réserve et ne porte du trafic que quand ce lien tombe.", +"satellites.its_blurb":"De bons vieux faisceaux en bande C et Ku qui couvrent tout un océan. Fiables, partout, et facturés en conséquence.", +"satellites.kac_blurb":"Des spots en bande Ka sur le Pacifique occidental : le Gbps le moins cher en orbite, si ton île est sous un spot.", +"satellites.meo_comes_at_level":"L’anneau MEO (environ 130 ms aller-retour) arrive au niveau {lv}.", +"satellites.meo_ring_misses_city":"L’anneau MEO ne voit pas {city} : il couvre {lat}° de part et d’autre de l’équateur.", +"satellites.meo_users_notice":"Bien plus près du sol, environ 130 ms aller-retour : les utilisateurs le remarquent à peine ({p} du service compte comme mauvais).", +"satellites.more_islands_and_towns":"Autres îles et villes en vue", +"satellites.ms_one_way_rtt":"{ms} ms aller, {rtt} ms aller-retour", +"satellites.ms_round_trip":"{ms} ms aller-retour", +"satellites.n_birds_see_both":{"one":"{n} satellite voit les deux","other":"{n} satellites voient les deux"}, +"satellites.n_circuits_go_on_standby":{"one":"Ton circuit satellite entre {a} et {b} passe en réserve à côté du nouveau lien : il ne porte du trafic que quand ce lien tombe.","other":"Tes {n} circuits satellite entre {a} et {b} passent en réserve à côté du nouveau lien : ils ne portent du trafic que quand ce lien tombe."}, +"satellites.n_places_in_reach":{"one":"{n} île ou ville isolée à portée à ton niveau.","other":"{n} îles et villes isolées à portée à ton niveau."}, +"satellites.needs_tracking_antennas":"L’anneau MEO a besoin d’antennes de poursuite à ton téléport de {city}.", +"satellites.new_pop_cost":"nouveau POP {cost}", +"satellites.no_bird_sees_both":"Aucun satellite en vente ne voit à la fois {a} et {b}.", +"satellites.no_bird_sees_this_city":"Aucun satellite en vente ne voit cette ville.", +"satellites.no_cable_needed_a_pop_here":"Pas besoin de câble : un circuit satellite depuis un de tes téléports met un POP à {city} en ligne.", +"satellites.no_pop_in_city":"Tu n’as pas de POP à {city}.", +"satellites.no_pop_there_yet":"Pas encore de POP à {city} : on en construit un au passage ({cost}).", +"satellites.no_such_circuit":"Ce circuit satellite n’existe pas.", +"satellites.no_teleport_in_city":"Tu n’as pas de téléport à {city}.", +"satellites.no_teleport_reaches_city":"Aucun de tes téléports n’atteint {city}. Construis-en un sur un POP dont les satellites la voient.", +"satellites.not_remote":"{city} est un trop gros marché pour de la capacité satellite : elle sert les petites îles et les villes isolées.", +"satellites.nothing_in_view_from_here":"Aucune île ni ville isolée en vue d’ici.", +"satellites.on_standby_beside_your_link":"Il attend en réserve à côté de ton lien entre les deux et ne porte du trafic que quand ce lien tombe.", +"satellites.orbit_unlocks_at_level":"Les satellites {orb} se débloquent au niveau {lv}.", +"satellites.out_of_footprint":"{bird} ne voit pas à la fois {a} et {b}.", +"satellites.pointing_dishes_and_testing":"Pointage des paraboles et tests", +"satellites.radio_path":"Trajet radio, montée et descente", +"satellites.reachable_from_your_teleports":"Tes téléports atteignent {city} par satellite :", +"satellites.really_close_it":"Vraiment le fermer ?", +"satellites.rent":"Location", +"satellites.rent_satellite_capacity":"Louer de la capacité satellite", +"satellites.satellite_capacity":"Capacité satellite", +"satellites.satellites":"Satellites", +"satellites.sea_americas":"Amériques", +"satellites.sea_atlantic":"Atlantique", +"satellites.sea_indian":"Océan Indien", +"satellites.sea_pacific":"Pacifique", +"satellites.sea_tropics":"jusqu’à 50° de l’équateur", +"satellites.sea_west_pacific":"Pacifique occidental", +"satellites.sesa_blurb":"Un anneau de satellites à 8 000 km au-dessus de l’équateur, pour les trois autres milliards. Sésame, ouvre-toi : environ 130 ms aller-retour.", +"satellites.shrink_to":"Réduire à {cap}", +"satellites.teleport":"Téléport", +"satellites.teleport_closed":"Le téléport de {city} est fermé.", +"satellites.teleport_up_in_city":"Téléport en service à {city}. De grandes paraboles sur le toit, pointées vers le ciel : loue d’ici de la capacité vers les îles en vue.", +"satellites.teleports_unlock_at_level":"Les téléports se débloquent au niveau {lv}.", +"satellites.tracking_antennas_up":"Antennes de poursuite en service à {city}. Elles suivent l’anneau MEO dans le ciel.", +"satellites.up_in_n_days":{"one":"en service dans {n} jour","other":"en service dans {n} jours"}, +"satellites.users_notice_geo_meo":"Les utilisateurs sentent le délai : le haut débit par GEO compte pour la moitié du service, par MEO presque pour tout. Un câble gagne toujours, donc tes routeurs n’envoient du trafic là-haut que s’il n’y a pas d’autre chemin.", +"satellites.users_ride_a_satellite":"utilisateurs sur satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Les satellites desservent les petites îles et les villes isolées que voit le même satellite que ton téléport. Choisis la destination.", +"satellites.your_pops_in_view":"Tes POP en vue", "save.cash_in_the_bank":"{cash} en banque", "save.import_failed_err":"Échec de l’import.
{err}", "save.load_name":"Charger {name} ?", diff --git a/site/i18n/it.js b/site/i18n/it.js index 06d88d6..e0b0bf0 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"su a {up}, giù a {down}", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pitcairn.uk_grant_needs_a_cable":"Contributo UK {mo}/mese solo con un cavo: la capacità satellitare in affitto non conta", "pitcairn.uk_sky_grant_mo":"Contributo UK via satellite {mo}/mese (la fibra prende {full})", "pni_all.additional_per_month":"Costo mensile aggiuntivo", "pni_all.all_at_port":"Peering con tutte le reti · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"La settimana scorsa {name} {list}.", "sales.w_now":"Questa settimana {name} {list}.", "sales.w_signed":{"one":"ha firmato un cliente ({rev}/mese)","other":"ha firmato {n} clienti ({rev}/mese)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Un teleport è un gateway satellitare: grandi parabole in questo POP che noleggiano capacità sui satelliti di altri, verso piccole isole e città remote che nessun cavo raggiunge, o che stanno appese a un solo cavo e a una preghiera.", +"satellites.add_tracking_antennas_cost_mo":"Antenne a inseguimento MEO {cost} + {mo}/mese", +"satellites.being_commissioned":"In attivazione", +"satellites.build_a_teleport_cost_mo":"Costruisci un teleport {cost} + {mo}/mese", +"satellites.by_satellite":"Via satellite", +"satellites.cancel_n_circuits_first":{"one":"Prima disdici il suo circuito satellitare.","other":"Prima disdici i suoi {n} circuiti satellitari."}, +"satellites.choose":"Scegli", +"satellites.circuit_ordered":{"one":"{cap} su {bird} ordinati. {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorno.","other":"{cap} su {bird} ordinati. {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorni."}, +"satellites.close_the_teleport":"Chiudi il teleport", +"satellites.costs_row":"Teleport e satelliti", +"satellites.geo_dishes":"Parabole GEO", +"satellites.geo_dishes_and_meo_tracking":"Parabole GEO e antenne a inseguimento MEO", +"satellites.geo_users_notice":"Da 36.000 km di quota il giro dura circa 600 ms: videochiamate e giochi scattano, e gli utenti contano {p} del servizio come pessimo.", +"satellites.grow_to":"Porta a {cap}", +"satellites.in_view_list":"In vista: {list}.", +"satellites.it_waits_on_standby":"Tra queste due hai già un link: il satellite aspetta in standby e porta traffico solo quando quel link cade.", +"satellites.its_blurb":"I classici fasci in banda C e Ku che coprono un oceano intero. Affidabili, ovunque, e con il prezzo che ne consegue.", +"satellites.kac_blurb":"Spot beam in banda Ka sul Pacifico occidentale: il Gbps più economico in orbita, se la tua isola sta sotto un fascio.", +"satellites.meo_comes_at_level":"L’anello MEO (circa 130 ms andata e ritorno) arriva al livello {lv}.", +"satellites.meo_ring_misses_city":"L’anello MEO non vede {city}: copre {lat}° a nord e a sud dell’equatore.", +"satellites.meo_users_notice":"Molto più vicino a terra, circa 130 ms andata e ritorno: gli utenti se ne accorgono appena ({p} del servizio conta come pessimo).", +"satellites.more_islands_and_towns":"Altre isole e città in vista", +"satellites.ms_one_way_rtt":"{ms} ms solo andata, {rtt} ms andata e ritorno", +"satellites.ms_round_trip":"{ms} ms andata e ritorno", +"satellites.n_birds_see_both":{"one":"{n} satellite vede entrambe","other":"{n} satelliti vedono entrambe"}, +"satellites.n_circuits_go_on_standby":{"one":"Il tuo circuito satellitare tra {a} e {b} va in standby accanto al nuovo link: porta traffico solo quando quel link cade.","other":"I tuoi {n} circuiti satellitari tra {a} e {b} vanno in standby accanto al nuovo link: portano traffico solo quando quel link cade."}, +"satellites.n_places_in_reach":{"one":"{n} isola o città remota a portata al tuo livello.","other":"{n} isole e città remote a portata al tuo livello."}, +"satellites.needs_tracking_antennas":"L’anello MEO vuole antenne a inseguimento al tuo teleport di {city}.", +"satellites.new_pop_cost":"nuovo POP {cost}", +"satellites.no_bird_sees_both":"Nessun satellite in vendita vede insieme {a} e {b}.", +"satellites.no_bird_sees_this_city":"Nessun satellite in vendita vede questa città.", +"satellites.no_cable_needed_a_pop_here":"Niente cavo: un circuito satellitare da uno dei tuoi teleport mette online un POP a {city}.", +"satellites.no_pop_in_city":"Non hai un POP a {city}.", +"satellites.no_pop_there_yet":"A {city} non c’è ancora un POP: così ne costruisci anche uno ({cost}).", +"satellites.no_such_circuit":"Questo circuito satellitare non esiste.", +"satellites.no_teleport_in_city":"Non hai un teleport a {city}.", +"satellites.no_teleport_reaches_city":"Nessuno dei tuoi teleport raggiunge {city}. Costruiscine uno in un POP i cui satelliti la vedano.", +"satellites.not_remote":"{city} è un mercato troppo grande per la capacità satellitare: quella serve piccole isole e città remote.", +"satellites.nothing_in_view_from_here":"Da qui non si vede nessuna isola né città remota.", +"satellites.on_standby_beside_your_link":"Aspetta in standby accanto al tuo link tra le due e porta traffico solo quando quel link cade.", +"satellites.orbit_unlocks_at_level":"I satelliti {orb} si sbloccano al livello {lv}.", +"satellites.out_of_footprint":"{bird} non vede insieme {a} e {b}.", +"satellites.pointing_dishes_and_testing":"Puntamento delle parabole e test", +"satellites.radio_path":"Percorso radio, su e giù", +"satellites.reachable_from_your_teleports":"I tuoi teleport raggiungono {city} via satellite:", +"satellites.really_close_it":"Lo chiudi davvero?", +"satellites.rent":"Noleggio", +"satellites.rent_satellite_capacity":"Noleggia capacità satellitare", +"satellites.satellite_capacity":"Capacità satellitare", +"satellites.satellites":"Satelliti", +"satellites.sea_americas":"Americhe", +"satellites.sea_atlantic":"Atlantico", +"satellites.sea_indian":"Oceano Indiano", +"satellites.sea_pacific":"Pacifico", +"satellites.sea_tropics":"entro 50° dall’equatore", +"satellites.sea_west_pacific":"Pacifico occidentale", +"satellites.sesa_blurb":"Un anello di satelliti a 8.000 km sopra l’equatore, per gli altri tre miliardi. Apriti sesamo: circa 130 ms andata e ritorno.", +"satellites.shrink_to":"Riduci a {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"Il teleport di {city} è chiuso.", +"satellites.teleport_up_in_city":"Teleport attivo a {city}. Grandi parabole sul tetto, puntate al cielo: da qui noleggi capacità verso le isole in vista.", +"satellites.teleports_unlock_at_level":"I teleport si sbloccano al livello {lv}.", +"satellites.tracking_antennas_up":"Antenne a inseguimento attive a {city}. Seguono l’anello MEO nel cielo.", +"satellites.up_in_n_days":{"one":"attivo tra {n} giorno","other":"attivo tra {n} giorni"}, +"satellites.users_notice_geo_meo":"Gli utenti sentono il ritardo: la banda larga via GEO conta come mezzo servizio, via MEO quasi come tutto. Un cavo vince sempre, quindi i tuoi router mandano traffico lassù solo se non c’è altra strada.", +"satellites.users_ride_a_satellite":"utenti via satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"I satelliti servono piccole isole e città remote che lo stesso satellite vede insieme al tuo teleport. Scegli la destinazione.", +"satellites.your_pops_in_view":"I tuoi POP in vista", "save.cash_in_the_bank":"{cash} in cassa", "save.import_failed_err":"Importazione fallita.
{err}", "save.load_name":"Caricare {name}?", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4714044..a8014bf 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3925,6 +3925,7 @@ "pie_traffic.via_dishes":"sobe em {up}, desce em {down}", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", +"pitcairn.uk_grant_needs_a_cable":"Subsídio do Reino Unido {mo}/mês só com cabo: capacidade de satélite alugada não conta", "pitcairn.uk_sky_grant_mo":"Subsídio britânico por satélite {mo}/mês (a fibra recebe {full})", "pni_all.additional_per_month":"Custo mensal adicional", "pni_all.all_at_port":"Peering com todas as redes · {port}", @@ -4532,6 +4533,75 @@ "sales.w_last":"Semana passada {name} {list}.", "sales.w_now":"Esta semana {name} {list}.", "sales.w_signed":{"one":"assinou um cliente ({rev}/mês)","other":"assinou {n} clientes ({rev}/mês)"}, +"satellites.a_teleport_is_a_satellite_gateway":"Um teleporto é um gateway de satélite: antenas grandes neste POP que alugam capacidade nos satélites dos outros, para ilhas pequenas e cidades remotas aonde nenhum cabo chega, ou que dependem de um só cabo e de uma reza.", +"satellites.add_tracking_antennas_cost_mo":"Antenas de rastreamento MEO {cost} + {mo}/mês", +"satellites.being_commissioned":"Em comissionamento", +"satellites.build_a_teleport_cost_mo":"Construir um teleporto {cost} + {mo}/mês", +"satellites.by_satellite":"Por satélite", +"satellites.cancel_n_circuits_first":{"one":"Cancele primeiro o circuito de satélite dele.","other":"Cancele primeiro os {n} circuitos de satélite dele."}, +"satellites.choose":"Escolher", +"satellites.circuit_ordered":{"one":"{cap} no {bird} encomendados. {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dia.","other":"{cap} no {bird} encomendados. {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dias."}, +"satellites.close_the_teleport":"Fechar o teleporto", +"satellites.costs_row":"Teleportos e satélites", +"satellites.geo_dishes":"Antenas GEO", +"satellites.geo_dishes_and_meo_tracking":"Antenas GEO e antenas de rastreamento MEO", +"satellites.geo_users_notice":"De 36.000 km de altura a ida e volta leva uns 600 ms: chamadas de vídeo e jogos travam, e os usuários contam {p} do serviço como ruim.", +"satellites.grow_to":"Aumentar para {cap}", +"satellites.in_view_list":"À vista: {list}.", +"satellites.it_waits_on_standby":"Você já tem um link entre as duas: o satélite espera de reserva e só leva tráfego quando esse link cai.", +"satellites.its_blurb":"Feixes clássicos em banda C e Ku que cobrem um oceano inteiro. Confiáveis, em todo lugar, e com preço à altura.", +"satellites.kac_blurb":"Feixes pontuais em banda Ka sobre o Pacífico ocidental: o Gbps mais barato em órbita, se a sua ilha estiver debaixo de um feixe.", +"satellites.meo_comes_at_level":"O anel MEO (uns 130 ms de ida e volta) chega no nível {lv}.", +"satellites.meo_ring_misses_city":"O anel MEO não vê {city}: ele cobre {lat}° de cada lado do equador.", +"satellites.meo_users_notice":"Muito mais perto do chão, uns 130 ms de ida e volta: os usuários mal percebem ({p} do serviço conta como ruim).", +"satellites.more_islands_and_towns":"Mais ilhas e cidades à vista", +"satellites.ms_one_way_rtt":"{ms} ms só de ida, {rtt} ms de ida e volta", +"satellites.ms_round_trip":"{ms} ms de ida e volta", +"satellites.n_birds_see_both":{"one":"{n} satélite vê as duas","other":"{n} satélites veem as duas"}, +"satellites.n_circuits_go_on_standby":{"one":"Seu circuito de satélite entre {a} e {b} fica de reserva ao lado do novo link: só leva tráfego quando esse link cai.","other":"Seus {n} circuitos de satélite entre {a} e {b} ficam de reserva ao lado do novo link: só levam tráfego quando esse link cai."}, +"satellites.n_places_in_reach":{"one":"{n} ilha ou cidade remota ao alcance no seu nível.","other":"{n} ilhas e cidades remotas ao alcance no seu nível."}, +"satellites.needs_tracking_antennas":"O anel MEO precisa de antenas de rastreamento no seu teleporto em {city}.", +"satellites.new_pop_cost":"POP novo {cost}", +"satellites.no_bird_sees_both":"Nenhum satélite à venda vê {a} e {b} ao mesmo tempo.", +"satellites.no_bird_sees_this_city":"Nenhum satélite à venda vê esta cidade.", +"satellites.no_cable_needed_a_pop_here":"Sem cabo: um circuito de satélite de um dos seus teleportos coloca um POP em {city} no ar.", +"satellites.no_pop_in_city":"Você não tem POP em {city}.", +"satellites.no_pop_there_yet":"Ainda não há POP em {city}: isto também constrói um ({cost}).", +"satellites.no_such_circuit":"Esse circuito de satélite não existe.", +"satellites.no_teleport_in_city":"Você não tem teleporto em {city}.", +"satellites.no_teleport_reaches_city":"Nenhum dos seus teleportos alcança {city}. Construa um num POP cujos satélites a vejam.", +"satellites.not_remote":"{city} é um mercado grande demais para capacidade de satélite: ela é para ilhas pequenas e cidades remotas.", +"satellites.nothing_in_view_from_here":"Daqui não há nenhuma ilha nem cidade remota à vista.", +"satellites.on_standby_beside_your_link":"Ele espera de reserva ao lado do seu link entre as duas e só leva tráfego quando esse link cai.", +"satellites.orbit_unlocks_at_level":"Satélites {orb} são liberados no nível {lv}.", +"satellites.out_of_footprint":"{bird} não vê {a} e {b} ao mesmo tempo.", +"satellites.pointing_dishes_and_testing":"Apontando antenas e testando", +"satellites.radio_path":"Caminho de rádio, subida e descida", +"satellites.reachable_from_your_teleports":"Seus teleportos alcançam {city} por satélite:", +"satellites.really_close_it":"Fechar mesmo?", +"satellites.rent":"Aluguel", +"satellites.rent_satellite_capacity":"Alugar capacidade de satélite", +"satellites.satellite_capacity":"Capacidade de satélite", +"satellites.satellites":"Satélites", +"satellites.sea_americas":"Américas", +"satellites.sea_atlantic":"Atlântico", +"satellites.sea_indian":"Oceano Índico", +"satellites.sea_pacific":"Pacífico", +"satellites.sea_tropics":"até 50° do equador", +"satellites.sea_west_pacific":"Pacífico ocidental", +"satellites.sesa_blurb":"Um anel de satélites a 8.000 km acima do equador, para os outros três bilhões. Abre-te, sésamo: uns 130 ms de ida e volta.", +"satellites.shrink_to":"Reduzir para {cap}", +"satellites.teleport":"Teleporto", +"satellites.teleport_closed":"O teleporto em {city} foi fechado.", +"satellites.teleport_up_in_city":"Teleporto no ar em {city}. Antenas enormes no telhado, apontadas para o céu: alugue daqui capacidade para as ilhas à vista.", +"satellites.teleports_unlock_at_level":"Teleportos são liberados no nível {lv}.", +"satellites.tracking_antennas_up":"Antenas de rastreamento no ar em {city}. Elas seguem o anel MEO pelo céu.", +"satellites.up_in_n_days":{"one":"no ar em {n} dia","other":"no ar em {n} dias"}, +"satellites.users_notice_geo_meo":"Os usuários sentem o atraso: banda larga por GEO conta como meio serviço, por MEO quase como o serviço inteiro. Um cabo sempre ganha, então seus roteadores só mandam tráfego para cima quando não há outro caminho.", +"satellites.users_ride_a_satellite":"usuários via satélite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Satélites atendem ilhas pequenas e cidades remotas que o mesmo satélite vê junto com o seu teleporto. Escolha o destino.", +"satellites.your_pops_in_view":"Seus POPs à vista", "save.cash_in_the_bank":"{cash} no banco", "save.import_failed_err":"Falha na importação.
{err}", "save.load_name":"Carregar {name}?", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js index 3a51abb..1d3d9a7 100644 --- a/src/agent/10-domains.js +++ b/src/agent/10-domains.js @@ -22,6 +22,8 @@ const API_DOMAINS={ vxcTier:{table:'VXC',kind:'index'}, routerModel:{table:'RG',kind:'index'}, scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + satBird:{table:'SATS',kind:'key'}, + satG:{kind:'enum',values:()=>[...new Set(Object.values(SAT_ORB).flatMap(o=>o.g))].sort((a,b)=>a-b)}, // Small fixed vocabularies the game itself checks by list membership. // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 8ea9a36..25cb8db 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -123,7 +123,7 @@ const API_CMD={ quote:a=>{const A=a.a,B=a.b,tier=a.tier; if(!S.pops[A])return {blocked:[linkFromWhy(A)]}; if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; - const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; const blocked=[],so=soldOut(A,B,tier,wr.cab); @@ -167,6 +167,22 @@ const API_CMD={ doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'}, siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'], doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'}, +/* ---------- teleports and satellite capacity (#83) ---------- */ + teleBuild:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TPORT_COST,monthly:TPORT_MO,blocked:[teleOf(a.city)?'there is a teleport here already':teleWhy(a.city)].filter(Boolean)}), + doc:'Build a teleport (a satellite gateway) at one of your POPs: it rents circuits on GEO birds to small islands and remote towns in their footprint. Refused where no satellite on sale at your level sees the city.'}, + teleTrk:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:TRK_COST,monthly:TRK_MO,blocked:[teleOf(a.city)===2?'this teleport has tracking antennas already':trkWhy(a.city)].filter(Boolean)}), + doc:'Add tracking antennas to a teleport, so it can work the MEO ring (about 130 ms round trip instead of GEO\'s 600). Only within 50 degrees of the equator, where the ring is in view.'}, + teleRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Close a teleport. Refused while circuits still start there.'}, + buySat:{args:[['a','cityId'],['b','cityId'],['bird','satBird'],['g','satG']], + quote:a=>{const ok=own(SATS,a.bird),mo=ok?satMo(a.bird,+a.g):0;return {setup:mo+(S.pops[a.b]||!CITY[a.b]?0:popCost(a.b)),monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[satWhy(a.a,a.b,a.bird,+a.g)].filter(Boolean)};}, + doc:'Rent a satellite circuit from your teleport in a to b (a small island or a remote town) on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas. The first month up front; builds a POP at b if there is none. Next to an existing link between the two it goes on standby, as backup; a link built later between the two puts it on standby too. Cancel with rmLink.'}, + satSize:{args:[['id','entityId'],['g','satG']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id&&x.kind==='sat'),g=+a.g,ok=!!l&&g!==l.g&&SAT_ORB[SATS[l.bird].orb].g.includes(g),mo=ok?satMo(l.bird,g):0; + return {setup:ok&&g>l.g?mo:0,monthly:mo,blocked:!l?['not a satellite circuit']:ok?[]:[tr('satellites.no_such_circuit')]};}, + doc:'Resize a satellite circuit on the same bird. A bigger one pays its new month up front.'}, /* ---------- dark fiber and own cable ---------- */ orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']], bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;}, @@ -574,6 +590,7 @@ const API_BOUND={ teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'}, trace:{command:'traceRun',arg:'from'}, decomToggle:{command:'decomGo',arg:'cities'}, + satOpen:{command:'buySat',note:'opens the satellite order sheet from a teleport (a) or for a city (b); buySat takes a, b, bird and g itself'}, openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'}, connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'}, cnPrem:{command:'buildLink',arg:'premiumCrossing'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 12d573e..e75ae3c 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -19,8 +19,8 @@ const API_STATE_DOC={ t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, auV:{type:'integer',doc:'Australia content level gate.'}, seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, - pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc) and express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics), each with an entity id.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas).'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'}, transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, rs:{type:'map',doc:'Route-server sessions by exchange city.'}, @@ -130,6 +130,7 @@ const API_RESULTS_DOC={ cityEye:{type:'map',doc:'Eyeballs online per city.'}, latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + satU:{type:'map',doc:'Of each city\'s served traffic, the Gbps that rode a rented satellite circuit (its users notice the orbit\'s latency on that share). Only there while you have a satellite circuit up.'}, demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, served:{type:'number',doc:'Total traffic served, in Gbps.'}, demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, diff --git a/src/agent/40-read.js b/src/agent/40-read.js index e767e2d..5ca278a 100644 --- a/src/agent/40-read.js +++ b/src/agent/40-read.js @@ -26,7 +26,7 @@ function apiJson(v){ carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders each recipe's script, because the source is a function and some read the live network. The recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SATS,SAT_ORB,SAT_PROV,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; const API_MADE={ BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 4f0835e..4fb1915 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -69,9 +69,9 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; const dfCap0=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):l.kind==='xp'?xpG(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):l.kind==='xp'?xpG(l):l.kind==='sat'?l.g:LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); -const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; -const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; +const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc'||l.kind==='sat')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;}; +const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='sat'?fmtCap(l.g)+' '+SAT_ORB[SATS[l.bird].orb].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n; diff --git a/src/game/10-catalog/75-satellites.js b/src/game/10-catalog/75-satellites.js new file mode 100644 index 0000000..b30143a --- /dev/null +++ b/src/game/10-catalog/75-satellites.js @@ -0,0 +1,61 @@ +/* ---------- Satellites (#83): capacity rented on someone else's birds ---------- + A teleport (a satellite gateway at one of your POPs) links to a small island or a remote town over rented capacity: + the early answer to "no cable lands there", and the warm backup for an island hanging on one cable. Geostationary + birds (GEO, 35,786 km up) see a whole ocean from one dish: no build, dear per Gbps, about 600 ms there and back. A + medium-orbit ring over the equator (MEO, 8,062 km up) gets that down to about 130 ms, but a teleport needs tracking + antennas to follow its satellites across the sky. Your own constellation (LEO, Pie in the Sky) comes much later. + The providers are vendors, like the fabrics: they sell you capacity, they are not networks you route to. */ +// h: km up; proc: ms of modems and error correction each way; loss: the share of a city's service its users stop counting +// once their traffic rides it (half for GEO, like any haul past 50 ms; MEO feels almost like fiber); days: to point and +// commission a new circuit; lv: the level it unlocks at; g: the sizes sold (Gbps). A MEO ring covers |lat| <= lat, and a +// circuit's two ends must see the same satellite at once: at most km apart, and at least el degrees above both horizons +// (what a ground terminal needs to clear the trees; far north, two ends 7,000 km apart lose it below the horizon). +const SAT_ORB={ + geo:{n:'GEO',h:35786,proc:25,loss:0.5,days:10,lv:2,g:[1,2,5,10]}, + meo:{n:'MEO',h:8062,proc:7,loss:0.08,days:21,lv:3,g:[2,5,10,20],lat:50,km:7500,el:5}, +}; +// pg: dollars a month for the first Gbps; bigger circuits cost less per Gbps (satMo). +const SAT_PROV={ + its:{n:'Intelsplat',col:'#2F8CFF',pg:2500,blurb:tr('satellites.its_blurb')}, + kac:{n:'Kacophony',col:'#FF8A3D',pg:1400,blurb:tr('satellites.kac_blurb')}, + sesa:{n:'SESame',col:'#16A866',pg:2000,blurb:tr('satellites.sesa_blurb')}, +}; +// The birds. A GEO sits over the equator at lon; r is how far its beams reach, in degrees of arc from the point under it +// (72: a global beam, down to about 5 degrees above the horizon; Kacophony's Ka-band spot beams cover less, for less). +const SATS={ + is18:{n:'Intelsplat 18',p:'its',orb:'geo',lon:180,r:72,sea:N_('satellites.sea_pacific')}, + is20:{n:'Intelsplat 20',p:'its',orb:'geo',lon:68.5,r:72,sea:N_('satellites.sea_indian')}, + is37:{n:'Intelsplat 37e',p:'its',orb:'geo',lon:-18,r:72,sea:N_('satellites.sea_atlantic')}, + kac1:{n:'Kacophony-1',p:'kac',orb:'geo',lon:150,r:50,sea:N_('satellites.sea_west_pacific')}, + gx19:{n:'Intelsplat 19',p:'its',orb:'geo',lon:-97,r:72,sea:N_('satellites.sea_americas')}, + o3b:{n:'O3bservant',p:'sesa',orb:'meo',sea:N_('satellites.sea_tropics')}, +}; +// The teleport itself (dishes, a building, the licences), and the MEO tracking antennas it may add. +const TPORT_COST=90000,TPORT_MO=2500,TRK_COST=250000,TRK_MO=3000; +// Who a satellite serves: a small island off the big continents, or a remote town anywhere, never a big city's market. +const SAT_MAIN=['af','am','eu','oc','sa'],SAT_ISLE_P=150,SAT_TOWN_P=5; +const SAT_RE=6371,SAT_C=300; +// The arc between two points on the globe, in degrees. +function satArc(la1,lo1,la2,lo2){const r=Math.PI/180,c=Math.sin(la1*r)*Math.sin(la2*r)+Math.cos(la1*r)*Math.cos(la2*r)*Math.cos((lo2-lo1)*r);return Math.acos(Math.max(-1,Math.min(1,c)))/r;} +// From a dish to a satellite h km up over a point arc degrees away, in a straight line. +function satSlant(arc,h){const Q=SAT_RE+h,a=arc*Math.PI/180;return Math.sqrt(SAT_RE*SAT_RE+Q*Q-2*SAT_RE*Q*Math.cos(a));} +// How high above a dish's horizon that satellite stands, in degrees (negative: below it, behind the Earth). +function satElev(arc,h){const a=arc*Math.PI/180;return Math.atan2(Math.cos(a)-SAT_RE/(SAT_RE+h),Math.sin(a))*180/Math.PI;} +// The longitude the bird sits over for a circuit: a GEO's slot; a MEO ring's satellite halfway between the two ends. +function satLon(id,a,b){const B=SATS[id];if(B.orb==='geo')return B.lon;const r=Math.PI/180,A=CITY[a],C=CITY[b]; + return Math.atan2(Math.sin(A.lon*r)+Math.sin(C.lon*r),Math.cos(A.lon*r)+Math.cos(C.lon*r))/r;} +// Whether bird id sees city c. +function satSees(id,c){const B=SATS[id],C=CITY[c];if(!B||!C)return false;return B.orb==='meo'?Math.abs(C.lat)<=SAT_ORB.meo.lat:satArc(0,B.lon,C.lat,C.lon)<=B.r;} +function satPairOk(id,a,b){if(a===b||!satSees(id,a)||!satSees(id,b))return false;if(SATS[id].orb!=='meo')return true;const O=SAT_ORB.meo; + if(kmBetween(a,b)>O.km)return false;const lon=satLon(id,a,b);return [a,b].every(c=>satElev(satArc(0,lon,CITY[c].lat,CITY[c].lon),O.h)>=O.el);} +// The radio path: up from one dish and down to the other, the km the signal really travels. It is the link's km, so the +// routers' metric (pairW) sees a satellite as the long way round it is, and a cable wins whenever there is one. +function satKm(id,a,b){const h=SAT_ORB[SATS[id].orb].h,lon=satLon(id,a,b),A=CITY[a],C=CITY[b]; + return Math.round(satSlant(satArc(0,lon,A.lat,A.lon),h)+satSlant(satArc(0,lon,C.lat,C.lon),h));} +// One way: the radio path at the speed of light in vacuum, plus the modems at both ends. +const satLat=l=>l.km/SAT_C+SAT_ORB[SATS[l.bird].orb].proc; +const satMo=(id,g)=>Math.round(SAT_PROV[SATS[id].p].pg*Math.pow(g,0.85)/10)*10; +const satRemote=c=>{const C=CITY[c];return !!C&&(C.P<=SAT_TOWN_P||C.P<=SAT_ISLE_P&&!SAT_MAIN.includes(C.land));}; +const satName=l=>SATS[l.bird]?SATS[l.bird].n:'?'; +// A subsea cable: a satellite circuit is stored as sub (never a land route) but is no cable on the seabed. +const seaLink=l=>!!l.sub&&l.kind!=='sat'; diff --git a/src/game/60-features/10-banks.js b/src/game/60-features/10-banks.js index 7795eb3..774e7a3 100644 --- a/src/game/60-features/10-banks.js +++ b/src/game/60-features/10-banks.js @@ -34,7 +34,7 @@ const COVS={ logo:{l:tr('banks.our_logo_goes_on_every_router'),ok:()=>true}, cash50:{l:tr('banks.never_let_cash_drop_below_50k'),ok:()=>S.cash>=50000}, nochina:{l:tr('banks.stay_out_of_mainland_china'),ok:()=>!Object.keys(S.pops).some(cnCity)}, - nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)}, + nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(seaLink).length<=(l.base&&l.base.sub||0)}, spaetzle:{l:tr('banks.peer_at_the_spatzle_ix_in'),ok:()=>S.ixp.stg!==undefined}, kehrwoche:{l:tr('banks.do_the_kehrwoche_keep_your_noc'),ok:()=>!S.inc.some(i=>S.day-i.start>7)}, app:{l:tr('banks.download_our_app_and_enable_all'),ok:()=>true}, @@ -102,7 +102,7 @@ function callOffer(amount){const T=CALL_TERMS[rating()];if(!T||!CALL_AMTS.includ const RESCUE_APR=0.02,RESCUE_TERM=60; function rescueLoan(){const amount=niceAmt(Math.max(250000,-S.cash+Math.max(150000,(R.costMo||0)*2))); S.cash+=amount;S.stats.rescues=(S.stats.rescues||0)+1;S.neg=0; - S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(x=>x.sub).length}}); + S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(seaLink).length}}); track('rescue');toast(`${tr('banks.bank_stepped_in',{bank:esc(BANKS.gov.name)})}
${tr('banks.a_rescue_loan_of_amount_keeps',{amount:fmt$(amount),pay:fmt$(Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)))})}`,'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]);sfx('coin');} function loanTick(d){ // conditions: 15-day grace, then a penalty every 30 days while broken diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 17cebc0..f7e52ed 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,12 +2,12 @@ gives the same world. Free play keeps using the browser's Math.random. */ const _rand=Math.random; Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();}; -const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; +const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='sat'?l.g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; -const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size; +const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>seaLink(l)&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size; // Ports count only on POPs your backbone joins to São Paulo: islands of POPs with a port each skipped the Amazon (playtest). const FTTB_G=500; // Gangnam Style Peering: traffic, how well Seoul is served (delivered and fast) and a monthly profit. diff --git a/src/game/60-features/45-teleports.js b/src/game/60-features/45-teleports.js new file mode 100644 index 0000000..ff2b9a6 --- /dev/null +++ b/src/game/60-features/45-teleports.js @@ -0,0 +1,73 @@ +/* ---------- Teleports and rented satellite capacity (#83) ---------- + The rules, the money and save repair. Catalog and physics: 10-catalog/75-satellites.js; actions: 90-actions/87-teleports.js; + panels: 93-ui/72-teleport-panels.js. A circuit is a link (kind 'sat'): routing, standby, metrics and the map treat it like + any other, with the radio path as its km and its orbit's latency. */ +// A POP's teleport (S.pops[c].tele): 0 none, 1 dishes for GEO birds, 2 with tracking antennas for the MEO ring too. +const teleOf=c=>{const p=S&&S.pops[c];return p&&(p.tele===1||p.tele===2)?p.tele:0;}; +const teleCities=()=>Object.keys(S.pops).filter(teleOf); +// The birds that see city c, whatever your level. +const teleSees=c=>Object.keys(SATS).filter(id=>satSees(id,c)); +// Why no teleport can go up at city c (nothing on sale sees it at your level, or no POP); '' when it can. +function teleWhy(c){if(!isCity(c)||!S.pops[c])return tr('satellites.no_pop_in_city',{city:isCity(c)?CITY[c].name:'?'}); + if(lvl()lvl()>=SAT_ORB[SATS[id].orb].lv)){const O=SAT_ORB[SATS[ids[0]].orb];return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});} + return '';} +// Why the teleport at c cannot add MEO tracking antennas; '' when it can. +function trkWhy(c){const O=SAT_ORB.meo;if(lvl()SATS[id].orb==='meo'))return tr('satellites.meo_ring_misses_city',{city:CITY[c].name,lat:O.lat}); + return '';} +// The birds that see both ends of a circuit: GEO first, then the cheapest. +function satBirds(a,b){return Object.keys(SATS).filter(id=>satPairOk(id,a,b)).sort((x,y)=>(SATS[x].orb>SATS[y].orb)-(SATS[x].orbC.id!==a&&satRemote(C.id)&&(S.pops[C.id]||cityOn(C.id))&&satBirds(a,C.id).length).map(C=>C.id) + .sort((x,y)=>(!S.pops[x])-(!S.pops[y])||kmBetween(a,x)-kmBetween(a,y));} +// Your teleports that can reach city b. +const satFrom=b=>satRemote(b)?teleCities().filter(a=>a!==b&&satBirds(a,b).length):[]; +// A new link between a and b (a wave, fiber, a fabric circuit, a cable): the circuits already there go on standby beside +// it, as one ordered next to a link does, and the player hears about it. Without this the pair's load is shared with orbit. +function satBeside(a,b){const ls=pairLinks(a,b).filter(l=>l.kind==='sat'&&!l.standby);for(const l of ls)l.standby=true; + if(ls.length)toast(trn('satellites.n_circuits_go_on_standby',ls.length,{a:CITY[a].name,b:CITY[b].name}));return ls.length;} +// What the teleports and their circuits cost a month (R.cost.sat). +function satMoAll(){let m=0;for(const c in S.pops){const t=teleOf(c);if(t)m+=TPORT_MO+(t>1?TRK_MO:0);}for(const l of S.links)if(l.kind==='sat')m+=l.mo||0;return m;} +/* compute(): what users notice on the edges a satellite circuit is on. sv: the losses of the orbits there; sx: the edge's + latency is the satellite's (no cable carries ahead of it), so it is no haul to transit on the ground. Returns how many + edges there were, for compute() to know a satellite is in the picture at all. */ +function satEdges(SE){for(const e of SE){let ta=false,ts=false,act=false;const v=e.sv; + for(const l of e.links){const sb=!!l.standby;if(!sb)act=true;if(l.kind==='sat'){const x=SAT_ORB[SATS[l.bird].orb].loss;if(!v.includes(x))v.push(x);}else if(sb)ts=true;else ta=true;} + e.sx=act?!ta:!ts;} + return SE.length;} +// A flow of ok Gbps from city index ci crossed these edges: keep it, and what each orbit would cost it beyond the tl its +// haul to transit already does (users count the worse of the two, not both). +function satNote(se,ci,ok,tl){for(let k=0;ktl)a[1+j]+=ok*(v[j]-tl);}} +/* After routing: each orbit's share of the edge's traffic, split as compute() splits it (active links by capacity, standby + ones the overflow). A satellite on standby beside a cable that has room carries nothing and costs nobody anything; one + that takes the overflow, or shares the load, costs the users of that share. LATP gets the lost service and SATU the + Gbps that rode a satellite, by city index. */ +function satAfter(SE,LATP,SATU){for(const e of SE){const ld=e.ld||0;if(!e.sa||ld<=1e-9)continue; + const v=e.sv,sh=new Float64Array(v.length),ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;let only=true,all=0; + for(const l of e.links){if(l.kind!=='sat'){only=false;continue;}const c=capOf(l);sh[v.indexOf(SAT_ORB[SATS[l.bird].orb].loss)]+=(l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0))/ld;} + if(only&&v.length===1)sh[0]=1;for(let j=0;jr&&r.satU&&r.citySrv&&r.citySrv[c]>0?Math.min(1,(r.satU[c]||0)/r.citySrv[c]):0; +// Saves: a teleport is 1 or 2; a circuit needs a known bird that sees both POPs, a teleport able to work it, a size it sells. +function satSanitize(s){ + for(const c of Object.keys(s.pops)){const p=s.pops[c];if(p.tele!==undefined&&p.tele!==1&&p.tele!==2)delete p.tele;} + s.links=s.links.filter(l=>{if(l.kind!=='sat')return true;const B=typeof l.bird==='string'&&own(SATS,l.bird)?SATS[l.bird]:null,p=s.pops[l.a]; + if(!B||!p||!p.tele||B.orb==='meo'&&p.tele<2||!s.pops[l.b]||!satPairOk(l.bird,l.a,l.b))return false; + const G=SAT_ORB[B.orb].g;if(!G.includes(l.g))l.g=G.reduce((x,v)=>v<=num(l.g,0)?v:x,G[0]); + l.km=satKm(l.bird,l.a,l.b);l.sub=true;l.ready=num(l.ready,0);l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of ['tier','cable','trench','mult','border','premium','vt','prov','own','sys','ch'])delete l[k];return true;});} diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index 3a4e1da..a190234 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -32,7 +32,7 @@ function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';cons for(const x of pieBhHops(e,h.from===b.city)){const ms=x.ms*2+0.05;if(x.k==='up')hop(`dish.${x.city}.${me}`,ip(hstr(x.city),5),ms,tr('traceroute.sky_up',{city:CITY[x.city].name,crust:tr(cr.n)})); else if(x.k==='las')hop(`laser.${b.cr}.${me}`,`10.255.${hstr(b.cr)%250}.${(x.km|0)%250}`,ms,tr('traceroute.sky_laser',{km:Math.round(x.km).toLocaleString()})); else hop(`dish.${x.city}.${me}`,ip(hstr(x.city),6),ms,tr('traceroute.sky_down',{city:CITY[x.city].name}));}continue;} - const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}}; + const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:satName(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}}; if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('traceroute.no_working_path_between_these_pops'));return {text:lines.join('\n'),why:tr('traceroute.no_path_every_route_between_these')};}walk(path);const bw=trBhWhy(bh,path);return {text:lines.join('\n'),why:bw+(S.te&&S.te.on?trn('traceroute.internal_path_over_n_link_chosen',path.length):trn('traceroute.internal_path_over_n_link_chosen_8620',path.length))};} const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined); lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`); diff --git a/src/game/60-features/85-pitcairn.js b/src/game/60-features/85-pitcairn.js index c220a47..ea026a9 100644 --- a/src/game/60-features/85-pitcairn.js +++ b/src/game/60-features/85-pitcairn.js @@ -1,12 +1,13 @@ /* Pitcairn (#124): no cable lands there yet, but you may land your own, and the UK pays a monthly grant while the - islanders are online through you: a POP with broadband, up and nearly fully served. */ -const GRANT_MO=300000; -const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9); + islanders are online through you: a POP with broadband, up and nearly fully served. The money is for a cable: with more + than GRANT_SAT of their traffic on a rented satellite circuit (#83) it never comes, however well MEO serves them. */ +const GRANT_MO=300000,GRANT_SAT=0.1; +const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9&&satShare(r,'pcn')<=GRANT_SAT); /* Satellite tier: Pitcairn online through your pies (its POP on backhaul, or home terminals there) is good enough for the UK at a lower bar, orbit's latency forgiven (sfOf() counts it, so the fiber grant never comes), for less money. */ const GRANT_SKY_MO=120000,GRANT_SKY_Q=0.9; function grantSky(r){if(!S||!S.pie||!r||!r.pie||grantOn(r))return false;const p=S.pops.pcn; if(p&&p.bb&&!(p.down>S.day)&&r.pie.bh.some(b=>b.city==='pcn'&&b.g>0)){const d=r.cityDem.pcn||0;if(d>1e-6&&(r.citySrv.pcn||0)/d>=GRANT_SKY_Q)return true;} return S.biz.some(b=>b.city==='pcn'&&b.type==='pizza'&&(r.pie.sf[b.id]||0)>=GRANT_SKY_Q);} -function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R); - return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} +function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R),sat=!on&&!sky&&satShare(R,'pcn')>GRANT_SAT; + return `${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):sat?tr('pitcairn.uk_grant_needs_a_cable',{mo:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}`;} diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 3277d96..9f944c6 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -260,7 +260,7 @@ const OPS_RUN={ for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){ if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). - decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go. if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;} for(const ls of by.values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}, diff --git a/src/game/60-features/96-pop-standard.js b/src/game/60-features/96-pop-standard.js index 425caa5..752d2d0 100644 --- a/src/game/60-features/96-pop-standard.js +++ b/src/game/60-features/96-pop-standard.js @@ -116,7 +116,7 @@ function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J // the sizes these upgrades give: never pay a month's rent on one it is about to return. if(D.wv!=='keep'){for(const {l} of ls)if(l.kind==='wave'&&l.tierl.tier;t--){if(subWaveWhy(t,l.km,l.sub)||soldOut(l.a,l.b,t,l.cable)||!waveOk(l.a,l.b,t))continue;wv.set(l,t);break;} if(wv.size&&opsHired()&&S.ops.on.decom){const by=new Map(),cf=x=>wv.has(x)?capOf(x)*LT[wv.get(x)].g/LT[x.tier].g:capOf(x); - for(const x of S.links)if(x.kind!=='vxc'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} + for(const x of S.links)if(x.kind!=='vxc'&&x.kind!=='sat'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);} for(const k of new Set([...wv.keys()].map(edgeKey)))for(const x of opsDecomPick(by.get(k),cf))wv.delete(x);}} for(const {l} of ls){const ch='l:'+l.id; if(l.kind==='wave'){const t=wv.get(l);if(t){const nm=Math.round(waveMo(l.km,l.sub,t)*(l.mult||1));job('fiber','wv',ch,l.a+'|'+l.b,nm,nm-(l.mo||0),()=>{ACT.upLink({id:l.id,tier:t});return l.tier===t;},{l});}continue;} diff --git a/src/game/60-features/99-pie-subsidies.js b/src/game/60-features/99-pie-subsidies.js index 6cd366d..703a46b 100644 --- a/src/game/60-features/99-pie-subsidies.js +++ b/src/game/60-features/99-pie-subsidies.js @@ -61,7 +61,7 @@ function pieEximOffer(d){const P=S.pie,G=P.gov;if(!P.fac||pieEximLoan()||!pieCan // Taking it: a loan like any other, plus its space covenants. function pieEximTake(){const P=S.pie,o=P.gov.ex;if(!o||pieEximLoan())return false;const pay=Math.round(annuity(o.amt,o.apr,o.term)); S.cash+=o.amt;S.stats.loans=(S.stats.loans||0)+1; - S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(x=>x.sub).length}, + S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(seaLink).length}, pie:{cc:o.cc,n:o.n,by:S.day+PIE_EXIM_BY,flown:0,br:0}}); P.gov.ex=null;track('loan_taken');return true;} // A breach (loanTick(), after the bank's own penalty): tighter terms, the launch target rescheduled, and a spat. diff --git a/src/game/80-simulation/10-dijkstra.js b/src/game/80-simulation/10-dijkstra.js index 5b53685..09df642 100644 --- a/src/game/80-simulation/10-dijkstra.js +++ b/src/game/80-simulation/10-dijkstra.js @@ -16,4 +16,4 @@ function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n) // 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};} // The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape. -function walkP(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,dead:0,ms:-1,fg:0};} +function walkP(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,dead:0,ms:-1,fg:0,mt:0,se:null};} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 1a4cf12..8ad4924 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -29,12 +29,14 @@ function compute(){RW.gen++; const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length; // The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order. const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); - const edges={},EA=[],TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; + const edges={},EA=[],TRX=teRules(),live=[];let NE=0,SE=null;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,RCON=RC.on,GK=RCON?rcGraphKey(pops,remote,EA):null, @@ -245,8 +247,11 @@ function compute(){RW.gen++; // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, // Korean users notice any exit far away, transit or not, and much sooner. - if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms<0){ms=0;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; + // Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose + // on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt). + if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){if(P.ms<0){let ms=0,mt=0,se=null;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0; + if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; // Where each flow left (the PNI list asks what a PNI here would take over, #175). if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} @@ -339,8 +344,10 @@ function compute(){RW.gen++; if(DD){let rem=0,jf=0;for(let i=0;i1e-6)rem+=FREM[i];if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf), lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});} + // R.satU only when a circuit is in the graph, so R stays as it was for networks without one. + const SATU=SATN?new Float64Array(NC):null;if(SATU){R2.satU={};satAfter(SE,LATP,SATU);} for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i]; - if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);} + if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);if(SATU&&SATU[i]>1e-9)R2.satU[c]=SATU[i];} // Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did. {const G=new Map();for(let k=0;kcur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}} @@ -362,7 +369,7 @@ function computeMoney(R2,PX=null){ const C=R2.cost,V=R2.rev,pm=S.priceMul; C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+cageMo(p.routers)+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0); - C.links=S.links.reduce((a,l)=>a+(l.mo||0),0); + C.links=S.links.reduce((a,l)=>a+(l.kind==='sat'?0:l.mo||0),0);{const m=satMoAll();if(m)C.sat=m;} C.nni=(S.nni||[]).reduce((a,x)=>a+nniMo(x),0); const htd=histToday();C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0,htd);R2.p95[t.id]=q;return a+transitMo(t,q);},0); C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index 87d5139..1a7e557 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -4,7 +4,7 @@ const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;} function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} // Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides). function linkCut(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))));} -function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l));} +function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l))||(l.kind==='sat'&&l.ready>S.day);} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} // Monthly price of one connection; compute() sums these, the connections overview lists them. diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index ed6494c..3c25690 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,7 +21,7 @@ function sanitize(s){ if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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!=='xp'&&l.kind!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); xpSanitize(s); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its @@ -114,6 +114,7 @@ function sanitize(s){ specSanitize(s);mpSanitize(s); pieSanitize(s);pieIncFix(s); ip4Fix(s); + satSanitize(s); if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} function migrate(s){sanitize(s); diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index f48a5fd..f633eae 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -30,7 +30,7 @@ const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg&&CITY[a].cc! function landMult(a,b){if(isSub(a,b))return 1;if(uaePair(a,b))return 3;return (landX(a,b)?LAND_X:1)*(andesPair(a,b)?2:1)*(nullPair(a,b)?NULLARBOR:1)*(rainPair(a,b)?2:1)*(borderPair(a,b)?2:1);} function landWhy(a,b){if(isSub(a,b))return '';if(uaePair(a,b))return tr('geography_and_latency.inside_the_uae_only_the_two'); const r=[];if(landX(a,b))r.push(tr('geography_and_latency.overland_between_continents_crosses',{x:LAND_X}));if(andesPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_andes_2'));if(nullPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_the_nullarbor_x',{x:NULLARBOR}));if(borderPair(a,b))r.push(tr('geography_and_latency.this_route_crosses_a_border_in'));if(rainPair(a,b))r.push(tr('geography_and_latency.this_route_goes_into_the_amazon'));return r.join(' ');} -function linkLat(l){if(l.kind==='xp')return xpLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} +function linkLat(l){if(l.kind==='xp')return xpLat(l);if(l.kind==='sat')return satLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;} /* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York). diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index b4e3650..607cc6a 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -4,7 +4,7 @@ const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair( const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); function fireFailure(only){ const opts=[]; - const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; + const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; // A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it. const bare=S.links.filter(xpBare),dug=live.concat(bare); if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);} diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 668478e..28d6afc 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -22,7 +22,7 @@ function mkTick(d){const M=S.monkey;if(!M)return; if(!mkElig()){if(M.on)mkLeave('quiet');return;} // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; - if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;} if(d>=M.until){mkLeave();return;} if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); @@ -30,7 +30,7 @@ function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint( Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} -function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&(!linkDown(l)||xpBare(l)));if(!live.length)return; +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l)));if(!live.length)return; // Weak spots first: a sample keeps this cheap on big networks. const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 7c2a989..ba7417b 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -81,7 +81,7 @@ function dayPost(d){ mkTick(d); if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). - if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} if(dirty)compute(); // the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 80ec9fc..3bd9588 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -13,7 +13,7 @@ const ACT={ takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;S.stats.loans=(S.stats.loans||0)+1;const B=BANKS[o.bank];let got=o.amount,note=''; if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=' '+(f>=1?tr('interface.tubecoin_moved_up_p_on_the',{p:Math.round(Math.abs(f-1)*100)}):tr('interface.tubecoin_moved_down_p_on_the',{p:Math.round(Math.abs(f-1)*100)}));} S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o); - S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}}); + S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(seaLink).length}}); track('loan_taken');toast(`${tr('interface.amt_from_bank_has_landed',{amt:fmt$(got),bank:esc(B.name)})}
${B.equity?tr('interface.they_now_own_p_of_your',{p:pct(o.share)}):loanSummary(o)}${note}`,'good');sfx('coin');after();renderBank();}, callBank:({amount})=>{if(!callOffer(amount))return;track('loan_called');sfx('click');renderBank();renderHUD();save();}, declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();renderHUD();save();}, diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index cf98a50..b99dcdf 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -14,13 +14,13 @@ Object.assign(ACT,{ myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name; S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();}, - buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); + buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return; if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;} const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;} {const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b)); if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} - const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);closeModal(); + const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal(); if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';} floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();}, // A new fabric port, or every member of one upgraded to a faster speed (#140): as fast as the router takes. @@ -36,7 +36,7 @@ Object.assign(ACT,{ openVxc:(a)=>openVxcModal(a), buyVxc:({a,b,prov,t})=>{t=+t;if(!CITY[a]||!CITY[b]||noTalk(a,b))return;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>nniCap(pa)+1e-9){toast(tr('links.not_enough_room_on_your_fabric'),'bad');sfx('err');return;} if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>nniCap(pb)+1e-9){toast(tr('links.not_enough_room_on_your_fab',{fab:esc(FAB[prov].name),city:CITY[b].name}),'bad');sfx('err');return;}} - const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal(); + const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});satBeside(a,b);closeModal(); toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();}, 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>nniCap(pt)+1e-9){toast(tr('links.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);prunePairMet();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();}, diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js index 089794d..5d1e315 100644 --- a/src/game/90-actions/86-specialist.js +++ b/src/game/90-actions/86-specialist.js @@ -3,7 +3,7 @@ Object.assign(ACT,{ toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();}, seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return; for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);} - const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)}); + const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)});satBeside(o.a,o.b); S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id}; toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, seatNo:()=>{S.seatOff=null;after();}, diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index 75b81db..d43e135 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -10,7 +10,7 @@ Object.assign(ACT,{ orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return; if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days; - S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1}); + S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});satBeside(a,b); const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false; S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id}; toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();}, @@ -20,7 +20,7 @@ Object.assign(ACT,{ if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);} const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'),id=uid(); const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false}; - S.links.push(l);closeModal();UI.sel={type:'link',id}; + S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id}; toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();}, regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; if(d<0&&((l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))||xpRegenBad(l,n))){toast(tr('fiber_and_hardware.those_optics_need_the_regen_site'),'bad');sfx('err');return;} diff --git a/src/game/90-actions/87-teleports.js b/src/game/90-actions/87-teleports.js new file mode 100644 index 0000000..542bde1 --- /dev/null +++ b/src/game/90-actions/87-teleports.js @@ -0,0 +1,27 @@ +// Teleports and satellite capacity (#83): build the gateway, rent circuits on its birds, resize them. Cancel is rmLink. +Object.assign(ACT,{ + teleBuild:({city})=>{const p=S.pops[city];if(!p||teleOf(city))return; + const why=teleWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TPORT_COST))return;p.tele=1;toast(tr('satellites.teleport_up_in_city',{city:CITY[city].name}),'good');after();}, + teleTrk:({city})=>{const p=S.pops[city];if(!p||teleOf(city)!==1)return; + const why=trkWhy(city);if(why){toast(why,'bad');sfx('err');return;} + if(!spend(TRK_COST))return;p.tele=2;toast(tr('satellites.tracking_antennas_up',{city:CITY[city].name}),'good');after();}, + // Closing a teleport asks twice, and never while circuits still start there. + teleRm:({city})=>{const p=S.pops[city];if(!p||!teleOf(city))return;const n=S.links.filter(l=>l.kind==='sat'&&l.a===city).length; + if(n){toast(trn('satellites.cancel_n_circuits_first',n),'bad');sfx('err');return;} + if(UI.confirm!=='tele:'+city){UI.confirm='tele:'+city;renderPanel();return;} + delete p.tele;UI.confirm=null;toast(tr('satellites.teleport_closed',{city:CITY[city].name}));after();}, + satOpen:({a,b})=>satModal(a,b), + // Rent a circuit from teleport a to b: the first month up front, like a wave; a POP at b comes with it if there is none. + // Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down. + buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;} + if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return; + if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);} + const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid(); + S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})}); + closeModal();UI.sel={type:'link',id}; + toast(trn('satellites.circuit_ordered',n,{cap:fmtCap(g),bird:esc(SATS[bird].n),a:CITY[a].name,b:CITY[b].name})+(sb?' '+tr('satellites.on_standby_beside_your_link'):''),'good');after();}, + // Bigger or smaller on the same bird: a bigger one pays its new month up front, as a wave upgrade does. + satSize:({id,g})=>{g=+g;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='sat'||g===l.g||!SAT_ORB[SATS[l.bird].orb].g.includes(g))return; + const mo=satMo(l.bird,g);if(g>l.g&&!spend(mo))return;l.g=g;l.mo=mo;sfx('click');after();}, +}); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index e104b38..fd7fbd6 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -3,14 +3,14 @@ function cityPanel(c){ // Your POP's router model, as a picture left of the name (10-catalog/25-router-art.js). const art=p?rgArt(p.rgen||0):''; let h=`
${art?`${art}`:''}
${REG[C.reg]} · ${esc(siteName(c,'a'))}

${C.name}

-
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${C.kr&&scnRule('sender')?`${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
+
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${satFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${C.kr&&scnRule('sender')?`${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
`; if(!p){ h+=`
${C.note?`

${esc(C.note)}

`:''} ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('city_panel.open_a_pop_here')}

${tr('city_panel.a_pop_point_of_presence_is')}

${C.ru?`

${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash${q.site2||q.gen?tr('pop_std.includes_the_build_standard',{list:esc(bstdPopParts({g:q.g,rt:q.rt,site2:q.site2,gen:q.gen}).join(', ')),cost:fmt$(q.cost),mo:fmt$(q.mo)}):tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}

`:''))(popStdQuote())}

${tr('city_panel.or_drag_from_one_of_your')}

${opsTplHtml(c)}`}`; - h+=offersHere(c); + h+=offersHere(c)+satNoPop(c); const trs=NETS.filter(n=>sellsAt(n,c)); const fh=FABS.filter(f=>f.cities.includes(c)); if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replace('

'+tr('common.internet_exchange')+'

','

'+tr('city_panel.remote_peering_at_the_ix')+'

'); @@ -103,10 +103,11 @@ function cityPanel(c){ else h+=`
${NNI.map((N,i)=>portShown(i)?btn(tr('city_panel.port_port_price_mo_197d',{port:N.n,price:fmt$(N.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash`; h+=`
`;} h+=``;} + h+=teleHtml(c); h+=`

${tr('city_panel.fiber_from_city',{city:C.name})}

${tr('city_panel.drag_from_this_router_to_any')}

`; if(!ls.length)h+=`

${tr('common.no_links_yet')}

`; for(const l of ls){const o=l.a===c?l.b:l.a,u=capOf(l)?(R.load[l.id]||0)/capOf(l):0,cut=linkDown(l); - h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?''+tr('common.cut')+'':''}
${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:esc(satName(l))})+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} h+=`
`; if(Object.keys(S.pops).length>1)h+=`

${tr('common.decommission')}

${tr('city_panel.shut_this_pop_down_its_links')}

${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}
`; } diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 200de31..48cb752 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -146,6 +146,7 @@ function offersHere(c){ function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} if(l.kind==='vxc')return vxcPanel(l); + if(l.kind==='sat')return satPanel(l); if(l.kind==='df')return dfPanel(l); if(l.kind==='xp')return xpPanel(l); const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk); diff --git a/src/game/93-ui/72-teleport-panels.js b/src/game/93-ui/72-teleport-panels.js new file mode 100644 index 0000000..1a7f3c8 --- /dev/null +++ b/src/game/93-ui/72-teleport-panels.js @@ -0,0 +1,60 @@ +// Teleports and satellite circuits on screen (#83): a POP's section, the order sheet, a circuit's panel. +const satLogo=P=>``; +// Round trip over bird id between a and b, in whole ms. +const satRtt=(id,a,b)=>Math.round(2*satLat({bird:id,km:satKm(id,a,b)})); +const satModalHead=(eye,title)=>`
🛰️ ${eye}

${title}

`; +// In a city's facts: its own users' traffic rides a satellite today (R.satU), and they count part of the service as bad (sfOf, R.latF). +const satFact=c=>R&&R.latF&&R.latF[c]<1&&R.satU&&R.satU[c]>1e-3?`🛰️ ${tr('satellites.users_ride_a_satellite')}`:''; +// The birds a dish at c sees, in words. +const satInView=c=>{const ids=teleSees(c);return ids.length?tr('satellites.in_view_list',{list:ids.map(id=>`${esc(SATS[id].n)} (${tr(SATS[id].sea)})`).join(', ')}):tr('satellites.no_bird_sees_this_city');}; +// In a POP's Infra tab: its teleport (build it, what it sees, its circuits), and the teleports that can reach it. +function teleHtml(c){if(pzOn())return '';const t=teleOf(c),from=satFrom(c),open=lvl()>=SAT_ORB.geo.lv;if(!t&&!open&&!from.length)return ''; + let h=`

🛰️ ${tr('satellites.satellites')}

`; + if(t){const out=S.links.filter(l=>l.kind==='sat'&&l.a===c),cf=UI.confirm==='tele:'+c,meo=teleSees(c).some(id=>SATS[id].orb==='meo'); + h+=`
${tr('satellites.teleport')}${t>1?tr('satellites.geo_dishes_and_meo_tracking'):tr('satellites.geo_dishes')} · ${tr('common.price_mo',{price:fmt$(TPORT_MO+(t>1?TRK_MO:0))})}
+
${satInView(c)}
`; + for(const l of out){const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0; + h+=`
→ ${CITY[l.b].name}${l.standby?' '+tr('common.standby')+'':''}
${capName(l)} · ${esc(satName(l))}${l.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:l.ready-S.day}):''} · ${tr('common.price_mo',{price:fmt$(l.mo)})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + h+=`
${btn(tr('satellites.rent_satellite_capacity'),'satOpen',{a:c},'pink sm')}${t===1&&lvl()>=SAT_ORB.meo.lv&&meo?btn(tr('satellites.add_tracking_antennas_cost_mo',{cost:fmt$(TRK_COST),mo:fmt$(TRK_MO)}),'teleTrk',{city:c},'sm',S.cash + ${t===1&&lvl()${tr('satellites.meo_comes_at_level',{lv:SAT_ORB.meo.lv})}

`:''}`;} + // Before the build: what its dishes would see and reach at your level, and no button to a teleport that reaches nothing. + else if(open){const why=teleWhy(c),n=why?0:satTargets(c).filter(x=>satBirds(c,x).some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)).length; + h+=`

${tr('satellites.a_teleport_is_a_satellite_gateway')}

${satInView(c)}${why?'':' '+trn('satellites.n_places_in_reach',n)}
${why&&teleSees(c).length?`
${esc(why)}
`:''} +
${btn(tr('satellites.build_a_teleport_cost_mo',{cost:fmt$(TPORT_COST),mo:fmt$(TPORT_MO)}),'teleBuild',{city:c},'sm',S.cash`;} + if(from.length)h+=satReach(c,from); + return h+`
`;} +// Teleports that reach city c: a button each, to the order sheet. +const satReach=(c,from)=>`

${tr('satellites.reachable_from_your_teleports',{city:CITY[c].name})}

${from.slice(0,4).map(a=>btn(tr('fiber_modals.from_city',{city:CITY[a].name}),'satOpen',{a,b:c},'ghost sm')).join('')}
`; +// A city without a POP of yours, that a teleport of yours reaches: a POP and a circuit in one go. +function satNoPop(c){if(pzOn()||S.pops[c])return '';const from=satFrom(c);if(!from.length)return ''; + return `

🛰️ ${tr('satellites.by_satellite')}

${tr('satellites.no_cable_needed_a_pop_here',{city:CITY[c].name})}

${satReach(c,from)}
`;} +// The order sheet: from teleport a to b. With one end missing it lists the choices first. +function satModal(a,b){a=isCity(a)?a:null;b=isCity(b)?b:null; + if(!a&&b){const fr=satFrom(b);if(fr.length===1)a=fr[0]; + else{openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.to_city',{city:CITY[b].name}))+(fr.length?fr.map(x=>`
${CITY[x].name}
${tr('satellites.teleport')} · ${trn('satellites.n_birds_see_both',satBirds(x,b).length)}
${btn(tr('satellites.choose'),'satOpen',{a:x,b},'sm')}
`).join(''):`

${tr('satellites.no_teleport_reaches_city',{city:CITY[b].name})}

`));return;}} + if(!a||!teleOf(a))return; + if(!b){const ts=satTargets(a),mine=ts.filter(x=>S.pops[x]),more=ts.filter(x=>!S.pops[x]).slice(0,12); + const row=x=>`
${CITY[x].name}
${S.pops[x]?tr('common.your_pop'):tr('satellites.new_pop_cost',{cost:fmt$(newPopCost(x))})} · ${kmBetween(a,x).toLocaleString()} km · ${trn('satellites.n_birds_see_both',satBirds(a,x).length)}
${btn(tr('satellites.choose'),'satOpen',{a,b:x},'sm')}
`; + openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.from_city',{city:CITY[a].name}))+`

${tr('satellites.who_a_satellite_serves')}

` + +(mine.length?`

${tr('satellites.your_pops_in_view')}

`+mine.map(row).join(''):'')+(more.length?`

${tr('satellites.more_islands_and_towns')}

`+more.map(row).join(''):'')+(ts.length?'':`

${tr('satellites.nothing_in_view_from_here')}

`));return;} + const pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).some(l=>l.kind!=='sat'),birds=satBirds(a,b); + const rows=birds.map(id=>{const B=SATS[id],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],why=satWhy(a,b,id); + return `
${satLogo(P)}
${esc(B.n)} ${O.n}
${esc(P.n)} · ${tr(B.sea)} · ${tr('satellites.ms_round_trip',{ms:satRtt(id,a,b)})} · ${trn('satellites.up_in_n_days',leadDays(O.days))}
${esc(P.blurb)}
${why?`
${esc(why)}
`:''} +
${O.g.map(g=>btn(`${fmtCap(g)} ${tr('common.price_mo',{price:fmt$(satMo(id,g))})}`,'buySat',{a,b,bird:id,g},'sm',!!why||S.cash
`;}).join(''); + openModal(satModalHead(tr('satellites.satellite_capacity'),`${CITY[a].name} → ${CITY[b].name}`)+`

${tr('satellites.users_notice_geo_meo')}

` + +(pop?`

${tr('satellites.no_pop_there_yet',{city:CITY[b].name,cost:fmt$(pop)})}

`:'')+(sib?`

${tr('satellites.it_waits_on_standby')}

`:'') + +(rows||`

${tr('satellites.no_bird_sees_both',{a:CITY[a].name,b:CITY[b].name})}

`));} +// A circuit's panel: what it carries, its latency and rent, a size up or down, standby and the metric, cancel. +function satPanel(l){const B=SATS[l.bird],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,ms=satLat(l); + let h=`
🛰️ ${esc(B.n)} · ${O.n} · ${esc(P.n)}

${CITY[l.a].name} ⇄ ${CITY[l.b].name}

`; + if(l.ready>S.day){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); + h+=`

${tr('satellites.being_commissioned')}

${tr('satellites.pointing_dishes_and_testing')}${tr('common.n_days_left',{n:l.ready-S.day})}
`;} + h+=`

${tr('common.capacity')}

${capName(l)}${l.standby?' · '+tr('common.standby'):''}${fmtG(load)} / ${fmtG(cap)}
+
${tr('common.latency')}${tr('satellites.ms_one_way_rtt',{ms:Math.round(ms),rtt:Math.round(2*ms)})}
+
${tr('satellites.radio_path')}${l.km.toLocaleString()} km
+
${tr('satellites.rent')}${tr('common.price_mo',{price:fmt$(l.mo)})}
+

${B.orb==='geo'?tr('satellites.geo_users_notice',{p:pct(O.loss)}):tr('satellites.meo_users_notice',{p:pct(O.loss)})} ${esc(P.blurb)}

+
${O.g.filter(g=>g!==l.g).map(g=>btn(`${g>l.g?tr('satellites.grow_to',{cap:fmtCap(g)}):tr('satellites.shrink_to',{cap:fmtCap(g)})} ${tr('common.price_mo',{price:fmt$(satMo(l.bird,g))})}`,'satSize',{id:l.id,g},'sm',g>l.g&&S.cash
+ ${trafficSection(l)}${metricSection(l)} +
${btn(UI.confirm===l.id?tr('common.really_cancel'):tr('common.cancel_circuit'),'rmLink',{id:l.id},'ghost sm')}
`; + return h;} diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index c5e56ab..c16c81f 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -10,7 +10,7 @@ function litOn(L,cap){const free=chMax(L)-(L.ch||[]).length-soldSlots(L)-xpSlots for(const o in OPT){const O=OPT[o];if(O.lvl>glassLvl()||(O.sys==='roadm'&&!isRdm(L.sys))||[L.a,L.b].some(c=>S.pops[c]&&RG[S.pops[c].rgen||0].cls{const [a,b]=k.split('|'),sub=isSub(a,b),mo=ls.reduce((s,l)=>s+(l.mo||0),0),cap=leaseCap(ls); const x={a,b,sub,ls,mo,cap,opts:[],own:pairLinks(a,b).find(l=>l.kind==='df'&&l.own&&l.ready<=S.day)};if(x.own){x.fit=litOn(x.own,cap);if(x.fit.fits)x.best=mo;return x;} // Waves and fabric circuits can also move onto a leased fiber pair: cheaper glass, but you buy the gear. diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index b1ede29..1802e8f 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -9,7 +9,7 @@ function renderDash(){checkLayer();
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')} -

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; +

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row'),sat:tr('satellites.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. diff --git a/src/game/94-dashboard/70-bank.js b/src/game/94-dashboard/70-bank.js index 72566a4..ee218dd 100644 --- a/src/game/94-dashboard/70-bank.js +++ b/src/game/94-dashboard/70-bank.js @@ -21,7 +21,7 @@ function renderBank(){ h+=CT?`
${tr('bank.bank_picks_up_apr_apr_over',{bank:esc(BANKS[CT.bank].name),apr:(CT.apr*100).toFixed(1),n:CALL_MONTHS,limit:fmt$(lim)})}
${CALL_AMTS.map(a=>btn(fmt$(a),'callBank',{amount:a},'sm',a>lim)).join('')}
`:`

${tr('bank.get_to_an_aa_rating_and')}

`;} h+=`

${tr('common.offers')}

`; if(!S.loanOffers.length)h+=`

${tr('bank.no_offers_right_now_banks_get')}

`; - for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`
${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}
${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}
${terms(o)}
${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}
${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}
`;} + for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`
${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}
${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}
${terms(o)}
${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(seaLink).length}})}
${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}
`;} h+=`

${tr('common.your_loans')}

`; if(!S.loans.length)h+=`

${tr('bank.debt_free_your_accountant_is')}

`; for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B); diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index daf9830..ba12d8f 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -1,7 +1,7 @@ function openLinkModal(a,b){ {const nt=noTalk(a,b);if(nt){openModal(`

${tr('common.not_happening')}

${tr(nt)}

`);return;}} if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`

${tr('link_modal.not_without_a_license')}

${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}

`);return;} - let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'); + let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'); if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1); if(border)route+=`

${tr('link_modal.cross_border_circuits_into_mainland')}

${a==='hkg'||b==='hkg'?`
${btn(tr('common.regular_crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('link_modal.premium_crossing_60_3_loss'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}
`:`

${tr('link_modal.premium_crossings_are_only_sold_in')}

`}`; if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`

${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}

diff --git a/src/game/96-map/55-link-look.js b/src/game/96-map/55-link-look.js index b0d354d..2ec50c9 100644 --- a/src/game/96-map/55-link-look.js +++ b/src/game/96-map/55-link-look.js @@ -5,9 +5,9 @@ const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5],[2,12],[14,5]]; // A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash. function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null; - const 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',xp=l.kind==='xp',bld=df&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); + const 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',xp=l.kind==='xp',st=l.kind==='sat',bld=(df||st)&&l.ready>day,cut=!bld&&!xp&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length||xp&&linkDown(l),vx=l.kind==='vxc'||st,idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx||xp?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)), - col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, + col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?(st?SAT_PROV[SATS[l.bird].p].col:FAB[l.prov].col):l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:xp?8:bld?3:idle?4:0, pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills // The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the // links and with the day's routing (R), not with the camera, so it is kept until one of those changes. diff --git a/src/i18n/en.js b/src/i18n/en.js index 46cf379..4e8068b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3926,6 +3926,7 @@ "pie_traffic.via_dishes":"up at {up}, down at {down}", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pitcairn.uk_grant_needs_a_cable":"UK grant {mo}/mo needs a cable: rented satellite capacity does not count", "pitcairn.uk_sky_grant_mo":"UK satellite grant {mo}/mo (fiber gets {full})", "pni_all.additional_per_month":"Additional monthly cost", "pni_all.all_at_port":"Peer all networks · {port}", @@ -4533,6 +4534,75 @@ "sales.w_last":"Last week {name} {list}.", "sales.w_now":"This week {name} {list}.", "sales.w_signed":{"one":"signed a customer ({rev}/mo)","other":"signed {n} customers ({rev}/mo)"}, +"satellites.a_teleport_is_a_satellite_gateway":"A teleport is a satellite gateway: big dishes at this POP that rent capacity on other people’s satellites, to small islands and remote towns no cable reaches, or that hang on one cable and a prayer.", +"satellites.add_tracking_antennas_cost_mo":"MEO tracking antennas {cost} + {mo}/mo", +"satellites.being_commissioned":"Being commissioned", +"satellites.build_a_teleport_cost_mo":"Build a teleport {cost} + {mo}/mo", +"satellites.by_satellite":"By satellite", +"satellites.cancel_n_circuits_first":{"one":"Cancel its satellite circuit first.","other":"Cancel its {n} satellite circuits first."}, +"satellites.choose":"Choose", +"satellites.circuit_ordered":{"one":"{cap} on {bird} ordered. {a} ⇄ {b} is being pointed and tested: up in {n} day.","other":"{cap} on {bird} ordered. {a} ⇄ {b} is being pointed and tested: up in {n} days."}, +"satellites.close_the_teleport":"Close the teleport", +"satellites.costs_row":"Teleports and satellites", +"satellites.geo_dishes":"GEO dishes", +"satellites.geo_dishes_and_meo_tracking":"GEO dishes and MEO tracking antennas", +"satellites.geo_users_notice":"From 36,000 km up the round trip is about 600 ms: video calls and games stutter, and users count {p} of the service as bad.", +"satellites.grow_to":"Grow to {cap}", +"satellites.in_view_list":"In view: {list}.", +"satellites.it_waits_on_standby":"You already have a link between these two: the satellite waits on standby and carries traffic only when that link is down.", +"satellites.its_blurb":"Old-school C-band and Ku-band beams that cover a whole ocean. Reliable, everywhere, and priced like it.", +"satellites.kac_blurb":"Ka-band spot beams over the western Pacific: the cheapest Gbps in orbit, if your island is under a beam.", +"satellites.meo_comes_at_level":"The MEO ring (about 130 ms round trip) comes at level {lv}.", +"satellites.meo_ring_misses_city":"The MEO ring does not see {city}: it covers {lat}° either side of the equator.", +"satellites.meo_users_notice":"Much closer to the ground, about 130 ms round trip: users barely notice ({p} of the service counts as bad).", +"satellites.more_islands_and_towns":"More islands and towns in view", +"satellites.ms_one_way_rtt":"{ms} ms one way, {rtt} ms round trip", +"satellites.ms_round_trip":"{ms} ms round trip", +"satellites.n_birds_see_both":{"one":"{n} satellite sees both","other":"{n} satellites see both"}, +"satellites.n_circuits_go_on_standby":{"one":"Your satellite circuit between {a} and {b} goes on standby beside the new link: it carries traffic only when that link is down.","other":"Your {n} satellite circuits between {a} and {b} go on standby beside the new link: they carry traffic only when that link is down."}, +"satellites.n_places_in_reach":{"one":"{n} island or remote town in reach at your level.","other":"{n} islands and remote towns in reach at your level."}, +"satellites.needs_tracking_antennas":"The MEO ring needs tracking antennas at your teleport in {city}.", +"satellites.new_pop_cost":"new POP {cost}", +"satellites.no_bird_sees_both":"No satellite on sale sees both {a} and {b}.", +"satellites.no_bird_sees_this_city":"No satellite on sale sees this city.", +"satellites.no_cable_needed_a_pop_here":"No cable needed: a satellite circuit from one of your teleports brings a POP in {city} online.", +"satellites.no_pop_in_city":"You have no POP in {city}.", +"satellites.no_pop_there_yet":"No POP in {city} yet: this builds one too ({cost}).", +"satellites.no_such_circuit":"No such satellite circuit.", +"satellites.no_teleport_in_city":"You have no teleport in {city}.", +"satellites.no_teleport_reaches_city":"None of your teleports can reach {city}. Build one at a POP whose satellites see it.", +"satellites.not_remote":"{city} is too big a market for satellite capacity: it serves small islands and remote towns.", +"satellites.nothing_in_view_from_here":"No island or remote town is in view from here.", +"satellites.on_standby_beside_your_link":"It waits on standby beside your link between the two and carries traffic only when that link is down.", +"satellites.orbit_unlocks_at_level":"{orb} satellites unlock at level {lv}.", +"satellites.out_of_footprint":"{bird} does not see both {a} and {b}.", +"satellites.pointing_dishes_and_testing":"Pointing dishes and testing", +"satellites.radio_path":"Radio path, up and down", +"satellites.reachable_from_your_teleports":"Your teleports can reach {city} by satellite:", +"satellites.really_close_it":"Really close it?", +"satellites.rent":"Rent", +"satellites.rent_satellite_capacity":"Rent satellite capacity", +"satellites.satellite_capacity":"Satellite capacity", +"satellites.satellites":"Satellites", +"satellites.sea_americas":"Americas", +"satellites.sea_atlantic":"Atlantic", +"satellites.sea_indian":"Indian Ocean", +"satellites.sea_pacific":"Pacific", +"satellites.sea_tropics":"within 50° of the equator", +"satellites.sea_west_pacific":"Western Pacific", +"satellites.sesa_blurb":"A ring of satellites 8,000 km up over the equator, for the other three billion. Open sesame: about 130 ms round trip.", +"satellites.shrink_to":"Shrink to {cap}", +"satellites.teleport":"Teleport", +"satellites.teleport_closed":"The teleport in {city} is closed.", +"satellites.teleport_up_in_city":"Teleport up in {city}. Big dishes on the roof, pointed at the sky: rent capacity from it to the islands in view.", +"satellites.teleports_unlock_at_level":"Teleports unlock at level {lv}.", +"satellites.tracking_antennas_up":"Tracking antennas up in {city}. They follow the MEO ring across the sky.", +"satellites.up_in_n_days":{"one":"up in {n} day","other":"up in {n} days"}, +"satellites.users_notice_geo_meo":"Users notice the lag: broadband over GEO counts as half the service, over MEO almost all of it. A cable always beats it, so your routers only send traffic up when there is no other way.", +"satellites.users_ride_a_satellite":"users ride a satellite", +"satellites.via_bird":"via {bird}", +"satellites.who_a_satellite_serves":"Satellites serve small islands and remote towns that the same satellite sees as your teleport. Pick where to.", +"satellites.your_pops_in_view":"Your POPs in view", "save.cash_in_the_bank":"{cash} in the bank", "save.import_failed_err":"Import failed.
{err}", "save.load_name":"Load {name}?", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 7d1f3e3..c0bb94c 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -32,7 +32,7 @@ const EXCEPTIONS = { W3: { ivc: 'Invercargill waits for its AI campus; nobody sells transit there yet', jub: 'Nobody sells transit in Juba: MTN and Zain haul it in from abroad', - pcn: 'Pitcairn: no cable, no network, land your own (#124), or reach it with a pie dish (backhaul through orbit)', + pcn: 'Pitcairn: no cable, no network, land your own (#124), reach it with a pie dish (backhaul through orbit), or rent a satellite circuit from a teleport (#83)', prr: 'Prince Rupert is a remote town with no carrier in it', smr: 'San Marino buys its transit from Italian carriers in Bologna and Rimini; nobody sells it in the town', sre: "Sucre has no exchange or carrier facility: Bolivia's transit is bought in La Paz", @@ -118,6 +118,8 @@ const REAL_NAMES = [ 'ACMA', 'ASEAN Explorer', 'ASEAN Protector', 'ASEAN Restorer', 'Cable Innovator', 'Cable Retriever', 'Global Marine', 'Léon Thévenin', 'MECMA', 'Orange Marine', 'Pierre de Fermat', 'René Descartes', 'SEAIOCMA', 'Sophie Germain', 'Sovereign', 'Wave Sentinel', 'Yokohama Zone', // rockets and satellite networks (Pie in the Sky) 'Blue Origin', 'Falcon 9', 'Falcon Heavy', 'Iridium', 'Kuiper', 'OneWeb', 'Project Kuiper', 'SpaceX', 'Starship', 'Starlink', + // satellite operators and their birds (teleports, #83) + 'Galaxy 19', 'Intelsat', 'Intelsat 18', 'Intelsat 20', 'Intelsat 37e', 'Intelsat Galaxy 19', 'Kacific', 'Kacific-1', 'O3b', 'O3b mPOWER', 'SES', // vendors 'Arista', 'Brocade', 'Ciena', 'Cisco', 'Extreme Networks', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia', ]; @@ -182,7 +184,7 @@ test('N2: names are puns: no network, cable, exchange, data center, router, opti const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim(); const real = new Set(REAL_NAMES.map(norm)); const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]), - ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n]),...PIE_NAMES.map(n=>['rocket company',tr(n)]),...Object.values(ROCKETS).map(r=>['rocket',tr(r.n)]),...Object.values(CRUSTS).map(c=>['constellation',tr(c.n)])].filter(x=>x[1])`); + ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n]),...PIE_NAMES.map(n=>['rocket company',tr(n)]),...Object.values(ROCKETS).map(r=>['rocket',tr(r.n)]),...Object.values(CRUSTS).map(c=>['constellation',tr(c.n)]),...Object.values(SAT_PROV).map(p=>['satellite operator',p.n]),...Object.values(SATS).map(b=>['satellite',b.n])].filter(x=>x[1])`); fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun'); fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word'); }); diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js index 50bf647..ea139e8 100644 --- a/tests/mcp-commands.test.js +++ b/tests/mcp-commands.test.js @@ -228,6 +228,7 @@ test('a dry run prices every command that has a price, and changes nothing', () opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df }, utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, pieRd: { k: 'reuse' }, pieAnt: { id: 'none' }, ip4Buy: { len: 24 }, ip4Lease: { len: 22 }, + teleBuild: { city: 'fra' }, teleTrk: { city: 'fra' }, buySat: { a: 'fra', b: 'rek', bird: 'is37', g: 1 }, satSize: { id: wave, g: 2 }, }; const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); assert.deepEqual(missing, [], 'every priced command with arguments has a sample here'); diff --git a/tests/satellites.test.js b/tests/satellites.test.js new file mode 100644 index 0000000..01e26cb --- /dev/null +++ b/tests/satellites.test.js @@ -0,0 +1,445 @@ +// Teleports and rented satellite capacity (#83): a teleport at a POP rents GEO or MEO circuits to small islands and +// remote towns its birds see. A circuit is a link (kind 'sat'): its radio path is its km, so routers take a cable +// whenever there is one; its orbit's latency is what users notice; next to the island's only cable it waits on standby. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { createSession, TOOLS } = require('../scripts/lib/mcp-game'); + +const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +// Level 3, Change Freeze (nothing breaks, lead times quick), plenty of cash. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');"; +// Sydney (transit, broadband) and Nuku'alofa (broadband, no transit of its own). +const ISLE = "ACT.buildPop({city:'syd'});ACT.launchBB({city:'syd'});ACT.buyTransit({city:'syd',net:'cog',tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});"; +function game(t, setup = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE + setup); + return h; +} +const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`)); +const sat = "S.links.find(l=>l.kind==='sat')"; +// Past the day a circuit is commissioned. +const ready = `S.day=${sat}.ready;compute()`; + +test('the footprint: which birds see where, who a satellite serves, and how long the trip is', (t) => { + const { ev, errors } = game(t); + const sees = J(ev, "[['is18','syd'],['is18','tbu'],['is18','mia'],['is37','mia'],['is37','sju'],['kac1','tbu'],['kac1','hnl'],['is20','mru'],['o3b','tbu'],['o3b','yfb']].map(([b,c])=>CITY[c]?satSees(b,c):null)"); + assert.deepEqual(sees, [true, true, false, true, true, true, false, true, true, false], 'the Pacific bird does not see Miami, Kacophony’s spot beams miss Hawaii, the MEO ring misses Iqaluit'); + // Both ends of a MEO circuit must see one satellite at a time. + assert.ok(ev("kmBetween('sju','hnl')") > ev('SAT_ORB.meo.km') && !ev("satPairOk('o3b','sju','hnl')"), 'San Juan to Honolulu is too far apart for one MEO satellite'); + assert.equal(ev("satPairOk('is18','syd','tbu')"), true); + assert.deepEqual(J(ev, "['tbu','pcn','asp','sju','lon','syd','mel'].map(satRemote)"), [true, true, true, true, false, false, false], 'small islands and remote towns, never a big city'); + const geo = ev("satRtt('is18','syd','tbu')"), meo = ev("satRtt('o3b','syd','tbu')"); + assert.ok(geo > 520 && geo < 650, 'GEO: about 600 ms round trip, got ' + geo); + assert.ok(meo > 110 && meo < 160, 'MEO: about 130 ms round trip, got ' + meo); + assert.ok(ev("satKm('is18','syd','tbu')") > 2 * 35786, 'the radio path goes up to the GEO belt and back down'); + // A MEO satellite halfway between Winnipeg and Vaduz is below both horizons: within 7,500 km and 50 degrees is not enough. + assert.ok(ev("kmBetween('ywg','vdz')") <= ev('SAT_ORB.meo.km') && ev("satSees('o3b','ywg')&&satSees('o3b','vdz')")); + assert.equal(ev("satPairOk('o3b','ywg','vdz')"), false, 'Winnipeg to Vaduz: no MEO satellite sees both'); + assert.ok(ev("satElev(satArc(0,satLon('o3b','ywg','vdz'),CITY.ywg.lat,CITY.ywg.lon),SAT_ORB.meo.h)") < ev('SAT_ORB.meo.el')); + assert.ok(ev("satPairOk('o3b','syd','tbu')") && ev("satElev(0,SAT_ORB.meo.h)") === 90, 'straight overhead is 90 degrees'); + // Every MEO pair on sale clears the horizon at both ends, so its radio path never runs through the Earth. + const low = J(ev, "(()=>{const O=SAT_ORB.meo,out=[];for(const A of CITIES)for(const B of CITIES){if(A.id>=B.id||!satRemote(B.id)||!satPairOk('o3b',A.id,B.id))continue;const lon=satLon('o3b',A.id,B.id);for(const C of [A,B])if(satElev(satArc(0,lon,C.lat,C.lon),O.h)Object.keys(SATS).some(id=>SATS[id].orb==='geo'&&satSees(id,c)))"), [true, true, true, true, true, true]); + assert.deepEqual(errors, []); +}); + +test('a teleport and a GEO circuit: level, price, lead time, capacity, latency, the bill, resizing and cancelling', (t) => { + const { ev, errors } = game(t, ISLE); + ev("S.lvl=1;ACT.teleBuild({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 0, 'teleports unlock at level 2'); + ev('S.lvl=3'); + let c0 = ev('S.cash'); + ev("ACT.teleBuild({city:'syd'})"); + assert.equal(ev("S.pops.syd.tele"), 1); + assert.equal(c0 - ev('S.cash'), ev('TPORT_COST')); + c0 = ev('S.cash'); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2})"); + const l = J(ev, sat); + assert.equal(l.bird, 'kac1'); + assert.equal(l.g, 2); + assert.equal(l.sub, true, 'never a land route'); + assert.equal(!!l.standby, false, 'alone between the two cities, it carries'); + assert.equal(c0 - ev('S.cash'), ev("satMo('kac1',2)"), 'no build: the first month up front'); + assert.equal(l.ready, ev('S.day+leadDays(SAT_ORB.geo.days)')); + ev('compute()'); + assert.equal(ev(`linkDown(${sat})`), true, 'down while it is pointed and tested'); + assert.equal(ev(`R.load[${sat}.id]||0`), 0); + ev(ready); + assert.equal(ev(`capOf(${sat})`), 2); + const ld = ev(`R.load[${sat}.id]`); + assert.ok(ld > 1 && ld <= 2 + 1e-9, 'the island’s traffic fills the circuit: ' + ld); + const ms = ev(`linkLat(${sat})`); + assert.ok(ms > 255 && ms < 310, 'one way over GEO: ' + ms); + assert.equal(ev('R.latF.tbu'), 0.5, 'broadband over GEO counts as half the service'); + assert.ok(ev("sfOf(R,'tbu')") <= 0.5); + ev("UI.sel={type:'city',id:'tbu'};UI.tab='cust';renderAll()"); + assert.match(ev("document.querySelector('#panel').textContent"), /users ride a satellite/, 'the island’s panel says why'); + assert.equal(ev('R.cost.sat'), ev(`TPORT_MO+${sat}.mo`), 'the teleport and the rent have a row of their own'); + assert.equal(ev("S.links.filter(l=>l.kind!=='sat').reduce((a,l)=>a+l.mo,0)"), ev('R.cost.links'), 'and are not in waves and fiber'); + // Bigger pays its month up front; smaller just costs less from now on. + c0 = ev('S.cash'); + ev(`ACT.satSize({id:${sat}.id,g:5})`); + assert.equal(c0 - ev('S.cash'), ev("satMo('kac1',5)")); + assert.equal(ev(`${sat}.mo`), ev("satMo('kac1',5)")); + c0 = ev('S.cash'); + ev(`ACT.satSize({id:${sat}.id,g:1})`); + assert.equal(ev('S.cash'), c0); + assert.equal(ev(`${sat}.g`), 1); + ev(`ACT.satSize({id:${sat}.id,g:3})`); + assert.equal(ev(`${sat}.g`), 1, 'only the sizes on sale'); + // Satellite capacity costs several times a subsea wave per Gbps, so a cable wins once there is one; the cheapest + // backup still fits inside what a small island's homes pay. + const wave = ev("waveMo(kmBetween('suv','tbu'),true,1)/LT[1].g"); + for (const id of ['is18', 'kac1']) assert.ok(ev(`satMo('${id}',10)/10`) > 3 * wave, id + ' per Gbps against a wave'); + assert.ok(ev("satMo('o3b',20)/20") > 3 * wave, 'MEO per Gbps against a wave'); + assert.ok(ev("satMo('kac1',1)") <= ev("CITY.suv.P*EYE_RATE"), 'a 1G backup costs less than Suva’s homes pay'); + // Cancelling asks twice. + ev(`ACT.rmLink({id:${sat}.id})`); + assert.ok(ev(`!!${sat}`), 'armed, not gone'); + ev(`ACT.rmLink({id:${sat}.id})`); + assert.equal(ev(`!!${sat}`), false); + assert.deepEqual(errors, []); +}); + +test('MEO needs tracking antennas and a higher level, and users barely notice it', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5})"); + assert.equal(ev(`!!${sat}`), false, 'no tracking antennas yet'); + assert.match(ev("satWhy('syd','tbu','o3b',5)"), /tracking antennas/); + ev("S.lvl=2;ACT.teleTrk({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'MEO comes at level 3'); + ev('S.lvl=3'); + const c0 = ev('S.cash'); + ev("ACT.teleTrk({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 2); + assert.equal(c0 - ev('S.cash'), ev('TRK_COST')); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5})"); + assert.equal(ev(`${sat}.bird`), 'o3b'); + assert.equal(ev(`${sat}.ready`), ev('S.day+leadDays(SAT_ORB.meo.days)')); + ev(ready); + const ms = ev(`linkLat(${sat})`); + assert.ok(ms > 55 && ms < 80, 'one way over MEO: ' + ms); + assert.ok(Math.abs(ev('R.latF.tbu') - 0.92) < 1e-9, 'MEO costs users 8% of the service, GEO half'); + assert.ok(ev("sfOf(R,'tbu')") >= 0.9, 'enough for broadband to keep growing'); + assert.equal(ev('R.cost.sat'), ev(`TPORT_MO+TRK_MO+${sat}.mo`)); + assert.deepEqual(errors, []); +}); + +test('orders outside a footprint, to a big city or without a teleport are refused, in words', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});ACT.buildPop({city:'mel'});ACT.buildPop({city:'sju'});"); + const tries = [ + ["{a:'syd',b:'tbu',bird:'is37',g:1}", /does not see both/], + ["{a:'syd',b:'sju',bird:'is18',g:1}", /does not see both/], + ["{a:'syd',b:'mel',bird:'is18',g:1}", /too big a market/], + ["{a:'tbu',b:'syd',bird:'is18',g:1}", /no teleport in Nuku/], + ["{a:'syd',b:'tbu',bird:'is18',g:3}", /No such satellite circuit/], + ["{a:'syd',b:'tbu',bird:'nope',g:1}", /No such satellite circuit/], + ]; + const c0 = ev('S.cash'); + for (const [a, why] of tries) { + const o = JSON.parse(ev(`JSON.stringify(${a})`)); + assert.match(ev(`satWhy(${JSON.stringify(o.a)},${JSON.stringify(o.b)},${JSON.stringify(o.bird)},${o.g})`), why, a); + ev(`ACT.buySat(${a})`); + } + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 0); + assert.equal(ev('S.cash'), c0, 'nothing charged'); + assert.deepEqual(errors, []); +}); + +test('beside the island’s only cable, a satellite waits on standby and takes over when the cable is cut', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'suv'});ACT.launchBB({city:'suv'});ACT.buyTransit({city:'suv',net:" + + "NETS.find(n=>sellsAt(n,'suv')).id,tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:1});ACT.teleBuild({city:'suv'});"); + const wave = "S.links.find(l=>l.kind==='wave')"; + assert.equal(ev(`${wave}.cable`), 'tonga', 'the wave rides the only cable'); + ev("ACT.buySat({a:'suv',b:'tbu',bird:'kac1',g:5})"); + assert.equal(ev(`${sat}.standby`), true, 'next to the cable it goes on standby by itself'); + ev(ready); + assert.equal(ev(`R.load[${sat}.id]`), 0, 'idle while the cable is up'); + assert.ok(ev(`R.load[${wave}.id]`) > 1); + assert.equal(ev('R.latF.tbu'), undefined, 'nobody notices a satellite that carries nothing'); + // The anchor drags across the cable: the satellite carries the island. + ev(`${wave}.cut=S.day+30;compute()`); + assert.ok(ev(`R.load[${sat}.id]`) > 1, 'the satellite takes over'); + assert.ok(ev('R.citySrv.tbu') > 1); + assert.equal(ev('R.latF.tbu'), 0.5, 'at GEO’s latency'); + // Without it, the island is dark. + ev(`S.links=S.links.filter(l=>l.kind!=='sat');compute()`); + assert.ok((ev('R.citySrv.tbu') || 0) < 1e-6, 'no satellite, no internet in Tonga'); + assert.deepEqual(errors, []); +}); + +test('a cable laid beside a circuit puts it on standby; overflow and a shared load cost users their share', (t) => { + // The issue's own order: the satellite first, a cable later. + const { ev, errors } = game(t, "ACT.buildPop({city:'suv'});ACT.launchBB({city:'suv'});ACT.buyTransit({city:'suv',net:" + + "NETS.find(n=>sellsAt(n,'suv')).id,tier:1});ACT.buildPop({city:'tbu'});ACT.launchBB({city:'tbu'});ACT.teleBuild({city:'suv'});"); + const wave = "S.links.find(l=>l.kind==='wave')"; + ev("ACT.buySat({a:'suv',b:'tbu',bird:'kac1',g:10});" + ready); + assert.equal(!!ev(`${sat}.standby`), false, 'alone, it carries the island'); + assert.equal(ev('R.latF.tbu'), 0.5); + ev("UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:0})"); + assert.equal(ev(`${sat}.standby`), true, 'the cable puts it on standby'); + assert.match(ev("document.querySelector('#toasts').textContent"), /goes on standby beside the new link/); + ev('compute()'); + assert.equal(ev(`R.load[${sat}.id]`), 0, 'idle while the cable has room'); + assert.ok(ev(`R.load[${wave}.id]`) > 1); + assert.equal(ev('R.latF.tbu'), undefined, 'nobody notices'); + assert.equal(ev("R.satU.tbu||0"), 0); + assert.doesNotMatch(ev("traceroute('tbu',{city:'suv'}).text"), /Kacophony/, 'the trace takes the cable'); + // The cable loses three quarters of its light: the satellite takes the overflow, and users notice that share. + ev(`${wave}.loss={until:S.day+60,f:0.25};compute()`); + const cab = ev(`capOf(${wave})`), dem = ev('R.cityDem.tbu'); + assert.ok(dem > cab, 'more than the cable carries'); + const sl = ev(`R.load[${sat}.id]`), wl = ev(`R.load[${wave}.id]`), share = sl / (sl + wl); + assert.ok(Math.abs(wl - cab) < 1e-6 && sl > 0.5, 'the cable fills, the satellite takes the rest'); + assert.ok(Math.abs(ev('R.latF.tbu') - (1 - 0.5 * share)) < 1e-6, 'GEO costs half the service of the share it carries: ' + ev('R.latF.tbu')); + assert.ok(Math.abs(ev('R.satU.tbu') / ev('R.citySrv.tbu') - share) < 1e-6); + ev("UI.sel={type:'city',id:'tbu'};UI.tab='cust';renderAll()"); + assert.match(ev("document.querySelector('#panel').textContent"), /users ride a satellite/); + ev("UI.sel={type:'city',id:'suv'};renderAll()"); + assert.doesNotMatch(ev("document.querySelector('#panel .facts').textContent"), /users ride a satellite/, 'not on the teleport’s own city'); + // Taken off standby by hand, it shares the load by capacity, and users notice that share too. + ev(`ACT.setStandby({id:${sat}.id,on:false})`); + const s2 = ev(`R.load[${sat}.id]`) / (ev(`R.load[${sat}.id]`) + ev(`R.load[${wave}.id]`)); + assert.ok(Math.abs(s2 - 10 / (10 + cab)) < 1e-6, 'split by capacity'); + assert.ok(Math.abs(ev('R.latF.tbu') - (1 - 0.5 * s2)) < 1e-6); + assert.deepEqual(errors, []); +}); + +test('the teleport city’s own users get the satellite tag only when they ride it', (t) => { + // Honolulu: transit only in Los Angeles (a haul users notice), and a teleport carrying Papeete. + const { ev, errors } = game(t, "ACT.buildPop({city:'lax'});ACT.buyTransit({city:'lax',net:NETS.find(n=>sellsAt(n,'lax')).id,tier:1});ACT.buildPop({city:'hnl'});ACT.launchBB({city:'hnl'});" + + "UI.pending={a:'hnl',b:'lax'};ACT.buildLink({tier:1});ACT.teleBuild({city:'hnl'});ACT.buildPop({city:'ppt'});ACT.launchBB({city:'ppt'});ACT.buySat({a:'hnl',b:'ppt',bird:'is18',g:1});"); + ev('S.day=Math.max(...S.links.map(l=>l.ready||0))+1;compute()'); + assert.ok(ev(`R.load[${sat}.id]`) > 0.5, 'Papeete rides the satellite'); + assert.ok(ev('R.latF.hnl') < 1, 'Honolulu’s users notice the haul to Los Angeles'); + assert.equal(ev("R.satU.hnl||0"), 0, 'but none of their traffic goes up'); + assert.equal(ev("satFact('hnl')"), ''); + assert.match(ev("satFact('ppt')"), /users ride a satellite/); + assert.deepEqual(errors, []); +}); + +test('subsea counts leave satellites out: a no-subsea covenant and the cables overseas of Fibre to the Basement', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev("S.loanOffers.push({id:'wf1',bank:'wf',amount:200000,exp:S.day+25,covs:['nosub','logo','reach99'],apr:0.15,term:12,pay:Math.round(annuity(200000,0.15,12))});ACT.takeLoan({id:'wf1'})"); + const L = "S.loans.find(l=>l.id==='wf1')"; + assert.equal(ev(`COVS.nosub.ok(${L})`), true); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1})"); + assert.equal(ev(`COVS.nosub.ok(${L})`), true, 'a satellite circuit is no subsea link'); + const bal = ev(`${L}.bal`); + ev('for(let i=0;i<40;i++){S.day++;loanTick(S.day);}'); + assert.ok(!(ev(`${L}.breach`) > 0), 'no breach'); + assert.ok(ev(`${L}.bal`) <= bal, 'no penalty'); + // A real subsea wave still breaks it. + ev("ACT.buildPop({city:'akl'});UI.pending={a:'syd',b:'akl'};ACT.buildLink({tier:1})"); + assert.equal(ev(`COVS.nosub.ok(${L})`), false); + assert.deepEqual(errors, []); +}); + +test('two satellite circuits are not two cables overseas in Fibre to the Basement', (t) => { + const { ev, errors } = game(t); + ev("ACT.startScn({id:'fttb'});S.cash=1e8;S.lvl=2;S.nextFail=S.nextEvent=1e9;ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1});ACT.buySat({a:'syd',b:'nou',bird:'kac1',g:1});"); + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 2); + ev('S.day=Math.max(...S.links.map(l=>l.ready||0))+1;compute()'); + assert.equal(ev('auExits()'), 0, 'no cable leaves Australia'); + assert.equal(J(ev, 'SCN_PROG.fttb()').find((r) => r.max === 2).v, 0, 'the progress row says so'); + assert.deepEqual(errors, []); +}); + +test('a teleport is offered only where a satellite on sale sees the POP, and tracking antennas only under the MEO ring', (t) => { + const { ev, errors } = game(t, "S.lvl=2;ACT.buildPop({city:'hpa'});ACT.buildPop({city:'chi'});ACT.buildPop({city:'lon'});"); + const panel = (c) => { ev(`UI.sel={type:'city',id:'${c}'};UI.tab='links';renderAll()`); return ev("document.querySelector('#panel').textContent"); }; + const disabled = (c) => ev(`(b=>!!b&&b.disabled)(document.querySelector('#panel [data-act="teleBuild"]'))`); + // Haparanda, by the Arctic Circle: nothing on sale sees it, and the panel says so before any money moves. + assert.match(panel('hpa'), /No satellite on sale sees this city/); + assert.equal(disabled('hpa'), true); + const c0 = ev('S.cash'); + ev("ACT.teleBuild({city:'hpa'})"); + assert.equal(ev("teleOf('hpa')"), 0); + assert.equal(ev('S.cash'), c0, 'nothing charged'); + assert.match(ev("teleWhy('hpa')"), /No satellite/); + // Chicago sees the bird over the Americas, and the panel says what is in reach before the build. + assert.match(panel('chi'), /In view: Intelsplat 19/); + assert.match(ev("document.querySelector('#panel').textContent"), /in reach at your level/); + assert.equal(disabled('chi'), false); + ev("ACT.teleBuild({city:'chi'})"); + assert.equal(ev("teleOf('chi')"), 1); + // London is north of the MEO ring: no tracking antennas there, at any level. + ev("S.lvl=3;ACT.teleBuild({city:'lon'})"); + assert.equal(ev("teleOf('lon')"), 1); + assert.ok(!J(ev, "(()=>{UI.sel={type:'city',id:'lon'};UI.tab='links';renderAll();return [...document.querySelectorAll('#panel [data-act]')].map(b=>b.dataset.act);})()").includes('teleTrk')); + const c1 = ev('S.cash'); + ev("ACT.teleTrk({city:'lon'})"); + assert.equal(ev("teleOf('lon')"), 1); + assert.equal(ev('S.cash'), c1); + assert.match(ev("trkWhy('lon')"), /does not see London/); + assert.equal(ev("trkWhy('chi')"), '', 'Chicago is under the ring'); + assert.deepEqual(errors, []); +}); + +test('the order sheet prices a new POP with your POP standard, as the list before it does', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});S.pops.syd.rgen=2;ACT.popStdSet({city:'syd'});"); + const std = ev('newPopCost("pcn")'); + assert.ok(std > ev('popCost("pcn")'), 'the standard adds routers'); + ev("ACT.satOpen({a:'syd'})"); + assert.ok(ev("document.querySelector('#modalCard').textContent").includes(ev(`fmt$(${std})`))); + ev("ACT.satOpen({a:'syd',b:'pcn'})"); + assert.ok(ev("document.querySelector('#modalCard').textContent").includes(ev(`fmt$(${std})`)), 'the same price one tap later'); + assert.deepEqual(errors, []); +}); + +test('MCP: dry runs for satellites quote what the game then does', () => { + const s = createSession(), T = (n, a = {}) => TOOLS.find((x) => x.name === n).run(s, a), ev = (x) => s.game.ev(x); + T('new_game', { city: 'syd', preset: 'sandbox', seed: 7, name: 'Probe' }); + ev('S.lvl=Math.max(S.lvl,3);S.cash=1e9'); + assert.deepEqual(T('act', { action: 'teleBuild', args: { city: 'syd' }, dryRun: true }).quote.blocked, []); + T('act', { action: 'teleBuild', args: { city: 'syd' } }); + assert.deepEqual(T('act', { action: 'teleTrk', args: { city: 'syd' }, dryRun: true }).quote.blocked, [], 'Sydney is under the MEO ring'); + assert.match(T('act', { action: 'teleTrk', args: { city: 'mel' }, dryRun: true }).quote.blocked.join(' '), /no teleport in Melbourne/); + T('act', { action: 'buySat', args: { a: 'syd', b: 'asp', bird: 'is18', g: 1 } }); + const id = ev("S.links.find(l=>l.kind==='sat').id"); + // A wave beside the circuit: no diversity premium, in the quote as in the bill. + const q = T('act', { action: 'buildLink', args: { a: 'syd', b: 'asp', tier: 1 }, dryRun: true }).quote; + const c0 = ev('S.cash'); + T('act', { action: 'buildLink', args: { a: 'syd', b: 'asp', tier: 1 } }); + assert.equal(q.setup, c0 - ev('S.cash'), 'quote equals charge'); + assert.equal(ev(`S.links.find(l=>l.id==='${id}').standby`), true); + // Resizing: only sizes the bird sells, and not the one it has. + for (const g of [20, 1]) { + const r = T('act', { action: 'satSize', args: { id, g }, dryRun: true }).quote; + assert.match(r.blocked.join(' '), /No such satellite circuit/, 'g ' + g); + } + const up = T('act', { action: 'satSize', args: { id, g: 5 }, dryRun: true }).quote; + assert.deepEqual(up.blocked, []); + const c1 = ev('S.cash'); + T('act', { action: 'satSize', args: { id, g: 5 } }); + assert.equal(up.setup, c1 - ev('S.cash')); + assert.deepEqual(s.errors(), []); +}); + +test('a satellite elsewhere is the long way round: routers use the cables and fall back to it only when cut', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.buildPop({city:'suv'});UI.pending={a:'syd',b:'suv'};ACT.buildLink({tier:1});UI.pending={a:'suv',b:'tbu'};ACT.buildLink({tier:1});ACT.teleBuild({city:'syd'});"); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'is18',g:5})"); + assert.equal(!!ev(`${sat}.standby`), false, 'no link between Sydney and Tonga: not on standby'); + ev(ready); + assert.ok(ev(`${sat}.km`) > 10 * ev("kmBetween('syd','tbu')"), 'its metric is the radio path'); + assert.equal(ev(`R.load[${sat}.id]||0`), 0, 'Tonga goes to Sydney over the cables, not the satellite'); + ev("S.links.find(l=>l.kind==='wave'&&(l.a==='tbu'||l.b==='tbu')).cut=S.day+30;compute()"); + assert.ok(ev(`R.load[${sat}.id]`) > 1, 'with the Tonga cable cut, the satellite carries it'); + // Nobody digs up a satellite: cuts land on the cables only. + ev("S.links.forEach(l=>l.cut=0);S.inc=[];for(let i=0;i<12;i++){fireFailure('cut');for(const l of S.links)if(l.kind!=='sat')l.cut=0;S.inc=[];}"); + assert.equal(ev(`${sat}.cut`), 0); + // The traceroute names the bird. + ev("S.links.find(l=>l.kind==='wave'&&(l.a==='tbu'||l.b==='tbu')).cut=S.day+30;compute()"); + assert.match(ev("traceroute('tbu',{city:'syd'}).text"), /via Intelsplat 18/); + assert.deepEqual(errors, []); +}); + +test('Pitcairn by satellite: a POP comes with the circuit, but GEO is not good enough for the UK grant', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + assert.equal(ev("!!S.pops.pcn"), false); + const c0 = ev('S.cash'); + ev("ACT.buySat({a:'syd',b:'pcn',bird:'is18',g:1})"); + assert.ok(ev('!!S.pops.pcn'), 'the order builds the POP'); + assert.equal(c0 - ev('S.cash'), ev("satMo('is18',1)+popCost('pcn')")); + ev("ACT.launchBB({city:'pcn'});" + ready); + assert.ok(ev('R.citySrv.pcn') > 0, 'the islanders are online'); + assert.ok(ev("sfOf(R,'pcn')") <= 0.5 + 1e-9); + assert.equal(ev('grantOn(R)'), false); + assert.equal(ev('R.rev.grant'), 0); + assert.deepEqual(errors, []); +}); + +test('Pitcairn over MEO serves the islanders well, but the UK pays its fiber grant only for a cable', (t) => { + const { ev, errors } = game(t, "ACT.buildPop({city:'akl'});ACT.launchBB({city:'akl'});ACT.buyTransit({city:'akl',net:NETS.find(n=>sellsAt(n,'akl')).id,tier:1});ACT.teleBuild({city:'akl'});ACT.teleTrk({city:'akl'});"); + assert.equal(ev("teleOf('akl')"), 2); + ev("ACT.buySat({a:'akl',b:'pcn',bird:'o3b',g:2});ACT.launchBB({city:'pcn'});" + ready); + assert.ok(ev('R.citySrv.pcn') > 0, 'the islanders are online'); + assert.ok(ev("sfOf(R,'pcn')") >= 0.9, 'MEO serves them nearly as well as fiber'); + assert.ok(Math.abs(ev("satShare(R,'pcn')") - 1) < 1e-9, 'all of it over the satellite'); + assert.equal(ev('grantOn(R)'), false, 'no fiber grant for a satellite'); + assert.equal(ev('R.rev.grant'), 0); + assert.match(ev("grantFact('pcn')"), /needs a cable/); + assert.deepEqual(errors, []); +}); + +test('saves: circuits survive a round trip, broken ones are dropped, and old saves load as they were', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});S.pops.syd.tele=2;ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2});ACT.buySat({a:'syd',b:'tbu',bird:'o3b',g:5});"); + const before = J(ev, "S.links.filter(l=>l.kind==='sat')"); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.deepEqual(J(ev, "S.links.filter(l=>l.kind==='sat')"), before, 'kind, bird, size and dates kept'); + // Garbage in: an unknown bird, an odd size, a MEO circuit on a GEO-only teleport, a teleport that is not 1 or 2. + ev("S.links.push({id:'x1',a:'syd',b:'tbu',kind:'sat',bird:'nope',g:1,km:1,mo:1,cut:0});S.links.find(l=>l.bird==='kac1').g=7;S.links.find(l=>l.bird==='kac1').km=3;S.pops.tbu.tele='big'"); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev("S.links.some(l=>l.id==='x1')"), false, 'an unknown bird is dropped'); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').g"), 5, 'an odd size becomes the largest size on sale under it'); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').km"), ev("satKm('kac1','syd','tbu')"), 'the radio path is the physics, not the save'); + assert.equal(ev("'tele' in S.pops.tbu"), false); + // A circuit's order day from a save: a number no later than today, so its commissioning bar is a real width. + ev("(k=>{k.day='junk';k.ready=S.day+5;})(S.links.find(l=>l.bird==='kac1'));S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').day"), ev('S.day')); + ev("S.links.find(l=>l.bird==='kac1').day=S.day+40;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.bird==='kac1').day"), ev('S.day'), 'not in the future'); + ev("delete S.links.find(l=>l.bird==='kac1').day;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.doesNotMatch(ev("satPanel(S.links.find(l=>l.bird==='kac1'))"), /NaN/); + ev("S.pops.syd.tele=1;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.some(l=>l.bird==='o3b')"), false, 'a MEO circuit needs tracking antennas at its teleport'); + ev("delete S.pops.syd.tele;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.filter(l=>l.kind==='sat').length"), 0, 'no teleport, no circuits'); + // A save from before satellites: nothing about it changes, not even a row in the bill. + ev("S=migrate(JSON.parse(" + JSON.stringify(SAVE) + "));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()"); + assert.equal(ev("S.links.some(l=>l.kind==='sat')||Object.values(S.pops).some(p=>'tele' in p)"), false); + assert.equal(ev("'sat' in R.cost"), false); + assert.ok(ev('R.served') > 0); + assert.deepEqual(errors, []); +}); + +test('closing: a teleport with circuits stays open; closing the island or the teleport’s POP takes the circuit along', (t) => { + const { ev, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:1});"); + ev("ACT.teleRm({city:'syd'});ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'not while a circuit starts there'); + ev("decommission(['tbu'])"); + assert.equal(ev(`!!${sat}`), false, 'the island’s POP takes its circuit along'); + ev("ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 1, 'the first tap only arms it'); + ev("ACT.teleRm({city:'syd'})"); + assert.equal(ev("teleOf('syd')"), 0); + ev("ACT.teleBuild({city:'syd'});ACT.buySat({a:'syd',b:'pcn',bird:'is18',g:1});decommission(['syd'])"); + assert.equal(ev("S.links.some(l=>l.kind==='sat')"), false, 'so does the teleport’s'); + assert.deepEqual(errors, []); +}); + +test('on a phone: the teleport section, the order sheet, a circuit’s panel and the map, at 360 px', (t) => { + const { ev, dom, errors } = game(t, ISLE + "ACT.teleBuild({city:'syd'});"); + ev('window.innerWidth=360;window.innerHeight=740;window.dispatchEvent(new window.Event("resize"))'); + assert.equal(ev('isPhone()'), true); + const text = (sel) => ev(`(document.querySelector('${sel}')||{}).textContent||''`); + const acts = (sel) => J(ev, `[...document.querySelectorAll('${sel} [data-act]')].map(b=>b.dataset.act)`); + ev("UI.sel={type:'city',id:'syd'};UI.tab='links';renderAll()"); + assert.match(text('#panel'), /Satellites/); + assert.ok(acts('#panel').includes('satOpen')); + // A city without a POP that the teleport reaches. + ev("UI.sel={type:'city',id:'apw'};renderAll()"); + assert.match(text('#panel'), /By satellite/); + ev("ACT.satOpen({a:'syd'})"); + assert.ok(acts('#modalCard').filter((a) => a === 'satOpen').length >= 2, 'a choice of destinations'); + ev("ACT.satOpen({a:'syd',b:'tbu'})"); + assert.ok(acts('#modalCard').filter((a) => a === 'buySat').length >= 8, 'every bird that sees both, every size'); + assert.equal(ev('document.getElementById("modal").hidden'), false); + ev("ACT.buySat({a:'syd',b:'tbu',bird:'kac1',g:2});" + ready + ';renderAll()'); + assert.match(text('#panel'), /round trip/); + assert.ok(acts('#panel').includes('satSize') && acts('#panel').includes('rmLink')); + for (const s of ['#panel', '#modalCard', '#toasts']) assert.doesNotMatch(text(s), /satellites\.|undefined|NaN/, s); + // How the tube looks on the map: dashed like a virtual circuit, in the operator's colour; then a frame is drawn. + const look = J(ev, `(()=>{const L=linkLook([${sat}],S.day);return {dash:L.dash,col:L.col,w:L.w0};})()`); + assert.equal(look.dash, 2); + assert.equal(look.col, ev("SAT_PROV.kac.col")); + ev('draw(performance.now())'); + assert.deepEqual(errors, []); + assert.equal(dom.window.document.querySelectorAll('#panel').length, 1); +}); From b533f3baa8304269dde5749e63ed19355456f2d8 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:12:23 +0100 Subject: [PATCH 8/8] Plans: multiplayer phase 2 design, and what is left after this round --- docs/plans/multiplayer-phase2.md | 404 +++++++++++++++++++++++++++++++ docs/plans/next-session.md | 55 +++++ 2 files changed, 459 insertions(+) create mode 100644 docs/plans/multiplayer-phase2.md create mode 100644 docs/plans/next-session.md diff --git a/docs/plans/multiplayer-phase2.md b/docs/plans/multiplayer-phase2.md new file mode 100644 index 0000000..346e1c7 --- /dev/null +++ b/docs/plans/multiplayer-phase2.md @@ -0,0 +1,404 @@ +# Multiplayer phase 2: players inside each other's simulations + +Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`. + +**Conventions:** +- Line numbers are `main` at `1e7638c`. +- Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`. +- Everything runs only when `MP_API` is stamped and `S.mpx` is not null. The plain GitHub Pages build is unchanged (`pages.test.js`, `build.test.js`). + +## 1. Starting point and grafts + +**Base: "contracts".** It had the best totals in two of the three scorings, and the best feasibility and risk. +- Players are pseudo carriers `mp:`, registered only in `NET` with single-entry `CONE`/`CONE_S`/`DOWN`/`ANC`. +- `NETS`, `NET_IDS`, `NSH`, `t1Need()`, seen/grace and the gameplay-rules tests never see a player. +- No catalog id contains `:`, and nothing iterates `NET`. + +**I checked this on big-network** (a throwaway probe, not committed): a buyer row on `mp:p1` in `S.transit` plus a player PNI, through `compute`, 5 day ticks, the intern, every panel and tab, traceroute, `t1Why`/`isTier1` and a `migrate` round trip. + +Results: +- No errors anywhere. +- The rows were kept while registered and dropped once unregistered. +- Warm compute went from 32.3 to 33.2 ms (median of 25 alternating runs). +- `R.sessions` rose by 1. That confirms the exploit fixed below. + +**How each fatal flaw the judges found is removed:** + +| Judged flaw | Fix | +|---|---| +| The seller's `S.biz` row is exposed to dropBiz, decommission, ddosTargets, Pie moods and the mood loop | The seller side is a deal entry read in exactly two places, demand and money (nets) | +| Peering is cosmetic, yet player PNIs count toward `isTier2`/`t1Club` | Player traffic ships with peering (§2.3). Player sessions never enter `R.sessions` | +| Health is all or nothing, and bought transit reaches every network | A capacity factor (`t.mpf`) and a `miss` id list, from day one | +| A↔B transit loops | The server refuses with 409; clients drop loop links in a fixed pid order (nets) | +| A stale or alt buyer keeps paying the commit forever | The seller earns, and carries load, only while the buyer's clock runs. Prices are capped against the catalog | +| A bought wave can be upgraded past its agreed price | `upLink`/`rmLink`/`setStandby` refuse it (gameplay) | +| "An active deal with no row" is ambiguous | A per-deal `made` flag (§5) | +| `NKN` flips inside `compute()` | It is always `NN+4` | + +**Grafted from the other designs:** +- From nets: the two-sided route-server rule; cones through players; PNI lead from `hstr`, with capacity set by the smaller side; the Tier 1 clique star. +- From gameplay: waves, tenders, poaching, consortium seats, notice on each player's own clock, and the LOA handshake. + +**Rejected:** players as `NETS` entries (a mutable catalog, a rescaled `NSH`), reach bitmaps (they break between builds), a Tier 1 that depends on other players, automatic ratio strikes, and own-day timers that end a deal (they fire within seconds at 8×; own-day notice only paces each side's own teardown). + +## 2. Mechanics + +### 2.1 Pseudo carriers (`src/game/30-networks/45-player-carriers.js`, new) + +`mpBind(s)` does three things: +1. deletes every `mp:*` key; +2. registers `{id:'mp:'+pid, name, asn, type:'t2', pol:'open', share:0, price:1, pops:[], up:[], ix:[], cc:'', col, blurb:tr('mp.another_player'), mp:1}` for each `s.mpx.who` entry; +3. sets `MPB.k`. + +It runs at the start of every `sanitize` and every `compute()` (`if(MPB.k!==(S.mpx?S.mpx.k:''))mpBind(S)`). That covers the route worker, slot switches, imports, the failed-load rollback (`91-slots.js:105`) and puzzles. `nocWinState` (`94-dashboard/90-noc-window.js:45`) calls it too. + +Because the carrier has `pops:[]` and is not in `NETS`, no catalog list ever offers a player: +- `sellsAt` and `buyTransit`; +- the intern's providers, `peerAll` and `pniAll`; +- the peering desk and own-exchange joins. + +The `peer` action returns at `ixMembers(city).includes(net)` (`40-sites-peering-caches.js:14`). + +### 2.2 Transit between players (the Tier 1 endgame) + +**Who can sell:** a player publishes `tp` ($/Gbps/month) while `R.reach >= 0.99` and they have at least one POP. + +**Buying:** "Buy transit from X here" posts a `t` deal (city, tier, LAG). The server makes it `live` at once (a price list is a standing offer) when all of these hold: +- the seller's card has `tp`; +- both cards list the city; +- there is no cycle; +- the limits hold. + +**Price:** `min(tp, mpCap(city))`, where `mpCap = 2 × the cheapest catalog transitPerG(n,city,false)` there, or the catalog median if nobody sells there. +- Both sides compute it from the static catalog, ignoring each save's own `priceMul`. +- Both clamp again when they receive the deal. + +**Buyer side: an ordinary `S.transit` row** `{id:'mt-'+deal, net:'mp:'+seller, city, tier, n, mp:deal, mpp:price}`. +- **Comes free:** the router port (`40-ports.js:20`), p95 history (`10-day-tick.js:37`), hot ports, traceroute, incidents, the panels, and `isTier1()===false`. +- **Billing:** `transitMo` (`40-billing.js:9`) uses `t.mpp` instead of `transitPerG(...)*S.priceMul`. The commit floor, `PORT.tmo` and `krFee` still apply. +- **Capacity:** `30-compute.js:53` multiplies by `t.mpf` = min(1, the seller's `sv[city]`/0.95), in 0.05 steps. +- **Reach:** `:54`'s `ok` also needs `!mm.has(n)` (the seller's `miss`). +- **Route cache:** the hash of every miss set joins the flags at `:70` (`+(S.mpx?S.mpx.xk:'')`), so `rcExitKey` rebuilds when a seller's reach changes. +- **Outage:** `t.down=S.day+1` when the seller's POP is down or the seller has left. + +**Seller side: a `sell` entry in `S.mpx.deals`, never in `S.biz`.** +- **Load:** `mpDem(bizBw)` after the biz loop (`:95`) adds `u`, the buyer's reported use. It leaves by catalog share over the seller's own backbone, peering and upstreams; a Tier 1 carries it settlement-free. +- **Money:** `V.mp = Σ price × max(q, 20% of port) × min(1, sfOf(R2,city)/0.95)`. `q` is the buyer's p95; the last factor is the business customers' SLA credit. `V.mp` is added to `revMo` (`:382`) and to the revshare base (`:380`). +- **Port:** the seller's port counts in `portsUsed` (`10-catalog/40-ports.js`, after `:21`). +- **Idle buyer:** if the buyer's roster `idle` is ≥ 300 s (no newer game day reached the server), load and revenue are 0. + - A paused or closed buyer has no traffic to bill, and a fast seller cannot bill a frozen buyer. + - An alt account has to keep playing, and still pays at most the capped price. + +**Loops:** +- The server returns 409 `loop` if the seller already buys from the buyer, directly or through others (a search over at most 12 players). +- Clients build the player-transit graph from `who[].pt` and add edges sorted by (buyer pid, seller pid), dropping any that closes a cycle, so every client drops the same edge. +- So reach passes down a reseller chain one push per hop, never settling at a false 1. + +**Tier 1 stays defined by the built-in networks.** +- `R.reach` only sums `NSH`, so neither `isTier1` (`80-hot-ports-and-rank.js:20`) nor the mood check `R.reach>0.99` (`10-day-tick.js:51`) can depend on players. +- Buying player transit costs Tier 1, and `t1Why` already says so. Selling never does. +- Refusing to peer blocks nobody's win. + +### 2.3 Peering between players, carrying traffic + +**PNI (`pni` deal, always accepted by hand).** Each side adds `S.pni` `{id:'mn-'+deal, net:'mp:'+other, city, tier, n, mp:deal, ready:S.day+lead}`. +- **Lead time:** `lead = pniNow() ? 0 : leadDays(14 + hstr(deal+myPid) % 29)`, with no random numbers. +- **Cost:** each side pays its own `pniMo`. +- **Capacity:** the smaller of the two sides (theirs comes from `dl[].g`). It is 0 until both cards report `ok`: the LOA and cross-connect handshake. + +**IX (`ix` deal).** The server makes it `live` if the responder's policy is open, `no` if closed, and `offer` if selective. Once live, both sides set `S.peers['mp:P@x']`. + +**Route server:** no deal. P peers with me at `x` when both `S.rs[x]` and `P.rs ∋ x` hold and both policies are open. That is the same rule on both clients. + +**Sessions:** +- `mpIx(x)` lists the player peers at an exchange. `ixSessions` (`20-exchanges.js:29`) stays catalog-only. +- At `30-compute.js:61`, player PNIs skip `R2.sessions++` (`if(!p.mp)`) and count in `R.mpSess` instead. +- So friends can never inflate `isTier2`/`t1Club`. + +**Player traffic** (new `src/game/80-simulation/36-mp-traffic.js`). `compute.js:343` calls `mpTraffic({E,SPP,NRES,HAS,R2,carry,NN})` once, after `citySrv` (`:341-342`). The parts are handed in the way `ddosLoad` gets them (`:188`). +- **Demand:** each POP sends `cityEye[c]·w_P` to each active player P. + - `w_P = min(0.02, (biz_P + 0.3·eye_P)/75000)`, and `Σw ≤ 0.1`. +- **Exits that reach P:** + - rank 2: a ready PNI with P, or an IX exit with `mpIx(x) ∋ P`; + - rank 2.5: the same exits toward Q when P buys from Q, which gives cones through players; + - rank 3: player transit from Q when `P===Q` or `Q.mr ∋ P`, and catalog transit when `P.on`; + - `pref:'low'` moves an exit to rank 4. +- **Pushing:** exits are sorted by distance once per POP. Traffic goes along `walkI(SPP[c],ci,e.ci)` and is limited by `l.res`, `NRES` and `e.cap-e.used`. +- **Recording:** each push calls `carry(l,e.ek,NN+3,…)`. `NKN` is always `NN+4` (`:130`), and that column is named `'players'` at `:16`. +- **Effects:** + - Transit p95, hot ports and link loads include player traffic, so peering saves transit money. + - `R2.mp={dem,srv,peer,lost,full,by}` records the totals. + - The pass runs after every catalog flow, so `R.served`, `R.demand`, moods, levels, `peerShare` and Tier 1 never change. + +**Cost of a de-peering war:** +- `computeMoney` applies `V.eyeballs *= 1 - mp.lost/(demand+mp.dem)`, where `lost` is traffic with no route at all. +- Two transit-free Tier 1 players who won't peer cannot reach each other: catalog Tier 1s don't pass on routes they learn from peers. Each loses up to 2% of eyeball revenue, which is real Level 3 vs Cogent drama at a bounded cost. Neither loses Tier 1. +- Two eyeball players who don't peer pay transit p95 for each other's traffic. + +**Clique star (cosmetic):** card `cq=1` when you are Tier 1 and reach every player whose card says `t1` by your own PNI or IX session. The leaderboard sorts the star first. + +**De-peering:** `end` the deal. Each side removes its rows 7 own days after it first sees the end. + +### 2.4 Competition + +**Overlap:** `clComp` (`75-customer-lifecycle.js:30`) also counts rival players whose card POPs cover the customer's cities. The rolls stay hash-stable (`clR`). + +**Poaching:** +- `clLeave` (`:64`), for "cheap" or "multi" with a rival POP in the city, posts the customer to `/lost`. +- The server gives it to one rival, chosen by `hstr`, as a gift. +- The rival checks it with `okBiz`, `BIZ_T` and `rate ≤ catalog×mkt()×1.2`, then puts it in `S.offers` with `ref` set to the loser's name. + +**Tenders:** +- **Issue:** while at least two players are active (`idle` < 300 s), the server issues `{n, city}` every 5 real minutes. The city is seeded from the active players' POPs. +- **Content:** derived from `hstr(seed|n)` and the `BIZ_T` lists, so every client sees the same tender. +- **Bids:** a ratio r from 0.6 to 1.0. You can bid while paused, and an optional standing auto-bid covers your cities. +- **Closing:** after 10 real minutes, or once every active player has bid. Wall-clock time, because no game clock is shared. +- **Winner:** the best `(1.2-r)·sq`, where `sq` is served share. The tender goes into `S.offers` with `mp:1`, expiring in 10 own days, and is signed with the normal `accept`. + +### 2.5 Shared fiber + +**Waves and IRUs (`wave`/`iru` deals):** +- **Seller side:** books spectrum or pairs via `+mpSold(l.id)` in the three counters (`60-requirements.js:72,75`, `37-fiber-broker.js:16`). It earns `V.mp += rate×(fiberOk?1:0)`. +- **Buyer side:** an `S.links` row `{kind:'wave'|'df', own:false, mo:price, mp:deal}`, which copies cut/eqDown/ready from `dl`. + +**Consortium seats:** built like `seatBuy` (`86-specialist.js:4`), at `ownCabCost(km)×myPairs/totalPairs` (`36-specialist.js:54`). + +**Deferred:** +- Joint exchanges, which need an id namespace (`isIx`, `50-sanitize.js:2`). +- An opt-in "Tier 1 must reach every Tier 1 player" rule. + +## 3. Server (`scripts/lib/mp-deals.js`, pure logic, with routes in phase 1's `scripts/lib/mp.js`) + +**The deal record** is public to the session, like PeeringDB. The session keeps a counter `dv`, bumped on every change. + +``` +{id:'d'+base36, k:'t'|'pni'|'ix'|'wave'|'iru', a, b, s (seller), at (city|ix|'a|b'), tier, n, price, slots, st, rev, t0, tl, te, by, why} +``` + +| from | event | to | allowed for | +|---|---|---|---| +| – | create `t` | `live`, or 409 `not_selling`/`no_pop`/`loop`/`dup`/`limit` | the buyer | +| – | create `ix` | `live` (b open and present) / `no` (b closed) / `offer` | a | +| – | create `pni`/`wave`/`iru` | `offer` | a | +| `offer` | accept / decline / withdraw / 7 days pass | `live` / `no` / `gone` / `gone` | b / b / a / server | +| `live` | end | `end` (`quit`) | a or b | +| `live` | a side's card never reports `ok` within 7 days | `end` (`unbuilt`) | server | +| `live` | no card from a party for 14 days | `end` (`idle`) | server | +| any open deal | a party leaves or is pruned | `end` (`left`) | server | +| `no`/`gone`/`end` | 7 days pass | deleted | server | + +**Errors:** every write sends `rev`. A stale `rev` or an illegal transition gets 409, and the wrong party gets 403. + +**Limits:** +- one open deal per (pair, kind, place); +- 10 open offers and 24 live deals per player; +- 300 deals per session; +- price 0.05–50, tier 0–15, n 1–8; +- 30 writes per minute per player. + +**Feed:** the server writes a line for each transition ("X sells transit to Y in Frankfurt", "X de-peered Y"). + +**Endpoints:** +- `POST /api/mp/sessions/:code/deals {k,to,at,tier,n,price?,slots?}` returns 201 `{deal,dv}`. +- `POST …/deals/:id {op,rev}` with `op` one of accept, decline, withdraw or end. +- `POST …/lost` reports a lost customer; `POST …/tenders/:n/bid {r}`; `PUT …/autobid`. +- The roster responses (`GET` the session, and `PUT` the card or save) add: + - `deals[]` (my deals, any state) and `dv`. Other players' links come from their cards' `pt`; + - `tenders[]` and my `gifts[]`; + - each player's `idle`: seconds since their card last carried a newer day. + +So nothing needs extra polling. + +## 4. Card fields beyond phase 1 + +Every field below is added to both `cleanCard` and `mpCardOk`. Phase 1's `transit` field stays catalog-only, because `NET_RE` would silently drop `mp:` ids. + +| field | content | +|---|---| +| `nv` | build version | +| `pt` | pids I buy transit from | +| `rs` | exchanges with my route server on | +| `tp` | my transit price, or null | +| `miss` | catalog ids I can't reach, biggest share first, ≤160 (a reach of 0.99 can still miss 72) | +| `on` | 1 if the internet of built-in networks can reach me: catalog transit, PNIs with every `t1Need()` network, or a seller with `on` | +| `mr` | pids I reach | +| `eye`, `biz` | Gbps, 2 significant digits | +| `sq` | served share | +| `sv` | `{city: delivered share}` where I sell, ≤64, in 0.05 steps | +| `dl` | `[{id,u,q,g,ok,up,cut,eq,rdy}]`, one per live deal, ≤64 | +| `cq` | clique star | + +The card grows by about 4 KB at most. ASNs need nothing new: phase 1 already sends the catalog ASNs to avoid (`mpAvoid`, `mp.js:238`). + +## 5. Client day flow (`src/game/60-features/89-player-deals.js`, new) + +Phase 1's `mpRosterOk` is extended to whitelist `deals`, `dv`, `tenders`, `gifts` and `idle` (plus new `MP_FEED` kinds). The validated roster stays in `MP.roster`, never in S. `mpDay(d)` runs first in `dayPre`, right after `S.day++` (`10-day-tick.js:10`): + +1. **Copy changes in.** If `dv`, `idle` or any card changed, rebuild `S.mpx.who` and `S.mpx.deals` from the validated data, with values in steps. Then recompute `k`/`xk` and call `mpBind(S)`. +2. **Reconcile each deal:** + - **live, not `made`:** create my row (`S.pops[at]`, `portOk`, `portGate`, `spend(setup)`) and set `made`. If that fails, the deal waits under a "waiting on you" badge, with no client timer; the server ends it as `unbuilt`. + - **live, `made`, but the row is gone** (for example after a decommission, which `decomImpact` warns about): post `end` with `why:'gone'`. Decommissioning a city where I sell also ends those sell deals. + - **ended** (or missing from the server's list): set `until=d+notice` (14 own days for transit, 7 for the rest) and remove the rows when it passes. +3. **Copy the coupling values onto the rows:** + - on transit rows: `t.mpf` and `t.down`; + - on PNI rows: their side's capacity and whether it is ready; + - on link rows: cut, eqDown and ready; + - on my seller entries: `u`, `q` and whether the buyer is active. +4. `compute()` runs (worker or not), then `dayPost`, then phase 1's push carries the new fields. `dl` comes from yesterday's R. + +**My own clicks** (`mpOffer`, `mpAnswer`, `mpEnd`, `mpSell`, `mpBid`) apply as soon as the server answers, with `mpApply();after()`. If `RW.job` is set, they apply at the next `dayPre` instead. + +Multiplayer code never calls `Math.random`. + +## 6. Saves and sanitize + +**New field:** `S.mpx = null | {k, xk, dv, who:[≤11], deals:[≤64]}`. `deals` holds only my own deals. Cones, `on` and who-buys-from-whom come from `who[].pt`. +- `mpx:null` is the default in `newGame` (`80-new-game.js:4`), so old saves get null. + +**Order in `sanitize`:** move phase 1's `mpSanitize(s)` from `50-sanitize.js:113` up to `:21`, then call `mpxSanitize(s)`. Both now run before `opsSanitize` (`:22`) and every `isNet` filter (`:34-35, :54-55`). + +**`mpxSanitize`:** +- **When it is null:** unless `MP_API` is stamped and `s.mp` is valid in normal mode. An imported multiplayer save then just loses its player rows. +- **Players (`who`):** pids checked against the regex, unique, never my own. +- **Names:** stripped like the phase 1 server does (control characters and `<>&"'\``, at most 32). They are not escaped, because `labOf`/`hotPorts` print catalog names unescaped too. +- **Ids:** pass `isCity`/`isIx`. `miss` must be catalog ids, and `pt`/`mr` must be pids in `who`. +- **Numbers:** clamped and stepped. +- **Deals:** kinds from a whitelist, the other party present, `at` checked, `tier` within `PORT`, the price at most `mpCap`. +- **Loops:** `pt` edges are dropped in (buyer, seller) pid order. +- **Keys:** `k`/`xk` are recomputed, never trusted. +- **Last step:** it ends with `mpBind(s)`. + +**`mpOrphans(s)`** runs right after `:113`: +- it drops tagged `transit`/`pni`/`links`/`peers` entries that have no deal; +- it drops untagged rows on `mp:` networks; +- it strips `mp`/`mpp`/`mpf` from untagged rows, so a forged `mpp:0` gives no free transit. + +**`RK_SKIP`:** `mpx` stays off it, because `compute` reads it. Phase 1's `mp` stays on, because `compute` must never read it; the `route-skip.test.js` proxy enforces both. + +**Size:** at most +15 KB per save. + +## 7. Ordered steps + +Each step ends with `npm test` green, the i18n check clean, MCP classification, a CHANGELOG bullet and perf numbers. + +**1. Dormant core (no server, no UI).** +- `45-player-carriers.js`. +- `80-new-game.js:4`; `50-sanitize.js:21`/`:113`. +- `30-compute.js`: + - `:28` bind check; + - `:53-54` `mpf` and `miss`; + - `:61` `if(!p.mp)`; + - `:62` `*(p.mp?mpPniF(p):1)`; + - `:70` `xk`; + - `:95` `mpDem`; + - `:130`/`:16` the players column; + - `:375-382` `V.mp`. +- `40-billing.js:9`; `40-ports.js:21`. +- **Guards:** + - `lagT`/`lagP`/`cancelTransit` (`20-pops-transit-ix.js:6,7,11`), `unpeer`/`cancelPni` (`40-sites-peering-caches.js:16,30`) and `downT` (`21-ix-downgrade.js:6`) route to `mpEnd` or a renegotiation offer; + - `cleanPipe` (`80-security-and-china.js:8`) refuses `mp` rows; + - `trExits` (`50-traceroute.js:20`) applies `miss`, and `hotPorts` (`80-hot-ports-and-rank.js:4`) applies `mpf`; + - `connUp` (`40-connections.js:18`) shows no upgrade for these rows; + - the intern (`95-standing-orders.js:155,180,250`) skips `mp` rows; + - `upLink`/`rmLink`/`setStandby` (`60-links.js:2,6`). +- `src/agent/30-docs.js`. +- **Tests:** `mp-sanitize`, and `mp-transit` with `S.mpx` injected. + +**2. Deals and transit, end to end.** +- `scripts/lib/mp-deals.js` and the `mp.js` routes and timers. +- The card fields. +- `89-player-deals.js`, called from `10-day-tick.js:10`. +- `90-actions/92-player-deals.js`, classified in `src/agent/20-commands.js`. +- `95-modals/49-player-deals.js`: a Deals tab in the session sheet, a bottom sheet at 360 px. +- `90-noc-window.js:45`; `decomImpact`; all six languages. +- **Tests:** `mp-deals-server`, and `mp-transit` with `fetch` mocked. + +**3. Peering and player traffic.** +- `pni`/`ix` deals, `mpIx`, and `36-mp-traffic.js` with its hook at `:343`. +- The `V.eyeballs` factor, `R.mpSess` and the star. +- Player Gbps in the PNI list and the connections list. +- **Test:** `mp-peering`. + +**4. Competition:** `clComp`, poaching, tenders. + +**5. Shared fiber:** waves, IRUs, seats. + +**6. `scripts/mp-soak.js`:** opt-in, never part of `npm test`. + +## 8. Performance budget + +**Single-player.** Each `compute()` costs one string comparison, one property read per transit and PNI row, and one more `ACN` column per edge. +- `npm run perf -- --base-ref origin/main` must stay within noise (≤1%). +- `emptyR()` gains no keys; `R.mp`, `R.mpSess` and `V.mp` exist only when `S.mpx` is set. + +**Multiplayer.** The carrier mechanics are measured above: 32.3 → 33.2 ms. A new `big-network-mp` workload (the fixture plus 11 players and 20 deals, built by `scripts/perf-mp-fixture.js`) must meet: +- `mpTraffic` ≤ 1.5 ms (one exit sort per POP, then O(players×exits), with paths cached for each pair of cities); +- `mpBind` ≤ 0.1 ms; +- warm `compute` ≤ +5% compared with the same fixture without players. + +A cold route happens only when `xk` changes, at most once a game day. Report jsdom and `--browser` numbers. + +## 9. Test plan + +**`mp-deals-server`** (spawned server, temporary directory): +- every transition and who may make it (403/409); +- the policy outcomes for `ix` (live, no, offer); +- 409 `loop` on A→B→C→A; +- the limits; +- the `unbuilt`, `idle` and `left` ends, and expiry, with an injected clock; +- card validation; +- restart persistence. + +**`mp-transit`:** +- the buyer's exit and label, `transitMo` using `mpp`, `isTier1` false; +- `mpf` scales capacity, and `miss` blocks reach and changes `xk`; +- the seller's demand rises by `u`, `V.mp` follows the formula, and the seller keeps Tier 1; +- an idle buyer gives zero load and revenue; +- a forged `mpp` is stripped; +- worker parity (the `route-worker.test.js` pattern); +- no `Math.random` calls; +- the inbox is never applied mid-day. + +**`mp-peering`:** +- a PNI carries traffic only once both ends are ready; +- de-peering raises transit p95; +- two unpeered Tier 1 players lose revenue, and both stay Tier 1; +- 24 player PNIs leave `R.sessions` unchanged; +- C reaches B through A's cone; +- the route-server rule is two-sided; +- the PNI lead time is stable. + +**`mp-sanitize`:** +- fuzzing does not throw and stays bounded: 1,000 entries, HTML in names, loops, unknown ids, `mp:` rows in a single-player save; +- old saves load; +- a multiplayer-to-single-player slot switch clears every `mp:*`; +- `` stays text in the panels and the Deals sheet at 360 px. + +**`mp-competition` and `mp-fiber`:** +- rival players raise `clComp`; +- gifts are validated; +- every client derives the same tender; +- cuts are copied; +- a bought wave can't be upgraded. + +**Existing gates:** +- `route-skip` (same digest with `S.mpx` null or empty), `compute-idempotent`, `routing-reference`, `route-cache`; +- `gameplay-rules`, plus a check that no `mp:` id is in `NETS`/`NSH`; +- `persist`, `save-size`, `save-text`, `mcp-commands`, `i18n`, `pages`, `build`, `multiplayer`, `mp-server`. + +**Soak test (the "hardcore" local run):** +- The server plus 12 seeded jsdom players in `worker_threads` (about 0.5 GB each, with `--jobs` capped). +- Each plays about 2,000 days at its own speed, with a random agent making, answering and ending deals. +- During the run: server restarts, reloads through `migrate`, a player leaving, tampered cards and a burst of 409s. +- It checks: no errors or NaN, an acyclic deal graph, each seller's `V.mp` matching the buyer's bill, every save reloading, and a single-player control game keeping `main`'s digest. + +## 10. Failure modes + +| Case | Handling | +|---|---| +| The other player is paused or offline | Their last card stands: an idle buyer brings no load or money, and a buyer keeps the seller's last values. After 14 days the server ends the deal (`idle`) | +| A player leaves | The deal ends (`left`) and each side tears down after notice. `mpBind` drops the carrier on the next sanitize | +| Server down | Play goes on with the frozen `S.mpx`. New deals fail with one toast | +| Two devices | Phase 1's seq/409 picks the save; `made` settles the rows | +| Version skew | Unknown `miss` ids are dropped; networks the seller's build lacks count as reachable | +| Tampered card or save | Whitelists, clamps, steps, local price caps, orphan stripping. Money comes only from local formulas | diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md new file mode 100644 index 0000000..deaef46 --- /dev/null +++ b/docs/plans/next-session.md @@ -0,0 +1,55 @@ +# What is left (as of 2026-11-07) + +Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard, multiplayer +phase 1, dark mode (#80), IPv4 address space (#150), express fiber (#58) and satellite teleports (#83). Everything below is +planned or known, not built. + +## Promised and not done yet + +1. **Router model and line system set in one place only.** The build standard (`S.popStd.g`, `S.popStd.sys`) and two + standing-order settings say the same thing: the `routers` order's `model` (upstream 1e7638c) and the `optup` order's + `sys` (upstream 647e302). Neither ever steps down, so they do not fight, but a player can pick two different targets. + Plan: the Build standard sheet becomes the only place to pick them. The `routers` order reads its model from the + standard, and `optup` its line system (their lists turn into a line "from the build standard: X, change"); sanitize + moves an old `model`/`sys` setting into `S.popStd` when the standard has none. +2. **One owner per fiber for line systems and optics.** `std` (sys/opt targets: a quiet fiber, or a parallel link with + room) and `optup` (one full routing without the fiber, one a night) can each darken a fiber in the same shift. Let `std` + use `optup`'s check (`opsDarkOk`) for line-system swaps, or skip fibers `optup` is working on. Today `std` also holds + any fiber that carries an express with traffic; `opsDarkOk` would handle that case by itself. + +## Next features + +3. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative + over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, + peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. +4. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is + the busier direction. It comes after #58 because both touch link capacity (express channels now count too). + +## Known limitations of what shipped + +- **Multiplayer:** other players' POPs are not drawn on the map (no clean hook yet); cards are what each browser reports, + the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone + landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every + player shares one address for the rate limits. +- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full; a wave + the standard just upgraded can still be handed back the same day by `decom` if a bigger parallel link carries it. +- **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG + and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser. +- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income + is not in the investor revenue share; blocks granted to old saves can be sold after two years (a one-off windfall); + CGNAT annoyance costs refunds but does not slow broadband growth; the NOC window's address-space button does nothing. +- **Express fiber (#58):** splicing a whole fiber pair through a city was left out on purpose (every fiber end is a POP; + expresses cover the need); loss and MTU incidents on a fiber do not reduce the expresses on it; the fiber panel's + "n of max channels" line does not count express slots (the Express section does); regen sites added later do not charge + regen cards for express channels. +- **Satellites (#83):** no WISP zones, no satellite incidents (rain fade, sun outage), no footprints on the map, no + satellite tab in the drag-to-link window (ordering is from the city panel); GEO/MEO losses and prices are design + numbers; well-cabled islands (Wellington, Hobart) also count as "can be served"; MEO needs 5° elevation (10° would drop + 416 pairs); Pitcairn's $120k satellite grant stays Pie-only. + +## Housekeeping + +- `npm run perf -- --browser` needs Chromium (`sudo pacman -S chromium`, then `PERF_CHROME=/usr/bin/chromium`); only the + jsdom benchmark has been run. +- Upstream release tags are not on `vanvik` yet: `git push vanvik --tags` if wanted. +- The merged worktrees under `.claude/worktrees/` and their `worktree-wf_*` branches can be removed.