From 8e1f2d66a5ffe42945b7cd4e5182beec9939f200 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sat, 7 Nov 2026 01:06:30 +0100 Subject: [PATCH] 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: {},