Compare commits

..

8 commits

Author SHA1 Message Date
jvanvik
b533f3baa8 Plans: multiplayer phase 2 design, and what is left after this round
Some checks failed
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
Container image / test (push) Waiting to run
Container image / publish (push) Blocked by required conditions
Auto-release / release (push) Has been cancelled
2026-11-07 01:12:23 +01:00
jvanvik
e1ae8e0164 Satellite teleports: GEO and MEO circuits for islands and remote towns (#83)
The early and mid-game satellite option, before Pie in the Sky. Build a
teleport at a POP that a satellite sees, then rent capacity from it to
a remote POP: GEO (Intelsplat, Kacophony) needs no capex but costs a lot
a month per Gbps, 1-10 Gbps at about 600 ms; MEO (O3bservant) needs
tracking antennas at the teleport and gives multi-Gbps at about 130 ms
where both ends are under its ring, at least 5 degrees up. Coverage
follows each bird's footprint by ocean region. Latency feeds the latency
model: users who ride a satellite notice, in proportion to the share.

A circuit beside a cable goes on standby, whichever came first, and
carries only what the cable cannot: the classic single-cable island
backup. Satellites are not subsea links for covenants, scenario goals or
subsidies (Pitcairn's UK grant needs a cable). Express fiber and the
build standard leave satellite circuits alone.
2026-11-07 01:12:23 +01:00
jvanvik
8e1f2d66a5 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.
2026-11-07 01:06:30 +01:00
jvanvik
eac0604300 IPv4 address space: scarce, bought, leased, leased out; IPv6 is free (#150)
A rule (ip4), on in On-call and BGP at 3 a.m., off in the gentler
presets, sandbox and puzzles; scenarios only when they opt in. You start
with a /21 from the registry, sized so the early game never notices
(a gameplay-rules F1 test plays six start cities for 50 days). Business
customers need a block by kind and size; broadband homes take what is
left and the rest go behind CGNAT, which costs a box per home and
annoys some customers. An offer that does not fit cannot be signed and
says why, and a customer that cannot grow at renewal stays its size.

The bank's Address space section buys and sells blocks on a transfer
market with a gentle trend, leases blocks in, and leases spare blocks
out for monthly income, in real CIDR sizes (/24 to /16), at most 256
blocks (what a save keeps). Old saves get what they already use, plus
room, so nothing changes on load. The dashboard's AS box now lists the
blocks you announce.
2026-11-07 01:04:00 +01:00
jvanvik
2cd6b71198 Dark mode: Light, Dark or Auto under Settings › Theme (#80)
A device preference (localStorage sot-theme, never in the save), applied
by a small script in <head> before the first paint, so there is no flash;
Auto follows prefers-color-scheme live, and a choice reaches other tabs
and the NOC window. Panels, HUD, drawers, toasts, modals, the phone tab
bar, charts, puzzles, the architect and Pie Control take their colours
from custom properties with night values (AA text contrast); light tints
keep their old colour as the fallback, so the light look is unchanged.

Both map renderers read a light and a dark palette (96-map/15-palette.js):
sea, land, clouds, coastlines, labels and the tube outline. A theme
switch repaints the cached layers once (the WebGL land buffers are
rebuilt once); nothing changes per frame. The multiplayer leaderboard's
own row and the menu rank badge follow the theme too.
2026-11-07 01:01:50 +01:00
jvanvik
95aa9b6532 Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard
Off unless the page is built with MP_API set (MP_API=/api/mp npm run
build): a plain build has no door, no chip and makes no requests. The
session server is scripts/mp-server.js (npm run mp), plain node:http,
which can also serve the built site so one process sits behind the
reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups.

A session has a six-character code, one seed and one rules preset, so
every player starts in the same world, and up to twelve players with
their own AS numbers. Saves go to the server on a new game day at most
every 15 s and when the page hides, ordered by a sequence number (409 on
a stale push, and the player picks which one to keep). Tokens live in
localStorage, never in the save; the server keeps only their hash. A
#mp= link moves a network to another device. The session panel shows
the leaderboard, the feed and a short chat; each player's public card
(tier, POPs, links, exchanges, transit, peak, customers, score) carries
what in-game peering between players will need next.

Server limits: body sizes, one upload per player, uploads per address
and in total, sessions per hour, wrong-code lockout; addresses counted
per IPv6 /64, X-Forwarded-For only with --trust-proxy.
2026-11-07 00:42:39 +01:00
jvanvik
2b48a6ad65 A build standard for the whole network, kept by the intern
One sheet sets the target state for every POP, port and fiber: router
model and count, a second building, a generator, LAG members (split over
both buildings), an exchange port wherever there is one, PNIs spread
over the cities that pay, the line system, the fastest optics that reach
and wave sizes. S.popStd keeps its name; an old {g,rt} standard loads
with the same meaning.

One read-only plan prices every job with the game's own cost helpers,
POPs busiest first, then ports, then fiber hottest first. The sheet's
summary, the MCP quote, "Bring everything up now" and the new "Keep to
the build standard" order all use it, so the quote is what the click
spends. The order works a few jobs a shift through the budget and the
cash floor: a second router before a swap on a busy POP, no generator
under a nogen covenant, no De-Kicks, a line system swap only where the
fiber is quiet or a parallel link carries it, one a shift. New POPs get
the POP part of the standard, and the template's kit no longer pays for
it twice. opsMoNow counts generators and second buildings.
2026-11-07 00:41:42 +01:00
Frederic Jung
647e302f1c
The intern upgrades optical transport
A new standing order, Upgrade optical transport. On fiber that is full
and runs above a level, it moves the line system up one size (the
Upgrade click), or trades the smallest lit channels for the biggest
optic that fits, one at a time (setChCount; the old optics go to
spares). With a line system chosen, every fiber below it is moved up,
both steps in one night if need be, cold or not.

A line system swap is a day without the fiber, so only where another
live path joins its cities, no customer rides it, and routing the
network without it serves as much as today (one compute, measured
against today's routing). One fiber is tested and swapped a night,
and a fiber that failed is left alone for a week (not saved), so the
order costs at most one routing more, and only on a night with a
fiber to try.
2026-11-06 18:26:24 +00:00
141 changed files with 8210 additions and 352 deletions

View file

@ -24,7 +24,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| --- | --- | --- |
| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. |
| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. |
| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, or reach it through a pie dish; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. |
| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. |
| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. |
| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. |
@ -33,7 +33,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| Id | Rule | Why |
| --- | --- | --- |
| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. |
| N2 | Names are puns: no network, cable, exchange, data center, router, optic, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. |
| N4 | No upstream cycles. | Cones must be trees, not loops. |
| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. |
@ -46,7 +46,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| --- | --- | --- |
| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. |
| M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. |
| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. |
| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4 and CGNAT (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. |
| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. |
| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. |
| M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). |
@ -64,7 +64,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| Id | Rule | Why |
| --- | --- | --- |
| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. |
| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. |
| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. |
| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. |
| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. |

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
node_modules/
_site/
.DS_Store
mp-data/

View file

@ -6,7 +6,14 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player.
- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80).
- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58)
- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order.
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section.
- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150).
## [3.0.0] — 2026-11-06

View file

@ -38,13 +38,13 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` |
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the theme (light, dark or Auto: `15-theme.js`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=<slot>`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints |
| `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals |
| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation |
| `96-map/` | The canvas: resize, the map's colours per theme (`15-palette.js`), land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation |
| `99-loop.js` | `frame()` and `boot()` |
`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone.
`src/styles/` holds the CSS the same way: base, the dark theme's colours (`05-theme.css`), HUD, drawers, toasts, modal, tablet, then phone.
`src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays
through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it);

211
docs/MULTIPLAYER.md Normal file
View file

@ -0,0 +1,211 @@
# Multiplayer (self-hosted copies)
The game at [seriesoftub.es](https://seriesoftub.es) is hosted on GitHub Pages and nowhere else
([ADR 0001](adr/0001-github-pages-only.md)), so it has no server and no multiplayer. This page is for a copy you host
yourself: there, a small session server that ships with the source (`scripts/mp-server.js`) lets players build their
networks side by side.
A plain `npm run build` is unchanged: the page has no multiplayer door, no chip and makes no request for it. Multiplayer
is switched on only when the build is told where the session server lives.
## What it does (phase 1)
- **Sessions by code.** One player starts a session from the title screen (Multiplayer: their network's name, home city
and rules preset, optionally a session name) and gets a six-character code such as `K7Q-2XD`. Friends join with that
code. Codes use Crockford's base32 (no I, L, O or U); they are case-insensitive, and the dash is optional.
- **One world.** Everyone in a session plays a Normal game with the creator's rules preset (Best Effort, Change Freeze,
On-call or BGP at 3 a.m.) and the session's random seed, so day 0 is the same world for all. The session hands each
player an AS number from 200000–214999 that nobody else in the session and no network on the map uses. Each network
is still simulated in its own player's browser; from the first different click on, the worlds drift apart.
- **Saves on the server.** Each network's save goes to the server on a new game day, at most every 15 seconds (gzipped
when it is big), and when the page is hidden or closed if anything changed since the last push (a paused game's
building too). Opening the network on any device fetches the server's save first and loads it if another device
played on.
- **Seeing each other.** Every push carries a small public *card*: day, tier, POPs, links between them (with capacity),
exchanges, transit providers, peering policy, reach, peak and served traffic, customers, revenue per month, cash as an
order of magnitude, and a score. The session panel (the 🌐 chip in the top bar, or the menu) shows the leaderboard
(Tier 1 first, then Tier 2, then traffic served), a feed (joins, leaves, Tier 2, Tier 1 and who got there first) and a
chat. While the panel is open it refreshes every 5 seconds; otherwise the roster rides along with each push.
- **Moving to another device.** The panel's "Move to another device" holds a link `https://your.host/#mp=CODE.pid.token`.
The part after `#` never reaches any server. Opening it (or copying the link) first sends this device's latest save,
and opening the link loads the network into that browser. Treat it like a password: anyone with it can play as you.
A browser keeps the link's token only once the server has accepted it, so a wrong or mistyped link never replaces the
one it already has; when the server cannot be reached, the link stays in the address bar for a reload to try again.
- **Offline.** The game never waits for the server. When it cannot be reached, the game says so once, keeps playing and
tries again later (30 s, then 1, 2, 4, at most 5 minutes apart; the open session panel keeps looking every 5 seconds
without stretching that wait).
Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries
what that will need (POPs, links, exchanges, transit, peering policy, reach).
## Build
```bash
MP_API=/api/mp npm run build # _site/ with multiplayer on; the page talks to /api/mp on its own origin
```
`MP_API` must be a path on the same origin (letters, digits, `/`, `_`, `-`; no trailing slash, and not starting with
`//`, which a browser reads as another host). Anything else fails the build. Without it, or empty, the build is the
plain one.
## Run the server
```bash
node scripts/mp-server.js --site _site --data /var/lib/tubes-mp --port 8090
# or: npm run mp -- --site _site --data /var/lib/tubes-mp
```
One process serves the API under `/api/mp` and, with `--site`, the built game too (like GitHub Pages would: `/` is
`index.html`, a missing file gets `404.html`, nothing outside the folder is ever served). It binds `127.0.0.1` by default:
put a reverse proxy with HTTPS in front. Plain `node:http`, no dependencies beyond Node 20 or newer.
| Option | Default | |
|---|---|---|
| `--port N` | 8090 (or `$PORT`) | port to listen on |
| `--host H` | 127.0.0.1 | address to bind |
| `--data DIR` | `./mp-data` | sessions and saves; created if missing |
| `--site DIR` | none | also serve the built game from DIR |
| `--base PATH` | `/api/mp` | the API's path; must match `MP_API` |
| `--prune-days N` | 60 | sessions nobody touched for N days are deleted, at startup and daily |
| `--max-sessions N` | 1000 | sessions on this server |
| `--max-players N` | 12 | players per session (at most 12) |
| `--create-per-hour N` | 10 | new sessions one address may start per hour |
| `--sessions-per-hour N` | 100 | new sessions per hour on the whole server, from all addresses together |
| `--trust-proxy` | off | take the client's address from `X-Forwarded-For` (only behind your own proxy) |
| `--verbose` | off | one log line per API request (never tokens) |
Behind a reverse proxy every request comes from the proxy's address, so the per-address limits only mean something with
`--trust-proxy` (the server then uses the last address in `X-Forwarded-For`, the one your proxy added); without it, all
players share one address's limits, such as 4 save uploads at once. An IPv6 address counts as its /64, since one phone
or home usually has a whole /64 to itself.
To try it locally without a build: `npm run dev -- --mp` runs the API inside the dev server (sessions in `mp-data/`) and
turns multiplayer on in the dev page. Open a second window (a private one counts as another browser) to be the second
player.
### nginx
```nginx
server {
listen 443 ssl http2;
server_name tubes.example.org;
ssl_certificate /etc/letsencrypt/live/tubes.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/tubes.example.org/privkey.pem;
client_max_body_size 5m; # a save is at most 4 MB
location / {
proxy_pass http://127.0.0.1:8090; # the game and /api/mp, from the one process
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Run the server with `--site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy`.
### Caddy
```caddy
tubes.example.org {
request_body {
max_size 5MB
}
reverse_proxy 127.0.0.1:8090
}
```
Caddy sets `X-Forwarded-For` itself and gets the certificate on its own; run the server with `--trust-proxy` as above.
### systemd
```ini
[Unit]
Description=Series of Tubes multiplayer
After=network.target
[Service]
ExecStart=/usr/bin/node /srv/tubes/scripts/mp-server.js --site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy
User=tubes
Restart=on-failure
StateDirectory=tubes-mp
[Install]
WantedBy=multi-user.target
```
## Backups
Everything is in the data folder: `<CODE>.json` per session (settings, players, cards, feed, and each save's number) and
`<CODE>.<pid>.save` per player's save (its text exactly as the game sent it). Every write goes to a temporary file that is then renamed over the old one, so a
copy of the folder (`rsync`, a snapshot, `tar`) taken while the server runs holds whole files. Restore by stopping the
server, putting the files back and starting it again. A player's token is stored only as its SHA-256, so a backup cannot
be used to play as anyone.
## Limits
- 12 players per session, 1000 sessions per server (configurable).
- A save is at most 4 MB of text (the game gzips anything over 32 kB: the big test network, 236 kB of JSON, goes as about 50 kB). Other
requests are at most 16 kB.
- Chat lines: at most 200 characters, one a second and six per 30 seconds per player. The feed keeps the last 100 lines.
- Per address and hour (an IPv6 address counts as its /64): 10 new sessions, 60 joins, 120 wrong codes (after that,
every code is refused for a while from there, so guessing codes gets nowhere; a player who sends their own session's
code with its token is never refused for it). At most 100 new sessions an hour on the whole server.
- Saves and cards: one save upload at a time per player (another one meanwhile gets 429), at most 4 at once from one
address and 16 on the whole server (503 with `busy: true` beyond that; the game then tries again a little later,
quietly), and per player at most 20 saves and 60 cards a minute (the game sends one every 15 seconds at most). A
save's body must arrive within two minutes. A card alone is written to disk within two seconds, together with any
others that came in meanwhile.
- Network names: at most 32 characters; control characters, `<`, `>`, `&`, quotes and backticks are removed. The page
escapes everything other players wrote anyway.
- A page that is being hidden or closed can only send 64 KiB (the browser's limit for such requests, counted in bytes),
so a network whose save does not fit sends its card alone then; its save goes with the next push from that device.
## How saves stay in order
Each network in a session carries a save number (`S.mp.seq`). When a save is due to go to the server, the game picks
the next number before it writes the save, so the save kept in the browser and the one sent carry the same number;
reopening the network then finds nothing newer on the server unless another device pushed one. The server refuses a
number that is not newer than its own (HTTP 409, with its number), and only counts a save once it is on disk. Then the
player is told once that the network moved on elsewhere and chooses: load the newer save from the server (only one at
least as new as the server said it had: never an older one), or keep this one (at the end of the current game day it
goes with `force` and a number past the server's).
The token is never part of the save: it lives in the browser's storage under `sot-mp:<code>:<pid>`. An exported or
imported save keeps its session but cannot talk to the server without the token (the game says it is no longer in its
session and plays on alone).
## API
JSON in and out, same origin, no cookies, no CORS headers. Every call but starting and joining needs
`Authorization: Bearer <pid>.<token>`. Errors are `{"error": "…"}` with a fitting status (400, 401, 404, 405, 409, 413,
415, 429, 503).
| Call | Body | Answer |
|---|---|---|
| `POST /api/mp/sessions` | `{net:{name,home}, preset, title?, avoid?}` | `201 {code, pid, token, seed, asn, preset, color, title}` |
| `POST /api/mp/sessions/:code/join` | `{net:{name,home}, avoid?}` | the same, for the joiner (`409 {full:true}` when full) |
| `GET /api/mp/sessions/:code` | | `{code, title, preset, seed, created, players:[{pid, name, asn, color, card, seen, joined}], feed}` |
| `PUT /api/mp/sessions/:code/card` | `{card}` | the roster |
| `PUT /api/mp/sessions/:code/save` | `{seq, at, data, card?, force?}` | `{ok, seq, at, roster}`, or `409 {seq, at}`; `429` while another one is on its way, `503` when the server is busy |
| `GET /api/mp/sessions/:code/save` | | `{seq, at, data}` (your own save only) |
| `POST /api/mp/sessions/:code/feed` | `{text}` | the roster |
| `DELETE /api/mp/sessions/:code/me` | | `{ok}`; the session goes when its last player leaves |
`avoid` lists AS numbers the server must not hand out (the game sends the map's own networks in that range). `preset` is
one of `soft`, `freeze`, `oncall`, `bgp`. `data` is the save as the game writes it: JSON text, or `gz:` and base64.
The card, as the server keeps it (unknown fields are dropped, numbers clamped, ids checked for shape; the page checks
the ids against its own catalogs again): `day`, `tier` (`t1`, `t2`, `t3`), `t1`, `lvl`, `pops` (city ids), `links`
(`[a, b, Gbps]`, up to 300), `ix`, `transit` (network ids), `ppol` (`open`, `selective`, `closed`), `reach` (0–1),
`peak`, `served` (Gbps), `cust`, `rev` (per month), `cashB` (−1 in debt, else the power of ten of the cash), `score`.
Cards are what each player's browser says: nothing on the server checks that a network really is that big.
## Code
- Server: `scripts/lib/mp.js` (the API and storage), `scripts/mp-server.js` (the command line and the static site).
- Game: `src/game/60-features/89-multiplayer.js` (state, sync, the card, the `#mp=` link),
`src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js`
(actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`.
- Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`.

View file

@ -0,0 +1,404 @@
# Multiplayer phase 2: players inside each other's simulations
Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`.
**Conventions:**
- Line numbers are `main` at `1e7638c`.
- Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`.
- Everything runs only when `MP_API` is stamped and `S.mpx` is not null. The plain GitHub Pages build is unchanged (`pages.test.js`, `build.test.js`).
## 1. Starting point and grafts
**Base: "contracts".** It had the best totals in two of the three scorings, and the best feasibility and risk.
- Players are pseudo carriers `mp:<pid>`, registered only in `NET` with single-entry `CONE`/`CONE_S`/`DOWN`/`ANC`.
- `NETS`, `NET_IDS`, `NSH`, `t1Need()`, seen/grace and the gameplay-rules tests never see a player.
- No catalog id contains `:`, and nothing iterates `NET`.
**I checked this on big-network** (a throwaway probe, not committed): a buyer row on `mp:p1` in `S.transit` plus a player PNI, through `compute`, 5 day ticks, the intern, every panel and tab, traceroute, `t1Why`/`isTier1` and a `migrate` round trip.
Results:
- No errors anywhere.
- The rows were kept while registered and dropped once unregistered.
- Warm compute went from 32.3 to 33.2 ms (median of 25 alternating runs).
- `R.sessions` rose by 1. That confirms the exploit fixed below.
**How each fatal flaw the judges found is removed:**
| Judged flaw | Fix |
|---|---|
| The seller's `S.biz` row is exposed to dropBiz, decommission, ddosTargets, Pie moods and the mood loop | The seller side is a deal entry read in exactly two places, demand and money (nets) |
| Peering is cosmetic, yet player PNIs count toward `isTier2`/`t1Club` | Player traffic ships with peering (§2.3). Player sessions never enter `R.sessions` |
| Health is all or nothing, and bought transit reaches every network | A capacity factor (`t.mpf`) and a `miss` id list, from day one |
| A↔B transit loops | The server refuses with 409; clients drop loop links in a fixed pid order (nets) |
| A stale or alt buyer keeps paying the commit forever | The seller earns, and carries load, only while the buyer's clock runs. Prices are capped against the catalog |
| A bought wave can be upgraded past its agreed price | `upLink`/`rmLink`/`setStandby` refuse it (gameplay) |
| "An active deal with no row" is ambiguous | A per-deal `made` flag (§5) |
| `NKN` flips inside `compute()` | It is always `NN+4` |
**Grafted from the other designs:**
- From nets: the two-sided route-server rule; cones through players; PNI lead from `hstr`, with capacity set by the smaller side; the Tier 1 clique star.
- From gameplay: waves, tenders, poaching, consortium seats, notice on each player's own clock, and the LOA handshake.
**Rejected:** players as `NETS` entries (a mutable catalog, a rescaled `NSH`), reach bitmaps (they break between builds), a Tier 1 that depends on other players, automatic ratio strikes, and own-day timers that end a deal (they fire within seconds at 8×; own-day notice only paces each side's own teardown).
## 2. Mechanics
### 2.1 Pseudo carriers (`src/game/30-networks/45-player-carriers.js`, new)
`mpBind(s)` does three things:
1. deletes every `mp:*` key;
2. registers `{id:'mp:'+pid, name, asn, type:'t2', pol:'open', share:0, price:1, pops:[], up:[], ix:[], cc:'', col, blurb:tr('mp.another_player'), mp:1}` for each `s.mpx.who` entry;
3. sets `MPB.k`.
It runs at the start of every `sanitize` and every `compute()` (`if(MPB.k!==(S.mpx?S.mpx.k:''))mpBind(S)`). That covers the route worker, slot switches, imports, the failed-load rollback (`91-slots.js:105`) and puzzles. `nocWinState` (`94-dashboard/90-noc-window.js:45`) calls it too.
Because the carrier has `pops:[]` and is not in `NETS`, no catalog list ever offers a player:
- `sellsAt` and `buyTransit`;
- the intern's providers, `peerAll` and `pniAll`;
- the peering desk and own-exchange joins.
The `peer` action returns at `ixMembers(city).includes(net)` (`40-sites-peering-caches.js:14`).
### 2.2 Transit between players (the Tier 1 endgame)
**Who can sell:** a player publishes `tp` ($/Gbps/month) while `R.reach >= 0.99` and they have at least one POP.
**Buying:** "Buy transit from X here" posts a `t` deal (city, tier, LAG). The server makes it `live` at once (a price list is a standing offer) when all of these hold:
- the seller's card has `tp`;
- both cards list the city;
- there is no cycle;
- the limits hold.
**Price:** `min(tp, mpCap(city))`, where `mpCap = 2 × the cheapest catalog transitPerG(n,city,false)` there, or the catalog median if nobody sells there.
- Both sides compute it from the static catalog, ignoring each save's own `priceMul`.
- Both clamp again when they receive the deal.
**Buyer side: an ordinary `S.transit` row** `{id:'mt-'+deal, net:'mp:'+seller, city, tier, n, mp:deal, mpp:price}`.
- **Comes free:** the router port (`40-ports.js:20`), p95 history (`10-day-tick.js:37`), hot ports, traceroute, incidents, the panels, and `isTier1()===false`.
- **Billing:** `transitMo` (`40-billing.js:9`) uses `t.mpp` instead of `transitPerG(...)*S.priceMul`. The commit floor, `PORT.tmo` and `krFee` still apply.
- **Capacity:** `30-compute.js:53` multiplies by `t.mpf` = min(1, the seller's `sv[city]`/0.95), in 0.05 steps.
- **Reach:** `:54`'s `ok` also needs `!mm.has(n)` (the seller's `miss`).
- **Route cache:** the hash of every miss set joins the flags at `:70` (`+(S.mpx?S.mpx.xk:'')`), so `rcExitKey` rebuilds when a seller's reach changes.
- **Outage:** `t.down=S.day+1` when the seller's POP is down or the seller has left.
**Seller side: a `sell` entry in `S.mpx.deals`, never in `S.biz`.**
- **Load:** `mpDem(bizBw)` after the biz loop (`:95`) adds `u`, the buyer's reported use. It leaves by catalog share over the seller's own backbone, peering and upstreams; a Tier 1 carries it settlement-free.
- **Money:** `V.mp = Σ price × max(q, 20% of port) × min(1, sfOf(R2,city)/0.95)`. `q` is the buyer's p95; the last factor is the business customers' SLA credit. `V.mp` is added to `revMo` (`:382`) and to the revshare base (`:380`).
- **Port:** the seller's port counts in `portsUsed` (`10-catalog/40-ports.js`, after `:21`).
- **Idle buyer:** if the buyer's roster `idle` is ≥ 300 s (no newer game day reached the server), load and revenue are 0.
- A paused or closed buyer has no traffic to bill, and a fast seller cannot bill a frozen buyer.
- An alt account has to keep playing, and still pays at most the capped price.
**Loops:**
- The server returns 409 `loop` if the seller already buys from the buyer, directly or through others (a search over at most 12 players).
- Clients build the player-transit graph from `who[].pt` and add edges sorted by (buyer pid, seller pid), dropping any that closes a cycle, so every client drops the same edge.
- So reach passes down a reseller chain one push per hop, never settling at a false 1.
**Tier 1 stays defined by the built-in networks.**
- `R.reach` only sums `NSH`, so neither `isTier1` (`80-hot-ports-and-rank.js:20`) nor the mood check `R.reach>0.99` (`10-day-tick.js:51`) can depend on players.
- Buying player transit costs Tier 1, and `t1Why` already says so. Selling never does.
- Refusing to peer blocks nobody's win.
### 2.3 Peering between players, carrying traffic
**PNI (`pni` deal, always accepted by hand).** Each side adds `S.pni` `{id:'mn-'+deal, net:'mp:'+other, city, tier, n, mp:deal, ready:S.day+lead}`.
- **Lead time:** `lead = pniNow() ? 0 : leadDays(14 + hstr(deal+myPid) % 29)`, with no random numbers.
- **Cost:** each side pays its own `pniMo`.
- **Capacity:** the smaller of the two sides (theirs comes from `dl[].g`). It is 0 until both cards report `ok`: the LOA and cross-connect handshake.
**IX (`ix` deal).** The server makes it `live` if the responder's policy is open, `no` if closed, and `offer` if selective. Once live, both sides set `S.peers['mp:P@x']`.
**Route server:** no deal. P peers with me at `x` when both `S.rs[x]` and `P.rs ∋ x` hold and both policies are open. That is the same rule on both clients.
**Sessions:**
- `mpIx(x)` lists the player peers at an exchange. `ixSessions` (`20-exchanges.js:29`) stays catalog-only.
- At `30-compute.js:61`, player PNIs skip `R2.sessions++` (`if(!p.mp)`) and count in `R.mpSess` instead.
- So friends can never inflate `isTier2`/`t1Club`.
**Player traffic** (new `src/game/80-simulation/36-mp-traffic.js`). `compute.js:343` calls `mpTraffic({E,SPP,NRES,HAS,R2,carry,NN})` once, after `citySrv` (`:341-342`). The parts are handed in the way `ddosLoad` gets them (`:188`).
- **Demand:** each POP sends `cityEye[c]·w_P` to each active player P.
- `w_P = min(0.02, (biz_P + 0.3·eye_P)/75000)`, and `Σw ≤ 0.1`.
- **Exits that reach P:**
- rank 2: a ready PNI with P, or an IX exit with `mpIx(x) ∋ P`;
- rank 2.5: the same exits toward Q when P buys from Q, which gives cones through players;
- rank 3: player transit from Q when `P===Q` or `Q.mr ∋ P`, and catalog transit when `P.on`;
- `pref:'low'` moves an exit to rank 4.
- **Pushing:** exits are sorted by distance once per POP. Traffic goes along `walkI(SPP[c],ci,e.ci)` and is limited by `l.res`, `NRES` and `e.cap-e.used`.
- **Recording:** each push calls `carry(l,e.ek,NN+3,…)`. `NKN` is always `NN+4` (`:130`), and that column is named `'players'` at `:16`.
- **Effects:**
- Transit p95, hot ports and link loads include player traffic, so peering saves transit money.
- `R2.mp={dem,srv,peer,lost,full,by}` records the totals.
- The pass runs after every catalog flow, so `R.served`, `R.demand`, moods, levels, `peerShare` and Tier 1 never change.
**Cost of a de-peering war:**
- `computeMoney` applies `V.eyeballs *= 1 - mp.lost/(demand+mp.dem)`, where `lost` is traffic with no route at all.
- Two transit-free Tier 1 players who won't peer cannot reach each other: catalog Tier 1s don't pass on routes they learn from peers. Each loses up to 2% of eyeball revenue, which is real Level 3 vs Cogent drama at a bounded cost. Neither loses Tier 1.
- Two eyeball players who don't peer pay transit p95 for each other's traffic.
**Clique star (cosmetic):** card `cq=1` when you are Tier 1 and reach every player whose card says `t1` by your own PNI or IX session. The leaderboard sorts the star first.
**De-peering:** `end` the deal. Each side removes its rows 7 own days after it first sees the end.
### 2.4 Competition
**Overlap:** `clComp` (`75-customer-lifecycle.js:30`) also counts rival players whose card POPs cover the customer's cities. The rolls stay hash-stable (`clR`).
**Poaching:**
- `clLeave` (`:64`), for "cheap" or "multi" with a rival POP in the city, posts the customer to `/lost`.
- The server gives it to one rival, chosen by `hstr`, as a gift.
- The rival checks it with `okBiz`, `BIZ_T` and `rate ≤ catalog×mkt()×1.2`, then puts it in `S.offers` with `ref` set to the loser's name.
**Tenders:**
- **Issue:** while at least two players are active (`idle` < 300 s), the server issues `{n, city}` every 5 real minutes. The city is seeded from the active players' POPs.
- **Content:** derived from `hstr(seed|n)` and the `BIZ_T` lists, so every client sees the same tender.
- **Bids:** a ratio r from 0.6 to 1.0. You can bid while paused, and an optional standing auto-bid covers your cities.
- **Closing:** after 10 real minutes, or once every active player has bid. Wall-clock time, because no game clock is shared.
- **Winner:** the best `(1.2-r)·sq`, where `sq` is served share. The tender goes into `S.offers` with `mp:1`, expiring in 10 own days, and is signed with the normal `accept`.
### 2.5 Shared fiber
**Waves and IRUs (`wave`/`iru` deals):**
- **Seller side:** books spectrum or pairs via `+mpSold(l.id)` in the three counters (`60-requirements.js:72,75`, `37-fiber-broker.js:16`). It earns `V.mp += rate×(fiberOk?1:0)`.
- **Buyer side:** an `S.links` row `{kind:'wave'|'df', own:false, mo:price, mp:deal}`, which copies cut/eqDown/ready from `dl`.
**Consortium seats:** built like `seatBuy` (`86-specialist.js:4`), at `ownCabCost(km)×myPairs/totalPairs` (`36-specialist.js:54`).
**Deferred:**
- Joint exchanges, which need an id namespace (`isIx`, `50-sanitize.js:2`).
- An opt-in "Tier 1 must reach every Tier 1 player" rule.
## 3. Server (`scripts/lib/mp-deals.js`, pure logic, with routes in phase 1's `scripts/lib/mp.js`)
**The deal record** is public to the session, like PeeringDB. The session keeps a counter `dv`, bumped on every change.
```
{id:'d'+base36, k:'t'|'pni'|'ix'|'wave'|'iru', a, b, s (seller), at (city|ix|'a|b'), tier, n, price, slots, st, rev, t0, tl, te, by, why}
```
| from | event | to | allowed for |
|---|---|---|---|
| – | create `t` | `live`, or 409 `not_selling`/`no_pop`/`loop`/`dup`/`limit` | the buyer |
| – | create `ix` | `live` (b open and present) / `no` (b closed) / `offer` | a |
| – | create `pni`/`wave`/`iru` | `offer` | a |
| `offer` | accept / decline / withdraw / 7 days pass | `live` / `no` / `gone` / `gone` | b / b / a / server |
| `live` | end | `end` (`quit`) | a or b |
| `live` | a side's card never reports `ok` within 7 days | `end` (`unbuilt`) | server |
| `live` | no card from a party for 14 days | `end` (`idle`) | server |
| any open deal | a party leaves or is pruned | `end` (`left`) | server |
| `no`/`gone`/`end` | 7 days pass | deleted | server |
**Errors:** every write sends `rev`. A stale `rev` or an illegal transition gets 409, and the wrong party gets 403.
**Limits:**
- one open deal per (pair, kind, place);
- 10 open offers and 24 live deals per player;
- 300 deals per session;
- price 0.05–50, tier 0–15, n 1–8;
- 30 writes per minute per player.
**Feed:** the server writes a line for each transition ("X sells transit to Y in Frankfurt", "X de-peered Y").
**Endpoints:**
- `POST /api/mp/sessions/:code/deals {k,to,at,tier,n,price?,slots?}` returns 201 `{deal,dv}`.
- `POST …/deals/:id {op,rev}` with `op` one of accept, decline, withdraw or end.
- `POST …/lost` reports a lost customer; `POST …/tenders/:n/bid {r}`; `PUT …/autobid`.
- The roster responses (`GET` the session, and `PUT` the card or save) add:
- `deals[]` (my deals, any state) and `dv`. Other players' links come from their cards' `pt`;
- `tenders[]` and my `gifts[]`;
- each player's `idle`: seconds since their card last carried a newer day.
So nothing needs extra polling.
## 4. Card fields beyond phase 1
Every field below is added to both `cleanCard` and `mpCardOk`. Phase 1's `transit` field stays catalog-only, because `NET_RE` would silently drop `mp:` ids.
| field | content |
|---|---|
| `nv` | build version |
| `pt` | pids I buy transit from |
| `rs` | exchanges with my route server on |
| `tp` | my transit price, or null |
| `miss` | catalog ids I can't reach, biggest share first, ≤160 (a reach of 0.99 can still miss 72) |
| `on` | 1 if the internet of built-in networks can reach me: catalog transit, PNIs with every `t1Need()` network, or a seller with `on` |
| `mr` | pids I reach |
| `eye`, `biz` | Gbps, 2 significant digits |
| `sq` | served share |
| `sv` | `{city: delivered share}` where I sell, ≤64, in 0.05 steps |
| `dl` | `[{id,u,q,g,ok,up,cut,eq,rdy}]`, one per live deal, ≤64 |
| `cq` | clique star |
The card grows by about 4 KB at most. ASNs need nothing new: phase 1 already sends the catalog ASNs to avoid (`mpAvoid`, `mp.js:238`).
## 5. Client day flow (`src/game/60-features/89-player-deals.js`, new)
Phase 1's `mpRosterOk` is extended to whitelist `deals`, `dv`, `tenders`, `gifts` and `idle` (plus new `MP_FEED` kinds). The validated roster stays in `MP.roster`, never in S. `mpDay(d)` runs first in `dayPre`, right after `S.day++` (`10-day-tick.js:10`):
1. **Copy changes in.** If `dv`, `idle` or any card changed, rebuild `S.mpx.who` and `S.mpx.deals` from the validated data, with values in steps. Then recompute `k`/`xk` and call `mpBind(S)`.
2. **Reconcile each deal:**
- **live, not `made`:** create my row (`S.pops[at]`, `portOk`, `portGate`, `spend(setup)`) and set `made`. If that fails, the deal waits under a "waiting on you" badge, with no client timer; the server ends it as `unbuilt`.
- **live, `made`, but the row is gone** (for example after a decommission, which `decomImpact` warns about): post `end` with `why:'gone'`. Decommissioning a city where I sell also ends those sell deals.
- **ended** (or missing from the server's list): set `until=d+notice` (14 own days for transit, 7 for the rest) and remove the rows when it passes.
3. **Copy the coupling values onto the rows:**
- on transit rows: `t.mpf` and `t.down`;
- on PNI rows: their side's capacity and whether it is ready;
- on link rows: cut, eqDown and ready;
- on my seller entries: `u`, `q` and whether the buyer is active.
4. `compute()` runs (worker or not), then `dayPost`, then phase 1's push carries the new fields. `dl` comes from yesterday's R.
**My own clicks** (`mpOffer`, `mpAnswer`, `mpEnd`, `mpSell`, `mpBid`) apply as soon as the server answers, with `mpApply();after()`. If `RW.job` is set, they apply at the next `dayPre` instead.
Multiplayer code never calls `Math.random`.
## 6. Saves and sanitize
**New field:** `S.mpx = null | {k, xk, dv, who:[≤11], deals:[≤64]}`. `deals` holds only my own deals. Cones, `on` and who-buys-from-whom come from `who[].pt`.
- `mpx:null` is the default in `newGame` (`80-new-game.js:4`), so old saves get null.
**Order in `sanitize`:** move phase 1's `mpSanitize(s)` from `50-sanitize.js:113` up to `:21`, then call `mpxSanitize(s)`. Both now run before `opsSanitize` (`:22`) and every `isNet` filter (`:34-35, :54-55`).
**`mpxSanitize`:**
- **When it is null:** unless `MP_API` is stamped and `s.mp` is valid in normal mode. An imported multiplayer save then just loses its player rows.
- **Players (`who`):** pids checked against the regex, unique, never my own.
- **Names:** stripped like the phase 1 server does (control characters and `<>&"'\``, at most 32). They are not escaped, because `labOf`/`hotPorts` print catalog names unescaped too.
- **Ids:** pass `isCity`/`isIx`. `miss` must be catalog ids, and `pt`/`mr` must be pids in `who`.
- **Numbers:** clamped and stepped.
- **Deals:** kinds from a whitelist, the other party present, `at` checked, `tier` within `PORT`, the price at most `mpCap`.
- **Loops:** `pt` edges are dropped in (buyer, seller) pid order.
- **Keys:** `k`/`xk` are recomputed, never trusted.
- **Last step:** it ends with `mpBind(s)`.
**`mpOrphans(s)`** runs right after `:113`:
- it drops tagged `transit`/`pni`/`links`/`peers` entries that have no deal;
- it drops untagged rows on `mp:` networks;
- it strips `mp`/`mpp`/`mpf` from untagged rows, so a forged `mpp:0` gives no free transit.
**`RK_SKIP`:** `mpx` stays off it, because `compute` reads it. Phase 1's `mp` stays on, because `compute` must never read it; the `route-skip.test.js` proxy enforces both.
**Size:** at most +15 KB per save.
## 7. Ordered steps
Each step ends with `npm test` green, the i18n check clean, MCP classification, a CHANGELOG bullet and perf numbers.
**1. Dormant core (no server, no UI).**
- `45-player-carriers.js`.
- `80-new-game.js:4`; `50-sanitize.js:21`/`:113`.
- `30-compute.js`:
- `:28` bind check;
- `:53-54` `mpf` and `miss`;
- `:61` `if(!p.mp)`;
- `:62` `*(p.mp?mpPniF(p):1)`;
- `:70` `xk`;
- `:95` `mpDem`;
- `:130`/`:16` the players column;
- `:375-382` `V.mp`.
- `40-billing.js:9`; `40-ports.js:21`.
- **Guards:**
- `lagT`/`lagP`/`cancelTransit` (`20-pops-transit-ix.js:6,7,11`), `unpeer`/`cancelPni` (`40-sites-peering-caches.js:16,30`) and `downT` (`21-ix-downgrade.js:6`) route to `mpEnd` or a renegotiation offer;
- `cleanPipe` (`80-security-and-china.js:8`) refuses `mp` rows;
- `trExits` (`50-traceroute.js:20`) applies `miss`, and `hotPorts` (`80-hot-ports-and-rank.js:4`) applies `mpf`;
- `connUp` (`40-connections.js:18`) shows no upgrade for these rows;
- the intern (`95-standing-orders.js:155,180,250`) skips `mp` rows;
- `upLink`/`rmLink`/`setStandby` (`60-links.js:2,6`).
- `src/agent/30-docs.js`.
- **Tests:** `mp-sanitize`, and `mp-transit` with `S.mpx` injected.
**2. Deals and transit, end to end.**
- `scripts/lib/mp-deals.js` and the `mp.js` routes and timers.
- The card fields.
- `89-player-deals.js`, called from `10-day-tick.js:10`.
- `90-actions/92-player-deals.js`, classified in `src/agent/20-commands.js`.
- `95-modals/49-player-deals.js`: a Deals tab in the session sheet, a bottom sheet at 360 px.
- `90-noc-window.js:45`; `decomImpact`; all six languages.
- **Tests:** `mp-deals-server`, and `mp-transit` with `fetch` mocked.
**3. Peering and player traffic.**
- `pni`/`ix` deals, `mpIx`, and `36-mp-traffic.js` with its hook at `:343`.
- The `V.eyeballs` factor, `R.mpSess` and the star.
- Player Gbps in the PNI list and the connections list.
- **Test:** `mp-peering`.
**4. Competition:** `clComp`, poaching, tenders.
**5. Shared fiber:** waves, IRUs, seats.
**6. `scripts/mp-soak.js`:** opt-in, never part of `npm test`.
## 8. Performance budget
**Single-player.** Each `compute()` costs one string comparison, one property read per transit and PNI row, and one more `ACN` column per edge.
- `npm run perf -- --base-ref origin/main` must stay within noise (≤1%).
- `emptyR()` gains no keys; `R.mp`, `R.mpSess` and `V.mp` exist only when `S.mpx` is set.
**Multiplayer.** The carrier mechanics are measured above: 32.3 → 33.2 ms. A new `big-network-mp` workload (the fixture plus 11 players and 20 deals, built by `scripts/perf-mp-fixture.js`) must meet:
- `mpTraffic` ≤ 1.5 ms (one exit sort per POP, then O(players×exits), with paths cached for each pair of cities);
- `mpBind` ≤ 0.1 ms;
- warm `compute` ≤ +5% compared with the same fixture without players.
A cold route happens only when `xk` changes, at most once a game day. Report jsdom and `--browser` numbers.
## 9. Test plan
**`mp-deals-server`** (spawned server, temporary directory):
- every transition and who may make it (403/409);
- the policy outcomes for `ix` (live, no, offer);
- 409 `loop` on A→B→C→A;
- the limits;
- the `unbuilt`, `idle` and `left` ends, and expiry, with an injected clock;
- card validation;
- restart persistence.
**`mp-transit`:**
- the buyer's exit and label, `transitMo` using `mpp`, `isTier1` false;
- `mpf` scales capacity, and `miss` blocks reach and changes `xk`;
- the seller's demand rises by `u`, `V.mp` follows the formula, and the seller keeps Tier 1;
- an idle buyer gives zero load and revenue;
- a forged `mpp` is stripped;
- worker parity (the `route-worker.test.js` pattern);
- no `Math.random` calls;
- the inbox is never applied mid-day.
**`mp-peering`:**
- a PNI carries traffic only once both ends are ready;
- de-peering raises transit p95;
- two unpeered Tier 1 players lose revenue, and both stay Tier 1;
- 24 player PNIs leave `R.sessions` unchanged;
- C reaches B through A's cone;
- the route-server rule is two-sided;
- the PNI lead time is stable.
**`mp-sanitize`:**
- fuzzing does not throw and stays bounded: 1,000 entries, HTML in names, loops, unknown ids, `mp:` rows in a single-player save;
- old saves load;
- a multiplayer-to-single-player slot switch clears every `mp:*`;
- `<img onerror>` stays text in the panels and the Deals sheet at 360 px.
**`mp-competition` and `mp-fiber`:**
- rival players raise `clComp`;
- gifts are validated;
- every client derives the same tender;
- cuts are copied;
- a bought wave can't be upgraded.
**Existing gates:**
- `route-skip` (same digest with `S.mpx` null or empty), `compute-idempotent`, `routing-reference`, `route-cache`;
- `gameplay-rules`, plus a check that no `mp:` id is in `NETS`/`NSH`;
- `persist`, `save-size`, `save-text`, `mcp-commands`, `i18n`, `pages`, `build`, `multiplayer`, `mp-server`.
**Soak test (the "hardcore" local run):**
- The server plus 12 seeded jsdom players in `worker_threads` (about 0.5 GB each, with `--jobs` capped).
- Each plays about 2,000 days at its own speed, with a random agent making, answering and ending deals.
- During the run: server restarts, reloads through `migrate`, a player leaving, tampered cards and a burst of 409s.
- It checks: no errors or NaN, an acyclic deal graph, each seller's `V.mp` matching the buyer's bill, every save reloading, and a single-player control game keeping `main`'s digest.
## 10. Failure modes
| Case | Handling |
|---|---|
| The other player is paused or offline | Their last card stands: an idle buyer brings no load or money, and a buyer keeps the seller's last values. After 14 days the server ends the deal (`idle`) |
| A player leaves | The deal ends (`left`) and each side tears down after notice. `mpBind` drops the carrier on the next sanitize |
| Server down | Play goes on with the frozen `S.mpx`. New deals fail with one toast |
| Two devices | Phase 1's seq/409 picks the save; `made` settles the rows |
| Version skew | Unknown `miss` ids are dropped; networks the seller's build lacks count as reachable |
| Tampered card or save | Whitelists, clamps, steps, local price caps, orphan stripping. Money comes only from local formulas |

View file

@ -0,0 +1,55 @@
# What is left (as of 2026-11-07)
Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard, multiplayer
phase 1, dark mode (#80), IPv4 address space (#150), express fiber (#58) and satellite teleports (#83). Everything below is
planned or known, not built.
## Promised and not done yet
1. **Router model and line system set in one place only.** The build standard (`S.popStd.g`, `S.popStd.sys`) and two
standing-order settings say the same thing: the `routers` order's `model` (upstream 1e7638c) and the `optup` order's
`sys` (upstream 647e302). Neither ever steps down, so they do not fight, but a player can pick two different targets.
Plan: the Build standard sheet becomes the only place to pick them. The `routers` order reads its model from the
standard, and `optup` its line system (their lists turn into a line "from the build standard: X, change"); sanitize
moves an old `model`/`sys` setting into `S.popStd` when the standard has none.
2. **One owner per fiber for line systems and optics.** `std` (sys/opt targets: a quiet fiber, or a parallel link with
room) and `optup` (one full routing without the fiber, one a night) can each darken a fiber in the same shift. Let `std`
use `optup`'s check (`opsDarkOk`) for line-system swaps, or skip fibers `optup` is working on. Today `std` also holds
any fiber that carries an express with traffic; `opsDarkOk` would handle that case by itself.
## Next features
3. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative
over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit,
peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`.
4. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is
the busier direction. It comes after #58 because both touch link capacity (express channels now count too).
## Known limitations of what shipped
- **Multiplayer:** other players' POPs are not drawn on the map (no clean hook yet); cards are what each browser reports,
the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone
landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every
player shares one address for the rate limits.
- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full; a wave
the standard just upgraded can still be handed back the same day by `decom` if a bigger parallel link carries it.
- **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG
and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser.
- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income
is not in the investor revenue share; blocks granted to old saves can be sold after two years (a one-off windfall);
CGNAT annoyance costs refunds but does not slow broadband growth; the NOC window's address-space button does nothing.
- **Express fiber (#58):** splicing a whole fiber pair through a city was left out on purpose (every fiber end is a POP;
expresses cover the need); loss and MTU incidents on a fiber do not reduce the expresses on it; the fiber panel's
"n of max channels" line does not count express slots (the Express section does); regen sites added later do not charge
regen cards for express channels.
- **Satellites (#83):** no WISP zones, no satellite incidents (rain fade, sun outage), no footprints on the map, no
satellite tab in the drag-to-link window (ordering is from the city panel); GEO/MEO losses and prices are design
numbers; well-cabled islands (Wellington, Hobart) also count as "can be served"; MEO needs 5° elevation (10° would drop
416 pairs); Pitcairn's $120k satellite grant stays Pie-only.
## Housekeeping
- `npm run perf -- --browser` needs Chromium (`sudo pacman -S chromium`, then `PERF_CHROME=/usr/bin/chromium`); only the
jsdom benchmark has been run.
- Upstream release tags are not on `vanvik` yet: `git push vanvik --tags` if wanted.
- The merged worktrees under `.claude/worktrees/` and their `worktree-wf_*` branches can be removed.

View file

@ -21,7 +21,8 @@
"perf": "node scripts/perf-bench.js",
"bench:gpu": "node scripts/gpu-bench.js",
"mcp": "node scripts/mcp.js",
"mcp:browser": "node scripts/mcp.js --browser"
"mcp:browser": "node scripts/mcp.js --browser",
"mp": "node scripts/mp-server.js"
},
"engines": {
"node": ">=20"

View file

@ -6,6 +6,8 @@
//
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the
// page talks to scripts/mp-server.js at that path, same origin
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
@ -19,6 +21,10 @@ const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
// Multiplayer is off unless MP_API names the session server's path on the page's own origin ("//host/x" would be
// another host, and the player's token would go there).
const MP_API = process.env.MP_API || '';
if (MP_API && !/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(MP_API)) die(`MP_API '${MP_API}' must be a path on the same origin, like /api/mp`);
fs.rmSync(OUT, { recursive: true, force: true });
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
@ -44,7 +50,9 @@ if (!html.includes(PH)) die('release-notes placeholder missing from the page');
// A release can also open with a story (prose before its first bullet), shown in full in "What's new".
const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]';
if (!html.includes(PS)) die('release-story placeholder missing from the page');
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')));
const PM = "/*__MP_API__*/''";
if (!html.includes(PM)) die('multiplayer placeholder missing from the page');
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`));
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story) }, null, 2) + '\n');
// Nothing may ship half-stamped.

View file

@ -7,6 +7,8 @@
// tools (node scripts/mcp.js --browser) drive the page this server serves.
// Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the
// relay's ws. For the production build as GitHub Pages will serve it: npm run serve.
// --mp also runs the multiplayer API (docs/MULTIPLAYER.md) at /api/mp, sessions kept in mp-data/, and turns multiplayer
// on in the page: two browser windows (or a private one) can then play one session locally.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
@ -23,17 +25,19 @@ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; ch
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json' };
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null;
const clients = new Set();
function page() {
const { html, map } = assemble({ dev: true });
// Errors report a line of the assembled page; the console also says which file under src/ that is.
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
return html.replace('</body>', `${hint}${RELOAD}</body>`);
return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('</body>', `${hint}${RELOAD}</body>`);
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (MP && MP.handle(req, res)) return;
if (url.pathname === '/__dev') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(': hi\n\n');
@ -69,6 +73,7 @@ server.listen(PORT, HOST, () => {
console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`);
console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`);
console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser');
if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`);
});
const shutdown = () => { relay.close(); process.exit(0); };
process.on('SIGINT', shutdown);

View file

@ -185,5 +185,8 @@
return { a, b, c };
};
const acts = () => Object.keys(ACT);
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen };
// Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls
// it only while the base has no such rule, so the pages play the same game until it lands.
const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } };
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen, noIp4 };
})();

448
scripts/lib/mp.js Normal file
View file

@ -0,0 +1,448 @@
// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the
// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies.
// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the
// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API.
//
// Storage: one JSON file per session (DIR/<CODE>.json: settings, players, cards, feed) and one file per player's save
// (DIR/<CODE>.<pid>.save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are
// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes
// part of a file name, and so is a player id.
const fs = require('node:fs');
const path = require('node:path');
const net = require('node:net');
const crypto = require('node:crypto');
// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up.
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
const PID_RE = /^[a-z0-9]{8}$/;
const TOKEN_RE = /^[0-9a-f]{64}$/;
const PRESETS = ['soft', 'freeze', 'oncall', 'bgp'];
const PPOL = ['open', 'selective', 'closed'];
const TIERS = ['t1', 't2', 't3'];
const ASN_LO = 200000, ASN_HI = 214999;
const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d'];
const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON)
const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 };
const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places)
const FEED_MAX = 100, CHAT_MAX = 200;
const DAY = 86400000;
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant.
function normCode(s) {
if (typeof s !== 'string' || s.length > 20) return null;
const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0');
return CODE_RE.test(c) ? c : null;
}
const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3);
const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; };
const randPid = () => crypto.randomBytes(4).toString('hex');
const sha = (t) => crypto.createHash('sha256').update(t).digest();
// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one
// space between words, at most max characters (whole characters, never half an emoji).
function cleanText(v, max) {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, max).join('').trim();
}
const cleanChat = (v) => {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, CHAT_MAX).join('').trim();
};
const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); };
const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d));
// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one.
const ids = (v, re, max) => {
if (!Array.isArray(v)) return [];
const out = new Set();
for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; }
return [...out];
};
const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/;
/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its
catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */
function cleanCard(c) {
if (!c || typeof c !== 'object' || Array.isArray(c)) return null;
const links = [];
if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) {
if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue;
links.push([l[0], l[1], num(l[2], 0, 1e7)]);
if (links.length >= 300) break;
}
return {
day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99),
pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64),
ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9),
cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15),
};
}
/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the
order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above
cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */
function limiter(n, ms, cap = 20000) {
const m = new Map();
const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; };
return {
// Counts one more, unless the key is already at its limit.
ok(k, now) {
const a = live(k, now), ok = a.length < n;
if (ok) a.push(now);
m.delete(k); m.set(k, a);
for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; }
return ok;
},
full: (k, now) => live(k, now).length >= n,
size: () => m.size,
};
}
/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an
IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */
function addrKey(a) {
a = String(a || '').trim();
if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0);
const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z);
const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1];
const v = net.isIP(a);
if (v === 4) return a;
if (v !== 6) return null;
const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : [];
// The groups :: stands for (a dotted IPv4 at the end is two of them).
const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0);
const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail];
return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64';
}
class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } }
const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); };
// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that
// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes.
function readJson(req, max, ms = 30000) {
return new Promise((resolve, reject) => {
const ct = String(req.headers['content-type'] || '');
if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); }
const len = +req.headers['content-length'];
if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); }
let parts = [], n = 0, done = false;
const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); };
const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms);
req.on('data', (b) => {
if (done) return;
n += b.length;
if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; }
parts.push(b);
});
req.on('end', () => {
if (done) return; done = true; clearTimeout(tm);
let j;
try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); }
if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object'));
resolve(j);
});
req.on('error', () => stop(new HttpError(400, 'request failed')));
req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); });
});
}
function send(res, status, body) {
if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; }
const txt = JSON.stringify(body);
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) });
res.end(txt);
}
/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API.
handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */
function createMp(o = {}) {
const dir = path.resolve(o.dir || 'mp-data');
const base = (o.base || '/api/mp').replace(/\/+$/, '');
const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60;
const now = o.now || Date.now, log = o.log || ((s) => console.log(s));
fs.mkdirSync(dir, { recursive: true });
const file = (code) => path.join(dir, code + '.json');
const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`);
const cache = new Map(), chains = new Map(), soon = new Map();
let codes = new Set(), tmpN = 0;
const HOUR = 3600000, MIN = 60000;
const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR);
// However many addresses ask, the server fills up slowly: a full server takes days, not minutes.
const createAll = limiter(o.sessionsPerHour || 100, HOUR);
const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000);
// Wrong codes, counted per address: guessing codes runs out long before it finds one.
const missRate = limiter(o.missesPerHour || 120, HOUR);
// A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they
// stop one player from keeping the disk busy rewriting their session.
const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN);
// Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes.
const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4;
// Atomic: write a temporary file next to it, then rename over the old one.
const writeAtomic = async (f, txt) => {
const tmp = `${f}.${process.pid}.${++tmpN}.tmp`;
await fs.promises.writeFile(tmp, txt);
await fs.promises.rename(tmp, f);
};
// One session's writes happen one after another, in the order they were asked for.
const queue = (code, job) => {
const p = (chains.get(code) || Promise.resolve()).then(job, job);
const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); });
chains.set(code, q);
q.then(() => { if (chains.get(code) === q) chains.delete(code); });
return p;
};
// A session that is gone (its last player left) is never written again, whatever was still on its way.
const persist = (s) => {
const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); }
s.touched = now();
if (s.dead) return Promise.resolve();
return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s)));
};
// Cards change often and matter little: their session is written a moment later, once for all of that moment's.
const persistSoon = (s) => {
s.touched = now();
if (s.dead || soon.has(s.code)) return;
const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000);
if (tm.unref) tm.unref();
soon.set(s.code, tm);
};
function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } }
// Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes.
function prune() {
const cut = now() - pruneDays * DAY; let n = 0;
for (const f of fs.readdirSync(dir)) {
const p = path.join(dir, f);
let st; try { st = fs.statSync(p); } catch (e) { continue; }
if (!st.isFile()) continue;
if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; }
const m = /^([0-9A-Z]{6})\.json$/.exec(f);
const live = m && cache.get(m[1]);
if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; }
}
for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); }
scan();
return n;
}
function drop(code) {
const s = cache.get(code); if (s) s.dead = true;
const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); }
for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true });
cache.delete(code); codes.delete(code);
}
function load(code) {
if (!CODE_RE.test(code)) return null;
if (cache.has(code)) return cache.get(code);
if (!codes.has(code)) return null;
let s = null;
try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; }
if (!s || s.code !== code || !Array.isArray(s.players)) return null;
// A hand-edited or damaged file: players without an id or a token hash cannot be anyone.
s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string');
for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) };
if (!Array.isArray(s.feed)) s.feed = [];
cache.set(code, s);
return s;
}
prune();
// The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last.
const ipOf = (req) => {
if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; }
return addrKey(req.socket.remoteAddress) || '?';
};
// The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for
// a player who is not there.
function player(req, s) {
const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || ''));
if (!m) return null;
const p = s.players.find((x) => x.pid === m[1]);
const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]);
return crypto.timingSafeEqual(want, got) && p ? p : null;
}
const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; };
// Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them.
const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p));
const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); };
const roster = (s) => ({
code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created,
players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })),
feed: s.feed,
});
// A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets
// the headline). A network that drops out and comes back is not news again.
function applyCard(s, p, c) {
const hit = p.hit || (p.hit = {});
if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); }
else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); }
p.card = c;
}
function newPlayer(s, body, ip) {
const net = body.net && typeof body.net === 'object' ? body.net : {};
const name = cleanText(net.name, 32);
if (!name) fail(400, 'name your network');
const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null;
if (!home) fail(400, 'pick a home city');
let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid));
const token = crypto.randomBytes(32).toString('hex');
const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a)));
for (const p of s.players) avoid.add(p.asn);
let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn));
const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length];
const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} };
s.players.push(p);
event(s, 'join', p);
return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title };
}
// The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped.
const readSave = async (code, pid) => {
const t = await fs.promises.readFile(saveFile(code, pid), 'utf8');
if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } }
return t;
};
// A save upload holds a place until it is done: one per player, a few per address and on the whole server.
function upTake(key, ip) {
if (up.has(key)) fail(429, 'a save of yours is still on its way');
if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true });
up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1);
return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); };
}
async function route(req, res, url) {
const rest = url.pathname.slice(base.length);
const t = now(), ip = ipOf(req), M = req.method;
if (rest === '/sessions') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now');
if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later');
if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now');
const preset = PRESETS.includes(body.preset) ? body.preset : null;
if (!preset) fail(400, 'unknown rules preset');
let code; do code = randCode(); while (codes.has(code));
const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] };
const out = newPlayer(s, body, ip);
codes.add(code); cache.set(code, s);
await persist(s);
return send(res, 201, out);
}
const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest);
if (!m) fail(404, 'not found');
const sub = m[2] || '';
let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ }
const code = normCode(raw), s = code && load(code);
// A player of this very session, with their token, is never held up by somebody else's wrong codes from the same
// address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either.
const me = s ? player(req, s) : null;
if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later');
if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later');
if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); }
if (sub === '/join') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (!still(s)) fail(404, 'no such session');
if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true });
const out = newPlayer(s, body, ip);
await persist(s);
return send(res, 200, out);
}
if (sub === '') {
if (M !== 'GET') fail(405, 'method not allowed');
authed(me);
return send(res, 200, roster(s));
}
if (sub === '/card') {
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me);
if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down');
const body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const c = cleanCard(body.card);
if (!c) fail(400, 'bad card');
applyCard(s, p, c);
persistSoon(s);
return send(res, 200, roster(s));
}
if (sub === '/save') {
if (M === 'GET') {
const p = authed(me);
if (!p.sv) fail(404, 'no save yet');
let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); }
return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data });
}
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me), key = code + '.' + p.pid;
const free = upTake(key, ip);
try {
if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down');
const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS);
if (!still(s, p)) fail(401, 'unauthorized');
const seq = body.seq, data = body.data;
if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer');
if (typeof data !== 'string' || !data.length) fail(400, 'no save data');
if (data.length > MAX_SAVE) fail(413, 'save too large');
if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save');
const card = body.card === undefined ? undefined : cleanCard(body.card);
if (card === null) fail(400, 'bad card');
const old = p.sv;
// Another device of the same player saved a newer game: never overwrite it unless the player says so.
if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at });
const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq;
// The session says it has this save only once the save is on disk.
await queue(code, () => writeAtomic(saveFile(code, p.pid), data));
if (!still(s, p)) fail(401, 'unauthorized');
p.sv = { seq: sq, at, size: data.length };
if (card) applyCard(s, p, card);
await persist(s);
return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) });
} finally { free(); }
}
if (sub === '/feed') {
if (M !== 'POST') fail(405, 'method not allowed');
const p = authed(me), body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const text = cleanChat(body.text);
if (!text) fail(400, 'say something');
if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little');
event(s, 'chat', p, { text });
await persist(s);
return send(res, 200, roster(s));
}
if (sub === '/me') {
if (M !== 'DELETE') fail(405, 'method not allowed');
const p = authed(me);
s.players = s.players.filter((x) => x !== p);
await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true }));
if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); }
event(s, 'leave', p);
await persist(s);
return send(res, 200, { ok: true });
}
fail(404, 'not found');
}
function handle(req, res) {
let url;
try { url = new URL(req.url, 'http://x'); } catch (e) { return false; }
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false;
const t0 = Date.now();
res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); });
route(req, res, url).catch((e) => {
// A body nobody read (refused before it was needed) is drained, so the client still gets its answer.
if (!req.complete && !req.destroyed) req.resume();
if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) });
log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`);
send(res, 500, { error: 'server error' });
});
return true;
}
// Everything written before the process goes, sessions waiting for their moment too.
const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); };
return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size };
}
module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE };

View file

@ -95,6 +95,8 @@ function playGame(pages, seed, opts = {}) {
preset: kind === 'sandbox' ? r.pick(['none', 'calm', 'normal', 'spicy']) : r.pick(PRESETS),
id: kind === 'scenario' ? r.pick(L.scn) : kind === 'puzzle' ? r.pick(L.pz) : kind === 'architect' ? r.pick(L.ar) : undefined };
const [s0, s1] = both('start', st);
// A base without scarce IPv4 (#150) plays the classic game: both pages switch the rule off. Once it is on main, both play it.
if (!base.call('acts').includes('ip4Buy')) both('noIp4');
same('start', s0, s1);
note('start ' + JSON.stringify(st));
// A normal game signs its charter first: a popup on newer pages (which seeded pages skip), a card on older ones. Both

117
scripts/mp-server.js Normal file
View file

@ -0,0 +1,117 @@
#!/usr/bin/env node
// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es
// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build.
// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so
// one process can sit behind a reverse proxy.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { createMp } = require('./lib/mp');
const HELP = `Series of Tubes multiplayer server
node scripts/mp-server.js [options] (npm run mp -- [options])
--port N port to listen on (default 8090, or $PORT)
--host H address to bind (default 127.0.0.1: put a reverse proxy in front)
--data DIR where sessions and saves are kept (default ./mp-data, created if missing)
--site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build)
--base PATH the API's path (default /api/mp; the page's MP_API must match)
--prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60)
--max-sessions N at most N sessions on this server (default 1000)
--max-players N at most N players per session (default 12, at most 12)
--create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64)
--sessions-per-hour N new sessions on the whole server per hour (default 100)
--trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy)
--verbose log one line per API request (never tokens)
--help this text
Storage: DIR/<CODE>.json per session and DIR/<CODE>.<pid>.save per player's save. Back up DIR.
API (JSON; every call but create and join needs Authorization: Bearer <pid>.<token>):
POST /api/mp/sessions {net:{name,home},preset,title?} start a session
POST /api/mp/sessions/:code/join {net:{name,home}} join one
GET /api/mp/sessions/:code roster, cards and feed
PUT /api/mp/sessions/:code/card {card} your public card
PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one)
GET /api/mp/sessions/:code/save your save
POST /api/mp/sessions/:code/feed {text} a chat line
DELETE /api/mp/sessions/:code/me leave
`;
const argv = process.argv.slice(2);
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); }
const die = (m) => { console.error(`error: ${m}`); process.exit(2); };
const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']);
for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`);
const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; };
const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; };
const PORT = pos('--port', +process.env.PORT || 8090, 65535);
const HOST = opt('--host') || '127.0.0.1';
const DATA = path.resolve(opt('--data') || 'mp-data');
const SITE = opt('--site') ? path.resolve(opt('--site')) : null;
const BASE = opt('--base') || '/api/mp';
// A path, never "//host/..." (which a browser reads as another host).
if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp');
if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`);
if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`);
const mp = createMp({
dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000),
maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100),
trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'),
});
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' };
// The page, the service worker and the files that change between releases are always checked; the rest may be cached.
const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//;
// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either.
const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } };
const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); };
// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE.
function serveSite(req, res) {
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); }
let rel;
try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; }
let file = null;
if (rel !== null && !rel.includes('\0')) {
if (rel.endsWith('/')) rel += 'index.html';
const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel));
if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); }
}
const status = file ? 200 : 404;
if (!file) file = path.join(SITE, '404.html');
if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); }
const r = path.relative(SITE, file).split(path.sep).join('/');
res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' });
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
}
const server = http.createServer((req, res) => {
try {
if (mp.handle(req, res)) return;
if (SITE) return serveSite(req, res);
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"not found"}');
} catch (e) {
// One line, never a stack: whatever went wrong, a request should not be able to fill the log.
console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`);
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"server error"}');
}
});
server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`);
});
setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref();
const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

View file

@ -397,6 +397,48 @@
"broker.win_text":"{name} (AS{asn}) hat in {days} Tagen eigene Kabel auf {n} Kontinente verlegt und verkauft anderen Carriern Kapazität für {mo} im Monat. Die Ozeane sind jetzt dein Graben.",
"broker.won_on_date":"Gewonnen am {date}: Deine eigenen Kabel überspannen die Ozeane, und Carrier zahlen dir für ihre Nutzung.",
"broker.your_glass_gear_is_already_yours":"Als Kabelmakler gehören dir jede Fiber, jedes Leitungssystem, jede Optik, jedes Seekabel und die Router, um sie zu beleuchten, schon jetzt, egal was das Level sagt.",
"bstd.all_up":"Alles entspricht dem Standard.",
"bstd.any_model":"beliebiges Modell",
"bstd.applied":{"one":"Ein Job für den Build-Standard erledigt, {cost}.","other":"{n} Jobs für den Build-Standard erledigt, {cost}."},
"bstd.applied_none":"Für den Build-Standard ließ sich gerade nichts machen.",
"bstd.apply_nothing":"Nichts unter dem Standard",
"bstd.apply_now":"Jetzt alles hochziehen · {cost}",
"bstd.apply_wait":"Nichts zu tun, bis diese Glasfasern frei sind",
"bstd.at_every_pop":"An jedem POP",
"bstd.at_least_n":"Mindestens {n}",
"bstd.below":"Heute unter dem Standard",
"bstd.both_buildings":"Über beide Gebäude",
"bstd.cost_mo":"Laufende Kosten",
"bstd.cost_now":"Um jetzt alles hochzuziehen",
"bstd.edit":"Build-Standard bearbeiten",
"bstd.every_exchange":"Wo es einen IX gibt",
"bstd.fastest":"Die schnellste, die reicht",
"bstd.fiber_note":"Ein Line-System-Tausch legt die Glasfaser einen Tag dunkel: nur wenn sie ruhig ist oder ein paralleler Link ihre Last trägt.",
"bstd.from_level":"(Level {lv})",
"bstd.g_fiber":"Glasfaser und Waves",
"bstd.g_port":"Ports und Peering",
"bstd.generator":"Generator",
"bstd.held":{"one":"Eine Glasfaser behält vorerst ihr Line System, bis sie ruhig ist oder ein paralleler Link ihre Last für den Tag trägt, an dem sie dunkel ist. Bis dahin bekommt sie die schnellste Optik, die ihr Line System nimmt.","other":"{n} Glasfasern behalten vorerst ihr Line System, bis sie ruhig sind oder ein paralleler Link ihre Last für den Tag trägt, an dem sie dunkel sind. Bis dahin bekommen sie die schnellste Optik, die ihr Line System nimmt."},
"bstd.hire_note":"Stell in Ops einen NOC-Praktikanten ein, dann hält er jeden POP, Port und jede Glasfaser auf dem Standard: ein paar Jobs pro Tag, die meistbelasteten zuerst, im Monatsbudget und nur mit Geld übrig.",
"bstd.in_n_cities":"In mindestens {n} Städten",
"bstd.intern_keeps":"{name} hält das Netz auf Standard",
"bstd.keep":"So lassen",
"bstd.l_ix":"IX-Port",
"bstd.l_lag":"LAG-Member",
"bstd.l_model":"Router-Modell",
"bstd.l_pni":"PNIs pro Netz",
"bstd.l_site2":"Zweites Gebäude",
"bstd.l_split":"LAGs aufteilen",
"bstd.left":{"one":"Noch eine Sache liegt darunter und wartet auf Geld, eine ruhige Glasfaser oder eine Erweiterung.","other":"Noch {n} Sachen liegen darunter und warten auf Geld, eine ruhige Glasfaser oder eine Erweiterung."},
"bstd.n_more_targets":{"one":"{n} weiteres Ziel","other":"{n} weitere Ziele"},
"bstd.new_pops_note":"Ein neuer POP bekommt das sofort, solange er noch leer ist: kein Wartungsfenster. Reicht das Geld nicht, bekommt er, was passt. Ein noch gesperrtes Modell heißt: das beste freigeschaltete darunter.",
"bstd.none_set":"Noch kein Standard: Jedes Ziel steht auf „So lassen“.",
"bstd.now_line":"Standard: {list}",
"bstd.or_better":"{x} oder besser",
"bstd.port_note":"LAGs und Aufteilung gelten für Transit-, IX- und PNI-Ports. Ein neues PNI-Member ist eine Erweiterung und kommt erst Wochen später.",
"bstd.second_building":"zweites Gebäude",
"bstd.tagline":"Ein Design fürs ganze Netz: was jeder POP, Port und jede Glasfaser haben soll. Neue POPs bekommen den POP-Teil am Tag der Eröffnung; dein Praktikant oder der Button unten zieht den Rest nach.",
"bstd.title":"Build-Standard",
"businesses.a_free_pni_with_voda_phony":"Ein kostenloser PNI mit Voda-Phony. Hardware: Absolute-Unit-3.2T-Router, 3.2T-Ports und 12.8T-Waves.",
"businesses.agi_lab_allegedly":"AGI-Labor (angeblich)",
"businesses.agi_labs_allegedly_wanting_ai_wans":"AGI-Labore (angeblich), die KI-WANs mit 12,8 bis 25,6 Tbps wollen, und kostenlose PNIs mit Du-opoly und Ooh-redoo. Hardware: Mikrowtik-CCR-3.2T-Router.",
@ -1978,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":"<b>{optic} geht auf diesem Express nicht.</b><br>{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":"<b>Über diese Glasfaser läuft ein Express-Lightpath.</b><br>Bau ihn zuerst ab: Öffne ihn im Express-Abschnitt dieser Glasfaser.","other":"<b>Über diese Glasfaser laufen {n} Express-Lightpaths.</b><br>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":"<b>Express leuchtet: {a} ⇄ {b}.</b><br>{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.",
@ -2598,6 +2680,54 @@
"interface.tubecoin_moved_down_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gefallen.",
"interface.tubecoin_moved_up_p_on_the":"TubeCoin ist auf dem Weg zu deinem Konto um {p} % gestiegen.",
"interface.you_bought_out_bank_they_flew":"<b>Du hast {bank} ausbezahlt.</b><br>Sie sind weitergeflogen, um ein anderes Startup zu finden.",
"ip4.block_size":"Blockgröße",
"ip4.blocks":"Deine Blöcke",
"ip4.bought":"Einen {p}-Block ({n} Adressen) für {price} gekauft.",
"ip4.bought_on":"Gekauft {date}",
"ip4.business":"Von Geschäftskunden genutzt",
"ip4.buy":"Kaufen {price}",
"ip4.cgnat_boxes":"CGNAT-Boxen",
"ip4.cgnat_note":"Mehr Haushalte pro Adresse macht Platz für Kunden, aber Spiele und Portweiterleitungen leiden: {p} der Rechnung eines CGNAT-Haushalts gehen als Erstattung zurück.",
"ip4.cgnat_ratio":"CGNAT: Haushalte pro Adresse",
"ip4.costs_row":"IPv4-Mieten und CGNAT",
"ip4.free":"Frei für neue Kunden (Haushalte kommen zuerst hinter CGNAT)",
"ip4.from_rir":"Von der RIR",
"ip4.give_back":"Zurückgeben",
"ip4.held":"Die RIR überträgt diesen Block erst ab {date} wieder.",
"ip4.homes":"Breitband-Haushalte",
"ip4.homes_cgnat":"{n}, davon {p} hinter CGNAT",
"ip4.in_use":"Deine Kunden brauchen diese Adressen: steck mehr Haushalte hinter CGNAT oder hol dir erst einen weiteren Block.",
"ip4.lease":"Mieten {price}/Monat",
"ip4.lease_out":"Vermieten +{price}/Monat",
"ip4.leased_in":"Einen {p}-Block ({n} Adressen) für {price}/Monat gemietet.",
"ip4.leased_in_mo":"Gemietet · {price}/Monat",
"ip4.leased_out":"Dein {p}-Block ist vermietet: +{price}/Monat.",
"ip4.leased_out_mo":"Vermietet · +{price}/Monat",
"ip4.leases_in":"Gemietete Blöcke",
"ip4.leases_out":"Vermietete Blöcke",
"ip4.market":"Transfermarkt",
"ip4.market_note":"IPv4 kostet etwa {px} pro Adresse (große Blöcke etwas weniger), zur Miete {lin} pro Adresse und Monat, und vermietet bringt es nach dem Anteil des Brokers {lout}. Ein Verkauf bringt {p} des Preises, und ein Block darf erst zwei Jahre nach seinem letzten Transfer wieder übertragen werden.",
"ip4.movable_from":"wieder übertragbar ab {date}",
"ip4.n_addresses":{"one":"{n} Adresse","other":"{n} Adressen"},
"ip4.n_homes_per_address":{"one":"{n} Haushalt pro Adresse","other":"{n} Haushalte pro Adresse"},
"ip4.no_grow":"{name} ({city}) wollte auf {bw} wachsen, aber du hattest keine freien IPv4-Adressen dafür.",
"ip4.no_space":"{name} braucht einen IPv4-Block {p} ({n} Adressen), und nur {free} sind frei. Kauf oder miete einen Block oder steck mehr Haushalte hinter CGNAT.",
"ip4.note":"IPv6 ist kostenlos und unendlich. IPv4 ist seit Jahren aus: Geschäftskunden brauchen öffentliche Blöcke davon, und Haushalte, die nicht mehr reinpassen, teilen sich Adressen hinter CGNAT (IPv6-Traffic läuft an der Box vorbei).",
"ip4.off":"Nach den Regeln dieses Spiels gibt es IPv4 reichlich.",
"ip4.offer_needs":"Braucht einen IPv4-Block {p} ({n} Adressen); nur {free} frei.",
"ip4.preset_plenty":"IPv4 gibt es reichlich für alle.",
"ip4.preset_scarce":"IPv4 ist knapp: kaufen, mieten oder hinter CGNAT teilen.",
"ip4.really_sell":"Wirklich für {price} verkaufen?",
"ip4.refunds":"Erstattungen an genervte Gamer",
"ip4.section":"Adressraum",
"ip4.sell":"Verkaufen {price}",
"ip4.sold":"Dein {p}-Block ist für {price} verkauft.",
"ip4.squeezed":"Kein Platz mehr: {p} der Haushalte passen nicht mal bei {r} Haushalten pro Adresse rein. Ihre Verbindungen brechen ab und sie wollen Geld zurück: kauf oder miete einen Block.",
"ip4.take_back":"Zurückholen",
"ip4.toast_cgnat":"<b>Dein IPv4 ist voll.</b> {p} deiner Haushalte teilen sich jetzt Adressen hinter CGNAT, und ein paar Gamer haben schon geschrieben.",
"ip4.toast_out":"<b>IPv4 ist aus.</b> Selbst bei {r} Haushalten pro Adresse passt nicht jeder hinter CGNAT: kauf oder miete einen Block bei der Bank.",
"ip4.too_many":"Du hast {n} IPv4-Blöcke, mehr kann ein Netz nicht führen. Verkauf kleine Blöcke oder gib sie zurück, um Platz für einen größeren zu schaffen.",
"ip4.yours":"Deine IPv4-Adressen",
"ix_downgrade.pni_downgraded":"Das PNI mit {net} in {city} ist jetzt {port}.",
"ix_downgrade.port_downgraded_at_ix":"Der Port bei {ix} ist jetzt {port}.",
"ix_downgrade.transit_downgraded":"{net}-Transit in {city} ist jetzt {port}.",
@ -3043,6 +3173,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"Das Original: Folge einem Paket vom WLAN bis zur Unterseeglasfaser.",
"modals.lay_your_own_subsea_cable":"Eigenes Seekabel verlegen…",
"modals.your_own_subsea_cable_level_n":"Eigenes Seekabel <small>Level {n} oder Tier 1</small>",
"mp.code":"Session-Code",
"mp.copy_link":"Link kopieren",
"mp.door_d":"Eine Welt, die Netze deiner Freunde neben deinem: Code teilen und um Tier 1 wetteifern.",
"mp.err_code":"Ein Session-Code hat sechs Buchstaben und Ziffern, etwa K7Q-2XD.",
"mp.err_full":"Diese Session ist voll: Alle Plätze darin sind vergeben.",
"mp.err_no_session":"Mit diesem Code gibt es keine Session.",
"mp.err_offline":"Der Multiplayer-Server ist gerade nicht erreichbar. Versuch es gleich noch mal.",
"mp.err_refused":"Das hat der Server nicht angenommen. Versuch einen anderen Netznamen.",
"mp.err_server_full":"Der Server nimmt gerade keine neuen Sessions an.",
"mp.err_slow":"Zu viele Versuche von hier. Warte kurz und versuch es noch mal.",
"mp.feed":"Feed",
"mp.feed_empty":"Noch nichts. Sag hallo!",
"mp.feed_join":"{name} ist der Session beigetreten.",
"mp.feed_leave":"{name} hat die Session verlassen.",
"mp.feed_t1":"{name} ist jetzt auch Tier 1.",
"mp.feed_t1first":"{name} ist das erste Tier 1 in dieser Session!",
"mp.feed_t2":"{name} ist jetzt Tier 2.",
"mp.intro":"Alle bauen ihr eigenes Netz in derselben Welt, ab demselben Tag 0, mit denselben Regeln. Rangliste und Feed zeigen, wer vorne liegt.",
"mp.join":"Beitreten",
"mp.join_a_session":"Einer Session beitreten",
"mp.join_note":"Welt und Regeln kommen von dem, der die Session gestartet hat, und deine AS-Nummer bekommst du von der Session.",
"mp.joined":"<b>Du bist Session {code} beigetreten.</b> Öffne die Session, um zu sehen, wer vorne liegt.",
"mp.keep_mine":"Diesen behalten",
"mp.leaderboard":"Rangliste",
"mp.leave":"Session verlassen",
"mp.leave_d":"{name} bleibt auf diesem Gerät als eigenes Spiel. Die Session vergisst es, und sein Spielstand auf dem Server wird gelöscht.",
"mp.leave_q":"Session {code} verlassen?",
"mp.left":"Du hast die Session verlassen. {name} spielt hier allein weiter.",
"mp.link_bad":"Dieser Multiplayer-Link hat nicht funktioniert: Er ist alt, oder dieses Netz hat nie in der Session gespeichert.",
"mp.link_copied":"Link kopiert. Öffne ihn auf deinem anderen Gerät.",
"mp.load_newer":"Neueren Spielstand laden",
"mp.loaded_newer":"Den neueren Spielstand von {name} aus der Session geladen ({date}).",
"mp.loading":"Frage den Server…",
"mp.move_device":"Auf ein anderes Gerät umziehen",
"mp.move_note":"Öffne diesen Link auf deinem anderen Handy oder Computer, um dort mit diesem Netz weiterzumachen. Es zählt, welches Gerät zuletzt speichert.",
"mp.move_warn":"Wer diesen Link hat, kann als du spielen. Behalte ihn für dich.",
"mp.moved_on_elsewhere":"<b>Die Session ist woanders weitergelaufen.</b> Dein Netz wurde seitdem auf einem anderen Gerät gespielt. Lade jenen Spielstand, oder behalte deinen hier und überschreib den auf dem Server.",
"mp.multiplayer":"Multiplayer",
"mp.n_customers":{"one":"{n} Kunde","other":"{n} Kunden"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"hat noch keinen Tag beendet",
"mp.no_newer":"Die Session hat keinen neueren Spielstand von {name}. Dieser bleibt und geht beim nächsten Speichern an den Server.",
"mp.not_in_session":"Dieses Netz ist nicht mehr in seiner Session. Es spielt hier allein weiter.",
"mp.play_with_friends":"Mit Freunden spielen",
"mp.save_unreadable":"Der Spielstand dieses Netzes in der Session war nicht lesbar. Es geht mit dem hier weiter.",
"mp.say":"Sag was",
"mp.send":"Senden",
"mp.server_away":"Der Multiplayer-Server ist weg. Dein Netz spielt hier weiter und holt auf, sobald er zurück ist.",
"mp.session":"Multiplayer-Session",
"mp.session_code":"Session {code}",
"mp.session_live":"<b>Session {code} läuft.</b> Teil den Code: Wer beitritt, baut in derselben Welt.",
"mp.session_title":"Name der Session (optional)",
"mp.share_line":"Komm in meine Series-of-Tubes-Session {code}: {url}",
"mp.share_note":"Freunde treten vom Startbildschirm aus bei: Multiplayer, dann dieser Code.",
"mp.slow_down":"Mach mal langsam: eine Zeile pro Sekunde.",
"mp.start_a_session":"Session starten",
"mp.talking":"Spreche mit dem Server…",
"mp.welcome_device":"<b>{name}</b> ist auf dieses Gerät umgezogen. Willkommen zurück in Session {code}.",
"mp.you":"du",
"networks.a_mobile_network_named_after_the":"Ein Mobilfunknetz, benannt nach dem Klang anstoßender Gläser. Prost auf jeden 5G-Mast.",
"networks.a_spanish_carrier_starring_in_every":"Ein spanischer Carrier mit Hauptrolle in jedem lateinamerikanischen Markt, zumindest bis er den nächsten verkauft.",
"networks.a_tiny_telco_in_a_country":"Eine winzige Telco in einem Land, in dem die Kabel der Welt an Land gehen. Die Preise passen dazu.",
@ -3226,6 +3415,8 @@
"ops.l_decom":{"one":"hat eine kleine Wave auf {where} zurückgegeben","other":"hat {n} kleine Waves zurückgegeben ({where})"},
"ops.l_line":"{name} {list}.",
"ops.l_optics":{"one":"hat einen Kanal auf {where} aufgeschaltet","other":"hat {n} Kanäle aufgeschaltet ({where})"},
"ops.l_optswap":{"one":"hat eine Optik auf {where} gegen eine größere getauscht","other":"hat {n} Optiken gegen größere getauscht ({where})"},
"ops.l_optup":{"one":"hat das Line System auf {where} ausgebaut","other":"hat {n} Line Systems ausgebaut ({where})"},
"ops.l_paid":"Kosten: {cost} einmalig, {mo}/Monat.",
"ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"},
"ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"},
@ -3235,6 +3426,7 @@
"ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"},
"ops.l_rs":{"one":"hat sich einem Route Server angeschlossen","other":"hat sich {n} Route Servern angeschlossen"},
"ops.l_snag":{"one":"ist bei {where} hängen geblieben und hat den Auftrag pausiert, bis du draufschaust","other":"ist bei {n} Aufträgen hängen geblieben ({where}) und hat sie pausiert, bis du draufschaust"},
"ops.l_std":{"one":"hat {where} auf den Build-Standard gebracht","other":"hat {n} Jobs für den Build-Standard erledigt ({where})"},
"ops.l_transit":{"one":"hat Transit in {where} aufgestockt","other":"hat {n}-mal Transit aufgestockt ({where})"},
"ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.",
"ops.model_next":"Nächste Generation, wenn ausgelastet",
@ -3258,6 +3450,8 @@
"ops.o_ix_d":"Jede Woche: den Route Servern beitreten und jedes willige Mitglied an jedem deiner Exchange-Ports fragen.",
"ops.o_optics":"Mehr Dark Fiber beleuchten",
"ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.",
"ops.o_optup":"Optischen Transport ausbauen",
"ops.o_optup_d":"Auf Glasfaser, die voll ist und heiß läuft, das Line System eine Größe hochziehen oder die kleinsten Kanäle gegen größere Optiken tauschen (die alten kommen ins Ersatzteillager). Wähl ein Line System, und jede Faser mit einem kleineren wird darauf hochgezogen. Ein Tausch des Line Systems legt die Faser für einen Tag lahm, also nur, wo der Traffic einen Weg drumherum hat und kein Kunde darauf fährt, einer pro Nacht.",
"ops.o_pni":"PNI mit den Großen",
"ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.",
"ops.o_ports":"Peering-Reserve halten",
@ -3266,6 +3460,8 @@
"ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.",
"ops.o_routers":"Router voraus halten",
"ops.o_routers_desc":"Einen Router dazustellen oder auf die nächste Generation tauschen, wo ein zweiter Router den Traffic trägt, sobald Last oder Ports eine Grenze überschreiten. Wähl ein Modell, und jeder POP mit einem kleineren wird darauf getauscht, der am meisten ausgelastete zuerst, im Rahmen des Budgets.",
"ops.o_std":"Build-Standard einhalten",
"ops.o_std_d":"POPs, Ports und Glasfaser auf deinen Build-Standard bringen, die meistbelasteten zuerst, ein paar Jobs pro Schicht. Vor einem Tausch kommt ein zweiter Router rein, und ein Line System wechselt nur auf einer ruhigen Glasfaser.",
"ops.o_transit":"Transit-Reserve halten",
"ops.o_transit_d":"Transit an jedem POP über einem Vielfachen seiner 30-Tage-Spitze halten: ein LAG-Member dazu oder eine Portgröße hoch.",
"ops.ops":"Ops",
@ -3278,6 +3474,8 @@
"ops.p_paid":"Paid Peering",
"ops.p_pick":"Optiken",
"ops.p_prov":"Anbieter",
"ops.p_swap":"Größere Optiken",
"ops.p_sys":"Line System",
"ops.p_tier":"Größe",
"ops.p_x":"Reserve",
"ops.paused":"Pausiert",
@ -3292,9 +3490,11 @@
"ops.shift_report":"{name}s Woche",
"ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung",
"ops.standing_orders":"Daueraufträge",
"ops.sys_next":"Das nächste, wenn voll",
"ops.template":"Neuer POP aus der Vorlage",
"ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.",
"ops.tpl_bb":"Breitband",
"ops.tpl_bstd":"Build-Standard",
"ops.tpl_done":"{name} hat {city} eröffnet: {list}.",
"ops.tpl_ix":"IX-Port",
"ops.tpl_just_pop":"nur den POP",
@ -3727,6 +3927,7 @@
"pie_traffic.via_dishes":"hoch in {up}, runter in {down}",
"pitcairn.uk_grant_mo":"Zuschuss aus UK {mo}/Monat",
"pitcairn.uk_grant_mo_once_islanders":"Zuschuss aus UK {mo}/Monat, sobald die Inselbewohner online sind",
"pitcairn.uk_grant_needs_a_cable":"Zuschuss aus UK {mo}/Monat nur mit Kabel: gemietete Satellitenkapazität zählt nicht",
"pitcairn.uk_sky_grant_mo":"Satelliten-Zuschuss aus UK {mo}/Monat (Glasfaser bekommt {full})",
"pni_all.additional_per_month":"Zusätzliche Kosten pro Monat",
"pni_all.all_at_port":"Mit allen Netzen peeren · {port}",
@ -3793,12 +3994,12 @@
"pnis.us_east_is_sold_out_until":"US East ist bis auf Weiteres ausverkauft. „Bis auf Weiteres“ ist auch ausverkauft.",
"pop_std.city_gets_the_standard_cost":"{city} bekommt den Standard: {n} × {model} für {cost}.",
"pop_std.clear":"Entfernen",
"pop_std.includes_the_build_standard":"Inklusive deines Build-Standards: {list}, {cost} + {mo}/Monat. Reicht das Geld nicht, bekommt der POP, was passt.",
"pop_std.includes_the_standard_n_model":"Inklusive deiner Standard-Router: {n} × {model}, {cost} + {mo}/Monat. Reicht das Geld nicht, bekommt der POP, was passt.",
"pop_std.make_this_the_standard":"Zum Standard machen",
"pop_std.new_pops_now_start_with":"Neue POPs starten jetzt mit {n} × {model}.",
"pop_std.new_pops_now_start_with_list":"Neue POPs starten jetzt mit {list}.",
"pop_std.none":"Keiner",
"pop_std.not_all_of_the_standard":"Nicht genug Geld oder Level für den ganzen Standard in {city}: Er bekam, was passte.",
"pop_std.standard_for_new_pops":"Standard für neue POPs",
"pops_transit_ix.40_off_for_6_months":"40 % Rabatt für 6 Monate",
"pops_transit_ix.40_off_ix_for_6_months":"<b>40 % Rabatt auf {ix} für 6 Monate.</b><br>Dein Account Manager ist erleichtert. Das Kleingedruckte liest du später.",
"pops_transit_ix.after_consulting_with_management_the":"<b>„Nach Rücksprache mit dem Management …“</b><br>Der Preis ist gestiegen. Das Management wurde konsultiert.",
@ -4334,6 +4535,75 @@
"sales.w_last":"Letzte Woche: {name} {list}.",
"sales.w_now":"Diese Woche: {name} {list}.",
"sales.w_signed":{"one":"hat einen Kunden gewonnen ({rev}/Monat)","other":"hat {n} Kunden gewonnen ({rev}/Monat)"},
"satellites.a_teleport_is_a_satellite_gateway":"Ein Teleport ist ein Satelliten-Gateway: große Schüsseln an diesem POP, die Kapazität auf fremden Satelliten mieten, für kleine Inseln und abgelegene Orte, die kein Kabel erreicht, oder die an einem Kabel und einem Stoßgebet hängen.",
"satellites.add_tracking_antennas_cost_mo":"MEO-Nachführantennen <small>{cost} + {mo}/Monat</small>",
"satellites.being_commissioned":"Wird in Betrieb genommen",
"satellites.build_a_teleport_cost_mo":"Teleport bauen <small>{cost} + {mo}/Monat</small>",
"satellites.by_satellite":"Per Satellit",
"satellites.cancel_n_circuits_first":{"one":"Kündige zuerst seine Satellitenverbindung.","other":"Kündige zuerst seine {n} Satellitenverbindungen."},
"satellites.choose":"Wählen",
"satellites.circuit_ordered":{"one":"<b>{cap} auf {bird} bestellt.</b> {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tag.","other":"<b>{cap} auf {bird} bestellt.</b> {a} ⇄ {b} wird ausgerichtet und getestet: läuft in {n} Tagen."},
"satellites.close_the_teleport":"Teleport schließen",
"satellites.costs_row":"Teleports und Satelliten",
"satellites.geo_dishes":"GEO-Schüsseln",
"satellites.geo_dishes_and_meo_tracking":"GEO-Schüsseln und MEO-Nachführantennen",
"satellites.geo_users_notice":"Aus 36.000 km Höhe dauert die Runde etwa 600 ms: Videocalls und Games ruckeln, und die Nutzer werten {p} des Service als schlecht.",
"satellites.grow_to":"Auf {cap} vergrößern",
"satellites.in_view_list":"In Sicht: {list}.",
"satellites.it_waits_on_standby":"Zwischen den beiden hast du schon einen Link: Der Satellit wartet im Standby und trägt Traffic nur, wenn dieser Link ausfällt.",
"satellites.its_blurb":"Klassische C- und Ku-Band-Strahlen, die einen ganzen Ozean abdecken. Zuverlässig, überall, und so bepreist.",
"satellites.kac_blurb":"Ka-Band-Spotbeams über dem Westpazifik: das billigste Gbps im Orbit, wenn deine Insel unter einem Beam liegt.",
"satellites.meo_comes_at_level":"Der MEO-Ring (etwa 130 ms hin und zurück) kommt auf Level {lv}.",
"satellites.meo_ring_misses_city":"Der MEO-Ring sieht {city} nicht: Er deckt {lat}° beiderseits des Äquators ab.",
"satellites.meo_users_notice":"Viel näher am Boden, etwa 130 ms hin und zurück: Die Nutzer merken kaum etwas ({p} des Service gilt als schlecht).",
"satellites.more_islands_and_towns":"Weitere Inseln und Orte in Sicht",
"satellites.ms_one_way_rtt":"{ms} ms pro Richtung, {rtt} ms hin und zurück",
"satellites.ms_round_trip":"{ms} ms hin und zurück",
"satellites.n_birds_see_both":{"one":"{n} Satellit sieht beide","other":"{n} Satelliten sehen beide"},
"satellites.n_circuits_go_on_standby":{"one":"Deine Satellitenverbindung zwischen {a} und {b} geht neben dem neuen Link in Standby: Sie trägt Traffic nur, wenn dieser Link ausfällt.","other":"Deine {n} Satellitenverbindungen zwischen {a} und {b} gehen neben dem neuen Link in Standby: Sie tragen Traffic nur, wenn dieser Link ausfällt."},
"satellites.n_places_in_reach":{"one":"{n} Insel oder abgelegener Ort in Reichweite auf deinem Level.","other":"{n} Inseln und abgelegene Orte in Reichweite auf deinem Level."},
"satellites.needs_tracking_antennas":"Der MEO-Ring braucht Nachführantennen an deinem Teleport in {city}.",
"satellites.new_pop_cost":"neuer POP {cost}",
"satellites.no_bird_sees_both":"Kein Satellit im Angebot sieht {a} und {b} zugleich.",
"satellites.no_bird_sees_this_city":"Kein Satellit im Angebot sieht diese Stadt.",
"satellites.no_cable_needed_a_pop_here":"Kein Kabel nötig: Eine Satellitenverbindung von einem deiner Teleports bringt einen POP in {city} online.",
"satellites.no_pop_in_city":"Du hast keinen POP in {city}.",
"satellites.no_pop_there_yet":"Noch kein POP in {city}: Der wird gleich mitgebaut ({cost}).",
"satellites.no_such_circuit":"Diese Satellitenverbindung gibt es nicht.",
"satellites.no_teleport_in_city":"Du hast keinen Teleport in {city}.",
"satellites.no_teleport_reaches_city":"Keiner deiner Teleports erreicht {city}. Bau einen an einem POP, dessen Satelliten die Stadt sehen.",
"satellites.not_remote":"{city} ist ein zu großer Markt für Satellitenkapazität: Die ist für kleine Inseln und abgelegene Orte da.",
"satellites.nothing_in_view_from_here":"Von hier ist keine Insel und kein abgelegener Ort in Sicht.",
"satellites.on_standby_beside_your_link":"Er wartet im Standby neben deinem Link zwischen den beiden und trägt Traffic nur, wenn dieser Link ausfällt.",
"satellites.orbit_unlocks_at_level":"{orb}-Satelliten gibt es ab Level {lv}.",
"satellites.out_of_footprint":"{bird} sieht nicht {a} und {b} zugleich.",
"satellites.pointing_dishes_and_testing":"Schüsseln ausrichten und testen",
"satellites.radio_path":"Funkweg, hoch und runter",
"satellites.reachable_from_your_teleports":"Deine Teleports erreichen {city} per Satellit:",
"satellites.really_close_it":"Wirklich schließen?",
"satellites.rent":"Miete",
"satellites.rent_satellite_capacity":"Satellitenkapazität mieten",
"satellites.satellite_capacity":"Satellitenkapazität",
"satellites.satellites":"Satelliten",
"satellites.sea_americas":"Amerika",
"satellites.sea_atlantic":"Atlantik",
"satellites.sea_indian":"Indischer Ozean",
"satellites.sea_pacific":"Pazifik",
"satellites.sea_tropics":"bis 50° um den Äquator",
"satellites.sea_west_pacific":"Westpazifik",
"satellites.sesa_blurb":"Ein Ring aus Satelliten 8.000 km über dem Äquator, für die anderen drei Milliarden. Sesam, öffne dich: etwa 130 ms hin und zurück.",
"satellites.shrink_to":"Auf {cap} verkleinern",
"satellites.teleport":"Teleport",
"satellites.teleport_closed":"Der Teleport in {city} ist geschlossen.",
"satellites.teleport_up_in_city":"<b>Teleport in {city} läuft.</b> Große Schüsseln auf dem Dach, ab in den Himmel: Miete von hier Kapazität zu den Inseln in Sicht.",
"satellites.teleports_unlock_at_level":"Teleports gibt es ab Level {lv}.",
"satellites.tracking_antennas_up":"<b>Nachführantennen in {city} laufen.</b> Sie folgen dem MEO-Ring über den Himmel.",
"satellites.up_in_n_days":{"one":"läuft in {n} Tag","other":"läuft in {n} Tagen"},
"satellites.users_notice_geo_meo":"Die Nutzer merken die Verzögerung: Breitband über GEO zählt als halber Service, über MEO fast als ganzer. Ein Kabel gewinnt immer, deine Router schicken Traffic also nur nach oben, wenn es keinen anderen Weg gibt.",
"satellites.users_ride_a_satellite":"Nutzer hängen am Satelliten",
"satellites.via_bird":"über {bird}",
"satellites.who_a_satellite_serves":"Satelliten bedienen kleine Inseln und abgelegene Orte, die derselbe Satellit sieht wie dein Teleport. Wähle das Ziel.",
"satellites.your_pops_in_view":"Deine POPs in Sicht",
"save.cash_in_the_bank":"{cash} auf der Bank",
"save.import_failed_err":"<b>Import fehlgeschlagen.</b><br>{err}",
"save.load_name":"{name} laden?",
@ -4428,12 +4698,15 @@
"settings.always_2d":"Immer 2D",
"settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.",
"settings.auto_draws_the_map_with_your":"Auto zeichnet die Karte mit deiner Grafikkarte, wenn der Browser es erlaubt, damit auch große Netze flüssig bleiben. Immer 2D läuft überall, ist auf großen Karten aber langsamer.",
"settings.auto_follows_your_device_s_light":"Auto folgt der Hell- oder Dunkel-Einstellung deines Geräts. Dunkel schont nachts die Augen und auf OLED-Bildschirmen den Akku.",
"settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.",
"settings.customers_and_alerts":"Kunden und Warnungen",
"settings.dark":"Dunkel",
"settings.diagnostic_info":"Diagnoseinfos",
"settings.display_and_sound":"Anzeige und Ton",
"settings.for_bug_reports_shows_your_screen":"Für Fehlerberichte: zeigt in einer Ecke die Größe deines Bildschirms, wie die Karte gezeichnet wird (Grafikkarte oder 2D, und warum) und wie schnell.",
"settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen",
"settings.light":"Hell",
"settings.map_drawing":"Kartendarstellung",
"settings.n_min":"{n} Min.",
"settings.n_sec":"{n} s",
@ -4447,6 +4720,7 @@
"settings.the_agent_moves_it":"Der Agent stellt sie",
"settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt",
"settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.",
"settings.theme":"Design",
"settings.this_browser_cannot_so_the_map":"Dieser Browser kann das nicht, also wird die Karte in 2D gezeichnet.",
"settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen",
"settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.",

View file

@ -395,6 +395,48 @@
"broker.win_text":"{name} (AS{asn}) tendió sus propios cables hasta {n} continentes y vende {mo} al mes de capacidad a otros operadores, en {days} días. Los océanos son ahora tu zanja.",
"broker.won_on_date":"Ganado el {date}: tus propios cables cruzan los océanos y los operadores te pagan por usarlos.",
"broker.your_glass_gear_is_already_yours":"Como bróker de cables, toda la fibra, los sistemas de línea, los ópticos, los cables submarinos y los routers para iluminarlos ya son tuyos, diga lo que diga el nivel.",
"bstd.all_up":"Todo cumple el estándar.",
"bstd.any_model":"cualquier modelo",
"bstd.applied":{"one":"Un trabajo hecho para el estándar de red, {cost}.","other":"{n} trabajos hechos para el estándar de red, {cost}."},
"bstd.applied_none":"Ahora mismo no se pudo hacer nada para el estándar de red.",
"bstd.apply_nothing":"Nada por debajo del estándar",
"bstd.apply_now":"Ponerlo todo al día ahora · {cost}",
"bstd.apply_wait":"Nada que hacer hasta que esas fibras estén libres",
"bstd.at_every_pop":"En cada POP",
"bstd.at_least_n":"Al menos {n}",
"bstd.below":"Por debajo del estándar hoy",
"bstd.both_buildings":"Repartidos en los dos edificios",
"bstd.cost_mo":"Costes mensuales",
"bstd.cost_now":"Para ponerlo todo al día ahora",
"bstd.edit":"Editar el estándar de red",
"bstd.every_exchange":"Donde haya un IX",
"bstd.fastest":"La más rápida que llegue",
"bstd.fiber_note":"Cambiar el sistema de línea deja la fibra apagada un día: solo si va tranquila o un enlace paralelo lleva su carga.",
"bstd.from_level":"(nivel {lv})",
"bstd.g_fiber":"Fibra y ondas",
"bstd.g_port":"Puertos y peering",
"bstd.generator":"generador",
"bstd.held":{"one":"Una fibra mantiene por ahora su sistema de línea, hasta que vaya tranquila o un enlace paralelo pueda llevar su carga el día que quede apagada. Mientras tanto recibe la óptica más rápida que admite su sistema de línea.","other":"{n} fibras mantienen por ahora su sistema de línea, hasta que vayan tranquilas o un enlace paralelo pueda llevar su carga el día que queden apagadas. Mientras tanto reciben la óptica más rápida que admite su sistema de línea."},
"bstd.hire_note":"Contrata a un becario del NOC en Ops y mantendrá cada POP, puerto y fibra en el estándar: unos pocos trabajos al día, los más cargados primero, dentro de un presupuesto mensual y solo con dinero de sobra.",
"bstd.in_n_cities":"En al menos {n} ciudades",
"bstd.intern_keeps":"{name} mantiene la red en el estándar",
"bstd.keep":"Dejar como está",
"bstd.l_ix":"Puerto en un IX",
"bstd.l_lag":"Miembros de LAG",
"bstd.l_model":"Modelo de router",
"bstd.l_pni":"PNI por red",
"bstd.l_site2":"Segundo edificio",
"bstd.l_split":"Repartir los LAG",
"bstd.left":{"one":"Queda una cosa por debajo, esperando dinero, una fibra tranquila o que llegue una ampliación.","other":"Quedan {n} cosas por debajo, esperando dinero, una fibra tranquila o que llegue una ampliación."},
"bstd.n_more_targets":{"one":"{n} objetivo más","other":"{n} objetivos más"},
"bstd.new_pops_note":"Un POP nuevo recibe esto enseguida, mientras sigue vacío: sin ventana de mantenimiento. Si falta dinero, recibe lo que alcance. Un modelo aún bloqueado significa el mejor desbloqueado por debajo.",
"bstd.none_set":"Aún no hay estándar: todos los objetivos dicen Dejar como está.",
"bstd.now_line":"Estándar: {list}",
"bstd.or_better":"{x} o mejor",
"bstd.port_note":"Los LAG y el reparto valen para los puertos de tránsito, IX y PNI. Un miembro nuevo de PNI es una ampliación y llega semanas después.",
"bstd.second_building":"segundo edificio",
"bstd.tagline":"Un solo diseño para toda la red: lo que debe tener cada POP, puerto y fibra. Los POP nuevos reciben la parte del POP el día que abren; tu becario, o el botón de abajo, pone el resto al día.",
"bstd.title":"Estándar de red",
"businesses.a_free_pni_with_voda_phony":"Un PNI gratis con Voda-Phony. Equipo: routers Absolute Unit 3.2T, puertos de 3.2T y ondas de 12.8T.",
"businesses.agi_lab_allegedly":"Laboratorio de AGI (supuestamente)",
"businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratorios de AGI (supuestamente) que quieren WAN de IA de 12.8 a 25.6 Tbps, y PNIs gratis con Du-opoly y Ooh-redoo. Equipo: routers Mikrowtik CCR 3.2T.",
@ -1976,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":"<b>No se puede encender {optic} en este exprés.</b><br>{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":"<b>Un lightpath exprés va por esta fibra.</b><br>Desmóntalo primero: ábrelo desde la sección Exprés de esta fibra.","other":"<b>{n} lightpaths exprés van por esta fibra.</b><br>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":"<b>Exprés encendido: {a} ⇄ {b}.</b><br>{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.",
@ -2596,6 +2678,54 @@
"interface.tubecoin_moved_down_p_on_the":"TubeCoin bajó un {p} % de camino a tu cuenta.",
"interface.tubecoin_moved_up_p_on_the":"TubeCoin subió un {p} % de camino a tu cuenta.",
"interface.you_bought_out_bank_they_flew":"<b>Compraste {bank}.</b><br>Se fueron volando a buscar otra startup.",
"ip4.block_size":"Tamaño del bloque",
"ip4.blocks":"Tus bloques",
"ip4.bought":"Has comprado un {p} ({n} direcciones) por {price}.",
"ip4.bought_on":"Comprado el {date}",
"ip4.business":"Usadas por clientes empresariales",
"ip4.buy":"Comprar {price}",
"ip4.cgnat_boxes":"Equipos CGNAT",
"ip4.cgnat_note":"Más hogares por dirección liberan espacio para clientes, pero los juegos y el port forwarding sufren: el {p} de la factura de un hogar con CGNAT se devuelve en reembolsos.",
"ip4.cgnat_ratio":"CGNAT: hogares por dirección",
"ip4.costs_row":"Alquiler de IPv4 y CGNAT",
"ip4.free":"Libres para nuevos clientes (los hogares pasan antes a CGNAT)",
"ip4.from_rir":"Del RIR",
"ip4.give_back":"Devolver",
"ip4.held":"El RIR no volverá a transferir ese bloque antes del {date}.",
"ip4.homes":"Hogares con banda ancha",
"ip4.homes_cgnat":"{n}, {p} detrás de CGNAT",
"ip4.in_use":"Tus clientes necesitan esas direcciones: pon más hogares detrás de CGNAT o consigue antes otro bloque.",
"ip4.lease":"Alquilar {price}/mes",
"ip4.lease_out":"Ceder en alquiler +{price}/mes",
"ip4.leased_in":"Has alquilado un {p} ({n} direcciones) por {price}/mes.",
"ip4.leased_in_mo":"Alquilado · {price}/mes",
"ip4.leased_out":"Tu {p} está cedido en alquiler: +{price}/mes.",
"ip4.leased_out_mo":"Cedido en alquiler · +{price}/mes",
"ip4.leases_in":"Bloques alquilados",
"ip4.leases_out":"Bloques cedidos en alquiler",
"ip4.market":"Mercado de transferencias",
"ip4.market_note":"IPv4 se vende a unos {px} por dirección (los bloques grandes, algo menos), se alquila a {lin} por dirección al mes y, cedido en alquiler, rinde {lout} tras la comisión del bróker. Una venta paga el {p} del precio, y un bloque solo puede volver a transferirse dos años después de su último traspaso.",
"ip4.movable_from":"transferible desde el {date}",
"ip4.n_addresses":{"one":"{n} dirección","other":"{n} direcciones"},
"ip4.n_homes_per_address":{"one":"{n} hogar por dirección","other":"{n} hogares por dirección"},
"ip4.no_grow":"{name} ({city}) quería crecer a {bw}, pero no tenías direcciones IPv4 libres para ello.",
"ip4.no_space":"{name} necesita un {p} de IPv4 ({n} direcciones) y solo hay {free} libres. Compra o alquila un bloque, o pon más hogares detrás de CGNAT.",
"ip4.note":"IPv6 es gratis e infinito. IPv4 se agotó hace años: los clientes empresariales necesitan bloques públicos, y los hogares que no caben comparten direcciones detrás de CGNAT (el tráfico IPv6 rodea la caja).",
"ip4.off":"Con las reglas de esta partida sobra IPv4.",
"ip4.offer_needs":"Necesita un {p} de IPv4 ({n} direcciones); solo hay {free} libres.",
"ip4.preset_plenty":"IPv4 de sobra para todos.",
"ip4.preset_scarce":"IPv4 escasea: cómpralo, alquílalo o compártelo detrás de CGNAT.",
"ip4.really_sell":"¿Vender de verdad por {price}?",
"ip4.refunds":"Reembolsos a gamers enfadados",
"ip4.section":"Espacio de direcciones",
"ip4.sell":"Vender {price}",
"ip4.sold":"Has vendido tu {p} por {price}.",
"ip4.squeezed":"Sin espacio: el {p} de los hogares no cabe ni con {r} hogares por dirección. Sus conexiones fallan y piden reembolsos: compra o alquila un bloque.",
"ip4.take_back":"Recuperar",
"ip4.toast_cgnat":"<b>Tu IPv4 está lleno.</b> El {p} de tus hogares comparte ahora direcciones detrás de CGNAT, y algunos gamers ya han escrito.",
"ip4.toast_out":"<b>Sin IPv4.</b> Ni con {r} hogares por dirección cabe todo el mundo en el CGNAT: compra o alquila un bloque en el banco.",
"ip4.too_many":"Tienes {n} bloques IPv4, el máximo que puede llevar una red. Vende o devuelve bloques pequeños para hacer sitio a uno más grande.",
"ip4.yours":"Tus direcciones IPv4",
"ix_downgrade.pni_downgraded":"El PNI con {net} en {city} ahora es {port}.",
"ix_downgrade.port_downgraded_at_ix":"El puerto en {ix} es ahora de {port}.",
"ix_downgrade.transit_downgraded":"El tránsito de {net} en {city} ahora es {port}.",
@ -3041,6 +3171,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"Lo de verdad: sigue un paquete del Wi-Fi a la fibra submarina.",
"modals.lay_your_own_subsea_cable":"Tender tu propio cable submarino…",
"modals.your_own_subsea_cable_level_n":"Tu propio cable submarino <small>nivel {n} o Tier 1</small>",
"mp.code":"Código de la sesión",
"mp.copy_link":"Copiar el enlace",
"mp.door_d":"Un mundo, las redes de tus amigos junto a la tuya: comparte un código y compite por llegar a Tier 1.",
"mp.err_code":"Un código de sesión tiene seis letras y cifras, como K7Q-2XD.",
"mp.err_full":"Esa sesión está llena: no queda ningún hueco libre.",
"mp.err_no_session":"No hay ninguna sesión con ese código.",
"mp.err_offline":"Ahora mismo no se puede contactar con el servidor multijugador. Inténtalo de nuevo en un momento.",
"mp.err_refused":"El servidor no lo aceptó. Prueba con otro nombre de red.",
"mp.err_server_full":"El servidor no acepta sesiones nuevas ahora mismo.",
"mp.err_slow":"Demasiados intentos desde aquí. Espera un poco y vuelve a intentarlo.",
"mp.feed":"Actividad",
"mp.feed_empty":"Nada todavía. ¡Saluda!",
"mp.feed_join":"{name} se unió a la sesión.",
"mp.feed_leave":"{name} dejó la sesión.",
"mp.feed_t1":"{name} también es Tier 1.",
"mp.feed_t1first":"¡{name} es el primer Tier 1 de esta sesión!",
"mp.feed_t2":"{name} llegó a Tier 2.",
"mp.intro":"Cada uno construye su propia red en el mismo mundo, desde el mismo día 0 y con las mismas reglas. La clasificación y la actividad muestran quién va delante.",
"mp.join":"Unirse",
"mp.join_a_session":"Unirse a una sesión",
"mp.join_note":"El mundo y las reglas los pone quien empezó la sesión, y la sesión te da tu número de AS.",
"mp.joined":"<b>Te uniste a la sesión {code}.</b> Abre la sesión para ver quién va delante.",
"mp.keep_mine":"Quedarme con esta",
"mp.leaderboard":"Clasificación",
"mp.leave":"Dejar la sesión",
"mp.leave_d":"{name} se queda en este dispositivo como una partida propia. La sesión se olvida de ella y su partida guardada en el servidor se borra.",
"mp.leave_q":"¿Dejar la sesión {code}?",
"mp.left":"Dejaste la sesión. {name} sigue jugando aquí por su cuenta.",
"mp.link_bad":"Ese enlace multijugador no funcionó: es antiguo, o esa red nunca guardó en la sesión.",
"mp.link_copied":"Enlace copiado. Ábrelo en tu otro dispositivo.",
"mp.load_newer":"Cargar la más reciente",
"mp.loaded_newer":"Se cargó desde la sesión la partida más reciente de {name} ({date}).",
"mp.loading":"Preguntando al servidor…",
"mp.move_device":"Pasar a otro dispositivo",
"mp.move_note":"Abre este enlace en tu otro móvil u ordenador para seguir allí con esta red. Gana el dispositivo que guarde el último.",
"mp.move_warn":"Cualquiera con este enlace puede jugar como tú. Guárdalo para ti.",
"mp.moved_on_elsewhere":"<b>Esta sesión siguió en otro sitio.</b> Desde entonces tu red se jugó en otro dispositivo. Carga esa partida, o quédate con esta y sobrescríbela.",
"mp.multiplayer":"Multijugador",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"aún no ha terminado ningún día",
"mp.no_newer":"La sesión no tiene una partida más reciente de {name}. Se queda esta, que irá al servidor con el próximo guardado.",
"mp.not_in_session":"Esta red ya no está en su sesión. Sigue jugando aquí por su cuenta.",
"mp.play_with_friends":"Jugar con amigos",
"mp.save_unreadable":"No se pudo leer la partida de esta red en la sesión. Se sigue con la de aquí.",
"mp.say":"Di algo",
"mp.send":"Enviar",
"mp.server_away":"El servidor multijugador no está. Tu red sigue jugando aquí y se pone al día cuando vuelva.",
"mp.session":"Sesión multijugador",
"mp.session_code":"Sesión {code}",
"mp.session_live":"<b>La sesión {code} está en marcha.</b> Comparte el código: quien se una construye en el mismo mundo.",
"mp.session_title":"Nombre de la sesión (opcional)",
"mp.share_line":"Únete a mi sesión de Series of Tubes {code}: {url}",
"mp.share_note":"Tus amigos se unen desde la pantalla de inicio: Multijugador y luego este código.",
"mp.slow_down":"Más despacio: una línea por segundo.",
"mp.start_a_session":"Empezar una sesión",
"mp.talking":"Hablando con el servidor…",
"mp.welcome_device":"<b>{name}</b> se pasó a este dispositivo. Bienvenido de nuevo a la sesión {code}.",
"mp.you":"tú",
"networks.a_mobile_network_named_after_the":"Una red móvil con el nombre del sonido de un brindis. Salud por cada torre 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un operador español protagonista en todos los mercados latinoamericanos, al menos hasta que vende el siguiente.",
"networks.a_tiny_telco_in_a_country":"Una telco diminuta en un país donde llegan a tierra los cables del mundo. Precios a juego.",
@ -3224,6 +3413,8 @@
"ops.l_decom":{"one":"devolvió una wave pequeña en {where}","other":"devolvió {n} waves pequeñas ({where})"},
"ops.l_line":"{name} {list}.",
"ops.l_optics":{"one":"encendió un canal en {where}","other":"encendió {n} canales ({where})"},
"ops.l_optswap":{"one":"cambió una óptica por una más grande en {where}","other":"cambió {n} ópticas por otras más grandes ({where})"},
"ops.l_optup":{"one":"mejoró el sistema de línea en {where}","other":"mejoró {n} sistemas de línea ({where})"},
"ops.l_paid":"Coste: {cost} de entrada, {mo}/mes.",
"ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"},
"ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"},
@ -3233,6 +3424,7 @@
"ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"},
"ops.l_rs":{"one":"se unió a un route server","other":"se unió a {n} route servers"},
"ops.l_snag":{"one":"se atascó con {where} y la pausó hasta que le eches un vistazo","other":"se atascó con {n} órdenes ({where}) y las pausó hasta que les eches un vistazo"},
"ops.l_std":{"one":"puso {where} al nivel del estándar de red","other":"hizo {n} trabajos para el estándar de red ({where})"},
"ops.l_transit":{"one":"amplió el tránsito en {where}","other":"amplió el tránsito {n} veces ({where})"},
"ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.",
"ops.model_next":"Siguiente generación, si va lleno",
@ -3256,6 +3448,8 @@
"ops.o_ix_d":"Cada semana: unirse a los route servers y pedir peering a cada miembro dispuesto en cada uno de tus puertos de exchange.",
"ops.o_optics":"Encender más fibra",
"ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.",
"ops.o_optup":"Mejorar el transporte óptico",
"ops.o_optup_d":"En la fibra que está llena y va caliente, sube el sistema de línea un tamaño o cambia los canales más pequeños por ópticas más grandes (las viejas van a la estantería). Elige un sistema de línea y cada fibra con uno más pequeño sube a ese. Cambiar el sistema de línea deja la fibra sin servicio un día, así que solo donde el tráfico puede rodearla y ningún cliente va por ella, uno por noche.",
"ops.o_pni":"PNI con los grandes",
"ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.",
"ops.o_ports":"Margen en puertos de peering",
@ -3264,6 +3458,8 @@
"ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.",
"ops.o_routers":"Routers por delante",
"ops.o_routers_desc":"Añadir un router, o pasar a la siguiente generación donde un segundo router lleve el tráfico, cuando la carga o los puertos pasen de un nivel. Elige un modelo y cada POP con uno más pequeño se cambia a ese, primero el más cargado, dentro del presupuesto.",
"ops.o_std":"Mantener el estándar de red",
"ops.o_std_d":"Poner los POP, los puertos y la fibra al nivel de tu estándar de red, los más cargados primero, unos pocos trabajos por turno. Antes de un cambio entra un segundo router, y el sistema de línea solo cambia en una fibra tranquila.",
"ops.o_transit":"Margen de tránsito",
"ops.o_transit_d":"Mantener el tránsito de cada POP por encima de un múltiplo de su pico de 30 días: un miembro LAG más o un tamaño de puerto mayor.",
"ops.ops":"Ops",
@ -3276,6 +3472,8 @@
"ops.p_paid":"Peering de pago",
"ops.p_pick":"Ópticas",
"ops.p_prov":"Proveedor",
"ops.p_swap":"Ópticas más grandes",
"ops.p_sys":"Sistema de línea",
"ops.p_tier":"Tamaño",
"ops.p_x":"Margen",
"ops.paused":"En pausa",
@ -3290,9 +3488,11 @@
"ops.shift_report":"La semana de {name}",
"ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura",
"ops.standing_orders":"Órdenes permanentes",
"ops.sys_next":"El siguiente, si está lleno",
"ops.template":"POP nuevo desde plantilla",
"ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.",
"ops.tpl_bb":"Banda ancha",
"ops.tpl_bstd":"estándar de red",
"ops.tpl_done":"{name} abrió {city}: {list}.",
"ops.tpl_ix":"Puerto IX",
"ops.tpl_just_pop":"solo el POP",
@ -3725,6 +3925,7 @@
"pie_traffic.via_dishes":"sube en {up}, baja en {down}",
"pitcairn.uk_grant_mo":"Subvención británica {mo}/mes",
"pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea",
"pitcairn.uk_grant_needs_a_cable":"Subvención británica {mo}/mes solo con cable: la capacidad satelital alquilada no cuenta",
"pitcairn.uk_sky_grant_mo":"Subvención británica por satélite {mo}/mes (la fibra recibe {full})",
"pni_all.additional_per_month":"Coste mensual adicional",
"pni_all.all_at_port":"Peering con todas las redes · {port}",
@ -3791,12 +3992,12 @@
"pnis.us_east_is_sold_out_until":"US East está agotado hasta nuevo aviso. El nuevo aviso también está agotado.",
"pop_std.city_gets_the_standard_cost":"{city} recibe el estándar: {n} × {model} por {cost}.",
"pop_std.clear":"Quitar",
"pop_std.includes_the_build_standard":"Incluye tu estándar de red: {list}, {cost} + {mo}/mes. Si falta dinero, el POP recibe lo que alcance.",
"pop_std.includes_the_standard_n_model":"Incluye tus routers estándar: {n} × {model}, {cost} + {mo}/mes. Si falta dinero, el POP recibe lo que alcance.",
"pop_std.make_this_the_standard":"Convertir en estándar",
"pop_std.new_pops_now_start_with":"Los nuevos POP empiezan ahora con {n} × {model}.",
"pop_std.new_pops_now_start_with_list":"Los nuevos POP empiezan ahora con {list}.",
"pop_std.none":"Ninguno",
"pop_std.not_all_of_the_standard":"No hay dinero o nivel para todo el estándar en {city}: recibió lo que cupo.",
"pop_std.standard_for_new_pops":"Estándar para nuevos POP",
"pops_transit_ix.40_off_for_6_months":"40 % de descuento durante 6 meses",
"pops_transit_ix.40_off_ix_for_6_months":"<b>40 % de descuento en {ix} durante 6 meses.</b><br>Tu gestor de cuenta está aliviado. Lee la letra pequeña más tarde.",
"pops_transit_ix.after_consulting_with_management_the":"<b>«Tras consultar con la dirección…»</b><br>El precio subió. Se consultó a la dirección.",
@ -4332,6 +4533,75 @@
"sales.w_last":"La semana pasada {name} {list}.",
"sales.w_now":"Esta semana {name} {list}.",
"sales.w_signed":{"one":"firmó un cliente ({rev}/mes)","other":"firmó {n} clientes ({rev}/mes)"},
"satellites.a_teleport_is_a_satellite_gateway":"Un teleport es una pasarela satelital: antenas grandes en este POP que alquilan capacidad en satélites ajenos, para islas pequeñas y pueblos remotos a los que no llega ningún cable, o que cuelgan de un solo cable y una plegaria.",
"satellites.add_tracking_antennas_cost_mo":"Antenas de seguimiento MEO <small>{cost} + {mo}/mes</small>",
"satellites.being_commissioned":"En puesta en servicio",
"satellites.build_a_teleport_cost_mo":"Construir un teleport <small>{cost} + {mo}/mes</small>",
"satellites.by_satellite":"Por satélite",
"satellites.cancel_n_circuits_first":{"one":"Primero cancela su circuito satelital.","other":"Primero cancela sus {n} circuitos satelitales."},
"satellites.choose":"Elegir",
"satellites.circuit_ordered":{"one":"<b>{cap} en {bird} pedidos.</b> {a} ⇄ {b} se está apuntando y probando: listo en {n} día.","other":"<b>{cap} en {bird} pedidos.</b> {a} ⇄ {b} se está apuntando y probando: listo en {n} días."},
"satellites.close_the_teleport":"Cerrar el teleport",
"satellites.costs_row":"Teleports y satélites",
"satellites.geo_dishes":"Antenas GEO",
"satellites.geo_dishes_and_meo_tracking":"Antenas GEO y antenas de seguimiento MEO",
"satellites.geo_users_notice":"Desde 36.000 km de altura la ida y vuelta tarda unos 600 ms: las videollamadas y los juegos se traban, y los usuarios cuentan {p} del servicio como malo.",
"satellites.grow_to":"Ampliar a {cap}",
"satellites.in_view_list":"A la vista: {list}.",
"satellites.it_waits_on_standby":"Ya tienes un enlace entre estas dos: el satélite espera en reserva y solo lleva tráfico cuando ese enlace cae.",
"satellites.its_blurb":"Haces de banda C y Ku de toda la vida que cubren un océano entero. Fiables, en todas partes, y con precio a juego.",
"satellites.kac_blurb":"Haces puntuales en banda Ka sobre el Pacífico occidental: el Gbps más barato en órbita, si tu isla queda bajo un haz.",
"satellites.meo_comes_at_level":"El anillo MEO (unos 130 ms de ida y vuelta) llega en el nivel {lv}.",
"satellites.meo_ring_misses_city":"El anillo MEO no ve {city}: cubre {lat}° a cada lado del ecuador.",
"satellites.meo_users_notice":"Mucho más cerca del suelo, unos 130 ms de ida y vuelta: los usuarios apenas lo notan ({p} del servicio cuenta como malo).",
"satellites.more_islands_and_towns":"Más islas y pueblos a la vista",
"satellites.ms_one_way_rtt":"{ms} ms de ida, {rtt} ms de ida y vuelta",
"satellites.ms_round_trip":"{ms} ms de ida y vuelta",
"satellites.n_birds_see_both":{"one":"{n} satélite ve los dos","other":"{n} satélites ven los dos"},
"satellites.n_circuits_go_on_standby":{"one":"Tu circuito satelital entre {a} y {b} pasa a reserva junto al nuevo enlace: solo lleva tráfico cuando ese enlace cae.","other":"Tus {n} circuitos satelitales entre {a} y {b} pasan a reserva junto al nuevo enlace: solo llevan tráfico cuando ese enlace cae."},
"satellites.n_places_in_reach":{"one":"{n} isla o pueblo remoto a tu alcance en tu nivel.","other":"{n} islas y pueblos remotos a tu alcance en tu nivel."},
"satellites.needs_tracking_antennas":"El anillo MEO necesita antenas de seguimiento en tu teleport de {city}.",
"satellites.new_pop_cost":"POP nuevo {cost}",
"satellites.no_bird_sees_both":"Ningún satélite a la venta ve a la vez {a} y {b}.",
"satellites.no_bird_sees_this_city":"Ningún satélite a la venta ve esta ciudad.",
"satellites.no_cable_needed_a_pop_here":"Sin cable: un circuito satelital desde uno de tus teleports pone en línea un POP en {city}.",
"satellites.no_pop_in_city":"No tienes POP en {city}.",
"satellites.no_pop_there_yet":"Aún no hay POP en {city}: esto también construye uno ({cost}).",
"satellites.no_such_circuit":"Ese circuito satelital no existe.",
"satellites.no_teleport_in_city":"No tienes teleport en {city}.",
"satellites.no_teleport_reaches_city":"Ninguno de tus teleports llega a {city}. Construye uno en un POP cuyos satélites la vean.",
"satellites.not_remote":"{city} es un mercado demasiado grande para capacidad satelital: es para islas pequeñas y pueblos remotos.",
"satellites.nothing_in_view_from_here":"Desde aquí no hay ninguna isla ni pueblo remoto a la vista.",
"satellites.on_standby_beside_your_link":"Espera en reserva junto a tu enlace entre las dos y solo lleva tráfico cuando ese enlace cae.",
"satellites.orbit_unlocks_at_level":"Los satélites {orb} se desbloquean en el nivel {lv}.",
"satellites.out_of_footprint":"{bird} no ve a la vez {a} y {b}.",
"satellites.pointing_dishes_and_testing":"Apuntando antenas y probando",
"satellites.radio_path":"Trayecto de radio, subida y bajada",
"satellites.reachable_from_your_teleports":"Tus teleports llegan a {city} por satélite:",
"satellites.really_close_it":"¿Cerrarlo de verdad?",
"satellites.rent":"Alquiler",
"satellites.rent_satellite_capacity":"Alquilar capacidad satelital",
"satellites.satellite_capacity":"Capacidad satelital",
"satellites.satellites":"Satélites",
"satellites.sea_americas":"Américas",
"satellites.sea_atlantic":"Atlántico",
"satellites.sea_indian":"Océano Índico",
"satellites.sea_pacific":"Pacífico",
"satellites.sea_tropics":"hasta 50° del ecuador",
"satellites.sea_west_pacific":"Pacífico occidental",
"satellites.sesa_blurb":"Un anillo de satélites a 8.000 km sobre el ecuador, para los otros tres mil millones. Ábrete, sésamo: unos 130 ms de ida y vuelta.",
"satellites.shrink_to":"Reducir a {cap}",
"satellites.teleport":"Teleport",
"satellites.teleport_closed":"El teleport de {city} está cerrado.",
"satellites.teleport_up_in_city":"<b>Teleport en marcha en {city}.</b> Antenas enormes en la azotea, apuntando al cielo: alquila desde aquí capacidad hacia las islas a la vista.",
"satellites.teleports_unlock_at_level":"Los teleports se desbloquean en el nivel {lv}.",
"satellites.tracking_antennas_up":"<b>Antenas de seguimiento en marcha en {city}.</b> Siguen el anillo MEO por el cielo.",
"satellites.up_in_n_days":{"one":"listo en {n} día","other":"listo en {n} días"},
"satellites.users_notice_geo_meo":"Los usuarios notan el retardo: la banda ancha por GEO cuenta como medio servicio, por MEO casi como el servicio entero. Un cable siempre gana, así que tus routers solo mandan tráfico arriba cuando no hay otro camino.",
"satellites.users_ride_a_satellite":"usuarios vía satélite",
"satellites.via_bird":"vía {bird}",
"satellites.who_a_satellite_serves":"Los satélites sirven a islas pequeñas y pueblos remotos que ve el mismo satélite que tu teleport. Elige el destino.",
"satellites.your_pops_in_view":"Tus POP a la vista",
"save.cash_in_the_bank":"{cash} en el banco",
"save.import_failed_err":"<b>Falló la importación.</b><br>{err}",
"save.load_name":"¿Cargar {name}?",
@ -4426,12 +4696,15 @@
"settings.always_2d":"Siempre 2D",
"settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.",
"settings.auto_draws_the_map_with_your":"Auto dibuja el mapa con tu tarjeta gráfica cuando el navegador lo permite, y así las redes grandes siguen fluidas. Siempre 2D funciona en todas partes, pero va más lento en mapas grandes.",
"settings.auto_follows_your_device_s_light":"Auto sigue el ajuste claro u oscuro de tu dispositivo. El oscuro descansa la vista de noche y ahorra batería en pantallas OLED.",
"settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.",
"settings.customers_and_alerts":"Clientes y alertas",
"settings.dark":"Oscuro",
"settings.diagnostic_info":"Información de diagnóstico",
"settings.display_and_sound":"Pantalla y sonido",
"settings.for_bug_reports_shows_your_screen":"Para informar de fallos: muestra en una esquina el tamaño de tu pantalla, cómo se dibuja el mapa (tarjeta gráfica o 2D, y por qué) y a qué velocidad.",
"settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue",
"settings.light":"Claro",
"settings.map_drawing":"Dibujo del mapa",
"settings.n_min":"{n} min",
"settings.n_sec":"{n} s",
@ -4445,6 +4718,7 @@
"settings.the_agent_moves_it":"Lo mueve el agente",
"settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente",
"settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.",
"settings.theme":"Tema",
"settings.this_browser_cannot_so_the_map":"Este navegador no puede, así que el mapa se dibuja en 2D.",
"settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta",
"settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.",

View file

@ -395,6 +395,48 @@
"broker.win_text":"{name} (AS{asn}) a posé ses propres câbles jusqu’à {n} continents et vend {mo} de capacité par mois à d’autres opérateurs, en {days} jours. Les océans sont ta tranchée maintenant.",
"broker.won_on_date":"Gagné le {date} : tes propres câbles traversent les océans, et les opérateurs te paient pour s’en servir.",
"broker.your_glass_gear_is_already_yours":"En courtier en câbles, toute la fibre, les systèmes de ligne, les optiques, les câbles sous-marins et les routeurs pour les allumer sont déjà à toi, quoi que dise le niveau.",
"bstd.all_up":"Tout est au standard.",
"bstd.any_model":"n’importe quel modèle",
"bstd.applied":{"one":"Un chantier fait pour le standard réseau, {cost}.","other":"{n} chantiers faits pour le standard réseau, {cost}."},
"bstd.applied_none":"Rien n’a pu être fait pour le standard réseau pour l’instant.",
"bstd.apply_nothing":"Rien sous le standard",
"bstd.apply_now":"Tout mettre à niveau maintenant · {cost}",
"bstd.apply_wait":"Rien à faire tant que ces fibres ne sont pas libres",
"bstd.at_every_pop":"Dans chaque POP",
"bstd.at_least_n":"Au moins {n}",
"bstd.below":"Sous le standard aujourd’hui",
"bstd.both_buildings":"Répartis sur les deux bâtiments",
"bstd.cost_mo":"Coûts mensuels",
"bstd.cost_now":"Pour tout mettre à niveau maintenant",
"bstd.edit":"Modifier le standard réseau",
"bstd.every_exchange":"Partout où il y a un IX",
"bstd.fastest":"La plus rapide qui porte",
"bstd.fiber_note":"Changer le système de ligne éteint la fibre pendant un jour : seulement si elle est calme ou qu’un lien parallèle porte sa charge.",
"bstd.from_level":"(niveau {lv})",
"bstd.g_fiber":"Fibre et longueurs d’onde",
"bstd.g_port":"Ports et peering",
"bstd.generator":"groupe électrogène",
"bstd.held":{"one":"Une fibre garde son système de ligne pour l’instant, jusqu’à ce qu’elle soit calme ou qu’un lien parallèle puisse porter sa charge le jour où elle est éteinte. D’ici là, elle reçoit l’optique la plus rapide que son système de ligne accepte.","other":"{n} fibres gardent leur système de ligne pour l’instant, jusqu’à ce qu’elles soient calmes ou qu’un lien parallèle puisse porter leur charge le jour où elles sont éteintes. D’ici là, elles reçoivent l’optique la plus rapide que leur système de ligne accepte."},
"bstd.hire_note":"Recrute un stagiaire NOC dans Ops et il garde chaque POP, port et fibre au standard : quelques chantiers par jour, les plus chargés d’abord, dans un budget mensuel et seulement avec de l’argent en trop.",
"bstd.in_n_cities":"Dans au moins {n} villes",
"bstd.intern_keeps":"{name} garde le réseau au standard",
"bstd.keep":"Laisser tel quel",
"bstd.l_ix":"Port IX",
"bstd.l_lag":"Membres de LAG",
"bstd.l_model":"Modèle de routeur",
"bstd.l_pni":"PNI par réseau",
"bstd.l_site2":"Second bâtiment",
"bstd.l_split":"Répartir les LAG",
"bstd.left":{"one":"Encore un élément en dessous : il attend de l’argent, une fibre calme ou une extension.","other":"Encore {n} éléments en dessous : ils attendent de l’argent, une fibre calme ou une extension."},
"bstd.n_more_targets":{"one":"{n} autre objectif","other":"{n} autres objectifs"},
"bstd.new_pops_note":"Un nouveau POP reçoit tout ça d’un coup, tant qu’il est vide : pas de fenêtre de maintenance. Si l’argent manque, il reçoit ce qui rentre. Un modèle pas encore débloqué veut dire le meilleur débloqué en dessous.",
"bstd.none_set":"Pas encore de standard : chaque objectif est sur Laisser tel quel.",
"bstd.now_line":"Standard : {list}",
"bstd.or_better":"{x} ou mieux",
"bstd.port_note":"LAG et répartition valent pour les ports de transit, IX et PNI. Un nouveau membre de PNI est une extension et arrive des semaines plus tard.",
"bstd.second_building":"second bâtiment",
"bstd.tagline":"Un seul design pour tout le réseau : ce que chaque POP, port et fibre doit avoir. Les nouveaux POP reçoivent la partie POP le jour de leur ouverture ; ton stagiaire, ou le bouton plus bas, met le reste à niveau.",
"bstd.title":"Standard réseau",
"businesses.a_free_pni_with_voda_phony":"Un PNI gratuit avec Voda-Phony. Matos : routeurs Absolute Unit 3.2T, ports 3.2T et longueurs d’onde 12.8T.",
"businesses.agi_lab_allegedly":"Labo d’AGI (soi-disant)",
"businesses.agi_labs_allegedly_wanting_ai_wans":"Des labos d’AGI (soi-disant) qui veulent des WAN IA de 12,8 à 25,6 Tbps, et des PNI gratuits avec Du-opoly et Ooh-redoo. Matos : routeurs Mikrowtik CCR 3.2T.",
@ -1976,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":"<b>Impossible d’allumer {optic} sur cet express.</b><br>{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":"<b>Un lightpath express passe par cette fibre.</b><br>Démonte-le d’abord : ouvre-le depuis la section Express de cette fibre.","other":"<b>{n} lightpaths express passent par cette fibre.</b><br>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":"<b>Express allumé : {a} ⇄ {b}.</b><br>{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.",
@ -2596,6 +2678,54 @@
"interface.tubecoin_moved_down_p_on_the":"Le TubeCoin a perdu {p} % en route vers ton compte.",
"interface.tubecoin_moved_up_p_on_the":"Le TubeCoin a pris {p} % en route vers ton compte.",
"interface.you_bought_out_bank_they_flew":"<b>Tu as racheté la part de {bank}.</b><br>Ils se sont envolés à la recherche d’une autre startup.",
"ip4.block_size":"Taille du bloc",
"ip4.blocks":"Tes blocs",
"ip4.bought":"Tu as acheté un {p} ({n} adresses) pour {price}.",
"ip4.bought_on":"Acheté le {date}",
"ip4.business":"Utilisées par les clients pros",
"ip4.buy":"Acheter {price}",
"ip4.cgnat_boxes":"Boîtiers CGNAT",
"ip4.cgnat_note":"Plus de foyers par adresse libère de la place pour les clients, mais les jeux et la redirection de ports en pâtissent : {p} de la facture d’un foyer derrière le CGNAT repart en remboursements.",
"ip4.cgnat_ratio":"CGNAT : foyers par adresse",
"ip4.costs_row":"Locations IPv4 et CGNAT",
"ip4.free":"Libres pour de nouveaux clients (les foyers passent d’abord derrière le CGNAT)",
"ip4.from_rir":"Attribué par le RIR",
"ip4.give_back":"Le rendre",
"ip4.held":"Le RIR ne transférera pas ce bloc avant le {date}.",
"ip4.homes":"Foyers en haut débit",
"ip4.homes_cgnat":"{n}, dont {p} derrière le CGNAT",
"ip4.in_use":"Tes clients ont besoin de ces adresses : mets plus de foyers derrière le CGNAT ou trouve d’abord un autre bloc.",
"ip4.lease":"Louer {price}/mois",
"ip4.lease_out":"Mettre en location +{price}/mois",
"ip4.leased_in":"Tu as loué un {p} ({n} adresses) pour {price}/mois.",
"ip4.leased_in_mo":"Loué · {price}/mois",
"ip4.leased_out":"Ton {p} est en location : +{price}/mois.",
"ip4.leased_out_mo":"Mis en location · +{price}/mois",
"ip4.leases_in":"Blocs loués",
"ip4.leases_out":"Blocs mis en location",
"ip4.market":"Marché des transferts",
"ip4.market_note":"L’IPv4 se vend environ {px} l’adresse (un peu moins pour les gros blocs), se loue {lin} l’adresse par mois et, mis en location, rapporte {lout} après la part du courtier. Une vente rapporte {p} du prix, et un bloc ne peut être transféré à nouveau que deux ans après son dernier transfert.",
"ip4.movable_from":"transférable à partir du {date}",
"ip4.n_addresses":{"one":"{n} adresse","other":"{n} adresses"},
"ip4.n_homes_per_address":{"one":"{n} foyer par adresse","other":"{n} foyers par adresse"},
"ip4.no_grow":"{name} ({city}) voulait passer à {bw}, mais tu n’avais pas d’adresses IPv4 libres pour ça.",
"ip4.no_space":"{name} a besoin d’un {p} d’IPv4 ({n} adresses), et seulement {free} sont libres. Achète ou loue un bloc, ou mets plus de foyers derrière le CGNAT.",
"ip4.note":"L’IPv6 est gratuit et sans fin. L’IPv4 est épuisé depuis des années : les clients pros ont besoin de blocs publics, et les foyers qui ne rentrent plus partagent des adresses derrière le CGNAT (le trafic IPv6 contourne la boîte).",
"ip4.off":"Avec les règles de cette partie, l’IPv4 ne manque pas.",
"ip4.offer_needs":"Il lui faut un {p} d’IPv4 ({n} adresses) ; seulement {free} libres.",
"ip4.preset_plenty":"De l’IPv4 à volonté pour tout le monde.",
"ip4.preset_scarce":"L’IPv4 est rare : achète-le, loue-le ou partage-le derrière le CGNAT.",
"ip4.really_sell":"Vraiment vendre pour {price} ?",
"ip4.refunds":"Remboursements aux gamers grincheux",
"ip4.section":"Espace d’adressage",
"ip4.sell":"Vendre {price}",
"ip4.sold":"Ton {p} est vendu pour {price}.",
"ip4.squeezed":"Plus de place : {p} des foyers ne rentrent pas, même à {r} foyers par adresse. Leurs connexions lâchent et ils veulent être remboursés : achète ou loue un bloc.",
"ip4.take_back":"Le reprendre",
"ip4.toast_cgnat":"<b>Ton IPv4 est plein.</b> {p} de tes foyers partagent maintenant des adresses derrière le CGNAT, et quelques gamers ont déjà écrit.",
"ip4.toast_out":"<b>Plus d’IPv4.</b> Même à {r} foyers par adresse, le CGNAT ne suffit pas pour tout le monde : achète ou loue un bloc à la banque.",
"ip4.too_many":"Tu as {n} blocs IPv4, le maximum qu’un réseau peut garder. Vends ou rends de petits blocs pour faire de la place à un plus grand.",
"ip4.yours":"Tes adresses IPv4",
"ix_downgrade.pni_downgraded":"Le PNI avec {net} à {city} est maintenant en {port}.",
"ix_downgrade.port_downgraded_at_ix":"Le port chez {ix} est maintenant en {port}.",
"ix_downgrade.transit_downgraded":"Le transit {net} à {city} est maintenant en {port}.",
@ -3041,6 +3171,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"La version réelle : suis un paquet du Wi-Fi à la fibre sous-marine.",
"modals.lay_your_own_subsea_cable":"Pose ton propre câble sous-marin…",
"modals.your_own_subsea_cable_level_n":"Ton propre câble sous-marin <small>niveau {n} ou Tier 1</small>",
"mp.code":"Code de la session",
"mp.copy_link":"Copier le lien",
"mp.door_d":"Un seul monde, les réseaux de tes amis à côté du tien : partage un code et fonce vers le Tier 1.",
"mp.err_code":"Un code de session a six lettres et chiffres, comme K7Q-2XD.",
"mp.err_full":"Cette session est pleine : toutes les places sont prises.",
"mp.err_no_session":"Aucune session n'a ce code.",
"mp.err_offline":"Le serveur multijoueur est injoignable pour l'instant. Réessaie dans un moment.",
"mp.err_refused":"Le serveur n'a pas accepté. Essaie un autre nom de réseau.",
"mp.err_server_full":"Le serveur n'accepte pas de nouvelles sessions pour l'instant.",
"mp.err_slow":"Trop d'essais depuis ici. Attends un peu et réessaie.",
"mp.feed":"Fil",
"mp.feed_empty":"Rien pour l'instant. Dis bonjour !",
"mp.feed_join":"{name} a rejoint la session.",
"mp.feed_leave":"{name} a quitté la session.",
"mp.feed_t1":"{name} est Tier 1 aussi.",
"mp.feed_t1first":"{name} est le premier Tier 1 de cette session !",
"mp.feed_t2":"{name} est passé Tier 2.",
"mp.intro":"Chacun construit son propre réseau dans le même monde, depuis le même jour 0, avec les mêmes règles. Le classement et le fil montrent qui mène.",
"mp.join":"Rejoindre",
"mp.join_a_session":"Rejoindre une session",
"mp.join_note":"Le monde et les règles viennent de qui a lancé la session, et la session te donne ton numéro d'AS.",
"mp.joined":"<b>Tu as rejoint la session {code}.</b> Ouvre la session pour voir qui mène.",
"mp.keep_mine":"Garder celle-ci",
"mp.leaderboard":"Classement",
"mp.leave":"Quitter la session",
"mp.leave_d":"{name} reste sur cet appareil comme une partie à part entière. La session l'oublie, et sa sauvegarde sur le serveur est supprimée.",
"mp.leave_q":"Quitter la session {code} ?",
"mp.left":"Tu as quitté la session. {name} continue ici en solo.",
"mp.link_bad":"Ce lien multijoueur n'a pas marché : il est trop vieux, ou ce réseau n'a jamais sauvegardé dans la session.",
"mp.link_copied":"Lien copié. Ouvre-le sur ton autre appareil.",
"mp.load_newer":"Charger la plus récente",
"mp.loaded_newer":"Sauvegarde plus récente de {name} chargée depuis la session ({date}).",
"mp.loading":"Je demande au serveur…",
"mp.move_device":"Passer sur un autre appareil",
"mp.move_note":"Ouvre ce lien sur ton autre téléphone ou ordinateur pour continuer ce réseau là-bas. C'est l'appareil qui sauvegarde en dernier qui gagne.",
"mp.move_warn":"Quiconque a ce lien peut jouer à ta place. Garde-le pour toi.",
"mp.moved_on_elsewhere":"<b>Cette session a avancé ailleurs.</b> Ton réseau a été joué sur un autre appareil depuis. Charge cette sauvegarde, ou garde celle-ci et écrase l'autre.",
"mp.multiplayer":"Multijoueur",
"mp.n_customers":{"one":"{n} client","other":"{n} clients"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POP"},
"mp.no_card":"n'a pas encore fini de journée",
"mp.no_newer":"La session n'a pas de sauvegarde plus récente de {name}. Celle-ci reste, et part au serveur à la prochaine sauvegarde.",
"mp.not_in_session":"Ce réseau n'est plus dans sa session. Il continue ici en solo.",
"mp.play_with_friends":"Jouer avec des amis",
"mp.save_unreadable":"La sauvegarde de ce réseau dans la session est illisible. On continue avec celle d'ici.",
"mp.say":"Dis quelque chose",
"mp.send":"Envoyer",
"mp.server_away":"Le serveur multijoueur est absent. Ton réseau continue ici et se met à jour à son retour.",
"mp.session":"Session multijoueur",
"mp.session_code":"Session {code}",
"mp.session_live":"<b>La session {code} est lancée.</b> Partage le code : qui la rejoint construit dans le même monde.",
"mp.session_title":"Nom de la session (facultatif)",
"mp.share_line":"Rejoins ma session Series of Tubes {code} : {url}",
"mp.share_note":"Tes amis rejoignent depuis l'écran d'accueil : Multijoueur, puis ce code.",
"mp.slow_down":"Doucement : une ligne par seconde.",
"mp.start_a_session":"Lancer une session",
"mp.talking":"Je parle au serveur…",
"mp.welcome_device":"<b>{name}</b> est passé sur cet appareil. Bon retour dans la session {code}.",
"mp.you":"toi",
"networks.a_mobile_network_named_after_the":"Un réseau mobile qui porte le nom du bruit d’un toast. Tchin-tchin à chaque antenne 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un opérateur espagnol en vedette sur chaque marché d’Amérique latine, au moins jusqu’à ce qu’il revende le suivant.",
"networks.a_tiny_telco_in_a_country":"Un tout petit opérateur dans un pays où les câbles du monde entier touchent terre. Tarifs à l’avenant.",
@ -3224,6 +3413,8 @@
"ops.l_decom":{"one":"a rendu une petite wave sur {where}","other":"a rendu {n} petites waves ({where})"},
"ops.l_line":"{name} {list}.",
"ops.l_optics":{"one":"a allumé un canal sur {where}","other":"a allumé {n} canaux ({where})"},
"ops.l_optswap":{"one":"a remplacé une optique par une plus grande sur {where}","other":"a remplacé {n} optiques par de plus grandes ({where})"},
"ops.l_optup":{"one":"a amélioré le système de ligne sur {where}","other":"a amélioré {n} systèmes de ligne ({where})"},
"ops.l_paid":"Coût : {cost} d'entrée, {mo}/mois.",
"ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"},
"ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"},
@ -3233,6 +3424,7 @@
"ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"},
"ops.l_rs":{"one":"a rejoint un route server","other":"a rejoint {n} route servers"},
"ops.l_snag":{"one":"a calé sur {where} et l'a mis en pause en attendant que tu jettes un œil","other":"a calé sur {n} ordres ({where}) et les a mis en pause en attendant que tu jettes un œil"},
"ops.l_std":{"one":"a mis {where} au standard réseau","other":"a fait {n} chantiers pour le standard réseau ({where})"},
"ops.l_transit":{"one":"a renforcé le transit à {where}","other":"a renforcé le transit {n} fois ({where})"},
"ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.",
"ops.model_next":"Génération suivante, si chargé",
@ -3256,6 +3448,8 @@
"ops.o_ix_d":"Chaque semaine : rejoindre les route servers et solliciter chaque membre partant sur chacun de tes ports d'exchange.",
"ops.o_optics":"Allumer plus de fibre",
"ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.",
"ops.o_optup":"Améliorer le transport optique",
"ops.o_optup_d":"Sur une fibre pleine qui chauffe, passer le système de ligne à la taille au-dessus, ou échanger les plus petits canaux contre des optiques plus grandes (les anciennes partent sur l’étagère). Choisissez un système de ligne, et chaque fibre équipée d’un plus petit y passe. Un changement de système de ligne coupe la fibre pour une journée : seulement là où le trafic peut la contourner et où aucun client ne passe, un par nuit.",
"ops.o_pni":"PNI avec les gros",
"ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.",
"ops.o_ports":"Garder de la marge sur les ports de peering",
@ -3264,6 +3458,8 @@
"ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.",
"ops.o_routers":"Garder les routeurs en avance",
"ops.o_routers_desc":"Ajouter un routeur, ou passer à la génération suivante là où un second routeur porte le trafic, quand la charge ou les ports dépassent un seuil. Choisissez un modèle, et chaque POP équipé d’un plus petit passe à celui-ci, le plus chargé d’abord, dans la limite du budget.",
"ops.o_std":"Tenir le standard réseau",
"ops.o_std_d":"Mettre POP, ports et fibre au niveau de ton standard réseau, les plus chargés d’abord, quelques chantiers par service. Un second routeur arrive avant un échange, et le système de ligne ne change que sur une fibre calme.",
"ops.o_transit":"Garder de la marge de transit",
"ops.o_transit_d":"Garder le transit de chaque POP au-dessus d'un multiple de son pic sur 30 jours : un membre LAG de plus, ou une taille de port au-dessus.",
"ops.ops":"Ops",
@ -3276,6 +3472,8 @@
"ops.p_paid":"Peering payant",
"ops.p_pick":"Optiques",
"ops.p_prov":"Fournisseur",
"ops.p_swap":"Optiques plus grandes",
"ops.p_sys":"Système de ligne",
"ops.p_tier":"Taille",
"ops.p_x":"Marge",
"ops.paused":"En pause",
@ -3290,9 +3488,11 @@
"ops.shift_report":"La semaine de {name}",
"ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture",
"ops.standing_orders":"Ordres permanents",
"ops.sys_next":"Le suivant, quand c’est plein",
"ops.template":"Nouveau POP depuis le modèle",
"ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.",
"ops.tpl_bb":"Haut débit",
"ops.tpl_bstd":"standard réseau",
"ops.tpl_done":"{name} a ouvert {city} : {list}.",
"ops.tpl_ix":"Port IX",
"ops.tpl_just_pop":"juste le POP",
@ -3725,6 +3925,7 @@
"pie_traffic.via_dishes":"monte à {up}, descend à {down}",
"pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois",
"pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne",
"pitcairn.uk_grant_needs_a_cable":"Subvention britannique {mo}/mois seulement avec un câble : la capacité satellite louée ne compte pas",
"pitcairn.uk_sky_grant_mo":"Subvention britannique satellite {mo}/mois (la fibre touche {full})",
"pni_all.additional_per_month":"Coût mensuel supplémentaire",
"pni_all.all_at_port":"Peering avec tous les réseaux · {port}",
@ -3791,12 +3992,12 @@
"pnis.us_east_is_sold_out_until":"US East est complet jusqu’à nouvel ordre. Le nouvel ordre est complet aussi.",
"pop_std.city_gets_the_standard_cost":"{city} reçoit le standard : {n} × {model} pour {cost}.",
"pop_std.clear":"Effacer",
"pop_std.includes_the_build_standard":"Inclut ton standard réseau : {list}, {cost} + {mo}/mois. Si l’argent manque, le POP reçoit ce qui rentre.",
"pop_std.includes_the_standard_n_model":"Inclut tes routeurs standard : {n} × {model}, {cost} + {mo}/mois. Si l’argent manque, le POP reçoit ce qui rentre.",
"pop_std.make_this_the_standard":"En faire le standard",
"pop_std.new_pops_now_start_with":"Les nouveaux POP démarrent désormais avec {n} × {model}.",
"pop_std.new_pops_now_start_with_list":"Les nouveaux POP démarrent désormais avec {list}.",
"pop_std.none":"Aucun",
"pop_std.not_all_of_the_standard":"Pas assez d'argent ou de niveau pour tout le standard à {city} : il a reçu ce qui passait.",
"pop_std.standard_for_new_pops":"Standard des nouveaux POP",
"pops_transit_ix.40_off_for_6_months":"40 % de remise pendant 6 mois",
"pops_transit_ix.40_off_ix_for_6_months":"<b>40 % de remise sur {ix} pendant 6 mois.</b><br>Ton account manager est soulagé. Lis les petites lignes plus tard.",
"pops_transit_ix.after_consulting_with_management_the":"<b>« Après consultation de la direction… »</b><br>Le prix a augmenté. La direction a été consultée.",
@ -4332,6 +4533,75 @@
"sales.w_last":"La semaine dernière, {name} {list}.",
"sales.w_now":"Cette semaine, {name} {list}.",
"sales.w_signed":{"one":"a signé un client ({rev}/mois)","other":"a signé {n} clients ({rev}/mois)"},
"satellites.a_teleport_is_a_satellite_gateway":"Un téléport est une passerelle satellite : de grandes paraboles sur ce POP qui louent de la capacité sur les satellites des autres, vers les petites îles et les villes isolées qu’aucun câble ne dessert, ou qui ne tiennent qu’à un câble et une prière.",
"satellites.add_tracking_antennas_cost_mo":"Antennes de poursuite MEO <small>{cost} + {mo}/mois</small>",
"satellites.being_commissioned":"Mise en service",
"satellites.build_a_teleport_cost_mo":"Construire un téléport <small>{cost} + {mo}/mois</small>",
"satellites.by_satellite":"Par satellite",
"satellites.cancel_n_circuits_first":{"one":"Résilie d’abord son circuit satellite.","other":"Résilie d’abord ses {n} circuits satellite."},
"satellites.choose":"Choisir",
"satellites.circuit_ordered":{"one":"<b>{cap} sur {bird} commandé.</b> {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jour.","other":"<b>{cap} sur {bird} commandé.</b> {a} ⇄ {b} est en cours de pointage et de test : en service dans {n} jours."},
"satellites.close_the_teleport":"Fermer le téléport",
"satellites.costs_row":"Téléports et satellites",
"satellites.geo_dishes":"Paraboles GEO",
"satellites.geo_dishes_and_meo_tracking":"Paraboles GEO et antennes de poursuite MEO",
"satellites.geo_users_notice":"Depuis 36 000 km d’altitude, l’aller-retour prend environ 600 ms : visios et jeux saccadent, et les utilisateurs comptent {p} du service comme mauvais.",
"satellites.grow_to":"Passer à {cap}",
"satellites.in_view_list":"En vue : {list}.",
"satellites.it_waits_on_standby":"Tu as déjà un lien entre ces deux villes : le satellite attend en réserve et ne porte du trafic que quand ce lien tombe.",
"satellites.its_blurb":"De bons vieux faisceaux en bande C et Ku qui couvrent tout un océan. Fiables, partout, et facturés en conséquence.",
"satellites.kac_blurb":"Des spots en bande Ka sur le Pacifique occidental : le Gbps le moins cher en orbite, si ton île est sous un spot.",
"satellites.meo_comes_at_level":"L’anneau MEO (environ 130 ms aller-retour) arrive au niveau {lv}.",
"satellites.meo_ring_misses_city":"L’anneau MEO ne voit pas {city} : il couvre {lat}° de part et d’autre de l’équateur.",
"satellites.meo_users_notice":"Bien plus près du sol, environ 130 ms aller-retour : les utilisateurs le remarquent à peine ({p} du service compte comme mauvais).",
"satellites.more_islands_and_towns":"Autres îles et villes en vue",
"satellites.ms_one_way_rtt":"{ms} ms aller, {rtt} ms aller-retour",
"satellites.ms_round_trip":"{ms} ms aller-retour",
"satellites.n_birds_see_both":{"one":"{n} satellite voit les deux","other":"{n} satellites voient les deux"},
"satellites.n_circuits_go_on_standby":{"one":"Ton circuit satellite entre {a} et {b} passe en réserve à côté du nouveau lien : il ne porte du trafic que quand ce lien tombe.","other":"Tes {n} circuits satellite entre {a} et {b} passent en réserve à côté du nouveau lien : ils ne portent du trafic que quand ce lien tombe."},
"satellites.n_places_in_reach":{"one":"{n} île ou ville isolée à portée à ton niveau.","other":"{n} îles et villes isolées à portée à ton niveau."},
"satellites.needs_tracking_antennas":"L’anneau MEO a besoin d’antennes de poursuite à ton téléport de {city}.",
"satellites.new_pop_cost":"nouveau POP {cost}",
"satellites.no_bird_sees_both":"Aucun satellite en vente ne voit à la fois {a} et {b}.",
"satellites.no_bird_sees_this_city":"Aucun satellite en vente ne voit cette ville.",
"satellites.no_cable_needed_a_pop_here":"Pas besoin de câble : un circuit satellite depuis un de tes téléports met un POP à {city} en ligne.",
"satellites.no_pop_in_city":"Tu n’as pas de POP à {city}.",
"satellites.no_pop_there_yet":"Pas encore de POP à {city} : on en construit un au passage ({cost}).",
"satellites.no_such_circuit":"Ce circuit satellite n’existe pas.",
"satellites.no_teleport_in_city":"Tu n’as pas de téléport à {city}.",
"satellites.no_teleport_reaches_city":"Aucun de tes téléports n’atteint {city}. Construis-en un sur un POP dont les satellites la voient.",
"satellites.not_remote":"{city} est un trop gros marché pour de la capacité satellite : elle sert les petites îles et les villes isolées.",
"satellites.nothing_in_view_from_here":"Aucune île ni ville isolée en vue d’ici.",
"satellites.on_standby_beside_your_link":"Il attend en réserve à côté de ton lien entre les deux et ne porte du trafic que quand ce lien tombe.",
"satellites.orbit_unlocks_at_level":"Les satellites {orb} se débloquent au niveau {lv}.",
"satellites.out_of_footprint":"{bird} ne voit pas à la fois {a} et {b}.",
"satellites.pointing_dishes_and_testing":"Pointage des paraboles et tests",
"satellites.radio_path":"Trajet radio, montée et descente",
"satellites.reachable_from_your_teleports":"Tes téléports atteignent {city} par satellite :",
"satellites.really_close_it":"Vraiment le fermer ?",
"satellites.rent":"Location",
"satellites.rent_satellite_capacity":"Louer de la capacité satellite",
"satellites.satellite_capacity":"Capacité satellite",
"satellites.satellites":"Satellites",
"satellites.sea_americas":"Amériques",
"satellites.sea_atlantic":"Atlantique",
"satellites.sea_indian":"Océan Indien",
"satellites.sea_pacific":"Pacifique",
"satellites.sea_tropics":"jusqu’à 50° de l’équateur",
"satellites.sea_west_pacific":"Pacifique occidental",
"satellites.sesa_blurb":"Un anneau de satellites à 8 000 km au-dessus de l’équateur, pour les trois autres milliards. Sésame, ouvre-toi : environ 130 ms aller-retour.",
"satellites.shrink_to":"Réduire à {cap}",
"satellites.teleport":"Téléport",
"satellites.teleport_closed":"Le téléport de {city} est fermé.",
"satellites.teleport_up_in_city":"<b>Téléport en service à {city}.</b> De grandes paraboles sur le toit, pointées vers le ciel : loue d’ici de la capacité vers les îles en vue.",
"satellites.teleports_unlock_at_level":"Les téléports se débloquent au niveau {lv}.",
"satellites.tracking_antennas_up":"<b>Antennes de poursuite en service à {city}.</b> Elles suivent l’anneau MEO dans le ciel.",
"satellites.up_in_n_days":{"one":"en service dans {n} jour","other":"en service dans {n} jours"},
"satellites.users_notice_geo_meo":"Les utilisateurs sentent le délai : le haut débit par GEO compte pour la moitié du service, par MEO presque pour tout. Un câble gagne toujours, donc tes routeurs n’envoient du trafic là-haut que s’il n’y a pas d’autre chemin.",
"satellites.users_ride_a_satellite":"utilisateurs sur satellite",
"satellites.via_bird":"via {bird}",
"satellites.who_a_satellite_serves":"Les satellites desservent les petites îles et les villes isolées que voit le même satellite que ton téléport. Choisis la destination.",
"satellites.your_pops_in_view":"Tes POP en vue",
"save.cash_in_the_bank":"{cash} en banque",
"save.import_failed_err":"<b>Échec de l’import.</b><br>{err}",
"save.load_name":"Charger {name} ?",
@ -4426,12 +4696,15 @@
"settings.always_2d":"Toujours en 2D",
"settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.",
"settings.auto_draws_the_map_with_your":"Auto dessine la carte avec ta carte graphique quand le navigateur le permet, ce qui garde les grands réseaux fluides. Toujours en 2D marche partout mais rame sur les grandes cartes.",
"settings.auto_follows_your_device_s_light":"Auto suit le réglage clair ou sombre de ton appareil. Le sombre repose les yeux la nuit et économise la batterie sur les écrans OLED.",
"settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.",
"settings.customers_and_alerts":"Clients et alertes",
"settings.dark":"Sombre",
"settings.diagnostic_info":"Infos de diagnostic",
"settings.display_and_sound":"Affichage et son",
"settings.for_bug_reports_shows_your_screen":"Pour signaler un bug : affiche dans un coin la taille de ton écran, comment la carte est dessinée (carte graphique ou 2D, et pourquoi) et à quelle vitesse.",
"settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer",
"settings.light":"Clair",
"settings.map_drawing":"Dessin de la carte",
"settings.n_min":"{n} min",
"settings.n_sec":"{n} s",
@ -4445,6 +4718,7 @@
"settings.the_agent_moves_it":"L'agent l'avance",
"settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue",
"settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.",
"settings.theme":"Thème",
"settings.this_browser_cannot_so_the_map":"Ce navigateur ne peut pas, la carte est donc dessinée en 2D.",
"settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent",
"settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.",

View file

@ -395,6 +395,48 @@
"broker.win_text":"{name} (AS{asn}) ha posato i propri cavi fino a {n} continenti e vende {mo} al mese di capacità ad altri operatori, in {days} giorni. Gli oceani ora sono la tua trincea.",
"broker.won_on_date":"Vinto il {date}: i tuoi cavi attraversano gli oceani e gli operatori ti pagano per usarli.",
"broker.your_glass_gear_is_already_yours":"Da broker di cavi, ogni fibra, sistema di linea, ottica, cavo sottomarino e i router per accenderli sono già tuoi, qualunque cosa dica il livello.",
"bstd.all_up":"Tutto è a standard.",
"bstd.any_model":"qualsiasi modello",
"bstd.applied":{"one":"Un lavoro fatto per lo standard di rete, {cost}.","other":"{n} lavori fatti per lo standard di rete, {cost}."},
"bstd.applied_none":"Per ora non si è potuto fare niente per lo standard di rete.",
"bstd.apply_nothing":"Niente sotto lo standard",
"bstd.apply_now":"Porta tutto a standard ora · {cost}",
"bstd.apply_wait":"Niente da fare finché quelle fibre non sono libere",
"bstd.at_every_pop":"In ogni POP",
"bstd.at_least_n":"Almeno {n}",
"bstd.below":"Sotto lo standard oggi",
"bstd.both_buildings":"Su entrambi gli edifici",
"bstd.cost_mo":"Costi mensili",
"bstd.cost_now":"Per portare tutto a standard ora",
"bstd.edit":"Modifica lo standard di rete",
"bstd.every_exchange":"Ovunque ci sia un IX",
"bstd.fastest":"La più veloce che arriva",
"bstd.fiber_note":"Cambiare il sistema di linea spegne la fibra per un giorno: solo se è tranquilla o se un link parallelo ne regge il carico.",
"bstd.from_level":"(livello {lv})",
"bstd.g_fiber":"Fibra e wave",
"bstd.g_port":"Porte e peering",
"bstd.generator":"generatore",
"bstd.held":{"one":"Una fibra tiene per ora il suo sistema di linea, finché non è tranquilla o un link parallelo può reggerne il carico il giorno in cui resta spenta. Nel frattempo riceve l’ottica più veloce che il suo sistema di linea accetta.","other":"{n} fibre tengono per ora il loro sistema di linea, finché non sono tranquille o un link parallelo può reggerne il carico il giorno in cui restano spente. Nel frattempo ricevono l’ottica più veloce che il loro sistema di linea accetta."},
"bstd.hire_note":"Assumi uno stagista NOC in Ops e terrà ogni POP, porta e fibra a standard: qualche lavoro al giorno, i più carichi prima, dentro un budget mensile e solo con soldi in avanzo.",
"bstd.in_n_cities":"In almeno {n} città",
"bstd.intern_keeps":"{name} tiene la rete a standard",
"bstd.keep":"Lascia com’è",
"bstd.l_ix":"Porta IX",
"bstd.l_lag":"Membri LAG",
"bstd.l_model":"Modello di router",
"bstd.l_pni":"PNI per rete",
"bstd.l_site2":"Secondo edificio",
"bstd.l_split":"Dividi i LAG",
"bstd.left":{"one":"Resta una cosa sotto lo standard: aspetta soldi, una fibra tranquilla o un ampliamento.","other":"Restano {n} cose sotto lo standard: aspettano soldi, una fibra tranquilla o un ampliamento."},
"bstd.n_more_targets":{"one":"{n} altro obiettivo","other":"altri {n} obiettivi"},
"bstd.new_pops_note":"Un POP nuovo riceve tutto subito, finché è vuoto: niente finestra di manutenzione. Se mancano i soldi, riceve quello che ci sta. Un modello non ancora sbloccato vuol dire il migliore sbloccato sotto di lui.",
"bstd.none_set":"Ancora nessuno standard: ogni obiettivo è su Lascia com’è.",
"bstd.now_line":"Standard: {list}",
"bstd.or_better":"{x} o meglio",
"bstd.port_note":"LAG e divisione valgono per le porte di transit, IX e PNI. Un nuovo membro di PNI è un ampliamento e arriva settimane dopo.",
"bstd.second_building":"secondo edificio",
"bstd.tagline":"Un solo design per tutta la rete: cosa deve avere ogni POP, porta e fibra. I POP nuovi ricevono la parte POP il giorno in cui aprono; il tuo stagista, o il pulsante qui sotto, porta il resto a standard.",
"bstd.title":"Standard di rete",
"businesses.a_free_pni_with_voda_phony":"Un PNI gratuito con Voda-Phony. Gear: router Absolute Unit 3.2T, porte 3.2T e wave 12.8T.",
"businesses.agi_lab_allegedly":"Laboratorio AGI (a sentir loro)",
"businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratori AGI (a sentir loro) che vogliono AI WAN da 12.8 a 25.6 Tbps, e PNI gratuiti con Du-opoly e Ooh-redoo. Gear: router Mikrowtik CCR 3.2T.",
@ -1976,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":"<b>Impossibile accendere {optic} su questo express.</b><br>{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":"<b>Su questa fibra passa un lightpath express.</b><br>Smontalo prima: aprilo dalla sezione Express di questa fibra.","other":"<b>Su questa fibra passano {n} lightpath express.</b><br>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":"<b>Express acceso: {a} ⇄ {b}.</b><br>{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.",
@ -2596,6 +2678,54 @@
"interface.tubecoin_moved_down_p_on_the":"TubeCoin è sceso del {p}% mentre arrivava sul tuo conto.",
"interface.tubecoin_moved_up_p_on_the":"TubeCoin è salito del {p}% mentre arrivava sul tuo conto.",
"interface.you_bought_out_bank_they_flew":"<b>Hai liquidato {bank}.</b><br>Sono volati via in cerca di un’altra startup.",
"ip4.block_size":"Dimensione del blocco",
"ip4.blocks":"I tuoi blocchi",
"ip4.bought":"Comprato un {p} ({n} indirizzi) per {price}.",
"ip4.bought_on":"Comprato il {date}",
"ip4.business":"Usati dai clienti business",
"ip4.buy":"Compra {price}",
"ip4.cgnat_boxes":"Apparati CGNAT",
"ip4.cgnat_note":"Più case per indirizzo liberano spazio per i clienti, ma giochi e port forwarding ne soffrono: il {p} della bolletta di una casa dietro il CGNAT torna indietro in rimborsi.",
"ip4.cgnat_ratio":"CGNAT: case per indirizzo",
"ip4.costs_row":"Affitti IPv4 e CGNAT",
"ip4.free":"Liberi per nuovi clienti (prima le case passano dietro il CGNAT)",
"ip4.from_rir":"Dal RIR",
"ip4.give_back":"Restituiscilo",
"ip4.held":"Il RIR non trasferisce di nuovo quel blocco prima del {date}.",
"ip4.homes":"Case in banda larga",
"ip4.homes_cgnat":"{n}, il {p} dietro il CGNAT",
"ip4.in_use":"I tuoi clienti hanno bisogno di quegli indirizzi: metti più case dietro il CGNAT o prendi prima un altro blocco.",
"ip4.lease":"Affitta {price}/mese",
"ip4.lease_out":"Dai in affitto +{price}/mese",
"ip4.leased_in":"Preso in affitto un {p} ({n} indirizzi) per {price}/mese.",
"ip4.leased_in_mo":"In affitto · {price}/mese",
"ip4.leased_out":"Il tuo {p} è dato in affitto: +{price}/mese.",
"ip4.leased_out_mo":"Dato in affitto · +{price}/mese",
"ip4.leases_in":"Blocchi presi in affitto",
"ip4.leases_out":"Blocchi dati in affitto",
"ip4.market":"Mercato dei trasferimenti",
"ip4.market_note":"IPv4 costa circa {px} a indirizzo (i blocchi grandi un po' meno), in affitto {lin} a indirizzo al mese, e dato in affitto rende {lout} dopo la quota del broker. Una vendita paga il {p} del prezzo, e un blocco si può trasferire di nuovo solo due anni dopo l'ultimo trasferimento.",
"ip4.movable_from":"trasferibile dal {date}",
"ip4.n_addresses":{"one":"{n} indirizzo","other":"{n} indirizzi"},
"ip4.n_homes_per_address":{"one":"{n} casa per indirizzo","other":"{n} case per indirizzo"},
"ip4.no_grow":"{name} ({city}) voleva crescere a {bw}, ma non avevi indirizzi IPv4 liberi per farlo.",
"ip4.no_space":"{name} ha bisogno di un {p} di IPv4 ({n} indirizzi), e ne restano liberi solo {free}. Compra o affitta un blocco, o metti più case dietro il CGNAT.",
"ip4.note":"IPv6 è gratis e infinito. IPv4 è finito anni fa: i clienti business hanno bisogno di blocchi pubblici, e le case che non ci stanno condividono gli indirizzi dietro il CGNAT (il traffico IPv6 gli passa accanto).",
"ip4.off":"Con le regole di questa partita l'IPv4 abbonda.",
"ip4.offer_needs":"Serve un {p} di IPv4 ({n} indirizzi); solo {free} liberi.",
"ip4.preset_plenty":"IPv4 in abbondanza per tutti.",
"ip4.preset_scarce":"IPv4 scarseggia: compralo, affittalo o condividilo dietro il CGNAT.",
"ip4.really_sell":"Vendere davvero per {price}?",
"ip4.refunds":"Rimborsi ai gamer arrabbiati",
"ip4.section":"Spazio di indirizzi",
"ip4.sell":"Vendi {price}",
"ip4.sold":"Venduto il tuo {p} per {price}.",
"ip4.squeezed":"Spazio esaurito: il {p} delle case non ci sta nemmeno con {r} case per indirizzo. Le connessioni saltano e vogliono un rimborso: compra o affitta un blocco.",
"ip4.take_back":"Riprendilo",
"ip4.toast_cgnat":"<b>Il tuo IPv4 è pieno.</b> Il {p} delle tue case ora condivide gli indirizzi dietro il CGNAT, e qualche gamer ha già scritto.",
"ip4.toast_out":"<b>IPv4 esaurito.</b> Nemmeno con {r} case per indirizzo il CGNAT basta per tutti: compra o affitta un blocco in banca.",
"ip4.too_many":"Hai {n} blocchi IPv4, il massimo che una rete può tenere. Vendi o restituisci qualche blocco piccolo per fare posto a uno più grande.",
"ip4.yours":"I tuoi indirizzi IPv4",
"ix_downgrade.pni_downgraded":"Il PNI con {net} a {city} ora è {port}.",
"ix_downgrade.port_downgraded_at_ix":"La porta su {ix} ora è da {port}.",
"ix_downgrade.transit_downgraded":"Il transito {net} a {city} ora è {port}.",
@ -3041,6 +3171,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"La versione vera: segui un pacchetto dal Wi-Fi alla fibra sottomarina.",
"modals.lay_your_own_subsea_cable":"Posa il tuo cavo sottomarino…",
"modals.your_own_subsea_cable_level_n":"Il tuo cavo sottomarino <small>livello {n} o Tier 1</small>",
"mp.code":"Codice della sessione",
"mp.copy_link":"Copia il link",
"mp.door_d":"Un solo mondo, le reti dei tuoi amici accanto alla tua: condividi un codice e corri verso il Tier 1.",
"mp.err_code":"Un codice di sessione ha sei lettere e cifre, tipo K7Q-2XD.",
"mp.err_full":"Quella sessione è piena: tutti i posti sono occupati.",
"mp.err_no_session":"Non c'è nessuna sessione con quel codice.",
"mp.err_offline":"Il server multigiocatore non è raggiungibile adesso. Riprova tra un attimo.",
"mp.err_refused":"Il server non l'ha accettato. Prova un altro nome per la rete.",
"mp.err_server_full":"Il server non accetta nuove sessioni in questo momento.",
"mp.err_slow":"Troppi tentativi da qui. Aspetta un po' e riprova.",
"mp.feed":"Bacheca",
"mp.feed_empty":"Ancora niente. Saluta!",
"mp.feed_join":"{name} è entrato nella sessione.",
"mp.feed_leave":"{name} ha lasciato la sessione.",
"mp.feed_t1":"Anche {name} è Tier 1.",
"mp.feed_t1first":"{name} è il primo Tier 1 di questa sessione!",
"mp.feed_t2":"{name} è arrivato a Tier 2.",
"mp.intro":"Ognuno costruisce la propria rete nello stesso mondo, dallo stesso giorno 0 e con le stesse regole. Classifica e bacheca mostrano chi è in testa.",
"mp.join":"Entra",
"mp.join_a_session":"Entra in una sessione",
"mp.join_note":"Il mondo e le regole li sceglie chi ha avviato la sessione, e il numero di AS te lo dà la sessione.",
"mp.joined":"<b>Sei entrato nella sessione {code}.</b> Apri la sessione per vedere chi è in testa.",
"mp.keep_mine":"Tieni questa",
"mp.leaderboard":"Classifica",
"mp.leave":"Lascia la sessione",
"mp.leave_d":"{name} resta su questo dispositivo come partita a sé. La sessione se ne dimentica e il suo salvataggio sul server viene cancellato.",
"mp.leave_q":"Lasciare la sessione {code}?",
"mp.left":"Hai lasciato la sessione. {name} continua qui per conto suo.",
"mp.link_bad":"Quel link multigiocatore non ha funzionato: è vecchio, oppure quella rete non ha mai salvato nella sessione.",
"mp.link_copied":"Link copiato. Aprilo sull'altro dispositivo.",
"mp.load_newer":"Carica quello più recente",
"mp.loaded_newer":"Caricato dalla sessione il salvataggio più recente di {name} ({date}).",
"mp.loading":"Chiedo al server…",
"mp.move_device":"Passa a un altro dispositivo",
"mp.move_note":"Apri questo link sull'altro telefono o computer per continuare lì con questa rete. Vince il dispositivo che salva per ultimo.",
"mp.move_warn":"Chiunque abbia questo link può giocare al posto tuo. Tienilo per te.",
"mp.moved_on_elsewhere":"<b>Questa sessione è andata avanti altrove.</b> Da allora la tua rete è stata giocata su un altro dispositivo. Carica quel salvataggio, oppure tieni questo e sovrascrivilo.",
"mp.multiplayer":"Multigiocatore",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clienti"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POP"},
"mp.no_card":"non ha ancora finito un giorno",
"mp.no_newer":"La sessione non ha un salvataggio più recente di {name}. Resta questo, che andrà al server al prossimo salvataggio.",
"mp.not_in_session":"Questa rete non è più nella sua sessione. Continua qui per conto suo.",
"mp.play_with_friends":"Gioca con gli amici",
"mp.save_unreadable":"Non si riesce a leggere il salvataggio di questa rete nella sessione. Si continua con quello qui.",
"mp.say":"Scrivi qualcosa",
"mp.send":"Invia",
"mp.server_away":"Il server multigiocatore non risponde. La tua rete continua a giocare qui e si rimette in pari quando torna.",
"mp.session":"Sessione multigiocatore",
"mp.session_code":"Sessione {code}",
"mp.session_live":"<b>La sessione {code} è partita.</b> Condividi il codice: chi entra costruisce nello stesso mondo.",
"mp.session_title":"Nome della sessione (facoltativo)",
"mp.share_line":"Entra nella mia sessione di Series of Tubes {code}: {url}",
"mp.share_note":"Gli amici entrano dalla schermata iniziale: Multigiocatore, poi questo codice.",
"mp.slow_down":"Piano: una riga al secondo.",
"mp.start_a_session":"Avvia una sessione",
"mp.talking":"Parlo con il server…",
"mp.welcome_device":"<b>{name}</b> è passata su questo dispositivo. Bentornato nella sessione {code}.",
"mp.you":"tu",
"networks.a_mobile_network_named_after_the":"Una rete mobile che porta il nome del suono di un brindisi. Cin cin a ogni antenna 5G.",
"networks.a_spanish_carrier_starring_in_every":"Un carrier spagnolo protagonista in ogni mercato latinoamericano, almeno finché non vende il prossimo.",
"networks.a_tiny_telco_in_a_country":"Una piccola telco in un paese dove approdano i cavi di mezzo mondo. Prezzi in proporzione.",
@ -3224,6 +3413,8 @@
"ops.l_decom":{"one":"ha restituito una wave piccola su {where}","other":"ha restituito {n} wave piccole ({where})"},
"ops.l_line":"{name} {list}.",
"ops.l_optics":{"one":"ha acceso un canale su {where}","other":"ha acceso {n} canali ({where})"},
"ops.l_optswap":{"one":"ha scambiato un’ottica con una più grande su {where}","other":"ha scambiato {n} ottiche con altre più grandi ({where})"},
"ops.l_optup":{"one":"ha potenziato il line system su {where}","other":"ha potenziato {n} line system ({where})"},
"ops.l_paid":"Costo: {cost} subito, {mo}/mese.",
"ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"},
"ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"},
@ -3233,6 +3424,7 @@
"ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"},
"ops.l_rs":{"one":"si è unito a un route server","other":"si è unito a {n} route server"},
"ops.l_snag":{"one":"si è bloccato su {where} e l'ha messo in pausa finché non dai un'occhiata","other":"si è bloccato su {n} ordini ({where}) e li ha messi in pausa finché non dai un'occhiata"},
"ops.l_std":{"one":"ha portato {where} allo standard di rete","other":"ha fatto {n} lavori per lo standard di rete ({where})"},
"ops.l_transit":{"one":"ha aumentato il transit a {where}","other":"ha aumentato il transit {n} volte ({where})"},
"ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.",
"ops.model_next":"Generazione successiva, se carico",
@ -3256,6 +3448,8 @@
"ops.o_ix_d":"Ogni settimana: entra nei route server e chiedi il peering a ogni membro disponibile su ciascuna delle tue porte di exchange.",
"ops.o_optics":"Accendi più fibra",
"ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.",
"ops.o_optup":"Potenzia il trasporto ottico",
"ops.o_optup_d":"Sulla fibra piena che va calda, porta il line system alla taglia successiva, o scambia i canali più piccoli con ottiche più grandi (le vecchie finiscono a scaffale). Scegli un line system e ogni fibra con uno più piccolo passa a quello. Cambiare line system spegne la fibra per un giorno, quindi solo dove il traffico può girarle intorno e nessun cliente ci passa, uno per notte.",
"ops.o_pni":"PNI con i grandi",
"ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.",
"ops.o_ports":"Margine sulle porte di peering",
@ -3264,6 +3458,8 @@
"ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.",
"ops.o_routers":"Router sempre avanti",
"ops.o_routers_desc":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia. Scegli un modello e ogni POP con uno più piccolo passa a quello, prima il più carico, nei limiti del budget.",
"ops.o_std":"Tieni lo standard di rete",
"ops.o_std_d":"Porta POP, porte e fibra al tuo standard di rete, i più carichi prima, qualche lavoro a turno. Prima di uno scambio arriva un secondo router, e il sistema di linea cambia solo su una fibra tranquilla.",
"ops.o_transit":"Margine di transit",
"ops.o_transit_d":"Tieni il transit di ogni POP sopra un multiplo del suo picco a 30 giorni: un membro LAG in più, o una porta più grande.",
"ops.ops":"Ops",
@ -3276,6 +3472,8 @@
"ops.p_paid":"Peering a pagamento",
"ops.p_pick":"Ottiche",
"ops.p_prov":"Fornitore",
"ops.p_swap":"Ottiche più grandi",
"ops.p_sys":"Line system",
"ops.p_tier":"Taglia",
"ops.p_x":"Margine",
"ops.paused":"In pausa",
@ -3290,9 +3488,11 @@
"ops.shift_report":"La settimana di {name}",
"ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta",
"ops.standing_orders":"Ordini permanenti",
"ops.sys_next":"Il successivo, quando è pieno",
"ops.template":"Nuovo POP da modello",
"ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.",
"ops.tpl_bb":"Banda larga",
"ops.tpl_bstd":"standard di rete",
"ops.tpl_done":"{name} ha aperto {city}: {list}.",
"ops.tpl_ix":"Porta IX",
"ops.tpl_just_pop":"solo il POP",
@ -3725,6 +3925,7 @@
"pie_traffic.via_dishes":"su a {up}, giù a {down}",
"pitcairn.uk_grant_mo":"Contributo UK {mo}/mese",
"pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online",
"pitcairn.uk_grant_needs_a_cable":"Contributo UK {mo}/mese solo con un cavo: la capacità satellitare in affitto non conta",
"pitcairn.uk_sky_grant_mo":"Contributo UK via satellite {mo}/mese (la fibra prende {full})",
"pni_all.additional_per_month":"Costo mensile aggiuntivo",
"pni_all.all_at_port":"Peering con tutte le reti · {port}",
@ -3791,12 +3992,12 @@
"pnis.us_east_is_sold_out_until":"US East è esaurito fino a nuovo avviso. Anche il nuovo avviso è esaurito.",
"pop_std.city_gets_the_standard_cost":"{city} riceve lo standard: {n} × {model} per {cost}.",
"pop_std.clear":"Rimuovi",
"pop_std.includes_the_build_standard":"Include il tuo standard di rete: {list}, {cost} + {mo}/mese. Se mancano i soldi, il POP riceve quello che ci sta.",
"pop_std.includes_the_standard_n_model":"Include i tuoi router standard: {n} × {model}, {cost} + {mo}/mese. Se mancano i soldi, il POP riceve quello che ci sta.",
"pop_std.make_this_the_standard":"Rendilo lo standard",
"pop_std.new_pops_now_start_with":"I nuovi POP ora partono con {n} × {model}.",
"pop_std.new_pops_now_start_with_list":"I nuovi POP ora partono con {list}.",
"pop_std.none":"Nessuno",
"pop_std.not_all_of_the_standard":"Non bastano soldi o livello per tutto lo standard a {city}: ha avuto quello che si poteva.",
"pop_std.standard_for_new_pops":"Standard per i nuovi POP",
"pops_transit_ix.40_off_for_6_months":"40% di sconto per 6 mesi",
"pops_transit_ix.40_off_ix_for_6_months":"<b>40% di sconto su {ix} per 6 mesi.</b><br>Il tuo account manager tira un sospiro di sollievo. Le clausole in piccolo leggile dopo.",
"pops_transit_ix.after_consulting_with_management_the":"<b>“Dopo un confronto con il management…”</b><br>Il prezzo è salito. Il management è stato consultato.",
@ -4332,6 +4533,75 @@
"sales.w_last":"La settimana scorsa {name} {list}.",
"sales.w_now":"Questa settimana {name} {list}.",
"sales.w_signed":{"one":"ha firmato un cliente ({rev}/mese)","other":"ha firmato {n} clienti ({rev}/mese)"},
"satellites.a_teleport_is_a_satellite_gateway":"Un teleport è un gateway satellitare: grandi parabole in questo POP che noleggiano capacità sui satelliti di altri, verso piccole isole e città remote che nessun cavo raggiunge, o che stanno appese a un solo cavo e a una preghiera.",
"satellites.add_tracking_antennas_cost_mo":"Antenne a inseguimento MEO <small>{cost} + {mo}/mese</small>",
"satellites.being_commissioned":"In attivazione",
"satellites.build_a_teleport_cost_mo":"Costruisci un teleport <small>{cost} + {mo}/mese</small>",
"satellites.by_satellite":"Via satellite",
"satellites.cancel_n_circuits_first":{"one":"Prima disdici il suo circuito satellitare.","other":"Prima disdici i suoi {n} circuiti satellitari."},
"satellites.choose":"Scegli",
"satellites.circuit_ordered":{"one":"<b>{cap} su {bird} ordinati.</b> {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorno.","other":"<b>{cap} su {bird} ordinati.</b> {a} ⇄ {b} si sta puntando e testando: attivo tra {n} giorni."},
"satellites.close_the_teleport":"Chiudi il teleport",
"satellites.costs_row":"Teleport e satelliti",
"satellites.geo_dishes":"Parabole GEO",
"satellites.geo_dishes_and_meo_tracking":"Parabole GEO e antenne a inseguimento MEO",
"satellites.geo_users_notice":"Da 36.000 km di quota il giro dura circa 600 ms: videochiamate e giochi scattano, e gli utenti contano {p} del servizio come pessimo.",
"satellites.grow_to":"Porta a {cap}",
"satellites.in_view_list":"In vista: {list}.",
"satellites.it_waits_on_standby":"Tra queste due hai già un link: il satellite aspetta in standby e porta traffico solo quando quel link cade.",
"satellites.its_blurb":"I classici fasci in banda C e Ku che coprono un oceano intero. Affidabili, ovunque, e con il prezzo che ne consegue.",
"satellites.kac_blurb":"Spot beam in banda Ka sul Pacifico occidentale: il Gbps più economico in orbita, se la tua isola sta sotto un fascio.",
"satellites.meo_comes_at_level":"L’anello MEO (circa 130 ms andata e ritorno) arriva al livello {lv}.",
"satellites.meo_ring_misses_city":"L’anello MEO non vede {city}: copre {lat}° a nord e a sud dell’equatore.",
"satellites.meo_users_notice":"Molto più vicino a terra, circa 130 ms andata e ritorno: gli utenti se ne accorgono appena ({p} del servizio conta come pessimo).",
"satellites.more_islands_and_towns":"Altre isole e città in vista",
"satellites.ms_one_way_rtt":"{ms} ms solo andata, {rtt} ms andata e ritorno",
"satellites.ms_round_trip":"{ms} ms andata e ritorno",
"satellites.n_birds_see_both":{"one":"{n} satellite vede entrambe","other":"{n} satelliti vedono entrambe"},
"satellites.n_circuits_go_on_standby":{"one":"Il tuo circuito satellitare tra {a} e {b} va in standby accanto al nuovo link: porta traffico solo quando quel link cade.","other":"I tuoi {n} circuiti satellitari tra {a} e {b} vanno in standby accanto al nuovo link: portano traffico solo quando quel link cade."},
"satellites.n_places_in_reach":{"one":"{n} isola o città remota a portata al tuo livello.","other":"{n} isole e città remote a portata al tuo livello."},
"satellites.needs_tracking_antennas":"L’anello MEO vuole antenne a inseguimento al tuo teleport di {city}.",
"satellites.new_pop_cost":"nuovo POP {cost}",
"satellites.no_bird_sees_both":"Nessun satellite in vendita vede insieme {a} e {b}.",
"satellites.no_bird_sees_this_city":"Nessun satellite in vendita vede questa città.",
"satellites.no_cable_needed_a_pop_here":"Niente cavo: un circuito satellitare da uno dei tuoi teleport mette online un POP a {city}.",
"satellites.no_pop_in_city":"Non hai un POP a {city}.",
"satellites.no_pop_there_yet":"A {city} non c’è ancora un POP: così ne costruisci anche uno ({cost}).",
"satellites.no_such_circuit":"Questo circuito satellitare non esiste.",
"satellites.no_teleport_in_city":"Non hai un teleport a {city}.",
"satellites.no_teleport_reaches_city":"Nessuno dei tuoi teleport raggiunge {city}. Costruiscine uno in un POP i cui satelliti la vedano.",
"satellites.not_remote":"{city} è un mercato troppo grande per la capacità satellitare: quella serve piccole isole e città remote.",
"satellites.nothing_in_view_from_here":"Da qui non si vede nessuna isola né città remota.",
"satellites.on_standby_beside_your_link":"Aspetta in standby accanto al tuo link tra le due e porta traffico solo quando quel link cade.",
"satellites.orbit_unlocks_at_level":"I satelliti {orb} si sbloccano al livello {lv}.",
"satellites.out_of_footprint":"{bird} non vede insieme {a} e {b}.",
"satellites.pointing_dishes_and_testing":"Puntamento delle parabole e test",
"satellites.radio_path":"Percorso radio, su e giù",
"satellites.reachable_from_your_teleports":"I tuoi teleport raggiungono {city} via satellite:",
"satellites.really_close_it":"Lo chiudi davvero?",
"satellites.rent":"Noleggio",
"satellites.rent_satellite_capacity":"Noleggia capacità satellitare",
"satellites.satellite_capacity":"Capacità satellitare",
"satellites.satellites":"Satelliti",
"satellites.sea_americas":"Americhe",
"satellites.sea_atlantic":"Atlantico",
"satellites.sea_indian":"Oceano Indiano",
"satellites.sea_pacific":"Pacifico",
"satellites.sea_tropics":"entro 50° dall’equatore",
"satellites.sea_west_pacific":"Pacifico occidentale",
"satellites.sesa_blurb":"Un anello di satelliti a 8.000 km sopra l’equatore, per gli altri tre miliardi. Apriti sesamo: circa 130 ms andata e ritorno.",
"satellites.shrink_to":"Riduci a {cap}",
"satellites.teleport":"Teleport",
"satellites.teleport_closed":"Il teleport di {city} è chiuso.",
"satellites.teleport_up_in_city":"<b>Teleport attivo a {city}.</b> Grandi parabole sul tetto, puntate al cielo: da qui noleggi capacità verso le isole in vista.",
"satellites.teleports_unlock_at_level":"I teleport si sbloccano al livello {lv}.",
"satellites.tracking_antennas_up":"<b>Antenne a inseguimento attive a {city}.</b> Seguono l’anello MEO nel cielo.",
"satellites.up_in_n_days":{"one":"attivo tra {n} giorno","other":"attivo tra {n} giorni"},
"satellites.users_notice_geo_meo":"Gli utenti sentono il ritardo: la banda larga via GEO conta come mezzo servizio, via MEO quasi come tutto. Un cavo vince sempre, quindi i tuoi router mandano traffico lassù solo se non c’è altra strada.",
"satellites.users_ride_a_satellite":"utenti via satellite",
"satellites.via_bird":"via {bird}",
"satellites.who_a_satellite_serves":"I satelliti servono piccole isole e città remote che lo stesso satellite vede insieme al tuo teleport. Scegli la destinazione.",
"satellites.your_pops_in_view":"I tuoi POP in vista",
"save.cash_in_the_bank":"{cash} in cassa",
"save.import_failed_err":"<b>Importazione fallita.</b><br>{err}",
"save.load_name":"Caricare {name}?",
@ -4426,12 +4696,15 @@
"settings.always_2d":"Sempre 2D",
"settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.",
"settings.auto_draws_the_map_with_your":"Auto disegna la mappa con la tua scheda grafica quando il browser lo consente, così anche le reti grandi restano fluide. Sempre 2D funziona ovunque ma è più lento sulle mappe grandi.",
"settings.auto_follows_your_device_s_light":"Auto segue l’impostazione chiara o scura del tuo dispositivo. Lo scuro riposa gli occhi di notte e fa risparmiare batteria sugli schermi OLED.",
"settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.",
"settings.customers_and_alerts":"Clienti e avvisi",
"settings.dark":"Scuro",
"settings.diagnostic_info":"Info di diagnostica",
"settings.display_and_sound":"Schermo e audio",
"settings.for_bug_reports_shows_your_screen":"Per segnalare bug: mostra in un angolo le dimensioni dello schermo, come viene disegnata la mappa (scheda grafica o 2D, e perché) e a che velocità.",
"settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA",
"settings.light":"Chiaro",
"settings.map_drawing":"Disegno della mappa",
"settings.n_min":"{n} min",
"settings.n_sec":"{n} s",
@ -4445,6 +4718,7 @@
"settings.the_agent_moves_it":"Lo muove l'agente",
"settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente",
"settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.",
"settings.theme":"Tema",
"settings.this_browser_cannot_so_the_map":"Questo browser non può, quindi la mappa è disegnata in 2D.",
"settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento",
"settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.",

View file

@ -395,6 +395,48 @@
"broker.win_text":"{name} (AS{asn}) lançou os próprios cabos até {n} continentes e vende {mo} por mês de capacidade a outras operadoras, em {days} dias. Os oceanos agora são a sua vala.",
"broker.won_on_date":"Vencido em {date}: seus próprios cabos cruzam os oceanos e as operadoras pagam para usá-los.",
"broker.your_glass_gear_is_already_yours":"Como corretor de cabos, toda fibra, sistema de linha, óptico, cabo submarino e os roteadores para acendê-los já são seus, diga o nível o que disser.",
"bstd.all_up":"Tudo está no padrão.",
"bstd.any_model":"qualquer modelo",
"bstd.applied":{"one":"Um trabalho feito para o padrão de rede, {cost}.","other":"{n} trabalhos feitos para o padrão de rede, {cost}."},
"bstd.applied_none":"Nada pôde ser feito para o padrão de rede agora.",
"bstd.apply_nothing":"Nada abaixo do padrão",
"bstd.apply_now":"Colocar tudo no padrão agora · {cost}",
"bstd.apply_wait":"Nada a fazer até essas fibras ficarem livres",
"bstd.at_every_pop":"Em cada POP",
"bstd.at_least_n":"Pelo menos {n}",
"bstd.below":"Abaixo do padrão hoje",
"bstd.both_buildings":"Nos dois prédios",
"bstd.cost_mo":"Custos mensais",
"bstd.cost_now":"Para colocar tudo no padrão agora",
"bstd.edit":"Editar o padrão de rede",
"bstd.every_exchange":"Onde houver um IX",
"bstd.fastest":"A mais rápida que alcança",
"bstd.fiber_note":"Trocar o sistema de linha apaga a fibra por um dia: só quando ela está tranquila ou um link paralelo leva a carga.",
"bstd.from_level":"(nível {lv})",
"bstd.g_fiber":"Fibra e waves",
"bstd.g_port":"Portas e peering",
"bstd.generator":"gerador",
"bstd.held":{"one":"Uma fibra mantém por enquanto o seu sistema de linha, até ficar tranquila ou um link paralelo poder levar a carga dela no dia em que ela fica apagada. Até lá, ela recebe a óptica mais rápida que o seu sistema de linha aceita.","other":"{n} fibras mantêm por enquanto o seu sistema de linha, até ficarem tranquilas ou um link paralelo poder levar a carga delas no dia em que ficam apagadas. Até lá, elas recebem a óptica mais rápida que o seu sistema de linha aceita."},
"bstd.hire_note":"Contrate um estagiário de NOC em Ops e ele mantém cada POP, porta e fibra no padrão: alguns trabalhos por dia, os mais carregados primeiro, dentro de um orçamento mensal e só com dinheiro sobrando.",
"bstd.in_n_cities":"Em pelo menos {n} cidades",
"bstd.intern_keeps":"{name} mantém a rede no padrão",
"bstd.keep":"Deixar como está",
"bstd.l_ix":"Porta no IX",
"bstd.l_lag":"Membros de LAG",
"bstd.l_model":"Modelo de roteador",
"bstd.l_pni":"PNIs por rede",
"bstd.l_site2":"Segundo prédio",
"bstd.l_split":"Dividir LAGs",
"bstd.left":{"one":"Ainda falta uma coisa abaixo do padrão, esperando dinheiro, uma fibra tranquila ou uma ampliação.","other":"Ainda faltam {n} coisas abaixo do padrão, esperando dinheiro, uma fibra tranquila ou uma ampliação."},
"bstd.n_more_targets":{"one":"mais {n} meta","other":"mais {n} metas"},
"bstd.new_pops_note":"Um POP novo recebe isso na hora, enquanto ainda está vazio: sem janela de manutenção. Se faltar dinheiro, recebe o que couber. Um modelo ainda bloqueado significa o melhor desbloqueado abaixo dele.",
"bstd.none_set":"Ainda sem padrão: toda meta está em Deixar como está.",
"bstd.now_line":"Padrão: {list}",
"bstd.or_better":"{x} ou melhor",
"bstd.port_note":"LAGs e divisão valem para portas de trânsito, IX e PNI. Um novo membro de PNI é uma ampliação e chega semanas depois.",
"bstd.second_building":"segundo prédio",
"bstd.tagline":"Um só design para a rede toda: o que cada POP, porta e fibra deve ter. POPs novos recebem a parte do POP no dia em que abrem; seu estagiário, ou o botão abaixo, coloca o resto no padrão.",
"bstd.title":"Padrão de rede",
"businesses.a_free_pni_with_voda_phony":"Um PNI grátis com a Voda-Phony. Gear: routers Absolute Unit 3.2T, portas 3.2T e waves de 12.8T.",
"businesses.agi_lab_allegedly":"Laboratório de AGI (supostamente)",
"businesses.agi_labs_allegedly_wanting_ai_wans":"Laboratórios de AGI (supostamente) querendo AI WANs de 12.8 a 25.6 Tbps, e PNIs grátis com a Du-opoly e a Ooh-redoo. Gear: routers Mikrowtik CCR 3.2T.",
@ -1976,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":"<b>Não dá para acender {optic} neste expresso.</b><br>{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":"<b>Um lightpath expresso passa por esta fibra.</b><br>Desmonte-o primeiro: abra-o na seção Expresso desta fibra.","other":"<b>{n} lightpaths expressos passam por esta fibra.</b><br>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":"<b>Expresso aceso: {a} ⇄ {b}.</b><br>{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.",
@ -2596,6 +2678,54 @@
"interface.tubecoin_moved_down_p_on_the":"A TubeCoin caiu {p}% no caminho até sua conta.",
"interface.tubecoin_moved_up_p_on_the":"A TubeCoin subiu {p}% no caminho até sua conta.",
"interface.you_bought_out_bank_they_flew":"<b>Você comprou a parte de {bank}.</b><br>Eles voaram em busca de outra startup.",
"ip4.block_size":"Tamanho do bloco",
"ip4.blocks":"Seus blocos",
"ip4.bought":"Você comprou um {p} ({n} endereços) por {price}.",
"ip4.bought_on":"Comprado em {date}",
"ip4.business":"Usados por clientes empresariais",
"ip4.buy":"Comprar {price}",
"ip4.cgnat_boxes":"Caixas de CGNAT",
"ip4.cgnat_note":"Mais casas por endereço liberam espaço para clientes, mas jogos e redirecionamento de portas sofrem: {p} da conta de uma casa atrás do CGNAT volta como reembolso.",
"ip4.cgnat_ratio":"CGNAT: casas por endereço",
"ip4.costs_row":"Aluguel de IPv4 e CGNAT",
"ip4.free":"Livres para novos clientes (as casas vão antes para trás do CGNAT)",
"ip4.from_rir":"Do RIR",
"ip4.give_back":"Devolver",
"ip4.held":"O RIR não transfere esse bloco de novo antes de {date}.",
"ip4.homes":"Casas com banda larga",
"ip4.homes_cgnat":"{n}, {p} atrás do CGNAT",
"ip4.in_use":"Seus clientes precisam desses endereços: coloque mais casas atrás do CGNAT ou arrume outro bloco antes.",
"ip4.lease":"Alugar {price}/mês",
"ip4.lease_out":"Alugar para terceiros +{price}/mês",
"ip4.leased_in":"Você alugou um {p} ({n} endereços) por {price}/mês.",
"ip4.leased_in_mo":"Alugado · {price}/mês",
"ip4.leased_out":"Seu {p} está alugado: +{price}/mês.",
"ip4.leased_out_mo":"Alugado para terceiros · +{price}/mês",
"ip4.leases_in":"Blocos alugados",
"ip4.leases_out":"Blocos alugados para terceiros",
"ip4.market":"Mercado de transferências",
"ip4.market_note":"IPv4 sai por cerca de {px} o endereço (blocos grandes, um pouco menos), aluga-se por {lin} o endereço por mês e, alugado para terceiros, rende {lout} depois da comissão do broker. Uma venda paga {p} do preço, e um bloco só pode ser transferido de novo dois anos depois da última transferência.",
"ip4.movable_from":"transferível a partir de {date}",
"ip4.n_addresses":{"one":"{n} endereço","other":"{n} endereços"},
"ip4.n_homes_per_address":{"one":"{n} casa por endereço","other":"{n} casas por endereço"},
"ip4.no_grow":"{name} ({city}) queria crescer para {bw}, mas você não tinha endereços IPv4 livres para isso.",
"ip4.no_space":"{name} precisa de um {p} de IPv4 ({n} endereços), e só {free} estão livres. Compre ou alugue um bloco, ou coloque mais casas atrás do CGNAT.",
"ip4.note":"IPv6 é grátis e infinito. IPv4 acabou há anos: clientes empresariais precisam de blocos públicos, e as casas que não cabem compartilham endereços atrás do CGNAT (o tráfego IPv6 passa por fora da caixa).",
"ip4.off":"Nas regras deste jogo, IPv4 não falta.",
"ip4.offer_needs":"Precisa de um {p} de IPv4 ({n} endereços); só {free} livres.",
"ip4.preset_plenty":"IPv4 de sobra para todo mundo.",
"ip4.preset_scarce":"IPv4 é escasso: compre, alugue ou compartilhe atrás do CGNAT.",
"ip4.really_sell":"Vender mesmo por {price}?",
"ip4.refunds":"Reembolsos para gamers irritados",
"ip4.section":"Espaço de endereços",
"ip4.sell":"Vender {price}",
"ip4.sold":"Seu {p} foi vendido por {price}.",
"ip4.squeezed":"Sem espaço: {p} das casas não cabem nem com {r} casas por endereço. As conexões caem e elas querem reembolso: compre ou alugue um bloco.",
"ip4.take_back":"Pegar de volta",
"ip4.toast_cgnat":"<b>Seu IPv4 está cheio.</b> {p} das suas casas agora compartilham endereços atrás do CGNAT, e alguns gamers já reclamaram.",
"ip4.toast_out":"<b>Acabou o IPv4.</b> Nem com {r} casas por endereço o CGNAT comporta todo mundo: compre ou alugue um bloco no banco.",
"ip4.too_many":"Você tem {n} blocos IPv4, o máximo que uma rede pode manter. Venda ou devolva blocos pequenos para abrir espaço para um maior.",
"ip4.yours":"Seus endereços IPv4",
"ix_downgrade.pni_downgraded":"O PNI com {net} em {city} agora é {port}.",
"ix_downgrade.port_downgraded_at_ix":"A porta em {ix} agora é de {port}.",
"ix_downgrade.transit_downgraded":"O trânsito de {net} em {city} agora é {port}.",
@ -3041,6 +3171,65 @@
"modal_and_names.the_real_thing_follow_a_packet":"A coisa de verdade: siga um pacote do Wi-Fi até a fibra submarina.",
"modals.lay_your_own_subsea_cable":"Lançar seu próprio cabo submarino…",
"modals.your_own_subsea_cable_level_n":"Seu próprio cabo submarino <small>nível {n} ou Tier 1</small>",
"mp.code":"Código da sessão",
"mp.copy_link":"Copiar o link",
"mp.door_d":"Um só mundo, as redes dos seus amigos ao lado da sua: compartilhe um código e corra para o Tier 1.",
"mp.err_code":"Um código de sessão tem seis letras e números, como K7Q-2XD.",
"mp.err_full":"Essa sessão está cheia: todas as vagas já estão ocupadas.",
"mp.err_no_session":"Não existe sessão com esse código.",
"mp.err_offline":"Não dá para falar com o servidor multijogador agora. Tente de novo daqui a pouco.",
"mp.err_refused":"O servidor não aceitou. Tente outro nome de rede.",
"mp.err_server_full":"O servidor não está aceitando sessões novas agora.",
"mp.err_slow":"Tentativas demais daqui. Espere um pouco e tente de novo.",
"mp.feed":"Mural",
"mp.feed_empty":"Nada ainda. Diga oi!",
"mp.feed_join":"{name} entrou na sessão.",
"mp.feed_leave":"{name} saiu da sessão.",
"mp.feed_t1":"{name} também é Tier 1.",
"mp.feed_t1first":"{name} é o primeiro Tier 1 desta sessão!",
"mp.feed_t2":"{name} chegou a Tier 2.",
"mp.intro":"Cada um constrói a própria rede no mesmo mundo, a partir do mesmo dia 0 e com as mesmas regras. O ranking e o mural mostram quem está na frente.",
"mp.join":"Entrar",
"mp.join_a_session":"Entrar numa sessão",
"mp.join_note":"O mundo e as regras vêm de quem começou a sessão, e a sessão te dá o seu número de AS.",
"mp.joined":"<b>Você entrou na sessão {code}.</b> Abra a sessão para ver quem está na frente.",
"mp.keep_mine":"Ficar com esta",
"mp.leaderboard":"Ranking",
"mp.leave":"Sair da sessão",
"mp.leave_d":"{name} fica neste dispositivo como um jogo próprio. A sessão se esquece dela, e o jogo salvo dela no servidor é apagado.",
"mp.leave_q":"Sair da sessão {code}?",
"mp.left":"Você saiu da sessão. {name} continua aqui por conta própria.",
"mp.link_bad":"Esse link multijogador não funcionou: é antigo, ou essa rede nunca salvou na sessão.",
"mp.link_copied":"Link copiado. Abra no seu outro dispositivo.",
"mp.load_newer":"Carregar o mais recente",
"mp.loaded_newer":"Carregado da sessão o jogo salvo mais recente de {name} ({date}).",
"mp.loading":"Perguntando ao servidor…",
"mp.move_device":"Passar para outro dispositivo",
"mp.move_note":"Abra este link no seu outro celular ou computador para continuar com esta rede lá. Vale o dispositivo que salvar por último.",
"mp.move_warn":"Qualquer um com este link pode jogar como você. Guarde só para você.",
"mp.moved_on_elsewhere":"<b>Esta sessão seguiu em outro lugar.</b> Desde então sua rede foi jogada em outro dispositivo. Carregue aquele jogo salvo, ou fique com este e sobrescreva o outro.",
"mp.multiplayer":"Multijogador",
"mp.n_customers":{"one":"{n} cliente","other":"{n} clientes"},
"mp.n_pops":{"one":"{n} POP","other":"{n} POPs"},
"mp.no_card":"ainda não terminou nenhum dia",
"mp.no_newer":"A sessão não tem um jogo salvo mais recente de {name}. Este fica e vai para o servidor no próximo salvamento.",
"mp.not_in_session":"Esta rede não está mais na sua sessão. Ela continua jogando aqui por conta própria.",
"mp.play_with_friends":"Jogar com amigos",
"mp.save_unreadable":"Não deu para ler o jogo salvo desta rede na sessão. Seguimos com o daqui.",
"mp.say":"Diga algo",
"mp.send":"Enviar",
"mp.server_away":"O servidor multijogador sumiu. Sua rede continua jogando aqui e se atualiza quando ele voltar.",
"mp.session":"Sessão multijogador",
"mp.session_code":"Sessão {code}",
"mp.session_live":"<b>A sessão {code} está no ar.</b> Compartilhe o código: quem entrar constrói no mesmo mundo.",
"mp.session_title":"Nome da sessão (opcional)",
"mp.share_line":"Entre na minha sessão de Series of Tubes {code}: {url}",
"mp.share_note":"Os amigos entram pela tela inicial: Multijogador, depois este código.",
"mp.slow_down":"Calma: uma linha por segundo.",
"mp.start_a_session":"Começar uma sessão",
"mp.talking":"Falando com o servidor…",
"mp.welcome_device":"<b>{name}</b> passou para este dispositivo. Bem-vindo de volta à sessão {code}.",
"mp.you":"você",
"networks.a_mobile_network_named_after_the":"Uma rede móvel com nome de brinde. Tim-tim para cada torre 5G.",
"networks.a_spanish_carrier_starring_in_every":"Uma operadora espanhola estrelando em todo mercado latino-americano, pelo menos até vender o próximo.",
"networks.a_tiny_telco_in_a_country":"Uma operadora minúscula num país onde os cabos do mundo chegam à terra. Os preços acompanham.",
@ -3224,6 +3413,8 @@
"ops.l_decom":{"one":"devolveu uma wave pequena em {where}","other":"devolveu {n} waves pequenas ({where})"},
"ops.l_line":"{name} {list}.",
"ops.l_optics":{"one":"acendeu um canal em {where}","other":"acendeu {n} canais ({where})"},
"ops.l_optswap":{"one":"trocou uma óptica por uma maior em {where}","other":"trocou {n} ópticas por maiores ({where})"},
"ops.l_optup":{"one":"melhorou o sistema de linha em {where}","other":"melhorou {n} sistemas de linha ({where})"},
"ops.l_paid":"Custo: {cost} de entrada, {mo}/mês.",
"ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"},
"ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"},
@ -3233,6 +3424,7 @@
"ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"},
"ops.l_rs":{"one":"entrou em um route server","other":"entrou em {n} route servers"},
"ops.l_snag":{"one":"travou em {where} e pausou a ordem até você dar uma olhada","other":"travou em {n} ordens ({where}) e pausou-as até você dar uma olhada"},
"ops.l_std":{"one":"colocou {where} no padrão de rede","other":"fez {n} trabalhos para o padrão de rede ({where})"},
"ops.l_transit":{"one":"reforçou o trânsito em {where}","other":"reforçou o trânsito {n} vezes ({where})"},
"ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.",
"ops.model_next":"Próxima geração, quando lotado",
@ -3256,6 +3448,8 @@
"ops.o_ix_d":"Toda semana: entrar nos route servers e pedir peering a cada membro disposto em cada uma das suas portas de exchange.",
"ops.o_optics":"Acender mais fibra",
"ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.",
"ops.o_optup":"Melhorar o transporte óptico",
"ops.o_optup_d":"Na fibra que está cheia e esquentando, sobe o sistema de linha um tamanho ou troca os canais menores por ópticas maiores (as antigas vão para a prateleira). Escolha um sistema de linha e cada fibra com um menor sobe para ele. Trocar o sistema de linha derruba a fibra por um dia, então só onde o tráfego consegue contorná-la e nenhum cliente passa por ela, uma por noite.",
"ops.o_pni":"PNI com os grandes",
"ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.",
"ops.o_ports":"Folga nas portas de peering",
@ -3264,6 +3458,8 @@
"ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.",
"ops.o_routers":"Roteadores à frente",
"ops.o_routers_desc":"Adicionar um roteador, ou trocar para a próxima geração onde um segundo roteador segura o tráfego, quando a carga ou as portas passarem de um nível. Escolha um modelo e cada POP com um menor é trocado para ele, o mais carregado primeiro, dentro do orçamento.",
"ops.o_std":"Manter o padrão de rede",
"ops.o_std_d":"Colocar POPs, portas e fibra no seu padrão de rede, os mais carregados primeiro, alguns trabalhos por turno. Antes de uma troca entra um segundo roteador, e o sistema de linha só muda numa fibra tranquila.",
"ops.o_transit":"Folga de trânsito",
"ops.o_transit_d":"Manter o trânsito de cada POP acima de um múltiplo do seu pico de 30 dias: mais um membro LAG, ou um tamanho de porta acima.",
"ops.ops":"Ops",
@ -3276,6 +3472,8 @@
"ops.p_paid":"Peering pago",
"ops.p_pick":"Ópticas",
"ops.p_prov":"Provedor",
"ops.p_swap":"Ópticas maiores",
"ops.p_sys":"Sistema de linha",
"ops.p_tier":"Tamanho",
"ops.p_x":"Folga",
"ops.paused":"Em pausa",
@ -3290,9 +3488,11 @@
"ops.shift_report":"A semana de {name}",
"ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura",
"ops.standing_orders":"Ordens permanentes",
"ops.sys_next":"O próximo, quando cheio",
"ops.template":"Novo POP por modelo",
"ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.",
"ops.tpl_bb":"Banda larga",
"ops.tpl_bstd":"padrão de rede",
"ops.tpl_done":"{name} abriu {city}: {list}.",
"ops.tpl_ix":"Porta de IX",
"ops.tpl_just_pop":"só o POP",
@ -3725,6 +3925,7 @@
"pie_traffic.via_dishes":"sobe em {up}, desce em {down}",
"pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês",
"pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online",
"pitcairn.uk_grant_needs_a_cable":"Subsídio do Reino Unido {mo}/mês só com cabo: capacidade de satélite alugada não conta",
"pitcairn.uk_sky_grant_mo":"Subsídio britânico por satélite {mo}/mês (a fibra recebe {full})",
"pni_all.additional_per_month":"Custo mensal adicional",
"pni_all.all_at_port":"Peering com todas as redes · {port}",
@ -3791,12 +3992,12 @@
"pnis.us_east_is_sold_out_until":"US East está esgotado até segunda ordem. A segunda ordem também esgotou.",
"pop_std.city_gets_the_standard_cost":"{city} recebe o padrão: {n} × {model} por {cost}.",
"pop_std.clear":"Limpar",
"pop_std.includes_the_build_standard":"Inclui seu padrão de rede: {list}, {cost} + {mo}/mês. Se faltar dinheiro, o POP recebe o que couber.",
"pop_std.includes_the_standard_n_model":"Inclui seus roteadores padrão: {n} × {model}, {cost} + {mo}/mês. Se faltar dinheiro, o POP recebe o que couber.",
"pop_std.make_this_the_standard":"Tornar este o padrão",
"pop_std.new_pops_now_start_with":"Novos POPs agora começam com {n} × {model}.",
"pop_std.new_pops_now_start_with_list":"Novos POPs agora começam com {list}.",
"pop_std.none":"Nenhum",
"pop_std.not_all_of_the_standard":"Sem dinheiro ou nível para todo o padrão em {city}: recebeu o que coube.",
"pop_std.standard_for_new_pops":"Padrão para novos POPs",
"pops_transit_ix.40_off_for_6_months":"40% de desconto por 6 meses",
"pops_transit_ix.40_off_ix_for_6_months":"<b>40% de desconto no {ix} por 6 meses.</b><br>Seu account manager respirou aliviado. Leia as letras miúdas depois.",
"pops_transit_ix.after_consulting_with_management_the":"<b>“Depois de consultar a diretoria…”</b><br>O preço subiu. A diretoria foi consultada.",
@ -4332,6 +4533,75 @@
"sales.w_last":"Semana passada {name} {list}.",
"sales.w_now":"Esta semana {name} {list}.",
"sales.w_signed":{"one":"assinou um cliente ({rev}/mês)","other":"assinou {n} clientes ({rev}/mês)"},
"satellites.a_teleport_is_a_satellite_gateway":"Um teleporto é um gateway de satélite: antenas grandes neste POP que alugam capacidade nos satélites dos outros, para ilhas pequenas e cidades remotas aonde nenhum cabo chega, ou que dependem de um só cabo e de uma reza.",
"satellites.add_tracking_antennas_cost_mo":"Antenas de rastreamento MEO <small>{cost} + {mo}/mês</small>",
"satellites.being_commissioned":"Em comissionamento",
"satellites.build_a_teleport_cost_mo":"Construir um teleporto <small>{cost} + {mo}/mês</small>",
"satellites.by_satellite":"Por satélite",
"satellites.cancel_n_circuits_first":{"one":"Cancele primeiro o circuito de satélite dele.","other":"Cancele primeiro os {n} circuitos de satélite dele."},
"satellites.choose":"Escolher",
"satellites.circuit_ordered":{"one":"<b>{cap} no {bird} encomendados.</b> {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dia.","other":"<b>{cap} no {bird} encomendados.</b> {a} ⇄ {b} está sendo apontado e testado: no ar em {n} dias."},
"satellites.close_the_teleport":"Fechar o teleporto",
"satellites.costs_row":"Teleportos e satélites",
"satellites.geo_dishes":"Antenas GEO",
"satellites.geo_dishes_and_meo_tracking":"Antenas GEO e antenas de rastreamento MEO",
"satellites.geo_users_notice":"De 36.000 km de altura a ida e volta leva uns 600 ms: chamadas de vídeo e jogos travam, e os usuários contam {p} do serviço como ruim.",
"satellites.grow_to":"Aumentar para {cap}",
"satellites.in_view_list":"À vista: {list}.",
"satellites.it_waits_on_standby":"Você já tem um link entre as duas: o satélite espera de reserva e só leva tráfego quando esse link cai.",
"satellites.its_blurb":"Feixes clássicos em banda C e Ku que cobrem um oceano inteiro. Confiáveis, em todo lugar, e com preço à altura.",
"satellites.kac_blurb":"Feixes pontuais em banda Ka sobre o Pacífico ocidental: o Gbps mais barato em órbita, se a sua ilha estiver debaixo de um feixe.",
"satellites.meo_comes_at_level":"O anel MEO (uns 130 ms de ida e volta) chega no nível {lv}.",
"satellites.meo_ring_misses_city":"O anel MEO não vê {city}: ele cobre {lat}° de cada lado do equador.",
"satellites.meo_users_notice":"Muito mais perto do chão, uns 130 ms de ida e volta: os usuários mal percebem ({p} do serviço conta como ruim).",
"satellites.more_islands_and_towns":"Mais ilhas e cidades à vista",
"satellites.ms_one_way_rtt":"{ms} ms só de ida, {rtt} ms de ida e volta",
"satellites.ms_round_trip":"{ms} ms de ida e volta",
"satellites.n_birds_see_both":{"one":"{n} satélite vê as duas","other":"{n} satélites veem as duas"},
"satellites.n_circuits_go_on_standby":{"one":"Seu circuito de satélite entre {a} e {b} fica de reserva ao lado do novo link: só leva tráfego quando esse link cai.","other":"Seus {n} circuitos de satélite entre {a} e {b} ficam de reserva ao lado do novo link: só levam tráfego quando esse link cai."},
"satellites.n_places_in_reach":{"one":"{n} ilha ou cidade remota ao alcance no seu nível.","other":"{n} ilhas e cidades remotas ao alcance no seu nível."},
"satellites.needs_tracking_antennas":"O anel MEO precisa de antenas de rastreamento no seu teleporto em {city}.",
"satellites.new_pop_cost":"POP novo {cost}",
"satellites.no_bird_sees_both":"Nenhum satélite à venda vê {a} e {b} ao mesmo tempo.",
"satellites.no_bird_sees_this_city":"Nenhum satélite à venda vê esta cidade.",
"satellites.no_cable_needed_a_pop_here":"Sem cabo: um circuito de satélite de um dos seus teleportos coloca um POP em {city} no ar.",
"satellites.no_pop_in_city":"Você não tem POP em {city}.",
"satellites.no_pop_there_yet":"Ainda não há POP em {city}: isto também constrói um ({cost}).",
"satellites.no_such_circuit":"Esse circuito de satélite não existe.",
"satellites.no_teleport_in_city":"Você não tem teleporto em {city}.",
"satellites.no_teleport_reaches_city":"Nenhum dos seus teleportos alcança {city}. Construa um num POP cujos satélites a vejam.",
"satellites.not_remote":"{city} é um mercado grande demais para capacidade de satélite: ela é para ilhas pequenas e cidades remotas.",
"satellites.nothing_in_view_from_here":"Daqui não há nenhuma ilha nem cidade remota à vista.",
"satellites.on_standby_beside_your_link":"Ele espera de reserva ao lado do seu link entre as duas e só leva tráfego quando esse link cai.",
"satellites.orbit_unlocks_at_level":"Satélites {orb} são liberados no nível {lv}.",
"satellites.out_of_footprint":"{bird} não vê {a} e {b} ao mesmo tempo.",
"satellites.pointing_dishes_and_testing":"Apontando antenas e testando",
"satellites.radio_path":"Caminho de rádio, subida e descida",
"satellites.reachable_from_your_teleports":"Seus teleportos alcançam {city} por satélite:",
"satellites.really_close_it":"Fechar mesmo?",
"satellites.rent":"Aluguel",
"satellites.rent_satellite_capacity":"Alugar capacidade de satélite",
"satellites.satellite_capacity":"Capacidade de satélite",
"satellites.satellites":"Satélites",
"satellites.sea_americas":"Américas",
"satellites.sea_atlantic":"Atlântico",
"satellites.sea_indian":"Oceano Índico",
"satellites.sea_pacific":"Pacífico",
"satellites.sea_tropics":"até 50° do equador",
"satellites.sea_west_pacific":"Pacífico ocidental",
"satellites.sesa_blurb":"Um anel de satélites a 8.000 km acima do equador, para os outros três bilhões. Abre-te, sésamo: uns 130 ms de ida e volta.",
"satellites.shrink_to":"Reduzir para {cap}",
"satellites.teleport":"Teleporto",
"satellites.teleport_closed":"O teleporto em {city} foi fechado.",
"satellites.teleport_up_in_city":"<b>Teleporto no ar em {city}.</b> Antenas enormes no telhado, apontadas para o céu: alugue daqui capacidade para as ilhas à vista.",
"satellites.teleports_unlock_at_level":"Teleportos são liberados no nível {lv}.",
"satellites.tracking_antennas_up":"<b>Antenas de rastreamento no ar em {city}.</b> Elas seguem o anel MEO pelo céu.",
"satellites.up_in_n_days":{"one":"no ar em {n} dia","other":"no ar em {n} dias"},
"satellites.users_notice_geo_meo":"Os usuários sentem o atraso: banda larga por GEO conta como meio serviço, por MEO quase como o serviço inteiro. Um cabo sempre ganha, então seus roteadores só mandam tráfego para cima quando não há outro caminho.",
"satellites.users_ride_a_satellite":"usuários via satélite",
"satellites.via_bird":"via {bird}",
"satellites.who_a_satellite_serves":"Satélites atendem ilhas pequenas e cidades remotas que o mesmo satélite vê junto com o seu teleporto. Escolha o destino.",
"satellites.your_pops_in_view":"Seus POPs à vista",
"save.cash_in_the_bank":"{cash} no banco",
"save.import_failed_err":"<b>Falha na importação.</b><br>{err}",
"save.load_name":"Carregar {name}?",
@ -4426,12 +4696,15 @@
"settings.always_2d":"Sempre 2D",
"settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.",
"settings.auto_draws_the_map_with_your":"Auto desenha o mapa com sua placa de vídeo quando o navegador permite, o que mantém redes grandes fluidas. Sempre 2D funciona em qualquer lugar, mas é mais lento em mapas grandes.",
"settings.auto_follows_your_device_s_light":"Auto segue a configuração clara ou escura do seu aparelho. O escuro descansa os olhos à noite e economiza bateria em telas OLED.",
"settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.",
"settings.customers_and_alerts":"Clientes e alertas",
"settings.dark":"Escuro",
"settings.diagnostic_info":"Informações de diagnóstico",
"settings.display_and_sound":"Tela e som",
"settings.for_bug_reports_shows_your_screen":"Para reportar bugs: mostra em um canto o tamanho da sua tela, como o mapa é desenhado (placa de vídeo ou 2D, e por quê) e a que velocidade.",
"settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar",
"settings.light":"Claro",
"settings.map_drawing":"Desenho do mapa",
"settings.n_min":"{n} min",
"settings.n_sec":"{n} s",
@ -4445,6 +4718,7 @@
"settings.the_agent_moves_it":"O agente move-o",
"settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga",
"settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.",
"settings.theme":"Tema",
"settings.this_browser_cannot_so_the_map":"Este navegador não consegue, então o mapa é desenhado em 2D.",
"settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito",
"settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.",

View file

@ -15,6 +15,8 @@ self.addEventListener('activate', (e) => {
self.addEventListener('fetch', (e) => {
const req = e.request;
if (req.method !== 'GET') return;
// Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached.
if (req.cache === 'no-store' || req.headers.has('authorization')) return;
const url = new URL(req.url);
// The update check must always ask the network.
if (url.origin === location.origin && url.pathname === '/version.json') return;

View file

@ -22,6 +22,8 @@ const API_DOMAINS={
vxcTier:{table:'VXC',kind:'index'},
routerModel:{table:'RG',kind:'index'},
scrubTier:{table:'SCRUB_TIERS',kind:'index'},
satBird:{table:'SATS',kind:'key'},
satG:{kind:'enum',values:()=>[...new Set(Object.values(SAT_ORB).flatMap(o=>o.g))].sort((a,b)=>a-b)},
// Small fixed vocabularies the game itself checks by list membership.
// The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric).
metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']},
@ -38,6 +40,8 @@ const API_DOMAINS={
opsKey:{table:'OPSK',kind:'key'},
opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()},
opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()},
// The build standard's targets (bstdSet).
bstdKey:{kind:'enum',values:()=>BSTD.map(x=>x.k)},
// The specialist's offers: a seat on a consortium cable, the charter, a vendor demo.
seatPairs:{kind:'enum',values:()=>SEAT_N.slice()},
callAmount:{kind:'enum',values:()=>CALL_AMTS.slice()},
@ -84,6 +88,9 @@ const API_DOMAINS={
pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'},
pieSpatChoice:{kind:'enum',values:[0,1]},
countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()},
// Address space: an IPv4 prefix length the market sells, and the CGNAT ratios.
ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)},
ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()},
scnId:{table:'SCN',kind:'id'},
// A traceroute target in the modal's own terms.
};

View file

@ -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'&&l.kind!=='sat'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B);
const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1);
const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]};
const blocked=[],so=soldOut(A,B,tier,wr.cab);
@ -167,6 +167,22 @@ const API_CMD={
doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'},
siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'],
doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'},
/* ---------- teleports and satellite capacity (#83) ---------- */
teleBuild:{args:[['city','cityId']],watch:['pops.#city'],
quote:a=>({setup:TPORT_COST,monthly:TPORT_MO,blocked:[teleOf(a.city)?'there is a teleport here already':teleWhy(a.city)].filter(Boolean)}),
doc:'Build a teleport (a satellite gateway) at one of your POPs: it rents circuits on GEO birds to small islands and remote towns in their footprint. Refused where no satellite on sale at your level sees the city.'},
teleTrk:{args:[['city','cityId']],watch:['pops.#city'],
quote:a=>({setup:TRK_COST,monthly:TRK_MO,blocked:[teleOf(a.city)===2?'this teleport has tracking antennas already':trkWhy(a.city)].filter(Boolean)}),
doc:'Add tracking antennas to a teleport, so it can work the MEO ring (about 130 ms round trip instead of GEO\'s 600). Only within 50 degrees of the equator, where the ring is in view.'},
teleRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'],
doc:'Close a teleport. Refused while circuits still start there.'},
buySat:{args:[['a','cityId'],['b','cityId'],['bird','satBird'],['g','satG']],
quote:a=>{const ok=own(SATS,a.bird),mo=ok?satMo(a.bird,+a.g):0;return {setup:mo+(S.pops[a.b]||!CITY[a.b]?0:popCost(a.b)),monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[satWhy(a.a,a.b,a.bird,+a.g)].filter(Boolean)};},
doc:'Rent a satellite circuit from your teleport in a to b (a small island or a remote town) on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas. The first month up front; builds a POP at b if there is none. Next to an existing link between the two it goes on standby, as backup; a link built later between the two puts it on standby too. Cancel with rmLink.'},
satSize:{args:[['id','entityId'],['g','satG']],watch:['links.#id'],
quote:a=>{const l=S.links.find(x=>x.id===a.id&&x.kind==='sat'),g=+a.g,ok=!!l&&g!==l.g&&SAT_ORB[SATS[l.bird].orb].g.includes(g),mo=ok?satMo(l.bird,g):0;
return {setup:ok&&g>l.g?mo:0,monthly:mo,blocked:!l?['not a satellite circuit']:ok?[]:[tr('satellites.no_such_circuit')]};},
doc:'Resize a satellite circuit on the same bird. A bigger one pays its new month up front.'},
/* ---------- dark fiber and own cable ---------- */
orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']],
bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;},
@ -230,9 +246,16 @@ 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 free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'},
doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'},
decline:{args:[['id','entityId']],
doc:'Throw an offer away.'},
salesHire:{args:[['id','salesPersona']],
@ -282,6 +305,23 @@ const API_CMD={
repayLoan:{args:[['id','entityId']],confirm:'double',
quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};},
doc:'Repay a loan early, or buy an equity investor out.'},
/* ---------- address space (IPv4, rule ip4: On-call and BGP at 3 a.m.) ---------- */
ip4Buy:{args:[['len','ip4Len']],watch:['ip4'],
quote:a=>({setup:ip4Cost(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}),
doc:'Buy an IPv4 block of this prefix length (24 = 256 addresses up to 16 = 65,536) on the transfer market at today\'s price. It can be sold again two years after this transfer. A network holds at most 256 blocks, bought, leased in and from the registry together.'},
ip4Lease:{args:[['len','ip4Len']],watch:['ip4'],
quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}),
doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'},
ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'],
doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every home behind CGNAT.'},
ip4Out:{args:[['id','entityId']],watch:['ip4'],
doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'},
ip4Back:{args:[['id','entityId']],watch:['ip4'],
doc:'End the lease of a block you leased out; its addresses are yours to use again.'},
ip4Return:{args:[['id','entityId']],watch:['ip4'],
doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'},
ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'],
doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'},
/* ---------- security, China, incidents ---------- */
buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'],
quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};},
@ -327,7 +367,7 @@ const API_CMD={
opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'],
doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead, such as the model to standardize routers on.'},
opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'],
doc:'Step the monthly budget of an order that has one: 10k, 25k, 50k, 100k, 250k, no limit. With v (a position in that list, 0 first) it picks that one.'},
doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'},
opsFloor:{args:[['v','string',false]],watch:['ops'],
doc:'Step the floor under your cash that the intern keeps clear when paying for jobs: 0, 50k, 250k, 1M, 5M. With v (a position in that list, 0 first) it picks that one.'},
opsPop:{args:[['k','opsPopKind'],['city','cityId']],watch:['ops'],
@ -376,11 +416,16 @@ const API_CMD={
layShip:{args:[['id','entityId']],watch:['links.#id'],
quote:a=>{const l=S.links.find(x=>x.id===a.id),q=l&&layQuote(l);return q?{setup:q.cost}:{};},
doc:'Book a second lay ship on your own cable before laying starts: it lays from the other end and halves that part of the build.'},
/* ---------- standard POPs ---------- */
/* ---------- the build standard ---------- */
popStdSet:{args:[['city','cityId']],watch:['popStd'],
doc:'Make a POP\'s routers the standard: every new POP starts with that model and that number of routers while it is still empty.'},
doc:'Make a POP\'s build the standard\'s POP part: its router model, router count, second building and generator. New POPs start with them at once; the other targets are kept.'},
popStdClear:{args:[],watch:['popStd'],
doc:'Stop setting a standard; new POPs go back to one basic router.'},
doc:'Clear the whole build standard; new POPs go back to one basic router.'},
bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'],
doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'},
bstdApply:{args:[],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
quote:a=>{const q=bstdQuote(false);return {setup:q.cost,monthly:q.mo,blocked:q.held.map(w=>w.split('|').map(c=>CITY[c].name).join('–')+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark')};},
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load: such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill.'},
/* ---------- utilities ---------- */
utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'],
doc:'Join the route server at every IX you have a port at. One call does what the button does.'},
@ -448,6 +493,8 @@ const API_CMD={
const API_VIEW={
pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'},
ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT and the transfer market.'},
ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'},
pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'},
pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'},
pieCity:{args:[['v','cityId']],doc:'Pick the POP the Dishes tab works on.'},
@ -507,6 +554,7 @@ const API_VIEW={
keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'},
routingOpen:{args:[],doc:'Open the Routing & DDoS window: the traceroute, backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'},
opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'},
bstdOpen:{args:[],doc:'Open the build standard sheet: every target, how many POPs, ports and links are below it, what bringing them up costs, and the intern\'s order that keeps them there.'},
salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'},
opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'},
utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'},
@ -542,6 +590,7 @@ const API_BOUND={
teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'},
trace:{command:'traceRun',arg:'from'},
decomToggle:{command:'decomGo',arg:'cities'},
satOpen:{command:'buySat',note:'opens the satellite order sheet from a teleport (a) or for a city (b); buySat takes a, b, bird and g itself'},
openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'},
connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'},
cnPrem:{command:'buildLink',arg:'premiumCrossing'},
@ -549,6 +598,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'},
@ -594,12 +644,14 @@ const API_WHY={
time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save',
slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game',
browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session',
};
const API_DENY={
speed:'time',phonePlay:'time',phoneSpeed:'time',
start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',themeSet:'prefs',vpSet:'prefs',
mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp',
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
};

View file

@ -9,7 +9,7 @@ const API_STATE_DOC={
cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'},
priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'},
mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'},
rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'},
rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the later rules (sea, confs, broke, moods, pnis, and ip4 for scarce IPv4, off outside On-call and BGP at 3 a.m.), which are only written where they differ from the classic game. They stay for the network\'s whole life.'},
charter:{type:'string',doc:'The charter a normal game signed when it started: global | boutique | broker. chartSet is false until one is signed.'},
baronWon:{type:'number',doc:'The day a broker won Glass Baron, or 0.'},
chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'},
@ -19,8 +19,8 @@ const API_STATE_DOC={
t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'},
auV:{type:'integer',doc:'Australia content level gate.'},
seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'},
pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'},
links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'},
pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas).'},
links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'},
transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'},
ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'},
rs:{type:'map',doc:'Route-server sessions by exchange city.'},
@ -61,7 +61,9 @@ const API_STATE_DOC={
ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'},
core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'},
ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'},
popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'},
ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, w: which warnings were shown. What customers use is derived from their kind and size.'},
popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen (true), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up.'},
mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'},
demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'},
seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'},
monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'},
@ -128,6 +130,7 @@ const API_RESULTS_DOC={
cityEye:{type:'map',doc:'Eyeballs online per city.'},
latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'},
latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'},
satU:{type:'map',doc:'Of each city\'s served traffic, the Gbps that rode a rented satellite circuit (its users notice the orbit\'s latency on that share). Only there while you have a satellite circuit up.'},
demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'},
served:{type:'number',doc:'Total traffic served, in Gbps.'},
demand:{type:'number',doc:'Total traffic demanded, in Gbps.'},

View file

@ -26,7 +26,7 @@ function apiJson(v){
carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders
each recipe's script, because the source is a function and some read the live network. The
recipes' relevance score is not exposed: judging which one fits is the agent's job. */
const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG};
const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SATS,SAT_ORB,SAT_PROV,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG};
const API_MADE={
BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id];
return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}),

View file

@ -15,7 +15,7 @@ function apiControls(root,player){
const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled}
// A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value.
:{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg,
select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled};
select:b.dataset.chg,args:apiParse(b.dataset.args),value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled};
if(player)o.player=true;
out.push(o);}
return out;}

View file

@ -115,7 +115,8 @@ function apiClick(n,value){
if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`);
if(b.disabled)apiFail(`"${b.label}" is greyed out.`);
if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`);
const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args;
// A list sends its own arguments with the value picked, as the page's change handler does (96-map/95-clicks.js).
const name=b.select||b.act,args=b.select?{...(b.args||{}),v:value===undefined?undefined:String(value)}:b.args;
if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`);
const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`);
if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};}

View file

@ -7,6 +7,9 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
// A big release's story, shown in full in "What's new" (paragraphs; **bold** allowed). Empty for most releases.
const RELEASE_STORY=/*__RELEASE_STORY__*/[];
const IS_DEV=APP_VERSION.startsWith('__');
// Multiplayer (docs/MULTIPLAYER.md): the path of a self-hosted copy's session server, stamped by MP_API=/api/mp npm run build.
// Empty, as in every plain build (and on seriesoftub.es), multiplayer stays off: no door, no requests.
const MP_API=/*__MP_API__*/'';
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){

View file

@ -26,7 +26,8 @@ const RCAGE=6,CAGE_MUL=1.5,CAGE_MO=2000;
const routerCost=(g,rt)=>Math.round((ROUTER_COST+RG[g].cost*0.8)*((rt||1)>=RCAGE?CAGE_MUL:1)*hwMul('rt')*techMul(RG[g].lvl));
const routerMo=g=>ROUTER_MO+RG[g].mo,cageMo=rt=>Math.max(0,(rt||1)-RCAGE)*CAGE_MO;
// Old routers go on eBuy when you swap models or remove one (#82), like spare optics (#45). Chassis age faster.
const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCost=(c,g)=>{const p=S.pops[c],rt=p.routers||1;return Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(p.rgen||0,rt));};
// swapCostOf: the same price for a POP on model old with rt routers (the build standard plans a few steps ahead).
const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCostOf=(g,old,rt)=>Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(old,rt)),swapCost=(c,g)=>{const p=S.pops[c];return swapCostOf(g,p.rgen||0,p.routers||1);};
const RMAX=16;
// The plain, badge-less model of each class is the default upgrade path; the others are side-grades.
const mainRG=k=>RG.findIndex(r=>r.cls===k&&!r.badge);

View file

@ -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 '';}

View file

@ -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):l.kind==='sat'?l.g:LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1);
// A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears.
const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]});
const tierW=l=>{if(l.kind==='wave')return l.tier;if(l.kind==='vxc')return 0;const g=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'||l.kind==='sat')return 0;const g=l.kind==='xp'?xpG(l):dfCap(l);return g>=6400?4:g>=1600?3:g>=400?2:g>=100?1:0;};
const capName=l=>l.kind==='vxc'?VXC[l.vt].n:l.kind==='sat'?fmtCap(l.g)+' '+SAT_ORB[SATS[l.bird].orb].n:l.kind==='xp'?(g=>g?tr('express.cap',{cap:fmtCap(g)}):tr('common.dark'))(xpG(l)):l.kind==='df'?(l.ready>S.day?tr('common.building'):(l.ch||[]).length?fmtCap(dfCap(l)||(l.ch||[]).reduce((a,c)=>a+optG(c,l),0))+' DF':tr('common.dark')):LT[l.tier].n;

View file

@ -0,0 +1,61 @@
/* ---------- Satellites (#83): capacity rented on someone else's birds ----------
A teleport (a satellite gateway at one of your POPs) links to a small island or a remote town over rented capacity:
the early answer to "no cable lands there", and the warm backup for an island hanging on one cable. Geostationary
birds (GEO, 35,786 km up) see a whole ocean from one dish: no build, dear per Gbps, about 600 ms there and back. A
medium-orbit ring over the equator (MEO, 8,062 km up) gets that down to about 130 ms, but a teleport needs tracking
antennas to follow its satellites across the sky. Your own constellation (LEO, Pie in the Sky) comes much later.
The providers are vendors, like the fabrics: they sell you capacity, they are not networks you route to. */
// h: km up; proc: ms of modems and error correction each way; loss: the share of a city's service its users stop counting
// once their traffic rides it (half for GEO, like any haul past 50 ms; MEO feels almost like fiber); days: to point and
// commission a new circuit; lv: the level it unlocks at; g: the sizes sold (Gbps). A MEO ring covers |lat| <= lat, and a
// circuit's two ends must see the same satellite at once: at most km apart, and at least el degrees above both horizons
// (what a ground terminal needs to clear the trees; far north, two ends 7,000 km apart lose it below the horizon).
const SAT_ORB={
geo:{n:'GEO',h:35786,proc:25,loss:0.5,days:10,lv:2,g:[1,2,5,10]},
meo:{n:'MEO',h:8062,proc:7,loss:0.08,days:21,lv:3,g:[2,5,10,20],lat:50,km:7500,el:5},
};
// pg: dollars a month for the first Gbps; bigger circuits cost less per Gbps (satMo).
const SAT_PROV={
its:{n:'Intelsplat',col:'#2F8CFF',pg:2500,blurb:tr('satellites.its_blurb')},
kac:{n:'Kacophony',col:'#FF8A3D',pg:1400,blurb:tr('satellites.kac_blurb')},
sesa:{n:'SESame',col:'#16A866',pg:2000,blurb:tr('satellites.sesa_blurb')},
};
// The birds. A GEO sits over the equator at lon; r is how far its beams reach, in degrees of arc from the point under it
// (72: a global beam, down to about 5 degrees above the horizon; Kacophony's Ka-band spot beams cover less, for less).
const SATS={
is18:{n:'Intelsplat 18',p:'its',orb:'geo',lon:180,r:72,sea:N_('satellites.sea_pacific')},
is20:{n:'Intelsplat 20',p:'its',orb:'geo',lon:68.5,r:72,sea:N_('satellites.sea_indian')},
is37:{n:'Intelsplat 37e',p:'its',orb:'geo',lon:-18,r:72,sea:N_('satellites.sea_atlantic')},
kac1:{n:'Kacophony-1',p:'kac',orb:'geo',lon:150,r:50,sea:N_('satellites.sea_west_pacific')},
gx19:{n:'Intelsplat 19',p:'its',orb:'geo',lon:-97,r:72,sea:N_('satellites.sea_americas')},
o3b:{n:'O3bservant',p:'sesa',orb:'meo',sea:N_('satellites.sea_tropics')},
};
// The teleport itself (dishes, a building, the licences), and the MEO tracking antennas it may add.
const TPORT_COST=90000,TPORT_MO=2500,TRK_COST=250000,TRK_MO=3000;
// Who a satellite serves: a small island off the big continents, or a remote town anywhere, never a big city's market.
const SAT_MAIN=['af','am','eu','oc','sa'],SAT_ISLE_P=150,SAT_TOWN_P=5;
const SAT_RE=6371,SAT_C=300;
// The arc between two points on the globe, in degrees.
function satArc(la1,lo1,la2,lo2){const r=Math.PI/180,c=Math.sin(la1*r)*Math.sin(la2*r)+Math.cos(la1*r)*Math.cos(la2*r)*Math.cos((lo2-lo1)*r);return Math.acos(Math.max(-1,Math.min(1,c)))/r;}
// From a dish to a satellite h km up over a point arc degrees away, in a straight line.
function satSlant(arc,h){const Q=SAT_RE+h,a=arc*Math.PI/180;return Math.sqrt(SAT_RE*SAT_RE+Q*Q-2*SAT_RE*Q*Math.cos(a));}
// How high above a dish's horizon that satellite stands, in degrees (negative: below it, behind the Earth).
function satElev(arc,h){const a=arc*Math.PI/180;return Math.atan2(Math.cos(a)-SAT_RE/(SAT_RE+h),Math.sin(a))*180/Math.PI;}
// The longitude the bird sits over for a circuit: a GEO's slot; a MEO ring's satellite halfway between the two ends.
function satLon(id,a,b){const B=SATS[id];if(B.orb==='geo')return B.lon;const r=Math.PI/180,A=CITY[a],C=CITY[b];
return Math.atan2(Math.sin(A.lon*r)+Math.sin(C.lon*r),Math.cos(A.lon*r)+Math.cos(C.lon*r))/r;}
// Whether bird id sees city c.
function satSees(id,c){const B=SATS[id],C=CITY[c];if(!B||!C)return false;return B.orb==='meo'?Math.abs(C.lat)<=SAT_ORB.meo.lat:satArc(0,B.lon,C.lat,C.lon)<=B.r;}
function satPairOk(id,a,b){if(a===b||!satSees(id,a)||!satSees(id,b))return false;if(SATS[id].orb!=='meo')return true;const O=SAT_ORB.meo;
if(kmBetween(a,b)>O.km)return false;const lon=satLon(id,a,b);return [a,b].every(c=>satElev(satArc(0,lon,CITY[c].lat,CITY[c].lon),O.h)>=O.el);}
// The radio path: up from one dish and down to the other, the km the signal really travels. It is the link's km, so the
// routers' metric (pairW) sees a satellite as the long way round it is, and a cable wins whenever there is one.
function satKm(id,a,b){const h=SAT_ORB[SATS[id].orb].h,lon=satLon(id,a,b),A=CITY[a],C=CITY[b];
return Math.round(satSlant(satArc(0,lon,A.lat,A.lon),h)+satSlant(satArc(0,lon,C.lat,C.lon),h));}
// One way: the radio path at the speed of light in vacuum, plus the modems at both ends.
const satLat=l=>l.km/SAT_C+SAT_ORB[SATS[l.bird].orb].proc;
const satMo=(id,g)=>Math.round(SAT_PROV[SATS[id].p].pg*Math.pow(g,0.85)/10)*10;
const satRemote=c=>{const C=CITY[c];return !!C&&(C.P<=SAT_TOWN_P||C.P<=SAT_ISLE_P&&!SAT_MAIN.includes(C.land));};
const satName=l=>SATS[l.bird]?SATS[l.bird].n:'?';
// A subsea cable: a satellite circuit is stored as sub (never a land route) but is no cable on the seabed.
const seaLink=l=>!!l.sub&&l.kind!=='sat';

View file

@ -6,17 +6,18 @@
// sea: cable ships sail out to subsea cuts, or (timer) a cut mends on its own clock. confs: conference season.
// broke: deep in the red ends the game, or (rescue) a state loan keeps it going. moods: patient customers sour half as fast.
// pnis: PNIs and their augments wait for the other network's team, or (instant) are up the moment they are ordered.
const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',mods:[]};
const RULE_LATE=['sea','confs','broke','moods','pnis'];
const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant']};
// ip4: IPv4 is scarce (#150, 33-address-space.js): customers need addresses, homes share them behind CGNAT.
const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',sea:'ships',confs:true,broke:'lose',moods:'normal',pnis:'wait',ip4:true,mods:[]};
const RULE_LATE=['sea','confs','broke','moods','pnis','ip4'];
const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open'],sea:['ships','timer'],confs:[true,false],broke:['lose','rescue'],moods:['normal','patient'],pnis:['wait','instant'],ip4:[true,false]};
// i: icon, n: name, d: the one-line joke, x: what is different, in small print.
const PRESETS={
soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant'},
freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder'},
soft:{i:'☕',n:tr('rules.best_effort'),d:tr('rules.no_sla_no_pager_no_promises'),x:tr('rules.rare_outages_no_ddos_pnis_at_once'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',sea:'timer',confs:false,broke:'rescue',moods:'patient',pnis:'instant',ip4:false},
freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder',ip4:false},
oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a_real'),clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder'},
bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,money:'normal',gates:'ladder'},
sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open'},
puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open'},
sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open',ip4:false},
puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open',ip4:false},
};
const NORMAL_PRESETS=['soft','freeze','oncall','bgp'];
// How often things break, against the classic game. Spicy outages also last half as long again.

View file

@ -34,7 +34,7 @@ const COVS={
logo:{l:tr('banks.our_logo_goes_on_every_router'),ok:()=>true},
cash50:{l:tr('banks.never_let_cash_drop_below_50k'),ok:()=>S.cash>=50000},
nochina:{l:tr('banks.stay_out_of_mainland_china'),ok:()=>!Object.keys(S.pops).some(cnCity)},
nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(x=>x.sub).length<=(l.base&&l.base.sub||0)},
nosub:{l:tr('banks.no_new_subsea_links_while_this'),ok:l=>S.links.filter(seaLink).length<=(l.base&&l.base.sub||0)},
spaetzle:{l:tr('banks.peer_at_the_spatzle_ix_in'),ok:()=>S.ixp.stg!==undefined},
kehrwoche:{l:tr('banks.do_the_kehrwoche_keep_your_noc'),ok:()=>!S.inc.some(i=>S.day-i.start>7)},
app:{l:tr('banks.download_our_app_and_enable_all'),ok:()=>true},
@ -102,7 +102,7 @@ function callOffer(amount){const T=CALL_TERMS[rating()];if(!T||!CALL_AMTS.includ
const RESCUE_APR=0.02,RESCUE_TERM=60;
function rescueLoan(){const amount=niceAmt(Math.max(250000,-S.cash+Math.max(150000,(R.costMo||0)*2)));
S.cash+=amount;S.stats.rescues=(S.stats.rescues||0)+1;S.neg=0;
S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(x=>x.sub).length}});
S.loans.push({id:uid(),bank:'gov',start:S.day,amount,got:amount,bal:amount,apr:RESCUE_APR,apr0:RESCUE_APR,pay:Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)),left:RESCUE_TERM,term:RESCUE_TERM,share:0,covs:[],base:{sub:S.links.filter(seaLink).length}});
track('rescue');toast(`<b>${tr('banks.bank_stepped_in',{bank:esc(BANKS.gov.name)})}</b><br>${tr('banks.a_rescue_loan_of_amount_keeps',{amount:fmt$(amount),pay:fmt$(Math.round(annuity(amount,RESCUE_APR,RESCUE_TERM)))})}`,'bad',[{l:tr('common.open_bank'),act:'bank',args:{}}]);sfx('coin');}
function loanTick(d){
// conditions: 15-day grace, then a penalty every 30 days while broken

View file

@ -2,12 +2,12 @@
gives the same world. Free play keeps using the browser's Math.random. */
const _rand=Math.random;
Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();};
const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g;
const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='sat'?l.g:l.kind==='xp'?xpHopG(l):l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g;
function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)<g)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l))continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// Looked up rather than read from the save, so it follows a language switch mid-scenario.
const scnName=()=>S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name;
const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size;
const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>seaLink(l)&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size;
// Ports count only on POPs your backbone joins to São Paulo: islands of POPs with a port each skipped the Amazon (playtest).
const FTTB_G=500;
// Gangnam Style Peering: traffic, how well Seoul is served (delivered and fast) and a monthly profit.
@ -44,6 +44,8 @@ function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let
const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]);
function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}}
function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal';
// A multiplayer session (89-multiplayer.js): the server's AS number, and its seed, so every player starts in the same world.
if(o.mp&&S.mode==='normal'){const m=o.mp;S.mp={code:m.code,pid:m.pid,asn:m.asn,seed:m.seed,preset:m.preset,color:m.color,title:m.title,seq:0};S.asn=m.asn;S.rng=m.seed|0;}
// The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules.
{const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);}
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
@ -55,4 +57,5 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci
track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city);
toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal');
// A Normal game asks for its charter first; the tutorial starts once it is signed.
renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}}
renderAll();if(S.mp)mpStarted(o.mp);save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle'){charterAsk();if(!$('modal').hidden&&$('modal').className==='charter')UI.tutLater=true;else tutorialStart();}
if(S.mp)mpStartTell();}

View file

@ -19,7 +19,7 @@ function confTick(d){S.confReg=S.confReg||{};
toast(tr('conferences.conf_in_city_you_shook_a',{conf:esc(cf.n),city:esc(CITY[cf.c].name),n:CONF_DAYS,region:esc(REG[reg])})+(sp?' '+tr('conferences.your_logo_was_on_every_lanyard',{region:esc(REG[reg])}):'')+(cf.cap?' '+tr('conferences.carriers_took_your_card_expect_big'):'')+extra,'goal');sfx('coin');}
capDealTick(d);}
function confSection(){const up=upcomingConfs(75).slice(0,3),cb=S.conf&&S.conf.until>S.day?S.conf:null;if(!up.length&&!cb)return '';
return `<h3 style="font-size:15px;margin:10px 0 4px">${tr('common.conferences')}</h3>${cb?`<div class="inc" style="background:#EAF7EE"><div class="nm">${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}</div><div class="meta">${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}</div></div>`:''}${up.map(confRow).join('')}`;}
return `<h3 style="font-size:15px;margin:10px 0 4px">${tr('common.conferences')}</h3>${cb?`<div class="inc" style="background:var(--tint-g,#EAF7EE)"><div class="nm">${tr('conferences.name_glow_n_days_left',{name:esc(cb.name),n:cb.until-S.day})}</div><div class="meta">${tr('conferences.selective_networks_in_region_need',{region:esc(REG[cb.reg])})}${cb.sp?' '+tr('conferences.as_a_sponsor_you_also_get',{region:esc(REG[cb.reg])}):''}</div></div>`:''}${up.map(confRow).join('')}`;}
function confRow(cf){const reg=S.confReg&&S.confReg[cf.key],open=cf.day>S.day,sp=confSp(cf),cost=confCost(cf),lk=cf.cap&&glassLvl()<CAP_LV;
const tags=(reg==='sp'?'<span class="tag st on">'+tr('conferences.sponsor')+'</span>':reg?'<span class="tag st on">'+tr('common.registered')+'</span>':open?'':'<span class="tag st">'+tr('common.registration_closed')+'</span>');
const btns=!open||reg==='sp'?'':(reg?'':lk?btn(tr('sites_and_service.level_n',{n:CAP_LV}),'confGo',{key:cf.key},'sm',true):btn(tr('conferences.attend_cost',{cost:fmt$(cost)}),'confGo',{key:cf.key},'sm',S.cash<cost))+(sp?btn(tr('conferences.sponsor_cost',{cost:fmt$(CONF_SP-(reg?CONF_COST:0))}),'confSponsor',{key:cf.key},'pink sm',S.cash<CONF_SP-(reg?CONF_COST:0)):'');

View file

@ -0,0 +1,89 @@
/* ---------- Address space (#150): IPv6 is free for everyone, IPv4 ran out years ago ----------
The network holds IPv4 blocks in real CIDR sizes (/24 to /16): its first allocation from the RIR, blocks bought on
the transfer market and blocks leased in by the month. Owned blocks can be leased out (a broker finds the tenant) or
sold, once two years have passed since they last moved (the RIRs' holding period, which also stops flipping).
Business customers on IP service take a public block each, sized by kind and port (a /29 for a small DIA port, a /23
for a big hosting company); broadband homes take what is left, and the homes that do not fit share addresses behind
CGNAT at the player's ratio. CGNAT costs a little per Gbps it carries (IPv6 goes around the box) and some gamers want
their money back. An offer that needs more than is free, with every home already behind CGNAT, cannot be signed, and a
customer renewing bigger stays at its size when the bigger block is not free (clGrow).
Nothing is stored per customer: what each one needs follows from its kind and size, so growing customers and old saves
need no new fields. On in On-call and BGP at 3 a.m. (rule ip4), off in the gentler presets, sandbox and puzzles;
scenarios only when they opt in (S.scn.rules.ip4). No random draws: the market price is a function of the day.
The first allocation is a /21: one transit's worth of broadband levels off at about 1,300 homes in every start city,
so the first months fit with room for a few customers (gameplay rule F1). */
// IP4_BLK: the most blocks a network holds; buying and leasing stop there, and a save keeps that many.
const IP4_START=21,IP4_MIN=16,IP4_MAX=24,IP4_HOLD=730,IP4_NAT=[8,16,32,64],IP4_NAT0=16,IP4_BLK=256;
// Public addresses per Gbps of busy-hour broadband (a home each), and the part of it CGNAT still carries: the rest is IPv6.
const IP4_BB=10,IP4_V4=0.55,IP4_CGN=2;
// The market: dollars per address, flat for half a year, then +3% a year on a slow four-year swing. Leases are by the
// month (a broker keeps a cut of what yours earn), sales pay 92% of the price after the broker's fee.
const IP4_PX=38,IP4_FREE=180,IP4_YR=0.03,IP4_IN=0.5,IP4_OUT=0.4,IP4_SELL=0.92;
// Of the bill of a home behind CGNAT, the share that comes back as refunds (gamers, mostly): more homes per address, more
// grumbling. Homes squeezed past the ratio (port exhaustion) are worse.
const IP4_ANNOY={8:0.01,16:0.015,32:0.025,64:0.04},IP4_SQZ=0.15;
// Per kind of customer: addresses per Gbps of port, and the smallest block it takes. Circuits, waves and fiber carry no
// addresses of yours; downstream ISPs and universities bring their own (universities sit on legacy /16s); orbit
// terminals sit behind the satellite operator's own CGNAT.
const IP4_BIZ={cgame:[0.5,256],dia:[2,8],fabip:[2,8],game:[2,16],gpu:[0.5,64],host:[4,64],metav:[0.25,256],scrub:[2,8],stream:[1,32]};
const ip4Sz=len=>2**(32-len),ip4LenOk=len=>Number.isInteger(len)&&len>=IP4_MIN&&len<=IP4_MAX;
const ip4Cidr=n=>'/'+(32-Math.ceil(Math.log2(Math.max(1,n)))),ip4N=n=>Math.round(n).toLocaleString();
function ip4On(){return !!S&&!!S.ip4&&rule('ip4')===true&&(S.scn?scnRule('ip4'):S.mode==='normal');}
function ip4Need(b){const k=b&&IP4_BIZ[b.type];if(!k||!(b.bw>0))return 0;return Math.min(4096,2**Math.ceil(Math.log2(Math.max(k[1],b.bw*k[0]))));}
/* Who uses what. T: usable addresses (owned and leased in, without what is leased out); B: business customers; H: homes;
cg: homes behind CGNAT; over: the share of homes that do not fit even at the ratio; free: what a new customer can have
with every home behind CGNAT. */
function ip4Use(s=S){const I=s.ip4,r=I.nat;let own=0,inn=0,out=0,B=0,H=0;
for(const b of I.b){const n=ip4Sz(b.len);if(b.k==='in')inn+=n;else if(b.out)out+=n;else own+=n;}
for(const b of s.biz)B+=ip4Need(b);
for(const c in s.pops){const p=s.pops[c];if(p.bb)H+=p.bb.d*IP4_BB;}
H=Math.ceil(H);const T=own+inn,A=Math.max(0,T-B),min=Math.ceil(H/r);let cg=0,over=0;
if(A<H){if(A>=min)cg=Math.min(H,Math.ceil((H-A)*r/(r-1)));else{cg=H;over=min?1-A/min:0;}}
return {T,own,inn,out,B,H,cg,over,free:T-B-min,r};}
const ip4Fits=o=>!ip4On()||ip4Need(o)<=Math.max(0,ip4Use().free);
// A customer renewing at bw: does the bigger block it needs fit what is free?
const ip4GrowOk=(b,bw)=>!ip4On()||ip4Need({type:b.type,bw})-ip4Need(b)<=Math.max(0,ip4Use().free);
const ip4Full=()=>S.ip4.b.length>=IP4_BLK;
// What you announce, as the AS box shows it: your blocks by prefix length, without the ones leased out to others.
const ip4Pfx=()=>{const c={};for(const b of S.ip4.b)if(!b.out)c[b.len]=(c[b.len]||0)+1;return Object.keys(c).sort((a,b)=>a-b).map(l=>`${c[l]} × /${l}`).join(', ');};
// Would giving this block up (selling, leasing it out, handing it back) still leave room for everyone?
const ip4Spare=b=>ip4Use().free>=ip4Sz(b.len);
const ip4Held=b=>b.k!=='in'&&S.day-b.d<IP4_HOLD;
function ip4Px(d=S.day){if(!rule('market')||d<=IP4_FREE)return IP4_PX;const y=(d-IP4_FREE)/365;return IP4_PX*(1+IP4_YR*y)*(1+0.12*Math.sin(2*Math.PI*y/4));}
// Bigger blocks are a little cheaper per address, as on the real market.
const ip4Cost=len=>Math.round(ip4Sz(len)*ip4Px()*(1-0.015*(IP4_MAX-len))/100)*100;
const ip4Value=len=>Math.round(ip4Cost(len)*IP4_SELL/100)*100;
const ip4InMo=len=>Math.round(ip4Sz(len)*IP4_IN*ip4Px()/IP4_PX),ip4OutMo=len=>Math.round(ip4Sz(len)*IP4_OUT*ip4Px()/IP4_PX);
// The month's IPv4 bill: leases in and out, CGNAT boxes, refunds (eye: what broadband earns a month).
function ip4Bill(eye){const u=ip4Use();let lin=0,lout=0;for(const b of S.ip4.b){if(b.k==='in')lin+=b.mo||0;else if(b.out)lout+=b.mo||0;}
const cgS=u.H?u.cg/u.H:0;return {u,lin,lout,box:u.cg/IP4_BB*IP4_V4*IP4_CGN,refund:eye*(cgS*IP4_ANNOY[u.r]+u.over*IP4_SQZ)};}
// computeMoney: only what is there, so a network with nothing to pay keeps its money rows as they were.
function ip4Money(C,V){if(!ip4On())return;const b=ip4Bill(V.eyeballs||0),c=Math.round(b.lin+b.box+b.refund);if(c>0)C.ip4=c;if(b.lout>0)V.ip4=b.lout;}
/* A new network gets its /21 from the RIR. An older save gets what it already uses registered to it and a quarter more to
grow into (about a month for a big, fast-growing network), rounded up to /24s in real CIDR blocks (a /21 at the
least), so nothing changes on load; those blocks move like any other two years on.
Their ids are fixed (rir0, rir1…), not uid(): a new game draws no id, so every id after it stays as it was. */
function ip4Grant(s){const d=s.day||0,b=[],add=len=>b.push({id:'rir'+b.length,len,k:'rir',d});let need=0;
for(const x of s.biz||[])need+=ip4Need(x);
for(const c in s.pops||{}){const p=s.pops[c];if(p&&p.bb&&p.bb.d>0)need+=p.bb.d*IP4_BB;}
need=Math.max(ip4Sz(IP4_START),Math.ceil(need*1.25/256)*256);
while(need>=ip4Sz(IP4_MIN)&&b.length<200){add(IP4_MIN);need-=ip4Sz(IP4_MIN);}
for(let len=IP4_MIN+1;len<=IP4_MAX;len++)if(need>=ip4Sz(len)){add(len);need-=ip4Sz(len);}
return {b,nat:IP4_NAT0,w:0};}
const ip4New=()=>ip4Grant({});
function ip4Fix(s){const I=s.ip4&&typeof s.ip4==='object'&&!Array.isArray(s.ip4)?s.ip4:null;if(!I){s.ip4=ip4Grant(s);return;}
const day=Math.max(0,num(s.day,0)),mo=v=>Math.round(Math.min(1e8,Math.max(0,num(v,0))));
const b=(Array.isArray(I.b)?I.b:[]).filter(x=>x&&typeof x==='object'&&ip4LenOk(x.len)&&['rir','buy','in'].includes(x.k)).slice(0,IP4_BLK).map(x=>{
const o={id:typeof x.id==='string'&&x.id&&x.id.length<=40?x.id:uid(),len:x.len,k:x.k,d:int(x.d,0,day,0)};
if(x.k==='in')o.mo=mo(x.mo);else if(x.out===true){o.out=true;o.mo=mo(x.mo);}return o;});
s.ip4={b,nat:IP4_NAT.includes(I.nat)?I.nat:IP4_NAT0,w:int(I.w,0,3,0)};}
/* Once a day: say so when homes go behind CGNAT (a percent of them at least), and when even CGNAT cannot fit them all
(w: what was said). Each rearms only with room to spare again, so homes hovering at the limit hear it once. */
function ip4Day(d){if(!ip4On())return;const I=S.ip4,u=ip4Use(),A=u.T-u.B,go=[{l:tr('ip4.section'),act:'ip4Open'}];
if(u.cg>=Math.max(1,u.H*0.01)){if(!(I.w&1)){I.w|=1;toast(tr('ip4.toast_cgnat',{p:pct(u.cg/u.H)}),'',go);}}else if(A>=u.H*1.05)I.w&=~1;
if(u.over>0){if(!(I.w&2)){I.w|=2;toast(tr('ip4.toast_out',{r:u.r}),'bad',go);sfx('err');}}else if(A>=Math.ceil(u.H/u.r)*1.1)I.w&=~2;}
// Renewals that wanted a bigger block than is free (clGrow, [customer, bandwidth]): they stay as they are, and hear why.
function ip4News(l=[]){for(const [b,bw] of l.slice(0,3))toast(tr('ip4.no_grow',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(bw)}),'',[{l:tr('ip4.section'),act:'ip4Open'}]);}
// The line under an offer that cannot be signed for want of addresses.
function ip4Why(o){if(ip4Fits(o))return '';const n=ip4Need(o);
return `<div class="why">${tr('ip4.offer_needs',{p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))})} ${btn(tr('ip4.section'),'ip4Open',{},'ghost sm')}</div>`;}

View file

@ -59,7 +59,7 @@ function seatOffer(c,d){const rs=(c?SEAT_ROUTES[c]||[]:Object.values(SEAT_ROUTES
if(!rs.length)return null;const r=rs[hstr(S.asn+'|seat|'+d)%rs.length];return {a:r[0],b:r[1],name:r[2],km:seatKm(r[0],r[1]),exp:d+SEAT_EXP};}
function seatConf(c){if(S.seatOff||lvl()<SEAT_LV||S.scn)return;S.seatOff=seatOffer(c,S.day);if(S.seatOff)toast(tr('specialist.a_consortium_is_selling_seats_on',{name:esc(S.seatOff.name),a:CITY[S.seatOff.a].name,b:CITY[S.seatOff.b].name}),'goal',[{l:tr('common.show_me'),act:'leftTab',args:{t:'deals'}}]);}
function seatSection(){const o=S.seatOff;if(!o||o.exp<=S.day)return '';const pop=[o.a,o.b].filter(c=>!S.pops[c]).reduce((x,c)=>x+newPopCost(c),0);
return `<div class="inc" style="background:#E6F4FF"><div class="nm">🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}</div><div class="meta">${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>
return `<div class="inc" style="background:var(--tint-b,#E6F4FF)"><div class="nm">🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}</div><div class="meta">${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>
<div class="meta">${tr('specialist.your_own_fiber_pairs_on_a')}${pop?' '+tr('specialist.includes_pops_at_the_landings_price',{price:fmt$(pop)}):''}</div>
<div class="btns">${SEAT_N.map(n=>{const c=seatCost(o.km,n)+pop;return btn(`${trn('specialist.n_fiber_pairs',n)} <small>${fmt$(c)} · ${tr('common.price_mo',{price:fmt$(seatMo(o.km,n))})}</small>`,'seatBuy',{n},'sm',S.cash<c);}).join('')}${btn(tr('common.decline'),'seatNo',{},'ghost sm')}</div></div>`;}
function seatPanel(l){if(!l.seat)return '';return `<div class="kv"><span>${tr('specialist.consortium_seat')}</span><b>${esc(l.cname||'')} · ${trn('specialist.n_fiber_pairs',Math.max(1,l.pairs|0))}</b></div><p class="note">${tr('specialist.the_consortium_runs_the_cable_your')}</p>`;}
@ -97,8 +97,8 @@ function charterAsk(){if(!charterDue()||!$('modal').hidden||window.__TUBES_TEST_
function charterCard(){if(S.scn||S.mode!=='normal')return '';
if(broker())return baronCard();
if(charter()!=='boutique')return '';
if(S.solWon)return `<div class="inc" style="background:#EAF7EE"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}</div></div>`;
const r=solRoutes();return `<div class="inc" style="background:#EEF0FF"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}</div>${r.slice(0,SOL_ROUTES).map(x=>`<div class="meta">✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} &lt; ${x.l.toFixed(1)}</div>`).join('')}</div>`;}
if(S.solWon)return `<div class="inc" style="background:var(--tint-g,#EAF7EE)"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}</div></div>`;
const r=solRoutes();return `<div class="inc" style="background:var(--tint-v,#EEF0FF)"><div class="nm">⚡ ${tr('specialist.speed_of_light')}</div><div class="meta">${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}</div>${r.slice(0,SOL_ROUTES).map(x=>`<div class="meta">✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} &lt; ${x.l.toFixed(1)}</div>`).join('')}</div>`;}
// Once a day: seats expire or call, the boutique checks its win and carriers call the broker.
function specDay(d){if(broker())brokerDay(d);if(S.seatOff&&S.seatOff.exp<=d)S.seatOff=null;
if(!S.seatOff&&!S.scn&&S.mode!=='puzzle'&&lvl()>=SEAT_LV&&hstr(S.asn+'|seatcall|'+d)%SEAT_ODDS===0)seatConf(null);

View file

@ -20,8 +20,8 @@ function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap
return Object.values(by).some(s=>s.size>=2);}
const baronOk=()=>cableConts()>=BARON_CONT&&capSalesMo()>=BARON_MO;
// On the goals tab, under the charter: how far Glass Baron is.
function baronCard(){if(S.baronWon)return `<div class="inc" style="background:#EAF7EE"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}</div></div>`;
return `<div class="inc" style="background:#E6F4FF"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}</div></div>`;}
function baronCard(){if(S.baronWon)return `<div class="inc" style="background:var(--tint-g,#EAF7EE)"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}</div></div>`;
return `<div class="inc" style="background:var(--tint-b,#E6F4FF)"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}</div></div>`;}
function showBaronWin(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">🌊 ${tr('broker.glass_baron')}</h1><p class="tagline">${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:S.day,n:BARON_CONT,mo:fmt$(capSalesMo())})}</p><div class="btns">${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}</div>`);}
/* Carriers call the broker now and then (about three times a year, from day 60) with a capacity deal on a route the
capacity conferences trade: the same deals at the same terms, without the trip. Picked by a hash of the day, so a

View file

@ -65,13 +65,13 @@ function salesDay(d){const L=S.sales;if(!L)return;
// With a rocket company, every other game is with the Founder, and in orbit (pieGolf, 99-pie-sales.js).
const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia'];
function salesGolf(d){if(pieGolf(d))return;const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return;
const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl());if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0];
const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0];
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name);
const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40};
const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b));
toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');}
// Declining an offer the CEO likes: about one in three, he already shook hands on it.
function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+slKey(o))>=0.33)return false;
function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||!ip4Fits(o)||slR('veto|'+slKey(o))>=0.33)return false;
const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;}
// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer.
function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null;

View file

@ -32,7 +32,7 @@ function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floo
const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;};
opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o);
if(A.min&&v<A.min){const b0=S.biz.length;ACT.decline({id:o.id});W.x++;if(S.biz.length>b0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;}
if(!A.on)continue;
if(!A.on||!ip4Fits(o))continue;
if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cash<bizMo(o)))continue;ACT.accept({id:o.id});if(won(o))used.set(k,(used.get(k)||0)+o.bw);continue;}
if(!bCities(o).every(popUp))continue;
if(p==='shark'){if(S.cash<bizMo(o)||(T.event&&!(o.start>d)))continue;ACT.accept({id:o.id});won(o);continue;}

View file

@ -0,0 +1,73 @@
/* ---------- Teleports and rented satellite capacity (#83) ----------
The rules, the money and save repair. Catalog and physics: 10-catalog/75-satellites.js; actions: 90-actions/87-teleports.js;
panels: 93-ui/72-teleport-panels.js. A circuit is a link (kind 'sat'): routing, standby, metrics and the map treat it like
any other, with the radio path as its km and its orbit's latency. */
// A POP's teleport (S.pops[c].tele): 0 none, 1 dishes for GEO birds, 2 with tracking antennas for the MEO ring too.
const teleOf=c=>{const p=S&&S.pops[c];return p&&(p.tele===1||p.tele===2)?p.tele:0;};
const teleCities=()=>Object.keys(S.pops).filter(teleOf);
// The birds that see city c, whatever your level.
const teleSees=c=>Object.keys(SATS).filter(id=>satSees(id,c));
// Why no teleport can go up at city c (nothing on sale sees it at your level, or no POP); '' when it can.
function teleWhy(c){if(!isCity(c)||!S.pops[c])return tr('satellites.no_pop_in_city',{city:isCity(c)?CITY[c].name:'?'});
if(lvl()<SAT_ORB.geo.lv)return tr('satellites.teleports_unlock_at_level',{lv:SAT_ORB.geo.lv});
const ids=teleSees(c);if(!ids.length)return tr('satellites.no_bird_sees_this_city');
if(!ids.some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)){const O=SAT_ORB[SATS[ids[0]].orb];return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});}
return '';}
// Why the teleport at c cannot add MEO tracking antennas; '' when it can.
function trkWhy(c){const O=SAT_ORB.meo;if(lvl()<O.lv)return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});
if(!isCity(c)||!teleOf(c))return tr('satellites.no_teleport_in_city',{city:isCity(c)?CITY[c].name:'?'});
if(!teleSees(c).some(id=>SATS[id].orb==='meo'))return tr('satellites.meo_ring_misses_city',{city:CITY[c].name,lat:O.lat});
return '';}
// The birds that see both ends of a circuit: GEO first, then the cheapest.
function satBirds(a,b){return Object.keys(SATS).filter(id=>satPairOk(id,a,b)).sort((x,y)=>(SATS[x].orb>SATS[y].orb)-(SATS[x].orb<SATS[y].orb)||SAT_PROV[SATS[x].p].pg-SAT_PROV[SATS[y].p].pg);}
// Why a circuit from teleport a to b over bird id (g Gbps, when given) cannot be ordered; '' when it can.
function satWhy(a,b,id,g){const B=own(SATS,id)?SATS[id]:null;if(!B||!isCity(a)||!isCity(b)||a===b)return tr('satellites.no_such_circuit');const O=SAT_ORB[B.orb];
if(lvl()<O.lv)return tr('satellites.orbit_unlocks_at_level',{orb:O.n,lv:O.lv});
if(!teleOf(a))return tr('satellites.no_teleport_in_city',{city:CITY[a].name});
if(B.orb==='meo'&&teleOf(a)<2)return tr('satellites.needs_tracking_antennas',{city:CITY[a].name});
if(!satRemote(b))return tr('satellites.not_remote',{city:CITY[b].name});
if(!satPairOk(id,a,b))return tr('satellites.out_of_footprint',{bird:B.n,a:CITY[a].name,b:CITY[b].name});
if(g!==undefined&&!O.g.includes(g))return tr('satellites.no_such_circuit');
const nt=noTalk(a,b);if(nt)return tr(nt);
if(!S.pops[b]){if(!cityOn(b))return popOffWhy(b);if(cnCity(b)&&!cnOk())return tr('pops_transit_ix.you_need_a_license_first_foreign');}
return '';}
// Where a teleport can reach: small islands and remote towns that one of its birds sees with it, your POPs first.
function satTargets(a){return CITIES.filter(C=>C.id!==a&&satRemote(C.id)&&(S.pops[C.id]||cityOn(C.id))&&satBirds(a,C.id).length).map(C=>C.id)
.sort((x,y)=>(!S.pops[x])-(!S.pops[y])||kmBetween(a,x)-kmBetween(a,y));}
// Your teleports that can reach city b.
const satFrom=b=>satRemote(b)?teleCities().filter(a=>a!==b&&satBirds(a,b).length):[];
// A new link between a and b (a wave, fiber, a fabric circuit, a cable): the circuits already there go on standby beside
// it, as one ordered next to a link does, and the player hears about it. Without this the pair's load is shared with orbit.
function satBeside(a,b){const ls=pairLinks(a,b).filter(l=>l.kind==='sat'&&!l.standby);for(const l of ls)l.standby=true;
if(ls.length)toast(trn('satellites.n_circuits_go_on_standby',ls.length,{a:CITY[a].name,b:CITY[b].name}));return ls.length;}
// What the teleports and their circuits cost a month (R.cost.sat).
function satMoAll(){let m=0;for(const c in S.pops){const t=teleOf(c);if(t)m+=TPORT_MO+(t>1?TRK_MO:0);}for(const l of S.links)if(l.kind==='sat')m+=l.mo||0;return m;}
/* compute(): what users notice on the edges a satellite circuit is on. sv: the losses of the orbits there; sx: the edge's
latency is the satellite's (no cable carries ahead of it), so it is no haul to transit on the ground. Returns how many
edges there were, for compute() to know a satellite is in the picture at all. */
function satEdges(SE){for(const e of SE){let ta=false,ts=false,act=false;const v=e.sv;
for(const l of e.links){const sb=!!l.standby;if(!sb)act=true;if(l.kind==='sat'){const x=SAT_ORB[SATS[l.bird].orb].loss;if(!v.includes(x))v.push(x);}else if(sb)ts=true;else ta=true;}
e.sx=act?!ta:!ts;}
return SE.length;}
// A flow of ok Gbps from city index ci crossed these edges: keep it, and what each orbit would cost it beyond the tl its
// haul to transit already does (users count the worse of the two, not both).
function satNote(se,ci,ok,tl){for(let k=0;k<se.length;k++){const x=se[k],v=x.sv,m=x.sa||(x.sa=new Map());let a=m.get(ci);if(!a)m.set(ci,a=new Float64Array(1+v.length));
a[0]+=ok;for(let j=0;j<v.length;j++)if(v[j]>tl)a[1+j]+=ok*(v[j]-tl);}}
/* After routing: each orbit's share of the edge's traffic, split as compute() splits it (active links by capacity, standby
ones the overflow). A satellite on standby beside a cable that has room carries nothing and costs nobody anything; one
that takes the overflow, or shares the load, costs the users of that share. LATP gets the lost service and SATU the
Gbps that rode a satellite, by city index. */
function satAfter(SE,LATP,SATU){for(const e of SE){const ld=e.ld||0;if(!e.sa||ld<=1e-9)continue;
const v=e.sv,sh=new Float64Array(v.length),ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;let only=true,all=0;
for(const l of e.links){if(l.kind!=='sat'){only=false;continue;}const c=capOf(l);sh[v.indexOf(SAT_ORB[SATS[l.bird].orb].loss)]+=(l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0))/ld;}
if(only&&v.length===1)sh[0]=1;for(let j=0;j<v.length;j++)all+=sh[j];if(all<=1e-12)continue;
for(const [ci,x] of e.sa){let p=0;for(let j=0;j<v.length;j++)p+=sh[j]*x[1+j];LATP[ci]+=p;SATU[ci]+=all*x[0];}}}
// The share of city c's served traffic that rode a satellite in r (0 to 1).
const satShare=(r,c)=>r&&r.satU&&r.citySrv&&r.citySrv[c]>0?Math.min(1,(r.satU[c]||0)/r.citySrv[c]):0;
// Saves: a teleport is 1 or 2; a circuit needs a known bird that sees both POPs, a teleport able to work it, a size it sells.
function satSanitize(s){
for(const c of Object.keys(s.pops)){const p=s.pops[c];if(p.tele!==undefined&&p.tele!==1&&p.tele!==2)delete p.tele;}
s.links=s.links.filter(l=>{if(l.kind!=='sat')return true;const B=typeof l.bird==='string'&&own(SATS,l.bird)?SATS[l.bird]:null,p=s.pops[l.a];
if(!B||!p||!p.tele||B.orb==='meo'&&p.tele<2||!s.pops[l.b]||!satPairOk(l.bird,l.a,l.b))return false;
const G=SAT_ORB[B.orb].g;if(!G.includes(l.g))l.g=G.reduce((x,v)=>v<=num(l.g,0)?v:x,G[0]);
l.km=satKm(l.bird,l.a,l.b);l.sub=true;l.ready=num(l.ready,0);l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of ['tier','cable','trench','mult','border','premium','vt','prov','own','sys','ch'])delete l[k];return true;});}

View file

@ -32,7 +32,7 @@ function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';cons
for(const x of pieBhHops(e,h.from===b.city)){const ms=x.ms*2+0.05;if(x.k==='up')hop(`dish.${x.city}.${me}`,ip(hstr(x.city),5),ms,tr('traceroute.sky_up',{city:CITY[x.city].name,crust:tr(cr.n)}));
else if(x.k==='las')hop(`laser.${b.cr}.${me}`,`10.255.${hstr(b.cr)%250}.${(x.km|0)%250}`,ms,tr('traceroute.sky_laser',{km:Math.round(x.km).toLocaleString()}));
else hop(`dish.${x.city}.${me}`,ip(hstr(x.city),6),ms,tr('traceroute.sky_down',{city:CITY[x.city].name}));}continue;}
const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}};
const lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.kind==='xp'?tr('express.trace_hop',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:satName(l)}):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}};
if(to.city){const path=P.path(to.city);lines.unshift(`traceroute to ${to.city}.${me} (${CITY[to.city].name}), 30 hops max`);if(!path){lines.push(' 2 * * * ← '+tr('traceroute.no_working_path_between_these_pops'));return {text:lines.join('\n'),why:tr('traceroute.no_path_every_route_between_these')};}walk(path);const bw=trBhWhy(bh,path);return {text:lines.join('\n'),why:bw+(S.te&&S.te.on?trn('traceroute.internal_path_over_n_link_chosen',path.length):trn('traceroute.internal_path_over_n_link_chosen_8620',path.length))};}
const N=NET[to.net],ex=trExits(to.net).filter(e=>P.dist[e.city]!==undefined);
lines.unshift(`traceroute to www.${slug(N.name)}.example (${N.name}, AS${N.asn}) from ${CITY[src].name}, 30 hops max`);

View file

@ -1,6 +1,6 @@
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}};
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null};
}

View file

@ -1,12 +1,13 @@
/* Pitcairn (#124): no cable lands there yet, but you may land your own, and the UK pays a monthly grant while the
islanders are online through you: a POP with broadband, up and nearly fully served. */
const GRANT_MO=300000;
const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9);
islanders are online through you: a POP with broadband, up and nearly fully served. The money is for a cable: with more
than GRANT_SAT of their traffic on a rented satellite circuit (#83) it never comes, however well MEO serves them. */
const GRANT_MO=300000,GRANT_SAT=0.1;
const grantOn=r=>!!(S&&S.pops.pcn&&S.pops.pcn.bb&&!(S.pops.pcn.down>S.day)&&sfOf(r,'pcn')>=0.9&&satShare(r,'pcn')<=GRANT_SAT);
/* Satellite tier: Pitcairn online through your pies (its POP on backhaul, or home terminals there) is good enough for the
UK at a lower bar, orbit's latency forgiven (sfOf() counts it, so the fiber grant never comes), for less money. */
const GRANT_SKY_MO=120000,GRANT_SKY_Q=0.9;
function grantSky(r){if(!S||!S.pie||!r||!r.pie||grantOn(r))return false;const p=S.pops.pcn;
if(p&&p.bb&&!(p.down>S.day)&&r.pie.bh.some(b=>b.city==='pcn'&&b.g>0)){const d=r.cityDem.pcn||0;if(d>1e-6&&(r.citySrv.pcn||0)/d>=GRANT_SKY_Q)return true;}
return S.biz.some(b=>b.city==='pcn'&&b.type==='pizza'&&(r.pie.sf[b.id]||0)>=GRANT_SKY_Q);}
function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R);
return `<span class="fact${on||sky?' mine':''}">${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}</span>`;}
function grantFact(c){if(c!=='pcn')return '';const on=grantOn(R),sky=!on&&grantSky(R),sat=!on&&!sky&&satShare(R,'pcn')>GRANT_SAT;
return `<span class="fact${on||sky?' mine':''}">${on?tr('pitcairn.uk_grant_mo',{mo:fmt$(GRANT_MO)}):sky?tr('pitcairn.uk_sky_grant_mo',{mo:fmt$(GRANT_SKY_MO),full:fmt$(GRANT_MO)}):sat?tr('pitcairn.uk_grant_needs_a_cable',{mo:fmt$(GRANT_MO)}):tr('pitcairn.uk_grant_mo_once_islanders',{mo:fmt$(GRANT_MO)})}</span>`;}

View file

@ -0,0 +1,180 @@
/* ================= MULTIPLAYER (docs/MULTIPLAYER.md) =================
Only in a self-hosted copy built with MP_API (scripts/mp-server.js on the same origin); with MP_API empty nothing here
runs. Players share a session by a six-character code: each builds their own network in the same world (one seed,
one rules preset), each network's save is also kept on the server (so it can move to another device), and a small
public card per player feeds the session's leaderboard and feed. The game itself stays local and keeps playing
when the server is away. S.mp = null | {code, pid, asn, seed, preset, color, title, seq}; the secret token is never in
S (saves get exported and shared): it lives in this browser's storage, sot-mp:<code>:<pid>. */
const MP_CODE=/^[0-9A-HJKMNP-TV-Z]{6}$/,MP_PID=/^[a-z0-9]{8}$/,MP_TOK=/^[0-9a-f]{64}$/,MP_COL=/^#[0-9a-f]{6}$/i;
// Pushes: a new game day, at most every 15 s; the roster every 5 s only while the session panel is open. A keepalive
// request (the page is going away) carries at most 64 KiB, so only a small save goes with it (MP_KEEP bytes of request,
// with room to spare), else the card alone.
const MP_GAP=15000,MP_POLL=5000,MP_KEEP=63000,MP_GZ=32768,MP_FEED=['join','leave','t2','t1','t1first','chat'];
/* cur: the push on its way ({cut, ac}); staleSeq: the server's number when it said it has a newer save; sig: what the
last push that landed looked like (mpSig); force: the player chose to keep this save; now: push at the next save. */
const MP={roster:null,day:-1,last:-1e9,busy:false,cur:null,stale:false,staleSeq:0,gone:false,leaving:false,wait:0,fails:0,told:false,poll:null,sig:'',force:false,now:false};
const mpIs=()=>!!(MP_API&&S&&S.mp&&!pzOn());
const mpShow=c=>c.slice(0,3)+'-'+c.slice(3);
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code, or null. I, L and O read as 1, 1 and 0 (Crockford's base32).
function mpNorm(s){if(typeof s!=='string'||s.length>20)return null;const c=s.toUpperCase().replace(/[\s-]/g,'').replace(/[IL]/g,'1').replace(/O/g,'0');return MP_CODE.test(c)?c:null;}
const mpPath=(m,p)=>'/sessions/'+m.code+(p||'');
const mpTokK=(c,p)=>'sot-mp:'+c+':'+p;
function mpTok(m){if(!m||!MP_CODE.test(m.code)||!MP_PID.test(m.pid))return null;const t=lsGet(mpTokK(m.code,m.pid));return typeof t==='string'&&MP_TOK.test(t)?t:null;}
function mpTokSet(c,p,t){try{if(t==null)localStorage.removeItem(mpTokK(c,p));else localStorage.setItem(mpTokK(c,p),t);}catch(e){}}
// The catalog's own AS numbers in the server's range: the server hands out one nobody on the map uses.
const mpAvoid=()=>NETS.filter(n=>n.asn>=200000&&n.asn<=214999).map(n=>n.asn).slice(0,64);
function mpSanitize(s){const m=s.mp;
if(!m||typeof m!=='object'||Array.isArray(m)||!MP_CODE.test(m.code)||!MP_PID.test(m.pid)||s.mode!=='normal'){s.mp=null;return;}
s.mp={code:m.code,pid:m.pid,asn:int(m.asn,200000,214999,200000),seed:int(m.seed,-2147483648,2147483647,0),preset:NORMAL_PRESETS.includes(m.preset)?m.preset:'oncall',
color:typeof m.color==='string'&&MP_COL.test(m.color)?m.color:'#ff4f9a',title:typeof m.title==='string'?m.title.slice(0,40):'',seq:int(m.seq,0,1e15,0)};}
// What the server said when a session started or someone joined: checked before it becomes S.mp.
function mpJoinOk(j){if(!j||typeof j!=='object'||!MP_CODE.test(j.code)||!MP_PID.test(j.pid)||typeof j.token!=='string'||!MP_TOK.test(j.token)||!Number.isInteger(j.seed)||!Number.isInteger(j.asn)||j.asn<200000||j.asn>214999)return null;
return {code:j.code,pid:j.pid,token:j.token,asn:j.asn,seed:j.seed|0,preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',color:typeof j.color==='string'&&MP_COL.test(j.color)?j.color:'#ff4f9a',title:typeof j.title==='string'?j.title.slice(0,40):''};}
/* One call to the session server. Same origin, never cached; a call that takes over 15 s gives up. Rejects with
{status, j} on an HTTP error, so callers can tell "no such session" from "server away". */
function mpReq(method,p,body,o={}){
if(!MP_API||typeof fetch!=='function')return Promise.reject(Object.assign(new Error('off'),{status:0}));
const h={};if(body!==undefined)h['content-type']='application/json';
// o.tok: a token not stored yet (a #mp= link's, until the server takes it).
if(o.auth){const t=o.tok||mpTok(o.auth);if(!t)return Promise.reject(Object.assign(new Error('no token'),{status:401}));h.authorization='Bearer '+o.auth.pid+'.'+t;}
const ac=o.keep?null:o.ac||(typeof AbortController==='function'?new AbortController():null),tm=ac?setTimeout(()=>ac.abort(),15000):0;
let f;try{f=fetch(MP_API+p,{method,headers:h,body:body===undefined?undefined:typeof body==='string'?body:JSON.stringify(body),cache:'no-store',credentials:'same-origin',...(o.keep?{keepalive:true}:{}),...(ac?{signal:ac.signal}:{})});}
catch(e){clearTimeout(tm);return Promise.reject(Object.assign(e,{status:0}));}
return Promise.resolve(f).then(r=>Promise.resolve(r.json?r.json():null).catch(()=>null).then(j=>{clearTimeout(tm);if(!r.ok)throw Object.assign(new Error(j&&j.error||'HTTP '+r.status),{status:r.status,j});return j;}),
e=>{clearTimeout(tm);throw Object.assign(e||new Error('failed'),{status:e&&e.status||0});});}
/* The public card: what the leaderboard shows (and what peering between players will need later). */
function mpCard(){let t1=false,tl='Tier 3';try{t1=isTier1();tl=tierLabel();}catch(e){}
const tier=tl==='Tier 1'?'t1':tl==='Tier 2'?'t2':'t3',pairs=new Map();
for(const l of S.links){if(l.ready>S.day)continue;const k=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let g=0;try{g=hopG(l)||0;}catch(e){}pairs.set(k,(pairs.get(k)||0)+g);}
const links=[...pairs].sort((a,b)=>b[1]-a[1]).slice(0,300).map(([k,g])=>{const [a,b]=k.split('|');return [a,b,Math.round(g)];});
const served=R.served||0;
return {day:S.day,name:S.name,asn:S.asn,tier,t1,lvl:S.lvl||1,pops:Object.keys(S.pops).slice(0,500),links,ix:Object.keys(S.ixp).slice(0,500),transit:[...new Set(S.transit.map(t=>t.net))].slice(0,64),
ppol:ppol(),reach:Math.round((R.reach||0)*1e4)/1e4,peak:Math.round((S.stats.peak||0)*10)/10,served:Math.round(served*10)/10,cust:S.biz.length,rev:Math.round(R.revMo||0),
cashB:S.cash<0?-1:Math.min(20,Math.floor(Math.log10(Math.max(1,S.cash)))),score:(t1?2e9:tier==='t2'?1e9:0)+Math.round(served)};}
/* Other players' data, as it comes back: the same whitelist the server keeps, and every id checked against our own
catalogs. Names and chat stay text: everything that shows them escapes them. */
function mpCardOk(c){if(!c||typeof c!=='object'||Array.isArray(c))return null;
const n=(v,lo,hi)=>{v=+v;return Number.isFinite(v)?Math.min(hi,Math.max(lo,v)):0;},L=(v,ok,max)=>Array.isArray(v)?[...new Set(v.filter(ok))].slice(0,max):[];
return {day:Math.round(n(c.day,0,1e7)),tier:['t1','t2','t3'].includes(c.tier)?c.tier:'t3',t1:c.t1===true,lvl:Math.round(n(c.lvl,0,99)),pops:L(c.pops,isCity,500),
links:(Array.isArray(c.links)?c.links:[]).filter(l=>Array.isArray(l)&&isCity(l[0])&&isCity(l[1])&&l[0]!==l[1]).slice(0,300).map(l=>[l[0],l[1],n(l[2],0,1e7)]),
ix:L(c.ix,isIx,500),transit:L(c.transit,isNet,64),ppol:PPOL.includes(c.ppol)?c.ppol:'open',reach:n(c.reach,0,1),peak:n(c.peak,0,1e9),served:n(c.served,0,1e9),
cust:Math.round(n(c.cust,0,1e7)),rev:n(c.rev,-1e13,1e13),cashB:Math.round(n(c.cashB,-1,20)),score:n(c.score,0,1e15)};}
function mpRosterOk(j){if(!j||typeof j!=='object'||Array.isArray(j)||!Array.isArray(j.players))return null;
const txt=(v,max)=>typeof v==='string'?v.slice(0,max):'';
const players=j.players.filter(p=>p&&typeof p==='object'&&MP_PID.test(p.pid)).slice(0,12).map(p=>({pid:p.pid,name:txt(p.name,32),asn:int(p.asn,0,4294967294,0),
color:typeof p.color==='string'&&MP_COL.test(p.color)?p.color:'#888888',card:mpCardOk(p.card),seen:num(p.seen,0),joined:num(p.joined,0)}));
const feed=(Array.isArray(j.feed)?j.feed:[]).filter(f=>f&&typeof f==='object'&&MP_FEED.includes(f.k)).slice(-100).map(f=>({k:f.k,pid:MP_PID.test(f.pid)?f.pid:'',name:txt(f.name,32),at:num(f.at,0),text:f.k==='chat'?txt(f.text,200):''}));
return {code:MP_CODE.test(j.code)?j.code:'',title:txt(j.title,40),preset:NORMAL_PRESETS.includes(j.preset)?j.preset:'oncall',players,feed};}
// Tier 1 first, then Tier 2, then whoever serves the most traffic; players who never pushed a card last.
const mpTierN=c=>c?(c.t1?3:c.tier==='t2'?2:1):0;
function mpRank(ps){return ps.slice().sort((a,b)=>mpTierN(b.card)-mpTierN(a.card)||(b.card?b.card.served:0)-(a.card?a.card.served:0)||(b.card?b.card.peak:0)-(a.card?a.card.peak:0)||a.joined-b.joined);}
/* ---------- staying in step with the server ---------- */
function mpOk(roster){MP.fails=0;MP.wait=0;if(MP.told)MP.told=false;const r=mpRosterOk(roster);if(r)MP.roster=r;if(MP_API)mpHud();mpPanelUpdate();}
/* The server is away: back off (30 s, 1, 2, 4 min, at most 5), say so once, and keep playing. Too many pushes at once
(429: another one still on its way, or too often; 503 busy: too many uploads on the server right now) is not "away":
wait a little, quietly. The session panel's own refresh (poll) runs every few seconds while it is open: it may say
the server is away, but never stretches the wait. */
function mpFail(e,poll){const st=e&&e.status;
if((st===401||st===404)&&S&&S.mp){MP.gone=true;toast(tr('mp.not_in_session'),'bad',[{l:tr('mp.session'),act:'mpOpen',args:{}}]);return;}
if(st===429||st===503&&e.j&&e.j.busy===true){MP.wait=performance.now()+MP_GAP*2;return;}
if(!poll||!MP.fails){MP.fails++;MP.wait=performance.now()+Math.min(300000,MP_GAP*2**MP.fails);}
if(!MP.told){MP.told=true;toast(tr('mp.server_away'),'bad');}}
const mpHid=()=>MP.leaving||document.visibilityState==='hidden';
// What a save looks like, in a few characters (FNV-1a and the length): a page hidden on the same game day pushes only
// when something changed since the last push.
function mpSig(t){let h=0x811c9dc5;for(let i=0;i<t.length;i++){h^=t.charCodeAt(i);h=Math.imul(h,16777619);}return (h>>>0).toString(36)+'.'+t.length;}
// The request's size in bytes (UTF-8), which is what the keepalive limit counts.
function mpBytes(t){let n=t.length;for(let i=0;i<t.length;i++){const c=t.charCodeAt(i);if(c>127)n+=c>2047&&(c<0xd800||c>0xdfff)?2:1;}return n;}
/* Does this save go to the server too? 1: yes; 2: if it changed since the last push (the page is being hidden, or the
player asked, on the same game day); 0: no. A push goes on a new game day at most every MP_GAP; at once when the page
is hidden or closed, when the player chose to keep this save (MP.force) or asked for it (MP.now). Never mid-day or in
a puzzle: save() returns before then. */
function mpDue(){if(!mpIs()||MP.stale||MP.gone||S.lost)return 0;
const hid=mpHid(),now=performance.now();
// One push at a time, except when the page goes away: that one cuts the one on its way short (mpPush).
if(MP.busy&&!hid)return 0;
const ask=MP.now;MP.now=false;
if(MP.force&&(hid||now>=MP.wait))return 1;
if(S.day===MP.day)return hid||ask?2:0;
return hid||ask||(now-MP.last>=MP_GAP&&now>=MP.wait)?1:0;}
/* save()'s text for a network in a session, and its push when one is due. The number the server will keep it under is
picked before the text is made, so the save here and the one on the server carry the same: reopening this device
then knows the server has nothing newer. A push that fails leaves this one ahead, which the server accepts. */
function mpSave(st){let d=mpDue();if(d===1)S.mp.seq=(S.mp.seq||0)+1;let txt=JSON.stringify(packSave(st));
if(d===2){if(mpSig(txt)===MP.sig)d=0;else{S.mp.seq=(S.mp.seq||0)+1;txt=JSON.stringify(packSave(st));}}
if(d)mpPush(txt);return txt;}
/* Sends that save (it carries S.mp.seq), gzipped when big, with the card. When the page is being hidden or closed it
goes at once, as a keepalive request: the save when the request fits in one, else the card alone. */
function mpPush(txt){if(!mpIs()||MP.stale||MP.gone||S.lost)return;
const m=S.mp,day=S.day,seq=m.seq||0,hid=mpHid(),force=MP.force,me={cut:false,ac:null};let card;try{card=mpCard();}catch(e){card=undefined;}
// A push still on its way while the page goes away with a newer save: that one is cut short, this one goes.
if(MP.cur){MP.cur.cut=true;try{if(MP.cur.ac)MP.cur.ac.abort();}catch(e){}}
MP.cur=me;MP.busy=true;MP.last=performance.now();
const sig=mpSig(txt),body=data=>({seq,at:Date.now(),data,card,...(force?{force:true}:{})});
// Only a save that went counts as this day's push; a card alone does not.
const done=j=>{if(me.cut)return;if(j&&j.seq!==undefined&&S&&S.mp===m){m.seq=Math.max(m.seq||0,int(j.seq,0,1e15,seq));MP.day=day;MP.sig=sig;if(force)MP.force=false;}mpOk(j&&(j.roster||j));};
const bad=e=>{if(me.cut)return;if(e&&e.status===409&&S&&S.mp===m){MP.stale=true;MP.staleSeq=int(e.j&&e.j.seq,0,1e15,seq);mpStaleTell();}else mpFail(e);};
const fin=()=>{if(MP.cur===me){MP.cur=null;MP.busy=false;}};
const send=(p,b,keep)=>{if(me.cut)return;if(!keep&&typeof AbortController==='function')me.ac=new AbortController();
mpReq('PUT',mpPath(m,p),b,{auth:m,keep,ac:me.ac}).then(done,bad).finally(fin);};
if(hid){const b=txt.length<MP_KEEP?JSON.stringify(body(txt)):'';
if(b&&mpBytes(b)<MP_KEEP)send('/save',b,true);
else if(card&&mpBytes(JSON.stringify({card}))<MP_KEEP)send('/card',{card},true);else fin();
return;}
const go=data=>send('/save',body(data),false);
if(txt.length>=MP_GZ&&gzOk())gzip(txt).then(go,()=>go(txt));else go(txt);}
// The page is going away (pagehide comes before save()'s own handler, which then pushes as a keepalive request).
if(MP_API){addEventListener('pagehide',()=>{MP.leaving=true;});addEventListener('pageshow',()=>{MP.leaving=false;});}
function mpStaleTell(){toast(tr('mp.moved_on_elsewhere'),'bad',[{l:tr('mp.load_newer'),act:'mpNewer',args:{}},{l:tr('mp.keep_mine'),act:'mpKeep',args:{}}]);}
// Pushes this network's save now if it changed since the last push (before a link to another device is handed out).
function mpSyncNow(){if(!mpIs())return;MP.now=true;save(true);}
// The server's save text as a game state: unzipped, parsed, and only if it is this very network.
function mpUnpack(data){if(typeof data!=='string')return Promise.reject(new Error('no save'));
return (data.startsWith(GZ)?gunzip(data):Promise.resolve(data)).then(t=>JSON.parse(t));}
function mpSaveOk(s,m){if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links)||s.lost)return false;
if(!Object.keys(s.pops).every(isCity))return false;return !!(s.mp&&s.mp.code===m.code&&s.mp.pid===m.pid);}
/* Opening a network of a session: if another device played on and pushed a newer save, that one is loaded instead.
Nothing is pushed until the answer is in. */
function mpResume(){if(!mpIs())return;const m=S.mp;mpReset({day:S.day,last:performance.now(),busy:true});mpHud();
// A push of the page going away meanwhile is its own: only an answer to this question frees the next one.
const free=()=>{if(!MP.cur)MP.busy=false;};
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{free();if(S&&S.mp===m&&j&&int(j.seq,0,1e15,0)>(m.seq||0))mpAdopt(j,m);else mpRefresh();},
e=>{free();if(e&&e.status===404&&S&&S.mp===m)mpRefresh();else mpFail(e);});}
// A network of a session opened or started: nothing from another one carries over (a push still on its way is forgotten).
function mpReset(o){if(MP.cur)MP.cur.cut=true;Object.assign(MP,{roster:null,cur:null,busy:false,stale:false,staleSeq:0,gone:false,fails:0,wait:0,told:false,sig:'',force:false,now:false},o);}
function mpAdopt(j,m,n=0){if(!S||S.mp!==m)return;
// A day still routing in the worker finishes first.
if(RW.job){if(n<50)setTimeout(()=>mpAdopt(j,m,n+1),100);return;}
mpUnpack(j.data).then(s=>{if(!S||S.mp!==m||!mpSaveOk(s,m))throw new Error('not this network');delete s.sv;const nx=migrate(s);nx.mp.seq=int(j.seq,0,1e15,0);
S=nx;compute();UI.sel=null;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);Object.assign(MP,{stale:false,staleSeq:0,force:false,day:S.day,last:performance.now()});
renderAll();save(true);toast(tr('mp.loaded_newer',{name:esc(S.name),date:dateStr(S.day)}),'good');mpRefresh();})
.catch(e=>{console.error('[tubes] loading the session save failed',e);toast(tr('mp.save_unreadable'),'bad');});}
function mpRefresh(poll){if(!mpIs()||MP.gone)return Promise.resolve();const m=S.mp;return mpReq('GET',mpPath(m),undefined,{auth:m}).then(mpOk,e=>mpFail(e,poll));}
/* ---------- a link to the same network on another device ----------
<origin>/#mp=<CODE>.<pid>.<token>: the fragment never reaches a server. At boot (before the slots are picked) the save
is fetched into a new slot, or the one this browser already has for that network is opened (one open in another tab
too: slotBoot then offers to take it over), and the fragment is cleared. The link's token is stored only once the
server took it: a wrong or old link never replaces nor deletes the one this browser already has. */
const mpLink=m=>{const t=mpTok(m);return t?location.origin+location.pathname+'#mp='+m.code+'.'+m.pid+'.'+t:'';};
function mpBoot(go){const hash=String(location.hash||''),h=MP_API?/^#mp=([0-9A-Za-z-]{6,8})\.([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(hash):null;
if(!h){go();return;}
try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}
const code=mpNorm(h[1]),m={code,pid:h[2]},tok=h[3],fin=b=>{UI.mpBoot=b;go();};
if(!code){fin({bad:1});return;}
const had=mpTok(m),keep=()=>{if(had!==tok)mpTokSet(code,m.pid,tok);};
// The server is away (or busy): the link may be fine, so it stays in the address bar for a reload to try again.
const no=e=>{console.error('[tubes] moving the network here failed',e);const st=e&&e.status,away=st===0||st===429||st>=500;
if(away)try{history.replaceState(null,'',location.pathname+location.search+hash);}catch(x){}fin(away?{away:1}:{bad:1});};
const ex=slotIdx(true).find(e=>e.mp===code+'.'+m.pid&&!e.broken);
if(ex){const open=()=>{ssSet(SLOT_SS,ex.id);fin({code});};
// Opening it fetches the server's save when that one is newer. A link with another token is asked about first.
if(had===tok)open();else mpReq('GET',mpPath(m),undefined,{auth:m,tok}).then(()=>{keep();open();},no);return;}
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m,tok}).then(j=>mpUnpack(j&&j.data).then(s=>{if(!mpSaveOk(s,m))throw new Error('not this network');
delete s.sv;s.mp.seq=int(j.seq,0,1e15,0);const txt=JSON.stringify(s);return (txt.length>=GZ_MIN&&gzOk()?gzip(txt):Promise.resolve(txt)).then(data=>{
const id=slotRid();localStorage.setItem(SLOT_K+id,data);keep();
slotIdxPut(slotIdx(true).filter(x=>x.id!==id).concat([slotClean({id,...slotMeta(s,null),seq:1,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})]));ssSet(SLOT_SS,id);});}))
.then(()=>fin({code}),no);}
// Said once the game is on screen (or the title is).
function mpBootTell(){const b=UI.mpBoot;if(!b)return;UI.mpBoot=null;
if(b.bad)toast(tr('mp.link_bad'),'bad');else if(b.away)toast(tr('mp.err_offline'),'bad');
else if(S&&S.mp&&S.mp.code===b.code)toast(tr('mp.welcome_device',{name:esc(S.name),code:mpShow(b.code)}),'goal');}

View file

@ -17,17 +17,23 @@ const OPS=[
{k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_desc'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])},
// A model to standardize on: every POP on a smaller one is swapped to it, busiest first, within the budget.
model:{d:'next',ok:v=>v==='next'||(Number.isInteger(v)&&!!RG[v]),l:N_('ops.p_model'),f:v=>v==='next'?tr('ops.model_next'):RG[v].n}}},
// The build standard (96-pop-standard.js): its targets are set in their own sheet, so here it has only the budget.
{k:'std',i:'📐',pop:1,cap:250000,t:N_('ops.o_std'),d:N_('ops.o_std_d'),p:{}},
{k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}},
{k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}},
{k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>v?tr('common.on'):tr('common.off')}}},
{k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}},
{k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},pick:{d:'cheap',v:['cheap','big'],l:N_('ops.p_pick'),f:v=>tr({cheap:N_('ops.pick_cheap'),big:N_('ops.pick_big')}[v])}}},
// Line systems up to a bigger one, and optics swapped for bigger ones, on fiber that is full and runs hot, or every fiber up to
// a chosen line system. A line system swap is a day without that fiber: only where the traffic gets around it.
{k:'optup',i:'🔭',cap:250000,t:N_('ops.o_optup'),d:N_('ops.o_optup_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},
sys:{d:'next',v:['next','roadm','cl'],l:N_('ops.p_sys'),f:v=>v==='next'?tr('ops.sys_next'):DF_SYS[v].n},swap:{d:true,v:[true,false],l:N_('ops.p_swap'),f:v=>v?tr('common.on'):tr('common.off')}}},
{k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>v?tr('common.on'):tr('common.off')}}},
];
const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k);
const OPS_TPL=['bb','transit','ix','kit'];
// What the shift log can say. One line per day: "{name} did this, that and the other."
const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
const OPS_SAY={std:N_('ops.l_std'),transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),optup:N_('ops.l_optup'),optswap:N_('ops.l_optswap'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
// Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little.
const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')];
const OPS_FF_RATE={oncall:1/150,bgp:1/60};
@ -99,7 +105,7 @@ const opsPaid=e=>e.up||e.mo?' '+tr('ops.l_paid',{cost:fmt$(e.up||0),mo:opsMo$(e.
// What the network costs every month before traffic: what a job adds to the bill (ports, routers, rent, links, cache boxes).
// PNIs count from the day they are ordered, at the size they are going to be.
function opsMoNow(){let m=cachesMo();
for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo;}
for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo+(p.gen?GEN_MO:0)+(p.site2?SITE2_MO:0);}
for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0);
for(const t of S.transit)m+=transitMo(t,0);
for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);}
@ -133,6 +139,8 @@ const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a
const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);};
// The orders. Each takes the shift and does its jobs through the player's own actions.
const OPS_RUN={
// Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js).
std(X){bstdShift(X);},
repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');},
routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
@ -196,16 +204,46 @@ 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.
const fit=Object.keys(OPT).filter(o=>!chWhy(l,o)),cheap=fit.slice().sort((a,b)=>gpd(b,l)-gpd(a,l)),
o=fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break;
// A build standard that wants the fastest optics gets those first, so the two orders never undo each other.
fast=bstdFast()&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)),
o=fast||fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break;
const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break;
X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break;
cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}},
optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a));
for(const l of ls){
// The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot.
const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]<SYS_RANK[goal]?goal:null;
if(want&&ups<OPTUP_MAX&&tries<OPTUP_TRY){const to=sysNext(l),cost=sysUpCost(l);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=opsDarkOk(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(ok){const s0=l.sys,top=goal==='next'?to:goal;
for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]<SYS_RANK[top];k++){const nx=sysNext(l);
if(!techOk('sys',nx,DF_SYS[nx].lvl)||!X.can('optup',sysUpCost(l))||!X.pay('optup',()=>{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;}
// The fiber is dark until tomorrow: its optics wait.
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);continue;}}}}
// Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and
// the old optics go on the shelf as spares.
if(!swap)continue;
for(let step=0;step<8&&full(l)&&hot(l);step++){const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1;
const lit=Object.keys(cnt).sort((a,b)=>optG(a,l)-optG(b,l)),o1=lit[0];if(!o1)break;
const ports=(o,c)=>S.pops[c]?chPorts(o,c):0,room=(o2,c)=>!S.pops[c]||portsUsed(c)+ports(o2,c)-ports(o1,c)<=portsMax(c)+1e-9;
// Asked with one small channel already out: a full fiber refuses any optic.
const ch0=l.ch,i1=ch0.indexOf(o1);l.ch=ch0.filter((k,i)=>i!==i1);let o2;
try{o2=Object.keys(OPT).filter(o=>optG(o,l)>optG(o1,l)&&!chWhy(l,o)&&room(o,l.a)&&room(o,l.b)).sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0];}finally{l.ch=ch0;}if(!o2)break;
const n2=(cnt[o2]||0)+1,cost=opticCountCost(l,o2,n2);if(!X.can('optup',cost))break;
const was=dfCap(l);
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));}}},
caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
@ -222,21 +260,39 @@ const OPS_RUN={
for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}},
// Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102).
decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}
decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}
// Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go.
if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;}
for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue;
let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0);
const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)<capOf(big)&&!S.biz.some(b=>b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a));
// The spare is there for when the big link's trench is cut, so it has to live in another trench.
if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);}
for(const l of small.reverse()){if(cap-capOf(l)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}},
for(const ls of by.values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}},
};
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first.
function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once,
// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week
// (not saved: after a reload it is simply tested again).
const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,roadm:1,cl:2},SYS_TAG={roadm:'ROADM',cl:'C+L'};
// Another live path between the fiber's two cities, without it: a plain walk, no routing.
function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing
// is the yardstick (routed again first if this shift already changed the network); R is put back after.
function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){compute();X.dirty=false;}
const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{};
try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);}
finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}}
// The waves decom hands back on one city pair (ls: every link between them): the smaller ones the rest carry with 25% to
// spare, smallest first, less the spare it keeps. cf: each link's capacity (the build standard asks with the sizes its
// wave upgrades will give, so it never upgrades one that goes back).
function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||cf(l)>cf(a)?l:a,null),out=[];if(!big)return out;
let cap=live.reduce((a,l)=>a+cf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0);
const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&cf(l)<cf(big)&&!S.biz.some(b=>b.link===l.id)).sort((a,b)=>cf(b)-cf(a));
// The spare is there for when the big link's trench is cut, so it has to live in another trench.
if(opsP('decom','keep')&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);}
for(const l of small.reverse()){if(cap-cf(l)<load*1.25)break;if(!opsDecomSafe(l,out))continue;cap-=cf(l);out.push(l);}
return out;}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first.
function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}}
const OPS_ORDER=['repair','routers','transit','ports','optics','caches','ix','pni','decom'];
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l&&!gone.includes(x));try{return was.every(chk);}finally{S.links=all;}}
const OPS_ORDER=['repair','std','routers','transit','ports','optup','optics','caches','ix','pni','decom'];
// The shift: once per game day from dayTick, after outages and events have had their turn.
function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// A new week: last week's tally becomes the shift report, and the one NOC notice of the week.
@ -262,8 +318,9 @@ function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))retur
if(T.transit&&!scnRule('noTransit')){net=opsProv(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}}
// Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those.
// The standard routers go in first (#261), so they are in the price and the kit is priced for them.
const sq=popStdQuote();if(sq){cost+=sq.cost;parts.push(tr('ops.tpl_std'));}
S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:sq?sq.rt:1,gen:false,rgen:sq?sq.g:0};
// The standard's building and generator too, so the kit only prices what the standard leaves out: nothing twice.
const sq=popStdQuote();if(sq){cost+=sq.cost;parts.push(sq.site2||sq.gen?tr('ops.tpl_bstd'):tr('ops.tpl_std'));}
S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:sq?sq.rt:1,gen:!!(sq&&sq.gen),rgen:sq?sq.g:0,...(sq&&sq.site2?{site2:true}:{})};
try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));}
if(T.kit){kit=utilityKit(c);if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}}}finally{delete S.pops[c];}
return {cost,net:net&&net.id,ix,kit:!!(kit&&kit.cost),parts};}

View file

@ -1,16 +1,210 @@
/* ---------- The standard POP (#240) ----------
Big networks run one design everywhere. A new POP gets the standard routers at once, while the box is still idle
(no maintenance window): the model if it is unlocked and affordable, then the extra routers as cash allows. */
/* ---------- The build standard (#240, grown into a target state for every POP, port and fiber) ----------
Big networks run one design everywhere. The standard says what every POP, port and fiber should have: the router
model and count, a second building and a generator, LAGs, an exchange port, PNIs spread over cities, the line
system, the optics and the waves. A new POP gets its POP part at once, while the box is still idle (no maintenance
window). The rest is brought up by the intern's "Keep to the build standard" order, or in one tap from the sheet. */
// Every target, with the values its list offers ("keep" first: no target) and its default. Saved sparse: a target left
// at its default is not in the save, so an old {g, rt} standard is exactly the routers it always was.
const BSTD=[
{k:'g',grp:'pop',l:N_('bstd.l_model'),d:'keep',v:()=>['keep',...RG.map((r,i)=>i).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cap-RG[b].cap||a-b)],ok:v=>v==='keep'||(Number.isInteger(v)&&!!RG[v])},
{k:'rt',grp:'pop',l:N_('common.routers'),d:1,v:()=>[1,2,3,4,6,8,12,16],ok:v=>Number.isInteger(v)&&v>=1&&v<=RMAX},
{k:'site2',grp:'pop',l:N_('bstd.l_site2'),d:false,v:()=>[false,true]},
{k:'gen',grp:'pop',l:N_('common.backup_generator'),d:false,v:()=>[false,true]},
{k:'lag',grp:'port',l:N_('bstd.l_lag'),d:1,v:()=>[1,2,4]},
{k:'split',grp:'port',l:N_('bstd.l_split'),d:false,v:()=>[false,true]},
{k:'ix',grp:'port',l:N_('bstd.l_ix'),d:false,v:()=>[false,true]},
{k:'pni',grp:'port',l:N_('bstd.l_pni'),d:0,v:()=>[0,2,3]},
{k:'sys',grp:'fiber',l:N_('common.line_system'),d:'keep',v:()=>['keep','roadm','cl']},
{k:'opt',grp:'fiber',l:N_('common.optics'),d:'keep',v:()=>['keep','fast']},
{k:'wv',grp:'fiber',l:N_('common.waves'),d:'keep',v:()=>['keep',...LT.map((x,i)=>i).filter(i=>i>0&&waveShown(i))],ok:v=>v==='keep'||(Number.isInteger(v)&&v>0&&!!LT[v])},
];
const BSTDK=Object.fromEntries(BSTD.map(x=>[x.k,x])),BSTD_MAX=16,BSTD_SYS={lite:0,roadm:1,cl:2};
const bstdOk=(x,v)=>x.ok?x.ok(v):x.v().includes(v);
// The whole standard, every target filled in. d: a saved one (untrusted: anything odd reads as "keep").
function bstd(d=S&&S.popStd){const o={},ob=d&&typeof d==='object'&&!Array.isArray(d)?d:{};
for(const x of BSTD){const v=ob[x.k];o[x.k]=x.k==='rt'?(own(ob,'rt')?int(v,1,RMAX,1):1):own(ob,x.k)&&bstdOk(x,v)?v:x.d;}return o;}
// Back to the saved form: the model and router count, and any other target that is not "keep". Nothing set: null.
function bstdPut(o){const d={};for(const x of BSTD)if(x.k==='rt'||o[x.k]!==x.d)d[x.k]=o[x.k];return Object.keys(d).length>1||d.rt>1?d:null;}
function popStdSanitize(s){s.popStd=s.popStd&&typeof s.popStd==='object'&&!Array.isArray(s.popStd)?bstdPut(bstd(s.popStd)):null;}
// A bank that forbids generators (Stormy Weather's covenant): the standard never installs one while that loan runs.
const bstdNoGen=()=>(S.loans||[]).some(l=>(l.covs||[]).includes('nogen'));
// The model a POP should get: the standard's if you can buy it, else the best main-line model that is unlocked and no
// bigger. Never a step down, never one that does not fit, and never one that would drop a POP out of the backbone core.
// c: an existing POP, or null for a new, empty one. -1: nothing to do. A vendor's demo unit (at its markup) only ever
// goes into a new POP, as before: swapping every POP onto one is the player's call, not the intern's. A new POP takes the
// model as chosen, even one smaller than the basic router (the Mikrowtik CCR has more ports): nothing is replaced there.
function bstdModel(g,c){if(g==='keep'||!RG[g])return -1;const p=c&&S.pops[c],cur=p?p.rgen||0:0,core=!!p&&coreRun()>0&&inCore(c);
const ok=i=>i>=0&&RG[i].cap<=RG[g].cap&&(!p||(RG[i].cap>RG[cur].cap&&!modelFits(c,i)&&(!core||rgCore(i,coreRun()))));
if((p?rgOpen(g):techOk('rg',g,RG[g].lvl))&&ok(g))return g;let b=-1;
for(let k=0;k<=4;k++){const i=mainRG(k);if(i!==g&&rgOpen(i)&&ok(i)&&(b<0||RG[i].cap>RG[b].cap))b=i;}return b;}
// What the standard adds to a fresh POP, priced the way popStdApply pays for it, so it can be on the button (#261).
function popStdQuote(){const d=S.popStd;if(!d||pzOn())return null;const g=techOk('rg',d.g,RG[d.g].lvl)?d.g:0;
let cost=g?Math.max(0,Math.round(RG[g].cost*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(0,1)):0;for(let n=1;n<d.rt;n++)cost+=routerCost(g,n);
const mo=(d.rt-1)*ROUTER_MO+cageMo(d.rt)+d.rt*RG[g].mo-RG[0].mo;return cost||mo?{cost,mo,g,rt:d.rt}:null;}
// A new POP's setup with the standard's routers, for every way a POP gets built (links, cables, seats).
function popStdQuote(){if(!S||!S.popStd||pzOn())return null;const D=bstd(),m=bstdModel(D.g,null),g=m>0?m:0,rt=D.rt;
let cost=g?swapCostOf(g,0,1):0;for(let n=1;n<rt;n++)cost+=routerCost(g,n);
let mo=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[g].mo-RG[0].mo;const site2=D.site2,gen=D.gen&&!bstdNoGen();
if(site2){cost+=SITE2_COST;mo+=SITE2_MO;}if(gen){cost+=GEN_COST;mo+=GEN_MO;}
return cost||mo?{cost,mo,g,rt,site2,gen}:null;}
// A new POP's setup with the standard, for every way a POP gets built (links, cables, seats).
function newPopCost(c){const q=popStdQuote();return popCost(c)+(q?q.cost:0);}
function popStdApply(city){const d=S.popStd,p=S.pops[city];if(!d||!p||pzOn())return;let miss=false;const c0=S.cash;
if(d.g!==(p.rgen||0)){if(techOk('rg',d.g,RG[d.g].lvl)&&S.cash>=swapCost(city,d.g)){spend(swapCost(city,d.g));p.rgen=d.g;}else miss=true;}
while((p.routers||1)<d.rt){const k=routerCost(p.rgen||0,p.routers||1);if(S.cash<k){miss=true;break;}spend(k);p.routers=(p.routers||1)+1;}
function popStdApply(city){const p=S.pops[city];if(!S.popStd||!p||pzOn())return;const D=bstd(),m=bstdModel(D.g,null),c0=S.cash;
// Short of the model asked for (it is locked): the best that is unlocked goes in, and the toast says so.
let miss=D.g!=='keep'&&RG[m>0?m:0].cap<RG[D.g].cap;
if(m>0&&m!==(p.rgen||0)){if(S.cash>=swapCost(city,m)){spend(swapCost(city,m));p.rgen=m;}else miss=true;}
while((p.routers||1)<D.rt){const k=routerCost(p.rgen||0,p.routers||1);if(S.cash<k){miss=true;break;}spend(k);p.routers=(p.routers||1)+1;}
if(D.site2&&!p.site2){if(S.cash>=SITE2_COST){spend(SITE2_COST);p.site2=true;p.site2Day=S.day;}else miss=true;}
if(D.gen&&!p.gen&&!bstdNoGen()){if(S.cash>=GEN_COST){spend(GEN_COST);p.gen=true;}else miss=true;}
if(c0===S.cash&&!miss)return;
toast(miss?tr('pop_std.not_all_of_the_standard',{city:CITY[city].name}):tr('pop_std.city_gets_the_standard_cost',{city:CITY[city].name,n:p.routers||1,model:esc(RG[p.rgen||0].n),cost:fmt$(c0-S.cash)}),miss?'bad':'good');}
// The line in a POP's router section: the standard, and a button to make this POP's routers the standard.
function popStdHtml(c){const p=S.pops[c];if(!p||pzOn())return '';const d=S.popStd,same=d&&d.g===(p.rgen||0)&&d.rt===(p.routers||1);
return `<div class="kv"><span>${tr('pop_std.standard_for_new_pops')}</span><b>${d?`${d.rt} × ${esc(RG[d.g].n)}`:tr('pop_std.none')}</b></div><div class="btns">${same?'':btn(tr('pop_std.make_this_the_standard'),'popStdSet',{city:c},'ghost sm')}${d?btn(tr('pop_std.clear'),'popStdClear',{},'ghost sm'):''}</div>`;}
// The line in a POP's router section: the standard, a button to edit it, and one to make this POP's build the standard.
function popStdHtml(c){const p=S.pops[c];if(!p||pzOn())return '';const D=bstd(),on=!!S.popStd,mine=bstd(bstdPut({...D,g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen})),
same=on&&BSTD.every(x=>D[x.k]===mine[x.k]);
return `<div class="kv"><span>${tr('bstd.title')}</span><b>${on?esc(bstdLine(D)):tr('pop_std.none')}</b></div><div class="btns">${btn(tr('bstd.edit'),'bstdOpen',{},'sm')}${same?'':btn(tr('pop_std.make_this_the_standard'),'popStdSet',{city:c},'ghost sm')}${on?btn(tr('pop_std.clear'),'popStdClear',{},'ghost sm'):''}</div>`;}
// "2 × Absolute Unit 3.2T, second building, generator": the POP part, what a new POP gets.
function bstdPopParts(D){const a=[];if(D.g!=='keep'||D.rt>1)a.push(`${D.rt} × ${D.g==='keep'?tr('bstd.any_model'):RG[D.g].n}`);if(D.site2)a.push(tr('bstd.second_building'));if(D.gen)a.push(tr('bstd.generator'));return a;}
// The POP part first, then how many other targets.
function bstdLine(D){const a=bstdPopParts(D),n=['lag','split','ix','pni','sys','opt','wv'].filter(k=>D[k]!==BSTDK[k].d).length;if(n)a.push(trn('bstd.n_more_targets',n));return a.join(', ')||tr('pop_std.none');}
/* What the standard still asks for, as jobs in the order they get done: POPs busiest first, then ports hottest first,
then fiber and waves hottest first. Pure: it reads S and R and changes nothing. Each job is priced with the game's
own helpers on a running copy of the few numbers earlier jobs change (routers, spares), so the sum is what the clicks
cost. Jobs that build on each other form a chain (ch: a POP's routers, a port, a fiber): when one cannot be done, the
rest of that chain waits. A job that needs another chain's work first (optics only the new router model takes, a split
that needs the second building) names that job in dep and waits for it too. Whether a fiber may go dark is settled
here, not on the way, so the plan is what the button does and its sum is the quote.
intern: only where the intern may work (per-POP exceptions). J.held: fibers whose line system has to wait. */
function bstdPlan(intern){const J=[];J.held=[];if(!S||!S.popStd||pzOn())return J;const D=bstd(),here=c=>!intern||opsHere('std',c);
const load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
const cs=Object.keys(S.pops).filter(here),ld={};for(const c of cs)ld[c]=load(c);cs.sort((a,b)=>ld[b]-ld[a]||(a<b?-1:1));
// Router ports: what the POP will have once its own jobs are done, less what pending PNI augments will take.
const V={},rmn={},resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0);
const room=c=>rmn[c]??(rmn[c]=(V[c]?portsMax(c,V[c].g,V[c].rt)-portsUsed(c,V[c].g):portsMax(c)-portsUsed(c))-resv(c)+1e-9);
const take=(c,n,dry)=>{if(n<=0)return true;if(room(c)<n)return false;if(!dry)rmn[c]-=n;return true;};
const job=(grp,k,ch,w,cost,mo,go,x)=>{const j={grp,k,ch,w,cost,mo,go,...x};J.push(j);return j;};
for(const c of cs){const p=S.pops[c],ch='p:'+c;let g=p.rgen||0,rt=p.routers||1,sw=null,s2=null;
const add=()=>{const g0=g,r0=rt;job('pop','rt',ch,c+' +1',routerCost(g0,r0),routerMo(g0)+cageMo(r0+1)-cageMo(r0),()=>{const n=S.pops[c].routers||1;ACT.addRouter({city:c});return (S.pops[c].routers||1)>n;},{c});rt++;};
const m=p.rupDay===S.day?-1:bstdModel(D.g,c);
if(m>=0){
// One router carrying traffic: a second goes in first, so the swap rolls through with no maintenance window.
if(rt===1&&!popIdle(c))add();
const old=g,r=rt;sw=job('pop','g',ch,c+' ⇧'+RG[m].pn,swapCostOf(m,old,r),r*(RG[m].mo-RG[old].mo),()=>{ACT.upRouter({city:c,g:m});return (S.pops[c].rgen||0)===m;},{c});g=m;}
while(rt<D.rt&&rt<RMAX)add();
// A building and a generator do not wait for the routers, nor for each other.
if(D.site2&&!p.site2)s2=job('pop','site2','s:'+c,c,SITE2_COST,SITE2_MO,()=>{ACT.addSite({city:c});return !!S.pops[c].site2;},{c});
if(D.gen&&!p.gen&&!bstdNoGen())job('pop','gen','e:'+c,c,GEN_COST,GEN_MO,()=>{if(bstdNoGen())return false;ACT.addGen({city:c});return !!S.pops[c].gen;},{c});
V[c]={g,rt,site2:!!p.site2||D.site2,sw,s2};}
// Ports: LAG members up to the standard, then the members split over both buildings.
if(D.lag>1||D.split){const P=[];
for(const t of S.transit)if(S.pops[t.city]&&here(t.city))P.push({k:'t',c:t.city,id:t.id,o:t,n:t.n||1,tier:t.tier,u:(R.useT[t.id]||0)/lagCap(PORT[t.tier].g,t.n)});
for(const x of S.pni)if(S.pops[x.city]&&here(x.city)&&pniOn(x)&&!x.up)P.push({k:'p',c:x.city,id:x.id,o:x,n:x.n||1,tier:x.tier,u:(R.usePni[x.id]||0)/lagCap(pniG(x),x.n)});
for(const x in S.ixp){const c=ixCity(x);if(!S.myIx[x]&&S.pops[c]&&here(c))P.push({k:'ix',c,id:x,n:(S.ixn||{})[x]||1,tier:S.ixp[x],u:(R.useIx[x]||0)/Math.max(1e-9,lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x]))});}
P.sort((a,b)=>b.u-a.u||(a.id<b.id?-1:1));
for(const o of P)bstdPort(o,D,V[o.c],take,job);}
// An exchange port at every POP in a city with an exchange (not DE-KICKS: they want a sales call first).
if(D.ix)for(const c of cs){if(hasIxAt(c))continue;const x=ixIdsIn(c).find(x=>!isDk(x)&&!S.myIx[x]&&!!ixName(x)&&S.ixp[x]===undefined);if(!x||!take(c,PORT_SLOT(0)))continue;
const ch='i:'+x,pm=ixPortMo(x,0);job('port','ix',ch,x+' +'+PORT[0].n,pm,pm,()=>{ACT.buyIx({city:x,tier:0});return S.ixp[x]!==undefined;},{c});
bstdPort({k:'ix',c,id:x,n:1,tier:0,fresh:true},D,V[c],take,job);}
// PNIs spread out: every network you have a PNI with gets one in at least that many cities, where one is worth it.
if(D.pni){const by={};for(const p of S.pni)(by[p.net]||(by[p.net]=new Set())).add(p.city);
for(const net of Object.keys(by).sort()){let k=D.pni-by[net].size;if(k<=0||!isNet(net))continue;
const opts=NET[net].pops.filter(c=>S.pops[c]&&here(c)&&!by[net].has(c)).map(c=>({c,v:pniVal(net,c)})).filter(o=>o.v.worth).sort((a,b)=>b.v.want-a.v.want||(a.c<b.c?-1:1));
for(const {c,v} of opts){if(k<=0)break;let q=null;for(let t=Math.max(v.tier,pniMin(net));t>=pniMin(net)&&!q;t--){const x=pniQuote(c,net,t,resv(c));if(x&&!x.why)q=x;}
if(!q||!take(c,q.slots))continue;const tier=q.tier;k--;
job('port','pni','n:'+net+'@'+c,c+' '+net,q.cost,pniMo({net,tier,n:1},0),()=>{const x=pniQuote(c,net,tier,resv(c));if(!x||x.why||!spend(x.cost))return false;pniPlace(x);return true;},{c});}}}
// Fiber and waves, hottest first. A POP excepted from the order keeps its links as they are too.
if(D.sys!=='keep'||D.opt!=='keep'||D.wv!=='keep'){const sp={...(S.spares||{})},dk=new Map(),wv=new Map();
const ls=S.links.filter(l=>(l.kind==='df'||l.kind==='wave')&&here(l.a)&&here(l.b)&&S.pops[l.a]&&S.pops[l.b]).map(l=>({l,u:(R.load[l.id]||0)/Math.max(1e-9,capOf(l))})).sort((a,b)=>b.u-a.u||(a.l.id<b.l.id?-1:1));
// Waves: the size each goes up to. The decom order hands back the smaller waves a pair no longer needs, judged with
// the sizes these upgrades give: never pay a month's rent on one it is about to return.
if(D.wv!=='keep'){for(const {l} of ls)if(l.kind==='wave'&&l.tier<D.wv)for(let t=D.wv;t>l.tier;t--){if(subWaveWhy(t,l.km,l.sub)||soldOut(l.a,l.b,t,l.cable)||!waveOk(l.a,l.b,t))continue;wv.set(l,t);break;}
if(wv.size&&opsHired()&&S.ops.on.decom){const by=new Map(),cf=x=>wv.has(x)?capOf(x)*LT[wv.get(x)].g/LT[x.tier].g:capOf(x);
for(const x of S.links)if(x.kind!=='vxc'&&x.kind!=='sat'){const k=edgeKey(x);(by.get(k)||by.set(k,[]).get(k)).push(x);}
for(const k of new Set([...wv.keys()].map(edgeKey)))for(const x of opsDecomPick(by.get(k),cf))wv.delete(x);}}
for(const {l} of ls){const ch='l:'+l.id;
if(l.kind==='wave'){const t=wv.get(l);if(t){const nm=Math.round(waveMo(l.km,l.sub,t)*(l.mult||1));job('fiber','wv',ch,l.a+'|'+l.b,nm,nm-(l.mo||0),()=>{ACT.upLink({id:l.id,tier:t});return l.tier===t;},{l});}continue;}
if(l.eqDown>S.day)continue;
let sys=l.sys;const lit=l.ready<=S.day,nx=D.sys!=='keep'&&BSTD_SYS[sys]<BSTD_SYS[D.sys]&&sysNext({sys});
// A lit fiber goes dark for a day. Busy with nothing parallel to carry it: it keeps its line system for now, and
// gets the best optics that one takes. A parallel fiber goes dark first in this plan: it waits for next time.
if(nx&&techOk('sys',nx,DF_SYS[nx].lvl)){
if(lit&&!bstdDarkOk(l))J.held.push(l);
else if(lit&&!bstdDarkOk(l,dk)){J.held.push(l);continue;}
else{const busy=lit&&bstdBusy(l);
while(BSTD_SYS[sys]<BSTD_SYS[D.sys]){const to=sysNext({sys});if(!to||!techOk('sys',to,DF_SYS[to].lvl))break;
const s0=sys;job('fiber','sys',ch,l.a+'|'+l.b,sysCost(to)*(to==='cl'&&l.own?Math.max(1,l.pairs|0):1),0,()=>{if(l.sys!==s0)return false;ACT.upSys({id:l.id});return l.sys===to;},{l,dark:lit,busy});sys=to;}
if(lit)dk.set(l.id,busy);}}
// Optics for the line system the fiber will have.
if(D.opt==='fast'&&lit&&(l.ch||[]).length)J.push(...bstdOptJobs(l,sys,sp,V,take,ch));}}
return J;}
// One port's LAG members up to the standard, then split over both buildings. A PNI's new member is an augment that
// lands later; it remembers to split when it does. o.fresh: a port the plan is buying (the IX job before it).
function bstdPort(o,D,v,take,job){const {k,c,id}=o,ch=(o.fresh?'i:':'x:'+k+':')+id;let n=o.n;
const site2=v?v.site2:!!(S.pops[c]&&S.pops[c].site2),split=D.split&&site2,
// A second building still to buy is a job of its own: the split waits for it, or it would be tried every shift.
sx={c,...(v&&v.s2&&!S.pops[c].site2?{dep:[v.s2]}:{})};
if(k==='p'){const x=o.o;
if(n<D.lag&&n<LAG_MAX&&!msfNope(x.net,c)&&take(c,PORT_SLOT(x.tier))){const n0=n,mo=x.g1?Math.round(PORT[0].pni/2):PORT[x.tier].pni;
job('port','lag',ch,c+' +1×'+pniPN(x),1500+PORT[x.tier].setup/2,mo,()=>{if((x.n||1)!==n0||x.up)return false;ACT.lagP({id,d:1});return !!x.up||(x.n||1)>n0;},{c});n++;}
if(split&&n>=2&&x.site!=='ab')job('port','split',ch,c,0,0,()=>{if(!S.pops[c].site2)return false;if(x.up){if(x.up.n<2)return false;x.up.site='ab';return true;}
if((x.n||1)<2)return false;ACT.siteSet({k:'p',id,s:'ab'});return x.site==='ab';},sx);
return;}
const t=k==='t'?o.o:null,tier=o.tier,each=k==='t'?PORT[tier].setup:ixPortMo(id,tier);
while(n<D.lag&&n<LAG_MAX&&(k!=='t'||portOk(c,tier))&&take(c,PORT_SLOT(tier))){const n0=n,mo=k==='t'?transitMo({...t,n:n0+1},0)-transitMo({...t,n:n0},0):each;
job('port','lag',ch,(k==='t'?c:id)+' +1×'+PORT[tier].n,each,mo,k==='t'?()=>{if((t.n||1)!==n0)return false;ACT.lagT({id,d:1});return (t.n||1)>n0;}
:()=>{const m=(S.ixn||{})[id]||1;if(m!==n0)return false;ACT.lagIx({city:id,d:1});return ((S.ixn||{})[id]||1)>m;},{c});n++;}
const cur=k==='t'?t.site:(S.ixSite||{})[id];
if(split&&n>=2&&cur!=='ab')job('port','split',ch,k==='t'?c:id,0,0,()=>{if(!S.pops[c].site2)return false;
if(k==='t'){if((t.n||1)<2)return false;ACT.siteSet({k:'t',id,s:'ab'});return t.site==='ab';}
if(((S.ixn||{})[id]||1)<2)return false;ACT.siteSet({k:'ix',id,s:'ab'});return (S.ixSite||{})[id]==='ab';},sx);}
// Can it see the fastest optic that reaches, ignoring the free-slot check (a swap frees its own slot first)? rg: each
// end's router model once the plan's swaps are in, so the optics a new model takes are part of the plan.
const bstdOptFits=(l,o,sys,rg)=>{const O=OPT[o];return techOk('opt',o,O.lvl)&&(O.sys!=='roadm'||isRdm(sys))&&!!optMode(o,l)&&[l.a,l.b].every(c=>!S.pops[c]||RG[rg(c)].cls>=O.rg);};
const bstdCnt=(l,o)=>(l.ch||[]).filter(k=>k===o).length;
// Swap a fiber's slower optics for the fastest that reaches on it, one job per kind, slowest first: the old ones go on
// the spares shelf (setChCount), the new ones come from the shelf first. sp: spares as earlier jobs leave them.
function bstdOptJobs(l,sys,sp,V,take,ch){const rg=c=>V[c]?V[c].g:(S.pops[c].rgen||0),fits=Object.keys(OPT).filter(o=>bstdOptFits(l,o,sys,rg));if(!fits.length)return [];
const best=fits.sort((a,b)=>optG(b,l)-optG(a,l)||optCost(a)-optCost(b))[0],bg=optG(best,l),g=c=>V[c]?V[c].g:undefined,out=[];
// Optics only the new router model takes wait for its swap: until it is in, nothing is pulled.
const low=c=>!!S.pops[c]&&RG[S.pops[c].rgen||0].cls<OPT[best].rg,dep=[l.a,l.b].filter(low).map(c=>V[c]&&V[c].sw).filter(Boolean);
for(const o0 of [...new Set(l.ch||[])].filter(o=>OPT[o]&&optG(o,l)<bg).sort((a,b)=>optG(a,l)-optG(b,l)||(a<b?-1:1))){
// A faster optic can take more router ports than the one it replaces: as many as both ends have room for.
const per=c=>Math.max(0,chPorts(best,c,g(c))-chPorts(o0,c,g(c)));let k=bstdCnt(l,o0);
while(k>0&&!(take(l.a,per(l.a)*k,true)&&take(l.b,per(l.b)*k,true)))k--;if(!k)continue;take(l.a,per(l.a)*k);take(l.b,per(l.b)*k);
const r=REGEN_CH*(l.regen|0),c=optCost(best),s=Math.max(0,Math.min(k,sp[best]|0)),cost=s*Math.round(c*r)+(k-s)*Math.round(c*(1+r));
sp[best]=(sp[best]|0)-s;sp[o0]=(sp[o0]|0)+k;
// price: what it costs when it runs. The plan's price counts on the shelf as the jobs before it leave it; one of those
// refused (budget, cash) leaves the shelf emptier, and the budget and the floor must see the real bill.
out.push({grp:'fiber',k:'opt',ch,w:l.a+'|'+l.b,cost,mo:0,l,...(dep.length?{dep}:{}),price:()=>opticCountCost(l,best,bstdCnt(l,best)+k),
go:()=>{const n0=bstdCnt(l,o0),h0=bstdCnt(l,best);if(n0<k||[l.a,l.b].some(low))return false;
ACT.setChCount({id:l.id,o:o0,n:n0-k});if(bstdCnt(l,o0)!==n0-k)return false;ACT.setChCount({id:l.id,o:best,n:h0+k});if(bstdCnt(l,best)===h0+k)return true;
// The new ones could not go in (ports, cash): the old optics go back in from the shelf.
(l.ch=l.ch||[]).push(...Array(k).fill(o0));S.spares[o0]-=k;return false;}});}
return out;}
// A line-system swap darkens the fiber for a day: only while it carries little, or its parallel links can take its load.
// 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);
// 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
// work stays bounded whatever goes wrong. Returns what was done.
function bstdDo(J,can,pay,one,max=1e9){const stop=new Set(),done=new Set(),dark=new Map();let n=0;
for(const j of J){if(n>=max)break;if(stop.has(j.ch))continue;if(j.dep&&!j.dep.every(d=>done.has(d))){stop.add(j.ch);continue;}
if(j.dark&&!dark.has(j.l.id)&&((one&&dark.size)||!bstdDarkOk(j.l,dark))){stop.add(j.ch);continue;}
if(!can(j)){stop.add(j.ch);continue;}n++;
if(!pay(j)){stop.add(j.ch);continue;}
if(j.dark)dark.set(j.l.id,!!j.busy);done.add(j);}
return [...done];}
// What a job costs as it runs (an optics swap is priced again then: see bstdOptJobs).
const bstdPrice=j=>j.price?j.price():j.cost;
// The sheet's summary and the MCP quote: how much is below the standard, and what bringing it all up costs. The plan is
// what the button does, so its sum is the bill. held: the fibers whose line system waits ("fra|ams"); they are below it.
function bstdQuote(intern){const J=bstdPlan(intern),P=new Set(),Q=new Set(),L=new Set(J.held.map(l=>l.id));let cost=0,mo=0;
for(const j of J){cost+=j.cost;mo+=j.mo;if(j.grp==='pop')P.add(j.c);else if(j.grp==='port')Q.add(j.ch);else L.add(j.l.id);}
return {cost:Math.round(cost),mo:Math.round(mo),pops:P.size,ports:Q.size,links:L.size,n:J.length,held:J.held.map(l=>l.a+'|'+l.b)};}
// The optics order lights the standard's fastest optics while this order keeps to a standard that wants them.
const bstdFast=()=>!!(S.popStd&&opsHired()&&S.ops.on.std&&bstd().opt==='fast');
// The intern's shift: the same plan, every job through the budget and the cash floor at what it costs then, a few at a time.
function bstdShift(X){bstdDo(bstdPlan(true),j=>X.can('std',bstdPrice(j),j.mo),j=>X.pay('std',()=>j.go())&&(X.did('std',j.w),true),true,BSTD_MAX);}

View file

@ -61,7 +61,7 @@ function pieEximOffer(d){const P=S.pie,G=P.gov;if(!P.fac||pieEximLoan()||!pieCan
// Taking it: a loan like any other, plus its space covenants.
function pieEximTake(){const P=S.pie,o=P.gov.ex;if(!o||pieEximLoan())return false;const pay=Math.round(annuity(o.amt,o.apr,o.term));
S.cash+=o.amt;S.stats.loans=(S.stats.loans||0)+1;
S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(x=>x.sub).length},
S.loans.push({id:uid(),bank:'exim',start:S.day,amount:o.amt,got:o.amt,bal:o.amt,apr:o.apr,apr0:o.apr,pay,left:o.term,term:o.term,share:0,covs:['pielaunch','piedish'],base:{sub:S.links.filter(seaLink).length},
pie:{cc:o.cc,n:o.n,by:S.day+PIE_EXIM_BY,flown:0,br:0}});
P.gov.ex=null;track('loan_taken');return true;}
// A breach (loanTick(), after the bank's own penalty): tighter terms, the launch target rescheduled, and a spat.

View file

@ -16,4 +16,4 @@ function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n)
// The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices.
function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};}
// The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape.
function walkP(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni,dead:0,ms:-1,fg:0};}
function walkP(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni,dead:0,ms:-1,fg:0,mt:0,se:null};}

View file

@ -29,12 +29,14 @@ function compute(){RW.gen++;
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
const edges={},EA=[],TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={};
const edges={},EA=[],TRX=teRules(),live=[];let NE=0,SE=null;R2.bizDem={};R2.bizSrv={};
for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
// The metric belongs to the city pair (a preset or a custom one); links on standby add capacity that fills only after the others (#122).
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,scap:0,w:Infinity,lat:Infinity,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,jk:0,f:TRX&&TRX.avoid.has(key)?60:1};EA.push(e);adj[ai].push([bi,e]);adj[bi].push([ai,e]);}
const c=capOf(l),lt=linkLat(l);e.cap+=c;e.links.push(l);e.w=Math.min(e.w,pairW(key,l.km)*e.f);if(l.standby){e.scap+=c;e.slat=Math.min(e.slat,lt);}else e.lat=Math.min(e.lat,lt);}
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,scap:0,w:Infinity,lat:Infinity,slat:Infinity,links:[],res:0,ld:0,tr:null,pl:0,jk:0,f:TRX&&TRX.avoid.has(key)?60:1,sx:0,sv:null,sa:null};EA.push(e);adj[ai].push([bi,e]);adj[bi].push([ai,e]);}
const c=capOf(l),lt=linkLat(l);e.cap+=c;e.links.push(l);e.w=Math.min(e.w,pairW(key,l.km)*e.f);if(l.standby){e.scap+=c;e.slat=Math.min(e.slat,lt);}else e.lat=Math.min(e.lat,lt);if(l.kind==='sat'&&!e.sv){e.sv=[];(SE||(SE=[])).push(e);}}
for(const k in edges){const e=edges[k];if(e.lat===Infinity)e.lat=e.slat;}
// The edges a satellite circuit is on (45-teleports.js): users notice the share of their traffic it carries, whatever the exit.
const SATN=SE?satEdges(SE):0;
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by;
// ALONE and the islands (COMP). Kept between calls while the graph is the same (29-route-cache.js).
const wW=e=>e.w,wLat=e=>e.lat+0.05,RCON=RC.on,GK=RCON?rcGraphKey(pops,remote,EA):null,
@ -140,11 +142,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<q.length;){const u=q[h++];if(u===b)break;for(const [v,l] of LA[u]||[])if(!seen[v]&&!(skip&&skip.has(srlg(l)))){seen[v]=1;prev[v]=l;q.push(v);}}
for(let h=0;h<q.length;){const u=q[h++];if(u===b)break;for(const [v,l] of LA[u]||[])if(!seen[v]&&!(skip&&hitR(skip,l))){seen[v]=1;prev[v]=l;q.push(v);}}
if(!seen[b])return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=CIDX[l.a]===v?CIDX[l.b]:CIDX[l.a];}return path;};
const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));};
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);
@ -244,8 +247,11 @@ function compute(){RW.gen++;
// Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then
// it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays,
// Korean users notice any exit far away, transit or not, and much sooner.
if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms<0){ms=0;for(let k=0;k<PN;k++)ms+=path[k].lat;P.ms=ms;}const rtt=2*ms,kl=snd&&CITIES[ci].kr;
if(rtt>(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok;
// Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose
// on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt).
if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){if(P.ms<0){let ms=0,mt=0,se=null;for(let k=0;k<PN;k++){const x=path[k];ms+=x.lat;if(!x.sx)mt+=x.lat;if(x.sv)(se||(se=[])).push(x);}P.ms=ms;P.mt=mt;P.se=se;}const rtt=2*P.mt,kl=snd&&CITIES[ci].kr;
const tl=(e.k==='t'||kl)&&rtt>(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0;
if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok;
// Where each flow left (the PNI list asks what a PNI here would take over, #175).
if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);}
if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}}
@ -338,8 +344,10 @@ function compute(){RW.gen++;
if(DD){let rem=0,jf=0;for(let i=0;i<NF;i++)if(FREM[i]>1e-6)rem+=FREM[i];if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;}
ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf),
lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});}
// R.satU only when a circuit is in the graph, so R stays as it was for networks without one.
const SATU=SATN?new Float64Array(NC):null;if(SATU){R2.satU={};satAfter(SE,LATP,SATU);}
for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i];
if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);}
if(LATP[i]>0&&SRV[i]>0)R2.latF[c]=clamp(1-LATP[i]/SRV[i],0,1);if(SATU&&SATU[i]>1e-9)R2.satU[c]=SATU[i];}
// Each city's slowest big exit: (path, source, exit) triples, one per path that went far, in the order they first did.
{const G=new Map();for(let k=0;k<FARL.length;k+=3){const P=FARL[k],src=FARL[k+1],to=FARL[k+2],key=src*NC+to,o=G.get(key);if(o){o.g+=P.fg;o.ms=Math.max(o.ms,2*P.ms);}else G.set(key,{src,to,g:P.fg,ms:2*P.ms});}
for(const o of G.values()){const c=CITIES[o.src].id,cur=R2.latFar[c];if(!cur||o.g>cur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}}
@ -361,7 +369,7 @@ function computeMoney(R2,PX=null){
const C=R2.cost,V=R2.rev,pm=S.priceMul;
C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+cageMo(p.routers)+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0);
C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0);
C.links=S.links.reduce((a,l)=>a+(l.mo||0),0);
C.links=S.links.reduce((a,l)=>a+(l.kind==='sat'?0:l.mo||0),0);{const m=satMoAll();if(m)C.sat=m;}
C.nni=(S.nni||[]).reduce((a,x)=>a+nniMo(x),0);
const htd=histToday();C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0,htd);R2.p95[t.id]=q;return a+transitMo(t,q);},0);
C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0);
@ -374,10 +382,11 @@ function computeMoney(R2,PX=null){
C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}}
const ids=linkIds();for(const b of S.biz){if(capPend(b)||BIZ_T[b.type].orbit)continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}
for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE;
ip4Money(C,V);
if(PX)pieMoney(PX,R2,V);
// The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js).
{const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;if(PX)V.gov=pieGovMo();if(PX)R2.pie.gov={rdf:V.gov||0,sky:sky?GRANT_SKY_MO:0};}
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix+(V.orbit||0));
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0);
R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0);
}

View file

@ -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))||(l.kind==='sat'&&l.ready>S.day);}
function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);}
function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);}
// Monthly price of one connection; compute() sums these, the connections overview lists them.

View file

@ -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!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;});
for(const l of s.links)repairSubUpgradeDates(l,s.day);
xpSanitize(s);
/* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its
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<MET[lo[k]].f)lo[k]=m;}if(l.standby!==true)delete l.standby;}
@ -62,8 +63,8 @@ function sanitize(s){
for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k];
if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};}
// The backbone's technology: a save from before it with Auto-TE bought keeps the old rules on RSVP-TE (legacy).
// The standard POP build (#240): a router model and how many.
{const d=s.popStd;s.popStd=d&&typeof d==='object'&&Number.isInteger(d.g)&&RG[d.g]?{g:d.g,rt:int(d.rt,1,RMAX,1)}:null;}
// The build standard (#240): a router model and how many, and since then every other target; odd values read as "keep".
popStdSanitize(s);
{const c=s.core&&typeof s.core==='object'?s.core:null,lv=c?int(c.lv,0,4,0):(s.te?2:0);s.core={lv,run:c?int(c.run,0,lv,lv):lv};if(c?c.legacy===true:!!s.te)s.core.legacy=true;if(c&&c.lab===true)s.core.lab=true;if(c&&c.since!==undefined)s.core.since=num(c.since,0);}
s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null;
s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i));
@ -110,8 +111,10 @@ function sanitize(s){
three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */
{const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{};
const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);}
specSanitize(s);
specSanitize(s);mpSanitize(s);
pieSanitize(s);pieIncFix(s);
ip4Fix(s);
satSanitize(s);
if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}}
return s;}
function migrate(s){sanitize(s);

View file

@ -27,11 +27,11 @@ function reqList(o){return (o.reqs||[]).map(k=>{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)));

View file

@ -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||d<o.km)best.set(n,{to:n,sp:path.slice(),km:d});}else if(n===b)out.push({to:n,sp:path.slice(),km:d});}
if(path.length<XP_HOPS&&n!==b)go(n,d);path.pop();seen.delete(n);}};
go(a,0);return (b==null?[...best.values()]:out).sort((x,y)=>x.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].cls<O.rg)return tr('action_helpers.needs_routers_with_pn_ports_or',{pn:RG[mainRG(O.rg)].pn,city:CITY[c].name});}
return '';}
// A channel: the optic (free from the spares shelf), a regen card at every regen site on the way, and the first one
// also pays for patching the express through the ROADM in every city it passes.
function xpCost(sp,o,fresh){const r=REGEN_CH*sp.reduce((a,s)=>a+(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));}

View file

@ -58,14 +58,16 @@ function clRenew(b,rate){b.rate=Math.max(0,Math.round(rate));b.mk=mkt();delete b
function clGone(b,why){S.biz=S.biz.filter(x=>x!==b);clNote('lost',why);}
const clWhere=b=>bCities(b).map(c=>CITY[c].name).join(' ⇄ ');
// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing.
function clGrow(b){const T=BIZ_T[b.type];if(T.fiber)return false;const up=(T.opts||[]).find(x=>x>b.bw);b.bw=up||b.bw*2;return true;}
// Growing: the next size up their type sells, or twice the bandwidth past the top one. Fiber grows by renewing. Not
// when the bigger IPv4 block it needs is not free (#150): out.v4 lists them for the day's news.
function clGrow(b,out){const T=BIZ_T[b.type];if(T.fiber)return false;const bw=(T.opts||[]).find(x=>x>b.bw)||b.bw*2;
if(!ip4GrowOk(b,bw)){if(out)out.v4.push([b,bw]);return false;}b.bw=bw;return true;}
// Leaving, or one of the not-your-fault turns that keeps them. Returns what the log says.
function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clWhere(b))};
if(b.mood<50){clGone(b,'sad');out.lost.push(tr('lifecycle.left_unhappy',v));return;}
const C=S.cl;if(d-C.odd>=CL_ODD_GAP&&clR(b,'odd')<0.25){C.odd=d;clGone(b,'odd');out.lost.push(tr('lifecycle.left_odd',{...v,why:tr(clPick(CL_ODD,b,'oddline'))}));return;}
const ks=Object.keys(CL_WHY).filter(k=>CL_WHY[k].ok(b.type)),k=clPick(ks,b,'why');
if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;}
if(k==='acq'&&clR(b,'acqbig')<0.3&&clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.ok.push(tr('lifecycle.acquired_stays_bigger',{...v,bw:fmtG(b.bw)}));return;}
if(k==='moved'){const reg=CITY[b.city].reg,to=Object.keys(S.pops).filter(c=>c!==b.city&&CITY[c].reg===reg&&bizCity(c)).sort();
const c2=to.length&&clR(b,'stay')<0.5?clPick(to,b,'to'):null;
if(c2){const from=CITY[b.city].name;b.city=c2;clRenew(b,clFair(b));clNote('ren');out.ok.push(tr('lifecycle.moved_stays',{name:v.name,from:esc(from),to:esc(CITY[c2].name)}));return;}}
@ -75,7 +77,7 @@ function clLeave(b,d,out){const T=BIZ_T[b.type],v={name:esc(b.name),city:esc(clW
/* A day of contracts, after the moods. 30 days before a term ends a customer with competitors around may ask for a
discount (at most three open at a time); at the end, the rest renew, grow or leave. An unanswered haggle renews at
the asked price. */
function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0);
function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],lost:[],hag:[],v4:[]};let open=S.biz.reduce((a,b)=>a+(b.hag?1:0),0);
const pat=rule('moods')==='patient'?0.5:1;
for(const b of S.biz.slice()){if(!b.te||!clOn(b))continue;
if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;}
@ -86,7 +88,7 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l
continue;}
const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat*salesLeaveMul(b);
if(clR(b,'leave')<leave){clLeave(b,d,out);continue;}
const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}}
const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b,out)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}}
clRenew(b,clFair(b));clNote('ren');out.ren++;}
clNews(out);clReferral(d);}
// What the day says: haggles one by one (they want an answer), the rest in a few lines so a big network is not a wall of toasts.
@ -94,7 +96,7 @@ function clNews(out){
for(const b of out.hag){const was=bizMo(b),now=BIZ_T[b.type].fiber?b.hag.rate:b.bw*b.hag.rate;
toast(tr('lifecycle.haggle',{name:esc(b.name),city:esc(clWhere(b)),price:fmt$(now),p:pct(1-now/Math.max(1,was)),n:b.hag.until-S.day}),'',[{l:tr('common.deals'),act:'leftTab',args:{t:'deals'}}],{a:'cust',v:b.id});}
const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);};
few(out.ok,'good');few(out.lost,'');
few(out.ok,'good');ip4News(out.v4);few(out.lost,'');
if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');}
const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});};

View file

@ -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);if(l.kind==='sat')return satLat(l);const f=l.kind==='df'?(l.own?(l.sub?seaLatencyFactor(l):1.1):1.25):l.kind==='vxc'?1.4:l.cable?(CAB[l.cable].lat||1):1.3;return l.km*f/200;}
/* Wave prices differ a lot by market (TeleGeography): Europe's dense, competitive metro and
long-haul routes are cheap (Frankfurt–London 100G ≈ $1,150/mo), the US costs more, and
routes into Africa are several times dearer (Africa–Europe ≈ 5.9× London–New York).

View file

@ -120,7 +120,7 @@ function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pop
function ddosPanel(){return S?ddosAll().filter(a=>S.pops[a.city]).map(ddosOne).join(''):'';}
const ddCities=l=>{const u=[...new Set(l)];return u.slice(0,3).map(c=>CITY[c].name).join(', ')+(u.length>3?' +'+(u.length-3):'');};
function ddosOne(a){const V=DDOS_VEC[a.vec]||{n:'?',fs:false},m=ddosReport(a),row=(ok,t)=>`<div class="meta">${ok===true?'✓':ok===false?'~':'—'} ${t}</div>`;
let h=`<div class="inc ddos" style="background:#FFE2E6;border:1px solid #FF8A9A"><div class="nm">🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}</div>
let h=`<div class="inc ddos" style="background:var(--tint-r,#FFE2E6);border:1px solid #FF8A9A"><div class="nm">🚨 ${tr('ddos.card_title',{g:fmtG(a.gbps),vec:esc(V.n)})}</div>
<div class="meta"><b>${esc(ddosWho(a))}</b> · ${tr('ui.n_d_left',{n:Math.max(1,a.until-S.day)})}${a.carpet?' · '+tr('ddos.carpet'):''}</div>`;
if(!m)return h+'</div>';
const engIdle=hasScrub()&&!a.bh&&m.eng<1&&S.scrubMode==='ondemand'&&S.ddosAuto&&S.ddosAuto.scrub===false&&a.eng===undefined;

View file

@ -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'&&l.kind!=='sat'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
// A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it.
const bare=S.links.filter(xpBare),dug=live.concat(bare);
if(dug.length){opts.push(['cut',2+Math.min(6,dug.length/2)]);}
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(`<b>${m[0]}</b><br>${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);

View file

@ -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(d<M.next)return;if(S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;}
if(!M.on){if(d<M.next)return;if(S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;}
if(d>=M.until){mkLeave();return;}
if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}}
function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121);
@ -30,7 +30,7 @@ function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(
Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home});
toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive');
if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);}
function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return;
function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l)));if(!live.length)return;
// Weak spots first: a sample keeps this cheap on big networks.
const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x]));
const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served;
@ -50,4 +50,4 @@ function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0
if(typeof mkEnd==='function')mkEnd(ok,true);}
// The NOC tab's card while it is here.
function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost();
return `<div class="inc" style="background:#FFF1D6;border:1px solid #FFC56B"><div class="nm">🐒 ${tr('chaos_monkey.loose')}</div><div class="meta">${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}</div><div class="btns">${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash<c)}</div></div>`;}
return `<div class="inc" style="background:var(--tint-o,#FFF1D6);border:1px solid #FFC56B"><div class="nm">🐒 ${tr('chaos_monkey.loose')}</div><div class="meta">${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}</div><div class="btns">${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash<c)}</div></div>`;}

View file

@ -81,7 +81,7 @@ function dayPost(d){
mkTick(d);
if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);}
// Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year).
if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;fireFailure('cut');}}
if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;fireFailure('cut');}}
if(cm&&d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);}
if(dirty)compute();
// the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them
@ -94,6 +94,7 @@ function dayPost(d){
scnTick(d);
confTick(d);
specDay(d);
ip4Day(d);
// money trouble
if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('day_tick.you_are_in_the_red_cancel'),'bad');}
else S.neg=0;

View file

@ -13,7 +13,7 @@ const ACT={
takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;S.stats.loans=(S.stats.loans||0)+1;const B=BANKS[o.bank];let got=o.amount,note='';
if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=' '+(f>=1?tr('interface.tubecoin_moved_up_p_on_the',{p:Math.round(Math.abs(f-1)*100)}):tr('interface.tubecoin_moved_down_p_on_the',{p:Math.round(Math.abs(f-1)*100)}));}
S.cash+=got;S.loanOffers=S.loanOffers.filter(x=>x!==o);
S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(x=>x.sub).length}});
S.loans.push({id:o.id,bank:o.bank,start:S.day,amount:o.amount,got,bal:o.model==='transit'?o.owe:o.amount,apr:o.apr||0,apr0:o.apr||0,pay:o.pay||0,left:o.term||0,term:o.term||0,share:o.share||0,model:o.model,cut:o.cut,covs:o.covs,base:{sub:S.links.filter(seaLink).length}});
track('loan_taken');toast(`<b>${tr('interface.amt_from_bank_has_landed',{amt:fmt$(got),bank:esc(B.name)})}</b><br>${B.equity?tr('interface.they_now_own_p_of_your',{p:pct(o.share)}):loanSummary(o)}${note}`,'good');sfx('coin');after();renderBank();},
callBank:({amount})=>{if(!callOffer(amount))return;track('loan_called');sfx('click');renderBank();renderHUD();save();},
declineLoan:({id})=>{S.loanOffers=S.loanOffers.filter(x=>x.id!==id);sfx('click');renderBank();renderHUD();save();},
@ -23,6 +23,7 @@ const ACT={
leaseSwap:({a,b,src})=>{if(!S.pops[a]||!S.pops[b]||a===b)return;$('dash').hidden=true;UI.lmode='df';UI.dfSrc=['lease','build','cable'].includes(src)?src:isSub(a,b)?'cable':'build';UI.dfSys=glassLvl()>=3?'roadm':'lite';openLinkModal(a,b);},
dashLink:({id})=>{$('dash').hidden=true;selectLink(id);focusLink(id);},
mapSet:({v})=>{if(!['auto','2d'].includes(v))return;mapGl(v==='auto');refreshSettings();},
themeSet:({v})=>{if(!themePick(v))return;refreshSettings();},
animSet:({v})=>{if(!['auto','on','off'].includes(v))return;UI.anim=v;try{localStorage.setItem('sot-anim',v);}catch(e){}applyAnim();refreshSettings();},
soundSet:({v})=>{UI.muted=v==='off';try{localStorage.setItem('sot-mute',UI.muted?'1':'0');}catch(e){}renderHUD();refreshSettings();},
langSet:({v})=>{if(!Object.hasOwn(LANGS,v)||v===LANG)return;try{localStorage.setItem('sot-lang',v);}catch(e){}save(true);location.reload();},

View file

@ -4,8 +4,8 @@ Object.assign(ACT,{
if(!w&&!p){toast(tr('customers.nothing_spare_to_sell_on_this'),'bad');sfx('err');return;}const L=l.list||(l.list={w:0,p:0});L.w+=w;L.p+=p;
toast(tr('broker.listed',{a:CITY[l.a].name,b:CITY[l.b].name}),'good');sfx('click');after();},
unlistFiber:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||!l.list)return;delete l.list;sfx('click');after();},
accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;}
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)<o.slots){toast(tr('customers.not_enough_free_channels_on_that'),'bad');return;}}
accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!ip4Fits(o)){const n=ip4Need(o);toast(tr('ip4.no_space',{name:esc(o.name),p:ip4Cidr(n),n:ip4N(n),free:ip4N(Math.max(0,ip4Use().free))}),'bad',[{l:tr('ip4.section'),act:'ip4Open'}]);sfx('err');return;}const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;}
if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)<o.slots){toast(tr('customers.not_enough_free_channels_on_that'),'bad');return;}}
if(BIZ_T[o.type].event&&S.day>=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).

View file

@ -0,0 +1,29 @@
/* Address space (#150, 33-address-space.js): buy, lease in, lease out, sell, hand back, and the CGNAT ratio. Every block
change keeps room for the customers already signed, with every home behind CGNAT. */
const ip4Re=()=>{after();renderBank();};
function ip4Can(){if(ip4On())return true;toast(tr('ip4.off'),'bad');sfx('err');return false;}
const ip4Blk=id=>S.ip4.b.find(b=>b.id===id);
function ip4Busy(){toast(tr('ip4.in_use'),'bad');sfx('err');}
// No more blocks than a save keeps (IP4_BLK): a new one is refused with the way out.
function ip4Room(){if(!ip4Full())return true;toast(tr('ip4.too_many',{n:IP4_BLK}),'bad');sfx('err');return false;}
Object.assign(ACT,{
ip4Open:()=>{if(!S||pzOn()||!ip4On())return;if(!$('modal').hidden)closeModal();ACT.bank();const g=$('bankIp4');if(g&&g.scrollIntoView)g.scrollIntoView({block:'start'});},
// The size the market rows quote (a dropdown: v is the prefix length).
ip4Pick:({v})=>{const len=Number(v);if(ip4LenOk(len))UI.ip4Len=len;renderBank();},
ip4Buy:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const c=ip4Cost(len);if(!spend(c))return;
S.ip4.b.push({id:uid(),len,k:'buy',d:S.day});toast(tr('ip4.bought',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(c)}),'good');sfx('coin');ip4Re();},
ip4Lease:({len})=>{if(!ip4Can())return;len=Number(len);if(!ip4LenOk(len)||!ip4Room())return;const mo=ip4InMo(len);
S.ip4.b.push({id:uid(),len,k:'in',d:S.day,mo});toast(tr('ip4.leased_in',{p:'/'+len,n:ip4N(ip4Sz(len)),price:fmt$(mo)}),'good');sfx('click');ip4Re();},
ip4Sell:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return;
if(ip4Held(b)){toast(tr('ip4.held',{date:dateStr(b.d+IP4_HOLD)}),'bad');sfx('err');return;}if(!ip4Spare(b)){ip4Busy();return;}
if(UI.confirm!==id){UI.confirm=id;renderBank();return;}UI.confirm=null;const v=ip4Value(b.len);S.ip4.b=S.ip4.b.filter(x=>x!==b);S.cash+=v;
toast(tr('ip4.sold',{p:'/'+b.len,price:fmt$(v)}),'good');sfx('coin');ip4Re();},
ip4Out:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k==='in'||b.out)return;if(!ip4Spare(b)){ip4Busy();return;}
b.out=true;b.mo=ip4OutMo(b.len);toast(tr('ip4.leased_out',{p:'/'+b.len,price:fmt$(b.mo)}),'good');sfx('coin');ip4Re();},
ip4Back:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||!b.out)return;delete b.out;delete b.mo;sfx('click');ip4Re();},
ip4Return:({id})=>{if(!ip4Can())return;const b=ip4Blk(id);if(!b||b.k!=='in')return;if(!ip4Spare(b)){ip4Busy();return;}
S.ip4.b=S.ip4.b.filter(x=>x!==b);sfx('click');ip4Re();},
// Fewer homes per address needs more addresses: refused when the customers already signed would not fit.
ip4Nat:({v})=>{if(!ip4Can())return;const r=Number(v);if(!IP4_NAT.includes(r)||r===S.ip4.nat)return;const u=ip4Use();
if(r<S.ip4.nat&&u.T-u.B<Math.ceil(u.H/r)){ip4Busy();UI._bh=null;renderBank();return;}S.ip4.nat=r;sfx('click');ip4Re();},
});

View file

@ -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,13 +14,13 @@ Object.assign(ACT,{
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
S.myIx[city]={name:nm,members:[],next:S.day+4};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if(!linkFromOk(a)||!linkToOk(b)||((cnCity(a)||cnCity(b))&&!cnOk()))return;
if(!waveOk(a,b,tier)){toast(tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:esc(waveNeed(tier))}),'bad');sfx('err');return;}
const wr=waveRoute(a,b,mult,border);if(!wr){toast(tr('links.no_cable_available_for_that_route'),'bad');sfx('err');return;}
{const so=soldOut(a,b,tier,wr.cab);if(so){toast(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}),'bad');sfx('err');return;}}{const w=subWaveWhy(tier,wr.km,wr.sub);if(w){toast(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:esc(w)}),'bad');sfx('err');return;}}const base=Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),cost=base+(S.pops[b]?0:popCost(b));
if(!portGate(a,1)||!portGate(b,1))return;if(!spend(cost))return;if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);}
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);closeModal();
const id=uid();const l={id,a,b,kind:'wave',border,premium:border&&!!UI.cnPrem&&(a==='hkg'||b==='hkg'),tier,km:wr.km,sub:wr.sub,cable:wr.cab,mo:base,mult:wr.wm,trench:wr.cab?'cab:'+wr.cab:(jn?jn.k:id),cut:0,day:S.day};S.links.push(l);satBeside(a,b);closeModal();
if(sib.length){UI.sel={type:'link',id};}else{UI.sel={type:'city',id:b};UI.tab='cust';}
floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');after();},
// A new fabric port, or every member of one upgraded to a faster speed (#140): as fast as the router takes.
@ -36,7 +36,7 @@ Object.assign(ACT,{
openVxc:(a)=>openVxcModal(a),
buyVxc:({a,b,prov,t})=>{t=+t;if(!CITY[a]||!CITY[b]||noTalk(a,b))return;const g=VXC[t].g,pa=nniPort(a,prov);if(!pa||nniUsed(a,prov)+g>nniCap(pa)+1e-9){toast(tr('links.not_enough_room_on_your_fabric'),'bad');sfx('err');return;}
if(S.pops[b]){const pb=nniPort(b,prov);if(!pb||nniUsed(b,prov)+g>nniCap(pb)+1e-9){toast(tr('links.not_enough_room_on_your_fab',{fab:esc(FAB[prov].name),city:CITY[b].name}),'bad');sfx('err');return;}}
const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});closeModal();
const km=kmBetween(a,b),sub=isSub(a,b),mo=vxcMo(km,sub,t);if(!spend(mo))return;S.links.push({id:uid(),a,b,kind:'vxc',prov,vt:t,km,sub,mo,cut:0,day:S.day});satBeside(a,b);closeModal();
toast(tr('links.circuit_up_in_59_seconds_vxc',{vxc:VXC[t].n,fab:esc(FAB[prov].name),a:CITY[a].name,b:CITY[b].name})+(S.pops[b]?'':' '+tr('links.now_grab_an_ix_port_there')),'good');if(!S.pops[b])selectCity(b);after();},
upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>nniCap(pt)+1e-9){toast(tr('links.fabric_port_in_city_is_full',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();},
cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);prunePairMet();const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();},

View file

@ -12,8 +12,10 @@ Object.assign(ACT,{
setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}},
route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);},
popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd={g:p.rgen||0,rt:p.routers||1};toast(tr('pop_std.new_pops_now_start_with',{n:S.popStd.rt,model:esc(RG[S.popStd.g].n)}),'good');sfx('click');after();},
popStdClear:()=>{S.popStd=null;sfx('click');after();},
// This POP's build becomes the standard's POP part: its model, routers, second building and generator.
popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd=bstdPut({...bstd(),g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen});
toast(tr('pop_std.new_pops_now_start_with_list',{list:esc(bstdPopParts(bstd()).join(', '))}),'good');sfx('click');after();if(bstdShown())bstdModal();},
popStdClear:()=>{S.popStd=null;sfx('click');after();if(bstdShown())bstdModal();},
addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();},
models:()=>{UI.models=!UI.models;renderPanel();},
rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();},

View file

@ -3,10 +3,12 @@ Object.assign(ACT,{
toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();},
seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return;
for(const c of miss){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(c);}
const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)});
const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)});satBeside(o.a,o.b);
S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id};
toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();},
seatNo:()=>{S.seatOff=null;after();},
charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;if($('modal').className==='charter')closeModal();
toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}after();},
toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');if(UI.tutLater){UI.tutLater=false;tutorialStart();}
// A new multiplayer session's code to share waited for the charter (95-modals/48-multiplayer.js).
if(UI.mpLater)mpStartTell();after();},
});

View file

@ -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();},
});

View file

@ -10,7 +10,7 @@ Object.assign(ACT,{
orderCable:()=>{const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;if(ownCabWhy(a,b)||!linkFromOk(a)||!linkToOk(b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return;
if(!S.pops[b]){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(b);}
const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,id=uid(),ship=layName({id}),days=q.days;
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});
S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1});satBeside(a,b);
const laid=S.links[S.links.length-1];laid.paid=q.cost;for(const k of Object.keys(SUB_UPGRADES))if(up[k])laid['sub'+k]=laid.ready;UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;
S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id};
toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();},
@ -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};
S.links.push(l);satBeside(a,b);closeModal();UI.sel={type:'link',id};
toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();},
regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||(l.sub&&!l.seat)||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return;
if(d<0&&(l.ch||[]).some(o=>!optMode(o,Object.assign({},l,{regen:n})))){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)<chMax(l)){toast(tr('fiber_and_hardware.fill_this_pair_first_light_all',{max:chMax(l)}),'bad');sfx('err');return;}if(!spend(pairCost(l)))return;l.pairs=n+1;toast(tr('fiber_and_hardware.fiber_pair_n_is_lit_a',{n:n+1,a:CITY[l.a].name,b:CITY[l.b].name,m:DF_SYS[l.sys].max}),'good');sfx('build');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)+xpSlots(l)<chMax(l)){toast(tr('fiber_and_hardware.fill_this_pair_first_light_all',{max:chMax(l)}),'bad');sfx('err');return;}if(!spend(pairCost(l)))return;l.pairs=n+1;toast(tr('fiber_and_hardware.fiber_pair_n_is_lit_a',{n:n+1,a:CITY[l.a].name,b:CITY[l.b].name,m:DF_SYS[l.sys].max}),'good');sfx('build');after();},
upSys:({id})=>{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).

View file

@ -0,0 +1,27 @@
// Teleports and satellite capacity (#83): build the gateway, rent circuits on its birds, resize them. Cancel is rmLink.
Object.assign(ACT,{
teleBuild:({city})=>{const p=S.pops[city];if(!p||teleOf(city))return;
const why=teleWhy(city);if(why){toast(why,'bad');sfx('err');return;}
if(!spend(TPORT_COST))return;p.tele=1;toast(tr('satellites.teleport_up_in_city',{city:CITY[city].name}),'good');after();},
teleTrk:({city})=>{const p=S.pops[city];if(!p||teleOf(city)!==1)return;
const why=trkWhy(city);if(why){toast(why,'bad');sfx('err');return;}
if(!spend(TRK_COST))return;p.tele=2;toast(tr('satellites.tracking_antennas_up',{city:CITY[city].name}),'good');after();},
// Closing a teleport asks twice, and never while circuits still start there.
teleRm:({city})=>{const p=S.pops[city];if(!p||!teleOf(city))return;const n=S.links.filter(l=>l.kind==='sat'&&l.a===city).length;
if(n){toast(trn('satellites.cancel_n_circuits_first',n),'bad');sfx('err');return;}
if(UI.confirm!=='tele:'+city){UI.confirm='tele:'+city;renderPanel();return;}
delete p.tele;UI.confirm=null;toast(tr('satellites.teleport_closed',{city:CITY[city].name}));after();},
satOpen:({a,b})=>satModal(a,b),
// Rent a circuit from teleport a to b: the first month up front, like a wave; a POP at b comes with it if there is none.
// Next to a link you already have between the two, it goes on standby: the backup that carries only when the cable is down.
buySat:({a,b,bird,g})=>{g=+g;const why=satWhy(a,b,bird,g);if(why){toast(why,'bad');sfx('err');return;}
if(!portGate(a,1)||!portGate(b,1))return;const mo=satMo(bird,g),pop=!S.pops[b];if(!spend(mo+(pop?popCost(b):0)))return;
if(pop){S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};popStdApply(b);}
const sb=pairLinks(a,b).some(l=>l.kind!=='sat'),n=leadDays(SAT_ORB[SATS[bird].orb].days),id=uid();
S.links.push({id,a,b,kind:'sat',bird,g,km:satKm(bird,a,b),sub:true,mo,cut:0,day:S.day,ready:S.day+n,...(sb?{standby:true}:{})});
closeModal();UI.sel={type:'link',id};
toast(trn('satellites.circuit_ordered',n,{cap:fmtCap(g),bird:esc(SATS[bird].n),a:CITY[a].name,b:CITY[b].name})+(sb?' '+tr('satellites.on_standby_beside_your_link'):''),'good');after();},
// Bigger or smaller on the same bird: a bigger one pays its new month up front, as a wave upgrade does.
satSize:({id,g})=>{g=+g;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='sat'||g===l.g||!SAT_ORB[SATS[l.bird].orb].g.includes(g))return;
const mo=satMo(l.bird,g);if(g>l.g&&!spend(mo))return;l.g=g;l.mo=mo;sfx('click');after();},
});

View file

@ -0,0 +1,14 @@
// The build standard sheet (93-ui/59-build-standard.js): pick a target, or bring everything up to the standard in one go.
Object.assign(ACT,{
bstdOpen:()=>{if(S&&!pzOn())bstdModal();},
// v: a position in the list the sheet shows; without v, the next value (the MCP tools step through a list).
bstdSet:({k,v})=>{if(!S||pzOn()||!own(BSTDK,k))return;const D=bstd(),x=opsPick(bstdOpts(k),D[k],v);if(x===undefined||!bstdOk(BSTDK[k],x))return;
D[k]=x;S.popStd=bstdPut(D);sfx('click');after();opsRedraw('bstdSet',{k},bstdModal);},
// The same jobs, in the same order and through the same gates as the intern's order, while the cash lasts. One
// recompute at the end, and one toast: what got done, and what still waits.
bstdApply:()=>{if(!S||pzOn()||!S.popStd)return;const J=bstdPlan(false);if(!J.length)return;const c0=S.cash;let n=0;
opsQuiet(()=>{n=bstdDo(J,j=>{const c=bstdPrice(j);return c<=0||S.cash>=c;},j=>!!j.go(),false).length;});
after();const q=bstdQuote(false),left=q.pops+q.ports+q.links;
toast((n?trn('bstd.applied',n,{cost:fmt$(c0-S.cash)}):tr('bstd.applied_none'))+(left?' '+trn('bstd.left',left):''),n?'good':'bad');sfx(n?'build':'err');
if(bstdShown())bstdModal();},
});

View file

@ -2,8 +2,10 @@
const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length];
// A pick from a list (v: its position, as the sheet's dropdown sends it), or without v the next value (the MCP tools step).
const opsPick=(a,cur,v)=>{if(v===undefined)return opsCycle(a,cur);const i=Number(v);return Number.isInteger(i)&&i>=0&&i<a.length?a[i]:undefined;};
// The sheet is drawn again after a pick: keep the keyboard on the list that was used.
const opsRedraw=(act,args)=>{opsModal();const j=JSON.stringify(args);for(const el of $('modalCard').querySelectorAll(`[data-chg="${act}"]`))if(el.dataset.args===j){el.focus();break;}};
// The sheet is drawn again after a pick: keep the keyboard on the list that was used. The build standard sheet shows the
// std order's switch and budget too: a pick there stays there.
const opsSheet=()=>(bstdShown()?bstdModal:opsModal)();
const opsRedraw=(act,args,draw=opsSheet)=>{draw();const j=JSON.stringify(args);for(const el of $('modalCard').querySelectorAll(`[data-chg="${act}"]`))if(el.dataset.args===j){el.focus();break;}};
Object.assign(ACT,{
opsOpen:()=>{if(S)opsModal();},
opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=monthIdx(S.day);O.intern=id;O.hired=S.day;O.wk=null;
@ -12,7 +14,7 @@ Object.assign(ACT,{
O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();},
opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null;
toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();},
opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsModal();},
opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsSheet();},
opsParam:({k,p,v})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p],x=opsPick(opsOpts(k,p),opsP(k,p),v);if(x===undefined||!(P.ok?P.ok(x):P.v.includes(x)))return;
(S.ops.p[k]||(S.ops.p[k]={}))[p]=x;sfx('click');after();opsRedraw('opsParam',{k,p});},
opsCap:({k,v})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;const x=opsPick(opsCaps(k),opsCap(k),v);if(x===undefined)return;S.ops.cap[k]=x;sfx('click');after();opsRedraw('opsCap',{k});},

View file

@ -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;

View file

@ -23,13 +23,13 @@ Object.assign(ACT,{
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');if(MP_API)mpResume();},
menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
<div class="menu-list">
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
</div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📐',tr('bstd.title'),'bstdOpen'],...(mpIs()?[['🌐',tr('mp.session'),'mpOpen']]:[]),['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p>
</div><div class="menu-plugs"><a class="mplug" href="${SIGNAL}" target="_blank" rel="noopener">💬 ${tr('modal_and_names.join_the_noc_chat')} →</a><a class="mplug" href="${ISSUES}" target="_blank" rel="noopener">🐛 ${tr('modal_and_names.found_a_bug_or_have_an')} →</a></div>`);},
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},

View file

@ -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,18 +32,18 @@ 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 `<span class="meta" style="align-self:center">${tr('action_helpers.n_fiber_pairs_lit_the_trench',{n})}</span>`;
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<c);}
const full=(l.ch||[]).length+soldSlots(l)+xpSlots(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<c);}
function chWhy(l,o){const O=OPT[o];if(!techOk('opt',o,O.lvl))return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl});if(O.sys==='roadm'&&!isRdm(l.sys))return tr('action_helpers.needs_a_roadmaster_9000_line_system');if(!optMode(o,l)){const mx=optModes(o,l).at(-1)[1];if(l.sub&&l.own&&!l.seat){const v={max:mx.toLocaleString(),span:spanKm(l).toLocaleString()};
// Terminals and engineering only stretch the long-haul transponders: where they cannot help this optic, say what reaches instead.
if(!optMode(o,withSubUps(l))){const alt=Object.keys(OPT).filter(x=>(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<O.rg)return tr('action_helpers.needs_routers_with_pn_ports_or',{pn:RG[mainRG(O.rg)].pn,city:CITY[c].name});}return '';}
function bbCost(c){return 15000+CITY[c].P*20;}
/* A click that changes nothing routing reads (the log, offers, cash, names, settings…) keeps the routing it has:
compute() gives the same R again for the same state (tests/compute-idempotent), so it is skipped. The key is the save
without the fields routing never reads (tests/route-skip checks each one); any other change routes again. */
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv']);
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv','popStd','mp']);
function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);}
function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;}
function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}

View file

@ -31,4 +31,4 @@ function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;U
// Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);
if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');if(MP_API)mpResume();}

View file

@ -0,0 +1,34 @@
// Multiplayer (60-features/89-multiplayer.js, 95-modals/48-multiplayer.js). Every one does nothing unless the build
// stamped MP_API; the title-screen ones are in the click delegate's no-game list (96-map/95-clicks.js).
Object.assign(ACT,{
mpDoor:()=>{if(!MP_API)return;const i=$('nmIn');UI.nm=((i&&i.value)||UI.nm||randomNetworkName()).slice(0,24);openModal(mpStartHtml());
const n=$('mpName');if(n)n.addEventListener('input',e=>{UI.nm=e.target.value;});
const c=$('mpCode');if(c)c.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpJoin({});}});},
mpBack:()=>{const n=$('mpName');if(n)UI.nm=n.value.slice(0,24);showTitle();},
mpStart:()=>{if(!MP_API||UI.mpBusy)return;const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra',preset=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',t=$('mpTitle');
mpBusy(true);mpReq('POST','/sessions',{net:{name:nm,home},preset,title:(t&&t.value||'').slice(0,40),avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,false);},e=>{mpBusy(false);mpErr(e);});},
mpJoin:()=>{if(!MP_API||UI.mpBusy)return;const i=$('mpCode'),code=mpNorm(i?i.value:'');if(!code){toast(tr('mp.err_code'),'bad');if(i)i.focus();return;}
const nm=mpNameIn(),home=homeOk(UI.startCity)?UI.startCity:'fra';
mpBusy(true);mpReq('POST','/sessions/'+code+'/join',{net:{name:nm,home},avoid:mpAvoid()}).then(j=>{mpBusy(false);mpBegin(j,nm,home,true);},e=>{mpBusy(false);mpErr(e);});},
mpOpen:()=>{if(!mpIs())return;openModal(mpPanelHtml(),'mp');const s=$('mpSay');if(s)s.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();ACT.mpChat({});}});
// About to move to another device: the server gets what this one has first, so the link opens it as it is now.
const d=document.querySelector('#mpPanel details.mpmove');if(d)d.addEventListener('toggle',()=>{if(d.open)mpSyncNow();});mpPoll();},
mpShare:()=>{if(!mpIs())return;mpSend(tr('mp.share_line',{code:mpShow(S.mp.code),url:location.origin+location.pathname}));},
// The link carries the secret: it goes to the clipboard, or is selected for copying by hand, never into a toast.
mpCopyLink:()=>{if(!mpIs())return;const l=mpLink(S.mp);if(!l)return;mpSyncNow();const sel=()=>{const i=$('mpLink');if(i){i.focus();i.select();}};
try{navigator.clipboard.writeText(l).then(()=>toast(tr('mp.link_copied'),'good'),sel);}catch(e){sel();}},
mpChat:()=>{if(!mpIs()||MP.gone)return;const i=$('mpSay'),t=(i?i.value:'').trim().slice(0,200);if(!t)return;const m=S.mp;
mpReq('POST',mpPath(m,'/feed'),{text:t},{auth:m}).then(j=>{if(i)i.value='';mpOk(j);},e=>{if(e&&e.status===429)toast(tr('mp.slow_down'),'bad');else mpFail(e);});},
mpLeaveAsk:()=>{if(!mpIs())return;openModal(`<h2 style="font-size:26px">${tr('mp.leave_q',{code:mpShow(S.mp.code)})}</h2><p class="tagline">${tr('mp.leave_d',{name:esc(S.name)})}</p><div class="btns">${btn(tr('mp.leave'),'mpLeave',{},'red big')}${btn(tr('common.keep_playing'),'mpOpen',{},'ghost big')}</div>`);},
// Leaving keeps the network, as a game of its own; the session forgets it (and a session that forgot it already too).
mpLeave:()=>{if(!mpIs())return;const m=S.mp,out=()=>{if(!S||S.mp!==m)return;S.mp=null;mpTokSet(m.code,m.pid,null);mpReset();
closeModal();renderAll();save(true);toast(tr('mp.left',{name:esc(S.name)}),'good');};
mpReq('DELETE',mpPath(m,'/me'),undefined,{auth:m}).then(out,e=>{if(e&&(e.status===401||e.status===404))out();else toast(tr('mp.server_away'),'bad');});},
// Only a save at least as new as the one the server said it has (after a conflict), or newer than this one, is loaded:
// "Load the newer save" never takes the player back to an older one.
mpNewer:()=>{if(!mpIs())return;const m=S.mp,min=(m.seq||0)+(MP.stale?0:1);
mpReq('GET',mpPath(m,'/save'),undefined,{auth:m}).then(j=>{if(!S||S.mp!==m)return;const sq=int(j&&j.seq,0,1e15,0);if(sq>=min){mpAdopt(j,m);return;}
m.seq=Math.max(m.seq||0,sq);MP.stale=false;toast(tr('mp.no_newer',{name:esc(S.name)}),'good');mpPanelUpdate();},mpFail);},
// Overwrite the server's save with this one: with a number past the server's, at the next save (never half a day).
mpKeep:()=>{if(!mpIs())return;S.mp.seq=Math.max(S.mp.seq||0,MP.staleSeq||0);Object.assign(MP,{stale:false,force:true,wait:0});save(true);mpPanelUpdate();},
});

View file

@ -62,6 +62,6 @@ Object.assign(ACT,{
// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's
// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone.
// This file is the last of the actions, so every one is here to wrap.
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']);
const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','linkCheck','mapSet','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','themeSet','updateLater','updateNow','vpSet','whatsNewShow']);
const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']);
for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);}

View file

@ -14,7 +14,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return;
const txt=JSON.stringify(packSave(st));
// A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js).
const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st));
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}

View file

@ -22,8 +22,11 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null;
tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz,
// A save marked damaged (bv: the game version that could not load it) is tried again by the next version: the fault is
// usually in the game, and the save itself is fine once it is fixed.
...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false})};}
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier});
...(e.broken&&e.bv===APP_VERSION?{broken:true,bv:e.bv}:{broken:false}),
// A network in a multiplayer session: <code>.<pid>, so a link from another device finds it again.
...(typeof e.mp==='string'&&/^[0-9A-HJKMNP-TV-Z]{6}\.[a-z0-9]{8}$/.test(e.mp)?{mp:e.mp}:{})};}
// mp is always there (null outside a session), so a network that left its session loses its badge in the list.
const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier,mp:s.mp&&s.mp.code?s.mp.code+'.'+s.mp.pid:null});
function slotKeys(){const out=[];try{for(let i=0;i<localStorage.length;i++){const k=localStorage.key(i);if(k===SLOT_OLD)out.old=true;else if(k&&k.startsWith(SLOT_K)&&slotOkId(k.slice(SLOT_K.length)))out.push(k.slice(SLOT_K.length));}}catch(e){}return out;}
// An index entry rebuilt from the save itself. A compressed one can only be read in the background: slotFix() fills it in.
function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return slotClean({id,gz:true,size:raw.length});
@ -46,7 +49,7 @@ function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null;
function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}}
function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id);
gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return;
if(m)Object.assign(x,slotClean({...x,...m}));else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}}
if(m){const c=slotClean({...x,...m});if(!c.mp)delete x.mp;Object.assign(x,c);}else{x.broken=true;x.bv=APP_VERSION;}slotIdxPut(l);slotRefresh();});}}
const slotByAt=l=>l.slice().sort((a,b)=>b.at-a.at);
// ---------- one writer per slot ----------
// The heartbeat: who has a slot open, refreshed every few seconds. A hidden tab's timers can be slowed to once a
@ -88,7 +91,7 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;}
if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);
const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false}));
const e=ent||{id};if(!ent)list.push(e);const c=slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false});if(!c.mp)delete e.mp;Object.assign(e,c);
slotIdxPut(list);return true;}
function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}}
// ---------- opening, leaving, losing ----------

View file

@ -0,0 +1,27 @@
/* ---------- Light or dark (#80) ----------
Settings › Theme: Auto follows the device's light or dark setting, or the player picks one. A choice per device
(localStorage sot-theme, like the animation and map settings), not part of the save. The page's <head> reads it and
sets <html data-theme> before the first paint, so a dark screen never flashes light; this keeps it in step when the
choice or the device's setting changes. The panels follow at once (CSS custom properties, 00-base.css); the map
keeps pictures painted in the old colours, so it paints them again, once (themeRepaint()). */
const THEME_OPTS=['auto','light','dark'],THEME_BAR={light:'#57C4E5',dark:'#0E2A44'}; // the browser bar: --sea
const THEME={pref:'auto',dark:false,mq:null,on:null};
function themeRead(){let v=null;try{v=localStorage.getItem('sot-theme');}catch(e){}return THEME_OPTS.includes(v)?v:'auto';}
const themeSys=()=>{try{return !!(THEME.mq&&THEME.mq.matches);}catch(e){return false;}};
// The page's colours from the choice (and the device's setting, on Auto). A switch repaints the map's cached pictures.
function themeApply(repaint=true){const dark=THEME.pref==='dark'||(THEME.pref==='auto'&&themeSys()),was=THEME.dark,R0=document.documentElement;
THEME.dark=dark;R0.setAttribute('data-theme',dark?'dark':'light');
for(const [n,v] of [['theme-color',THEME_BAR[dark?'dark':'light']],['color-scheme',dark?'dark':'light']]){const m=document.querySelector(`meta[name="${n}"]`);if(m)m.setAttribute('content',v);}
if(repaint&&was!==dark)themeRepaint();return dark;}
function themePick(v){if(!THEME_OPTS.includes(v))return false;THEME.pref=v;try{v==='auto'?localStorage.removeItem('sot-theme'):localStorage.setItem('sot-theme',v);}catch(e){}themeApply();return true;}
// Reads the choice and listens to the device's setting, which Auto follows as it changes (a phone at dusk).
function themeInit(){THEME.pref=themeRead();THEME.on=()=>{if(THEME.pref==='auto')themeApply();};
try{THEME.mq=window.matchMedia?matchMedia('(prefers-color-scheme: dark)'):null;}catch(e){}
const q=THEME.mq;if(q){try{q.addEventListener?q.addEventListener('change',THEME.on):q.addListener(THEME.on);}catch(e){}}
THEME.dark=document.documentElement.getAttribute('data-theme')==='dark';return themeApply(false);}
/* What the map painted in the old colours: the land (the 2D picture, the card's coastlines), every sprite (labels,
cities), the Pie globe unless the player chose its day or night. All painted again on the next frame, not every frame. */
function themeRepaint(){WL.key=null;FRAME.length=0;UI.drawnAt=0;spritesReset();glLandDrop();
let g=null;try{g=localStorage.getItem('sot-globe');}catch(e){}if(!g){PG.night=THEME.dark;PG.g=null;PG.dirty=true;}}
// Picked in another tab: this one follows, and so does the NOC window on a second screen.
if(!RW_IN){themeInit();addEventListener('storage',e=>{if(e.key==='sot-theme'||e.key===null){THEME.pref=themeRead();themeApply();}});}

View file

@ -8,7 +8,7 @@ function installRow(){if(isStandalone())return '';
return `<div class="row icard"><div class="grow"><div class="nm">📲 ${tr('install.best_played_as_an_app')}</div><div class="meta">${tr('install.full_screen_works_offline_one_tap')}${isIOS()?' '+tr('install.install_it_before_you_start_a'):''}</div></div>${btn(tr('common.install'),'install',{},'pink sm')}</div>`;}
/* Phones get a real pitch before a new game: an installed app is full screen, works offline, and on iPhone
keeps its save away from Safari's clean-ups. Storage is separate on iOS, so installing first matters. */
const SHARE_SVG='<svg width="16" height="18" viewBox="0 0 16 18" aria-hidden="true"><path d="M8 1v10M4.5 4.5 8 1l3.5 3.5M5 7H2.5v9.5h11V7H11" fill="none" stroke="#1E2640" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const SHARE_SVG='<svg width="16" height="18" viewBox="0 0 16 18" aria-hidden="true"><path d="M8 1v10M4.5 4.5 8 1l3.5 3.5M5 7H2.5v9.5h11V7H11" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const needPitch=()=>isPhone()&&!isStandalone();
function installSteps(){
if(isIOS())return `<ol class="isteps"><li>${tr('install.tap_share_icon_in_the_browser',{icon:SHARE_SVG})}</li><li>${tr('install.tap_add_to_home_screen_you')}</li><li>${tr('install.open_series_of_tubes_from_your')}</li></ol>`;

View file

@ -6,6 +6,7 @@ function renderHUD(){
// A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
$('muteBtn').style.opacity=UI.muted?.4:1;
if(MP_API)mpHud();// the session chip: also hidden again on the title screen and in a puzzle
if(!S)return;
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}
{const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';}
@ -43,10 +44,10 @@ function renderLeft(){checkLayer();
}else if(UI.left==='deals'){
{const st=custStats();if(st.n)h+=`<div class="row" style="margin-bottom:8px"><div class="grow"><div class="nm">${tr('common.your_customers')} <span class="meta">${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}</span></div><div class="bar ${moodCls(st.avg)}"><i style="width:${st.avg}%"></i></div>${st.unhappy?`<div class="why">${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}</div>`:''}</div>${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}</div>`;}
h+=salesCard()+clDealsHtml()+confSection()+seatSection();
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}</div><div class="meta">${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}</div></div>`;}
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:var(--tint-y,#FFF6CF)"><div class="nm">${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}</div><div class="meta">${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}</div></div>`;}
if(!S.offers.length)h+=`<p class="empty">${tr('hud_and_panels.no_open_offers_right_now_businesses')}</p>`;
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}</div>${o.refN?`<div class="meta">${tr('lifecycle.referred_by',{name:esc(o.refN)})}</div>`:''}${spotWhy(o)}${bRisk(o)}${reqList(o)}
h+=`<div class="row"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · <b>${bTerms(o)}</b> · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}</div>${o.refN?`<div class="meta">${tr('lifecycle.referred_by',{name:esc(o.refN)})}</div>`:''}${spotWhy(o)}${ip4Why(o)}${bRisk(o)}${reqList(o)}
<div class="btns">${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}</div>${has?'':`<div class="why">${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div></div>`;}
}else if(UI.left==='noc'){
h+=`<div class="btns" style="margin-bottom:8px">${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${pieNocBtn()}${btn(`⚙️ ${tr('routing.routing_and_ddos')}${S.te&&!coreTE()?'<span class="cnt red dot" aria-hidden="true"></span>':''}`,'routingOpen',{},'')}</div>`;

View file

@ -3,14 +3,14 @@ function cityPanel(c){
// Your POP's router model, as a picture left of the name (10-catalog/25-router-art.js).
const art=p?rgArt(p.rgen||0):'';
let h=`<div class="ph">${art?`<span class="rgpic big phpic">${art}</span>`:''}<div style="min-width:0"><div class="eyebrow">${REG[C.reg]} · ${esc(siteName(c,'a'))}</div><h2>${C.name}</h2>
<div class="facts"><span class="fact">${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}</span>${grantFact(c)}${latSlow(c)?`<span class="fact bad">🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}</span>`:''}${regionMult(c)>1?`<span class="fact">${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}</span>`:''}${C.kr&&scnRule('sender')?`<span class="fact">${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}</span>`:''}${colo(c)>1?`<span class="fact">${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">'+tr('city_panel.underserved_users_grow_60_faster')+'</span>':''}${ix?`<span class="fact ixf">${tr('city_panel.ix_ix',{ix:esc(ix)})}</span>`:''}${p?`<span class="fact mine">${tr('common.your_pop')}</span><button class="fact trb" data-act="trace" data-args='{"city":"${c}"}'>🔍 ${tr('common.traceroute')}</button>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
<div class="facts"><span class="fact">${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}</span>${grantFact(c)}${satFact(c)}${latSlow(c)?`<span class="fact bad">🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}</span>`:''}${regionMult(c)>1?`<span class="fact">${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}</span>`:''}${C.kr&&scnRule('sender')?`<span class="fact">${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}</span>`:''}${colo(c)>1?`<span class="fact">${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}</span>`:''}${C.reg==='AS'&&!C.cn?'<span class="fact ixf">'+tr('city_panel.underserved_users_grow_60_faster')+'</span>':''}${ix?`<span class="fact ixf">${tr('city_panel.ix_ix',{ix:esc(ix)})}</span>`:''}${p?`<span class="fact mine">${tr('common.your_pop')}</span><button class="fact trb" data-act="trace" data-args='{"city":"${c}"}'>🔍 ${tr('common.traceroute')}</button>`:''}${down?`<span class="fact down">DOWN</span>`:''}</div></div>
<button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div>`;
if(!p){
h+=`<div class="scroll">${C.note?`<p class="note" style="margin-top:0">${esc(C.note)}</p>`:''}
${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`<section><h3>${tr('city_panel.open_a_pop_here')}</h3><p class="lead">${tr('city_panel.a_pop_point_of_presence_is')}</p>
${C.ru?`<p class="why">${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}</p>`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash<popCost(c))+(q?`<p class="note">${tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}</p>`:''))(popStdQuote())}
${C.ru?`<p class="why">${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}</p>`:''}${(q=>btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)+(q?q.cost:0)),mo:fmt$(popMo(c)+(q?q.mo:0))}),'buildPop',{city:c},'pink big',S.cash<popCost(c))+(q?`<p class="note">${q.site2||q.gen?tr('pop_std.includes_the_build_standard',{list:esc(bstdPopParts({g:q.g,rt:q.rt,site2:q.site2,gen:q.gen}).join(', ')),cost:fmt$(q.cost),mo:fmt$(q.mo)}):tr('pop_std.includes_the_standard_n_model',{n:q.rt,model:esc(RG[q.g].n),cost:fmt$(q.cost),mo:fmt$(q.mo)})}</p>`:''))(popStdQuote())}
<p class="note">${tr('city_panel.or_drag_from_one_of_your')}</p></section>${opsTplHtml(c)}`}`;
h+=offersHere(c);
h+=offersHere(c)+satNoPop(c);
const trs=NETS.filter(n=>sellsAt(n,c));
const fh=FABS.filter(f=>f.cities.includes(c));
if(ix&&fh.length){if(remoteCities().includes(c))h+=ixSection(c).replace('<h3>'+tr('common.internet_exchange')+'</h3>','<h3>'+tr('city_panel.remote_peering_at_the_ix')+'</h3>');
@ -103,10 +103,11 @@ function cityPanel(c){
else h+=`<div class="btns">${NNI.map((N,i)=>portShown(i)?btn(tr('city_panel.port_port_price_mo_197d',{port:N.n,price:fmt$(N.mo)}),'buyNni',{city:c,prov:f.id,tier:i},'sm',S.cash<N.mo||!portOk(c,i)):'').join('')}</div>`;
h+=`</div></div>`;}
h+=`</section>`;}
h+=teleHtml(c);
h+=`<section><h3>${tr('city_panel.fiber_from_city',{city:C.name})}</h3><p class="lead">${tr('city_panel.drag_from_this_router_to_any')}</p>`;
if(!ls.length)h+=`<p class="empty">${tr('common.no_links_yet')}</p>`;
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+=`<div class="row"><div class="grow"><div class="nm">→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}</div><div class="meta">${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)})}</div><div class="bar ${barCls(u)}"><i style="width:${u*100}%"></i></div></div>${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}</div>`;}
h+=`<div class="row"><div class="grow"><div class="nm">→ ${CITY[o].name}${l.mult>1?' · '+tr('common.diverse'):''} ${cut?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}</div><div class="meta">${capName(l)} · ${l.km.toLocaleString()} km ${l.kind==='vxc'?tr('city_panel.virtual_circuit_via_fab',{fab:esc(FAB[l.prov].name)}):l.kind==='xp'?tr('express.city_via',{via:xpVia(l)}):l.kind==='sat'?tr('satellites.via_bird',{bird:esc(satName(l))})+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.kind==='df'?(l.own?(l.sub&&l.cname?tr('city_panel.your_own_subsea_cable_name',{name:esc(l.cname)}):tr('common.own_dark_fiber')):tr('city_panel.dark_fiber_iru'))+(l.ready>S.day?` · ${tr('city_panel.ready_in_n_d',{n:l.ready-S.day})}`:''):l.sub?tr('common.subsea'):tr('common.terrestrial')} · ${tr('common.price_mo',{price:fmt$(l.mo)})}</div><div class="bar ${barCls(u)}"><i style="width:${u*100}%"></i></div></div>${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}</div>`;}
h+=`</section>`;
if(Object.keys(S.pops).length>1)h+=`<section><h3>${tr('common.decommission')}</h3><p class="lead">${tr('city_panel.shut_this_pop_down_its_links')}</p><div class="btns">${btn(tr('city_panel.decommission_city',{city:C.name}),'decomOpen',{city:c},'ghost sm')}${btn(tr('city_panel.decommission_several_pops'),'decomOpen',{},'ghost sm')}</div></section>`;
}

View file

@ -12,6 +12,7 @@ const opsCapName=(k,v)=>v?tr('common.price_mo',{price:(OPSK[k].mo?'+':'')+fmt$(v
function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0);
return `<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${d.i}</span><div class="grow"><div class="nm">${tr(d.t)}</div><div class="meta">${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO),big:fmt$(CACHE_BIG_MO)}):''}</div></div>
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"${k}"}' aria-pressed="${on}" aria-label="${esc(tr(d.t))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
${k==='std'?`<div class="meta">${tr('bstd.now_line',{list:S.popStd?esc(bstdLine(bstd())):tr('pop_std.none')})}</div><div class="btns">${btn(tr('bstd.edit'),'bstdOpen',{},'ghost sm')}</div>`:''}
${on?`<div class="ops-p">${Object.keys(d.p).map(p=>opsSel(tr(d.p[p].l),'opsParam',{k,p},opsOpts(k,p),opsP(k,p),v=>opsVal(k,p,v))).join('')}
${d.cap?opsSel(d.mo?tr('ops.budget_running'):tr('ops.budget'),'opsCap',{k},opsCaps(k),cap,v=>opsCapName(k,v)):''}</div>
${sp||am?`<div class="meta">${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}</div>`:''}
@ -41,7 +42,8 @@ function opsReportHtml(){const O=S.ops,w=Math.floor(S.day/7),cur=O.wk&&O.wk.w===
const row=(t,x)=>`<div class="ops-rep"><div class="eyebrow">${t}</div><div>${esc(opsWeekLine(x))}</div></div>`;
return (rep?row(tr('ops.report_last'),rep):'')+(cur?row(tr('ops.report_now'),cur):'');}
// The big one-off batches (#181, #192) live here now, next to the orders that run them every week.
const opsOnceHtml=()=>`<section><h3>${tr('ops.by_hand')}</h3><p class="meta">${tr('ops.by_hand_note')}</p><div class="btns">${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}</div></section>`;
// The build standard too: its sheet works with or without an intern (targets, new POPs, everything up in one tap).
const opsOnceHtml=()=>`<section><h3>${tr('ops.by_hand')}</h3><p class="meta">${tr('ops.by_hand_note')}</p><div class="btns">${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}${pzOn()?'':btn(tr('bstd.title'),'bstdOpen',{},'sm')}</div></section>`;
// On a city without a POP: open it from the template in one tap.
function opsTplHtml(c){if(!opsHired())return '';const q=opsTplQuote(c);if(!q)return '';
return `<section><h3>${tr('ops.template')}</h3><p class="meta">${esc(tr('ops.tpl_offer',{name:opsName(),list:[tr('ops.tpl_pop'),...q.parts].join(', ')}))}</p><div class="btns">${btn(tr('ops.tpl_open',{cost:fmt$(q.cost)}),'opsNewPop',{city:c},'pink',S.cash<q.cost)}</div></section>`;}

View file

@ -0,0 +1,38 @@
/* The build standard sheet: every target as a list (two to a row on a phone), grouped POP / ports and peering / fiber;
what is below the standard and what bringing it up costs, priced without changing anything; one tap to do it now;
and the intern's order that keeps it there. A bottom sheet on phones, like the Ops sheet it sits next to. */
const BSTD_GRP=[['pop',N_('common.pops')],['port',N_('bstd.g_port')],['fiber',N_('bstd.g_fiber')]];
// Every value a target can take, in the order its list shows them; the current one is always on the list.
function bstdOpts(k){const L=BSTDK[k].v(),cur=bstd()[k];if(!L.includes(cur))L.push(cur);return L;}
function bstdVal(k,v){if(v===BSTDK[k].d&&k!=='rt')return tr('bstd.keep');
switch(k){case 'g':return RG[v].n+(rgOpen(v)?'':' '+tr('bstd.from_level',{lv:RG[v].lvl}));
case 'rt':return v>1?tr('bstd.at_least_n',{n:v}):tr('bstd.keep');
case 'site2':case 'gen':return tr('bstd.at_every_pop');
case 'lag':return tr('bstd.at_least_n',{n:v});
case 'split':return tr('bstd.both_buildings');
case 'ix':return tr('bstd.every_exchange');
case 'pni':return tr('bstd.in_n_cities',{n:v});
case 'sys':return tr('bstd.or_better',{x:DF_SYS[v].n});
case 'opt':return tr('bstd.fastest');
case 'wv':return tr('bstd.or_better',{x:LT[v].n});}
return String(v);}
const bstdShown=()=>!!$('modal')&&!$('modal').hidden&&!!$('modalCard').querySelector('[data-sheet="bstd"]');
function bstdModal(){if(!S||pzOn())return;const D=bstd(),q=bstdQuote(false),hired=opsHired(),on=hired&&S.ops.on.std;
let h=`<div data-sheet="bstd" style="display:flex;align-items:center"><div><div class="eyebrow">${tr('ops.ops')}</div><h2 style="font-size:26px">${tr('bstd.title')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('bstd.tagline')}</p>`;
for(const [g,lab] of BSTD_GRP)h+=`<section><h3>${tr(lab)}</h3><div class="ops-p">${BSTD.filter(x=>x.grp===g).map(x=>opsSel(tr(x.l),'bstdSet',{k:x.k},bstdOpts(x.k),D[x.k],v=>bstdVal(x.k,v))).join('')}</div>
<p class="note">${g==='pop'?tr('bstd.new_pops_note'):g==='port'?tr('bstd.port_note'):tr('bstd.fiber_note')}</p></section>`;
// What is below it today, and what bringing it all up costs: a quote, nothing changes until the button. A fiber whose
// line system has to wait is below it too, but not on the bill.
const n={pop:q.pops,port:q.ports,fiber:q.links},w=q.held.length;
h+=`<section><h3>${tr('bstd.below')}</h3>${q.n||w?BSTD_GRP.map(([g,lab])=>`<div class="kv"><span>${tr(lab)}</span><b>${n[g]}</b></div>`).join('')
+`<div class="kv"><span>${tr('bstd.cost_now')}</span><b>${fmt$(q.cost)}</b></div><div class="kv"><span>${tr('bstd.cost_mo')}</span><b>${tr('common.price_mo',{price:opsMo$(q.mo)})}</b></div>`
+(w?`<p class="meta">${trn('bstd.held',w)}</p>`:'')
:`<p class="meta">${S.popStd?tr('bstd.all_up'):tr('bstd.none_set')}</p>`}</section>`;
// The intern keeps it there: the order's switch and budget, or a word on hiring one.
h+=`<section><h3>${tr('ops.o_std')}</h3>${hired?`<div class="ops-o${on?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${INTERNS[S.ops.intern].i}</span><div class="grow"><div class="nm">${esc(tr('bstd.intern_keeps',{name:opsName()}))}</div><div class="meta">${tr('ops.o_std_d')}</div></div>
<button class="b sm ${on?'green':'ghost'}" data-act="opsToggle" data-args='{"k":"std"}' aria-pressed="${on}" aria-label="${esc(tr('ops.o_std'))}">${on?tr('common.on'):tr('ops.paused')}</button></div>
${on?`<div class="ops-p">${opsSel(tr('ops.budget'),'opsCap',{k:'std'},opsCaps('std'),opsCap('std'),v=>opsCapName('std',v))}</div>`:''}</div>`
:`<p class="meta">${tr('bstd.hire_note')}</p><div class="btns">${btn(tr('ops.hire_an_intern'),'opsOpen',{},'ghost sm',!opsCanHire()||!rule('clock'))}</div>`}</section>`;
h+=`<div class="btns cta">${btn(q.n?tr('bstd.apply_now',{cost:fmt$(q.cost)}):w?tr('bstd.apply_wait'):tr('bstd.apply_nothing'),'bstdApply',{},'pink',!q.n)}</div>`;
openModal(h,'ops');}

View file

@ -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)};}

View file

@ -49,7 +49,7 @@ function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE;
}finally{S=save;R=live;UI.hotMap=hot;TE_CACHE=cache;}}
function linkCheckModal(l){const t=linkTrial(l.id);if(!t)return;
const title=t.split?tr('link_panels.this_backhoe_wins'):t.loss>.01?tr('link_panels.connected_but_tight'):tr('link_panels.one_backhoe_is_not_enough');
openModal(`<div style="display:flex;align-items:center;justify-content:space-between;gap:10px"><h2>${tr('common.redundancy_check')}</h2><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div><p class="eyebrow">${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}</p><div class="inc" style="background:${t.split?'#FFE3E3':t.loss>.01?'#FFF6CF':'#EAF7EE'}"><div class="nm">${title}</div><p class="lead">${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}</p><div class="kv"><span>${tr('link_panels.additional_traffic_lost')}</span><b>${fmtG(t.loss)}</b></div></div>${t.losses.length?`<h3>${tr('common.service_affected')}</h3>${t.losses.map(x=>`<div class="kv"><span>${esc(x.name)}</span><b>−${fmtG(x.g)}</b></div>`).join('')}`:''}${t.busy.length?`<h3>${tr('link_panels.full_links_during_the_test')}</h3>${t.busy.slice(0,6).map(x=>`<div class="kv"><span>${esc(x.name)}</span><b>${fmtG(x.g)} / ${fmtG(x.cap)}</b></div>`).join('')}`:''}<p class="note">${tr('link_panels.snapshot_only_one_selected_link')}</p><div class="btns">${btn(tr('common.close'),'closeModal',{},'ghost')}</div>`,'link-check');}
openModal(`<div style="display:flex;align-items:center;justify-content:space-between;gap:10px"><h2>${tr('common.redundancy_check')}</h2><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div><p class="eyebrow">${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}</p><div class="inc" style="background:${t.split?'var(--tint-r,#FFE3E3)':t.loss>.01?'var(--tint-y,#FFF6CF)':'var(--tint-g,#EAF7EE)'}"><div class="nm">${title}</div><p class="lead">${t.split?tr('link_panels.no_alternate_backbone_path_connects'):t.loss>.01?tr('link_panels.an_alternate_path_exists_but_current'):tr('link_panels.with_current_demand_and_routing_this')}</p><div class="kv"><span>${tr('link_panels.additional_traffic_lost')}</span><b>${fmtG(t.loss)}</b></div></div>${t.losses.length?`<h3>${tr('common.service_affected')}</h3>${t.losses.map(x=>`<div class="kv"><span>${esc(x.name)}</span><b>−${fmtG(x.g)}</b></div>`).join('')}`:''}${t.busy.length?`<h3>${tr('link_panels.full_links_during_the_test')}</h3>${t.busy.slice(0,6).map(x=>`<div class="kv"><span>${esc(x.name)}</span><b>${fmtG(x.g)} / ${fmtG(x.cap)}</b></div>`).join('')}`:''}<p class="note">${tr('link_panels.snapshot_only_one_selected_link')}</p><div class="btns">${btn(tr('common.close'),'closeModal',{},'ghost')}</div>`,'link-check');}
function linkCheckControl(l){return `<section><h3>${tr('common.redundancy_check')}</h3><p class="note">${tr('link_panels.what_happens_if_this_link_fails')}</p>${btn(tr('common.check_redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}</section>`;}
// At its own POP a carrier's port always takes that carrier's traffic (25-direct-egress.js). From POPs with no port of it, the
// traffic goes to the nearest transit port, or across your network to this one. Only worth asking when something else could take it.
@ -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+=`<section><h3>${l.own?tr('common.under_construction'):tr('common.being_spliced')}</h3><div class="kv"><span>${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}</span><b>${tr('common.n_days_left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own&&l.sub?layPanel(l):l.own?`<div class="btns">${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash<crewCost(l))}${btn(trn('link_panels.all_crews_done_in_n_days_price',Math.max(1,crewFloor(l)-S.day),{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash<crewSteps(l)*crewCost(l))}</div>${!crewSteps(l)&&l.ready>S.day+1?`<p class="note">${tr('link_panels.crews_can_halve_a_build_at_most')}</p>`:''}`:''}<p class="note">${tr('link_panels.you_can_pre_install_optics_now')}</p></section>`;}
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">${tr('common.dark_6bf5')}</h3><p class="lead">${esc(inc.msg)}</p>${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${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)})}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${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))}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
${seatPanel(l)}${l.own&&l.sub?`<div class="kv"><span>${tr('common.cable_design')}</span><b>${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}</b></div>`:''}
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}</b></div><div class="kv"><span>${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}</span><b>${tr('common.price_mo',{price:fmt$(l.mo)})}</b></div><div class="kv"><span>${tr('link_panels.n_amp_huts',{n:amps})}</span><b>${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">${tr('link_panels.this_fiber_is_dark_add_optics')}</p>`:''}</section>`;
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,18 +134,21 @@ 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+=`</section><section><h3>${tr('common.line_system')}</h3><div class="kv"><span>${esc(sysD.n)}</span><b>${tr('link_panels.n_amplifiers',{n:amps})}</b></div>
<div class="kv"><span>${tr('common.regen_sites')}</span><b>${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}</b></div><p class="note">${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}</p>${l.seat?`<p class="note">${tr('broker.seat_regen_note')}</p>`:''}${l.sub&&l.own&&!l.seat?`<p class="note">${tr('link_panels.no_regen_sites_in_the_middle')}</p>`:`<div class="btns">${rg<REGEN_MAX?btn(tr('link_panels.regen_site_price',{price:fmt$(rgAdd)}),'regen',{id:l.id,d:1},'sm',S.cash<rgAdd):''}${rg?btn(tr('common.regen_site'),'regen',{id:l.id,d:-1},'ghost sm'):''}</div>`}<p class="note">${esc(sysD.blurb)}</p><div class="btns">${(()=>{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<c);})()}${pairBtn(l)}${btn(l.spares?tr('link_panels.spares_kit_on'):tr('link_panels.keep_a_spares_kit_price_mo',{price:fmt$(Math.round(150+(l.ch||[]).length*80))}),'spares',{id:l.id},l.spares?'green sm':'sm')}</div><p class="note">${tr('link_panels.spare_optics_and_amplifier_cards_on')}</p></section>`;
h+=xpDfSection(l);
{const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`<section><h3>${tr('common.redundancy')}</h3><p class="lead">${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}</p>${sib.map(x=>`<div class="row"><div class="grow"><div class="nm">${esc(capName(x))} ${linkDown(x)?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}${x.standby?' <span class="tag st">'+tr('common.standby')+'</span>':''}</div><div class="meta">${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}</div></div>${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')}<div class="btns">${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}</div></section>`;}
h+=`${trafficSection(l)}${metricSection(l)}<section>${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?`<p class="note">${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}</p>`:''}</section></div>`;
return h;
}
function offersHere(c){
const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return '';
return `<section><h3>${tr('common.offers_here')}</h3>${os.map(o=>`<div class="row${o.id===UI.offerAt?' on':''}"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}</div>`:''}${o.type==='scrub'&&!hasScrub()?`<div class="why">${tr('link_panels.needs_your_own_scrubbing_center')}</div>`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`<div class="why">${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div>${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
return `<section><h3>${tr('common.offers_here')}</h3>${os.map(o=>`<div class="row${o.id===UI.offerAt?' on':''}"><div class="grow"><div class="nm">${esc(o.name)}</div><div class="meta">${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}</div>${spotWhy(o)}${R.reach<0.99&&!BIZ_T[o.type].l2?`<div class="why">${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}</div>`:''}${o.type==='scrub'&&!hasScrub()?`<div class="why">${tr('link_panels.needs_your_own_scrubbing_center')}</div>`:''}${ip4Why(o)}${bRisk(o)}${reqList(o)}${bHas(o)?'':`<div class="why">${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}</div>`}</div>${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}</div>`).join('')}</section>`;
}
function linkPanel(id){
const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';}
if(l.kind==='vxc')return vxcPanel(l);
if(l.kind==='sat')return satPanel(l);
if(l.kind==='df')return dfPanel(l);
if(l.kind==='xp')return xpPanel(l);
const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk);
let h=`<div class="ph"><div><div class="eyebrow">${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div><div class="scroll">`;
if(cut)h+=`<section><h3 style="color:var(--bad)">${tr('common.cut_2e50')}</h3><p class="lead">${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}</p>${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
@ -169,7 +172,7 @@ function svgChart(rows,stackKeys,lines,fmtY,id){
for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`<line x1="${L}" x2="${W-Rr}" y1="${yy}" y2="${yy}" stroke="#D5DEEC" stroke-width="1"/><text x="${L-6}" y="${yy+3}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${fmtY(v)}</text>`;}
const base=rows.map(()=>0);
for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i<rows.length;i++)d+=`L${x(i)},${y(top[i])}`;for(let i=rows.length-1;i>=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=`<path d="${d}Z" fill="${EGC[k][1]}" fill-opacity=".85" stroke="#1E2640" stroke-width=".8"/>`;top.forEach((v,i)=>base[i]=v);}
for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=`<path d="${d}" fill="none" stroke="${ln.col}" stroke-width="2.5" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/>`;const last=rows[rows.length-1][ln.k]||0;g+=`<circle cx="${x(rows.length-1)}" cy="${y(last)}" r="3.5" fill="${ln.col}" stroke="#1E2640" stroke-width="1.5"/>`;}
for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=`<path d="${d}" fill="none" style="stroke:${ln.col}" stroke-width="2.5" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/>`;const last=rows[rows.length-1][ln.k]||0;g+=`<circle cx="${x(rows.length-1)}" cy="${y(last)}" r="3.5" style="fill:${ln.col}" stroke="#1E2640" stroke-width="1.5"/>`;}
g+=`<text x="${L}" y="${H-5}" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[0].d)}</text><text x="${W-Rr}" y="${H-5}" text-anchor="end" font-size="10" fill="#55608A" font-weight="700">${dateStr(rows[rows.length-1].d)}</text>`;
return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img"${id?` data-ch="${id}"`:''}>${g}</svg>`;}
// For a network you currently reach over transit: the cheapest way to move it to peering.

View file

@ -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=`<div class="ph"><div><div class="eyebrow">${tr('express.eyebrow',{km:Math.round(l.km).toLocaleString()})}</div><h2>${A} ⇄ ${B}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div><div class="scroll">`;
if(down)h+=`<section><h3 style="color:var(--bad)">${tr('common.dark_6bf5')}</h3>${xpDarkWhy(l).map(t=>`<p class="lead">${t}</p>`).join('')}</section>`;
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${trn('express.n_channels',ch.length)}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}</b></div><div class="kv"><span>${tr('express.optical_run')}</span><b>${run.toLocaleString()} km</b></div>
<p class="note">${tr('express.passes',{via:esc(xpVia(l))})}</p></section>`;
if(sp)h+=`<section><h3>${tr('express.its_fibers')}</h3>${sp.map(s=>`<div class="row"><div class="grow"><div class="nm">${xpSpanName(s)} ${linkCut(s)?'<span class="tag restrictive">'+tr('common.cut')+'</span>':''}</div><div class="meta">${xpSpanMeta(s)}</div></div>${btn(tr('common.open'),'selLink',{id:s.id},'ghost sm')}</div>`).join('')}<p class="note">${tr('express.slot_note')}</p></section>`;
if(sp){h+=`<section><h3>${tr('common.optics')}</h3>`;
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+=`<div class="row"><div class="grow"><div class="nm">${O.n}</div><div class="meta">${xpModes(k,run)}${n?` · <b>${tr('link_panels.n_lit',{n})}</b>`:''}${spn?` · ${trn('link_panels.n_spare_on_the_shelf',spn)}`:''}</div>${why?`<div class="why">${esc(why)}</div>`:''}</div>${n&&ch.length>1?btn('−','xpCh',{id:l.id,o:k,d:-1},'ghost sm'):''}${btn(`+ <small>${spn?tr('link_panels.spare_price',{price:fmt$(c)}):fmt$(c)}</small>`,'xpCh',{id:l.id,o:k,d:1},'sm',!!why||S.cash<c)}</div>`;}
h+=`<p class="note">${tr('link_panels.unplugged_optics_go_on_the_spares')}</p></section>`;}
h+=`${trafficSection(l)}${metricSection(l)}<section>${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):tr('express.tear_down'),'rmLink',{id:l.id},'ghost sm')}<p class="note">${tr('express.tear_down_note')}</p></section></div>`;
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=`<section><h3>${tr('express.title')}</h3><p class="lead">${tr('express.lead')}</p>`;
if(!rdm)h+=`<p class="why">${tr('express.needs_roadm')}</p>`;
if(on.length)h+=`<h4 class="sub4">${tr('express.riding_here')}</h4>`+on.map(x=>`<div class="row"><div class="grow"><div class="nm">${CITY[x.a].name} ⇄ ${CITY[x.b].name} ${linkDown(x)?'<span class="tag restrictive">'+tr('common.dark')+'</span>':''}</div><div class="meta">${capName(x)} · ${trn('express.n_channels',(x.ch||[]).length)} · ${tr('express.city_via',{via:esc(xpVia(x))})}</div></div>${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}</div>`).join('')+`<p class="note">${tr('express.riding_note')}</p>`;
if(tg.length)h+=`<h4 class="sub4">${tr('express.express_to')}</h4>`+tg.map(t=>{const cs=xpCities(t.from,t.sp);return `<div class="row"><div class="grow"><div class="nm">${CITY[t.from].name} → ${CITY[t.to].name}</div><div class="meta">${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(t.km).toLocaleString()})}</div></div>${btn(tr('express.plan'),'xpOpen',{a:t.from,b:t.to,via:t.sp.map(s=>s.id).join(',')},'pink sm')}</div>`;}).join('');
return h+`</section>`;}
// 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=`<p class="lead" style="margin-top:8px">${tr('express.modal_lead',{a:CITY[a].name,b:CITY[b].name})}</p>`;
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+=`<h4 class="sub4">${tr('express.via_km',{via:cs.slice(1,-1).map(c=>CITY[c].name).join(', '),km:Math.round(r.km).toLocaleString()})}</h4>
${sp.map(s=>`<div class="meta">${xpSpanName(s)} · ${xpSpanMeta(s)}</div>`).join('')}
<div class="kv"><span>${tr('express.optical_run')}</span><b>${run.toLocaleString()} km</b></div><div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:lat.toFixed(1)})}</b></div>
${old?`<p class="note">${trn('express.already',(old.ch||[]).length)}</p>`:''}
<div class="tiers">${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 `<button class="tierbtn" data-act="xpBuild" data-args="${esc(JSON.stringify({a,b,via:ids.join(','),o:k}))}"${why||S.cash<c?' disabled':''}><span class="grow"><span class="onm">${O.n}</span><span class="meta">${why?esc(why):tr('express.runs_at',{g:fmtG(g)})}</span></span><span class="pr num">${fmt$(c)}</span></button>`;}).join('')}</div>`;}
return h+`<p class="note">${tr('express.modal_note',{price:fmt$(XP_PASS)})}</p>`;}

View file

@ -0,0 +1,60 @@
// Teleports and satellite circuits on screen (#83): a POP's section, the order sheet, a circuit's panel.
const satLogo=P=>`<span class="logo" style="--c:${P.col}">${esc(P.n.slice(0,2).toUpperCase())}</span>`;
// Round trip over bird id between a and b, in whole ms.
const satRtt=(id,a,b)=>Math.round(2*satLat({bird:id,km:satKm(id,a,b)}));
const satModalHead=(eye,title)=>`<div style="display:flex;align-items:center"><div><div class="eyebrow">🛰️ ${eye}</div><h2 style="font-size:24px">${title}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>`;
// In a city's facts: its own users' traffic rides a satellite today (R.satU), and they count part of the service as bad (sfOf, R.latF).
const satFact=c=>R&&R.latF&&R.latF[c]<1&&R.satU&&R.satU[c]>1e-3?`<span class="fact bad">🛰️ ${tr('satellites.users_ride_a_satellite')}</span>`:'';
// The birds a dish at c sees, in words.
const satInView=c=>{const ids=teleSees(c);return ids.length?tr('satellites.in_view_list',{list:ids.map(id=>`<b>${esc(SATS[id].n)}</b> (${tr(SATS[id].sea)})`).join(', ')}):tr('satellites.no_bird_sees_this_city');};
// In a POP's Infra tab: its teleport (build it, what it sees, its circuits), and the teleports that can reach it.
function teleHtml(c){if(pzOn())return '';const t=teleOf(c),from=satFrom(c),open=lvl()>=SAT_ORB.geo.lv;if(!t&&!open&&!from.length)return '';
let h=`<section><h3>🛰️ ${tr('satellites.satellites')}</h3>`;
if(t){const out=S.links.filter(l=>l.kind==='sat'&&l.a===c),cf=UI.confirm==='tele:'+c,meo=teleSees(c).some(id=>SATS[id].orb==='meo');
h+=`<div class="kv"><span>${tr('satellites.teleport')}</span><b>${t>1?tr('satellites.geo_dishes_and_meo_tracking'):tr('satellites.geo_dishes')} · ${tr('common.price_mo',{price:fmt$(TPORT_MO+(t>1?TRK_MO:0))})}</b></div>
<div class="meta">${satInView(c)}</div>`;
for(const l of out){const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;
h+=`<div class="row"><div class="grow"><div class="nm">→ ${CITY[l.b].name}${l.standby?' <span class="tag st">'+tr('common.standby')+'</span>':''}</div><div class="meta">${capName(l)} · ${esc(satName(l))}${l.ready>S.day?' · '+tr('city_panel.ready_in_n_d',{n:l.ready-S.day}):''} · ${tr('common.price_mo',{price:fmt$(l.mo)})}</div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div>${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}</div>`;}
h+=`<div class="btns">${btn(tr('satellites.rent_satellite_capacity'),'satOpen',{a:c},'pink sm')}${t===1&&lvl()>=SAT_ORB.meo.lv&&meo?btn(tr('satellites.add_tracking_antennas_cost_mo',{cost:fmt$(TRK_COST),mo:fmt$(TRK_MO)}),'teleTrk',{city:c},'sm',S.cash<TRK_COST):''}${out.length?'':btn(cf?tr('satellites.really_close_it'):tr('satellites.close_the_teleport'),'teleRm',{city:c},'ghost sm')}</div>
${t===1&&lvl()<SAT_ORB.meo.lv&&meo?`<p class="note">${tr('satellites.meo_comes_at_level',{lv:SAT_ORB.meo.lv})}</p>`:''}`;}
// Before the build: what its dishes would see and reach at your level, and no button to a teleport that reaches nothing.
else if(open){const why=teleWhy(c),n=why?0:satTargets(c).filter(x=>satBirds(c,x).some(id=>lvl()>=SAT_ORB[SATS[id].orb].lv)).length;
h+=`<p class="lead">${tr('satellites.a_teleport_is_a_satellite_gateway')}</p><div class="meta">${satInView(c)}${why?'':' '+trn('satellites.n_places_in_reach',n)}</div>${why&&teleSees(c).length?`<div class="why">${esc(why)}</div>`:''}
<div class="btns">${btn(tr('satellites.build_a_teleport_cost_mo',{cost:fmt$(TPORT_COST),mo:fmt$(TPORT_MO)}),'teleBuild',{city:c},'sm',S.cash<TPORT_COST||!!why)}</div>`;}
if(from.length)h+=satReach(c,from);
return h+`</section>`;}
// Teleports that reach city c: a button each, to the order sheet.
const satReach=(c,from)=>`<p class="note">${tr('satellites.reachable_from_your_teleports',{city:CITY[c].name})}</p><div class="btns">${from.slice(0,4).map(a=>btn(tr('fiber_modals.from_city',{city:CITY[a].name}),'satOpen',{a,b:c},'ghost sm')).join('')}</div>`;
// A city without a POP of yours, that a teleport of yours reaches: a POP and a circuit in one go.
function satNoPop(c){if(pzOn()||S.pops[c])return '';const from=satFrom(c);if(!from.length)return '';
return `<section><h3>🛰️ ${tr('satellites.by_satellite')}</h3><p class="lead">${tr('satellites.no_cable_needed_a_pop_here',{city:CITY[c].name})}</p>${satReach(c,from)}</section>`;}
// The order sheet: from teleport a to b. With one end missing it lists the choices first.
function satModal(a,b){a=isCity(a)?a:null;b=isCity(b)?b:null;
if(!a&&b){const fr=satFrom(b);if(fr.length===1)a=fr[0];
else{openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.to_city',{city:CITY[b].name}))+(fr.length?fr.map(x=>`<div class="row"><div class="grow"><div class="nm">${CITY[x].name}</div><div class="meta">${tr('satellites.teleport')} · ${trn('satellites.n_birds_see_both',satBirds(x,b).length)}</div></div>${btn(tr('satellites.choose'),'satOpen',{a:x,b},'sm')}</div>`).join(''):`<p class="empty">${tr('satellites.no_teleport_reaches_city',{city:CITY[b].name})}</p>`));return;}}
if(!a||!teleOf(a))return;
if(!b){const ts=satTargets(a),mine=ts.filter(x=>S.pops[x]),more=ts.filter(x=>!S.pops[x]).slice(0,12);
const row=x=>`<div class="row"><div class="grow"><div class="nm">${CITY[x].name}</div><div class="meta">${S.pops[x]?tr('common.your_pop'):tr('satellites.new_pop_cost',{cost:fmt$(newPopCost(x))})} · ${kmBetween(a,x).toLocaleString()} km · ${trn('satellites.n_birds_see_both',satBirds(a,x).length)}</div></div>${btn(tr('satellites.choose'),'satOpen',{a,b:x},'sm')}</div>`;
openModal(satModalHead(tr('satellites.satellite_capacity'),tr('fiber_modals.from_city',{city:CITY[a].name}))+`<p class="lead" style="margin-top:8px">${tr('satellites.who_a_satellite_serves')}</p>`
+(mine.length?`<h4 class="sub4">${tr('satellites.your_pops_in_view')}</h4>`+mine.map(row).join(''):'')+(more.length?`<h4 class="sub4">${tr('satellites.more_islands_and_towns')}</h4>`+more.map(row).join(''):'')+(ts.length?'':`<p class="empty">${tr('satellites.nothing_in_view_from_here')}</p>`));return;}
const pop=S.pops[b]?0:newPopCost(b),sib=pairLinks(a,b).some(l=>l.kind!=='sat'),birds=satBirds(a,b);
const rows=birds.map(id=>{const B=SATS[id],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],why=satWhy(a,b,id);
return `<div class="row">${satLogo(P)}<div class="grow"><div class="nm">${esc(B.n)} <span class="tag">${O.n}</span></div><div class="meta">${esc(P.n)} · ${tr(B.sea)} · ${tr('satellites.ms_round_trip',{ms:satRtt(id,a,b)})} · ${trn('satellites.up_in_n_days',leadDays(O.days))}</div><div class="meta">${esc(P.blurb)}</div>${why?`<div class="why">${esc(why)}</div>`:''}
<div class="btns">${O.g.map(g=>btn(`${fmtCap(g)} <small>${tr('common.price_mo',{price:fmt$(satMo(id,g))})}</small>`,'buySat',{a,b,bird:id,g},'sm',!!why||S.cash<satMo(id,g)+pop)).join('')}</div></div></div>`;}).join('');
openModal(satModalHead(tr('satellites.satellite_capacity'),`${CITY[a].name} → ${CITY[b].name}`)+`<p class="lead" style="margin-top:8px">${tr('satellites.users_notice_geo_meo')}</p>`
+(pop?`<p class="note">${tr('satellites.no_pop_there_yet',{city:CITY[b].name,cost:fmt$(pop)})}</p>`:'')+(sib?`<p class="note">${tr('satellites.it_waits_on_standby')}</p>`:'')
+(rows||`<p class="empty">${tr('satellites.no_bird_sees_both',{a:CITY[a].name,b:CITY[b].name})}</p>`));}
// A circuit's panel: what it carries, its latency and rent, a size up or down, standby and the metric, cancel.
function satPanel(l){const B=SATS[l.bird],O=SAT_ORB[B.orb],P=SAT_PROV[B.p],load=R.load[l.id]||0,cap=capOf(l),u=cap?load/cap:0,ms=satLat(l);
let h=`<div class="ph"><div><div class="eyebrow">🛰️ ${esc(B.n)} · ${O.n} · ${esc(P.n)}</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div><div class="scroll">`;
if(l.ready>S.day){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
h+=`<section><h3>${tr('satellites.being_commissioned')}</h3><div class="kv"><span>${tr('satellites.pointing_dishes_and_testing')}</span><b>${tr('common.n_days_left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div></section>`;}
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${capName(l)}${l.standby?' · '+tr('common.standby'):''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('satellites.ms_one_way_rtt',{ms:Math.round(ms),rtt:Math.round(2*ms)})}</b></div>
<div class="kv"><span>${tr('satellites.radio_path')}</span><b>${l.km.toLocaleString()} km</b></div>
<div class="kv"><span>${tr('satellites.rent')}</span><b>${tr('common.price_mo',{price:fmt$(l.mo)})}</b></div>
<p class="note">${B.orb==='geo'?tr('satellites.geo_users_notice',{p:pct(O.loss)}):tr('satellites.meo_users_notice',{p:pct(O.loss)})} ${esc(P.blurb)}</p>
<div class="btns">${O.g.filter(g=>g!==l.g).map(g=>btn(`${g>l.g?tr('satellites.grow_to',{cap:fmtCap(g)}):tr('satellites.shrink_to',{cap:fmtCap(g)})} <small>${tr('common.price_mo',{price:fmt$(satMo(l.bird,g))})}</small>`,'satSize',{id:l.id,g},'sm',g>l.g&&S.cash<satMo(l.bird,g))).join('')}</div></section>
${trafficSection(l)}${metricSection(l)}
<section>${btn(UI.confirm===l.id?tr('common.really_cancel'):tr('common.cancel_circuit'),'rmLink',{id:l.id},'ghost sm')}</section></div>`;
return h;}

View file

@ -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<O.rg))continue;const g=optG(o,L),c=chCost(L,o);if(g&&(!b||c/g<b.c/b.g))b={o,g,c};}
if(!b)return {free,n:0,fits:false};const n=Math.ceil(cap/b.g);return {free,n,up:n*b.c,fits:n<=free};}
function leaseSwaps(){const by={};
for(const l of S.links){if(l.kind==='df'&&l.own||!S.pops[l.a]||!S.pops[l.b])continue;const k=[l.a,l.b].sort().join('|');(by[k]=by[k]||[]).push(l);}
for(const l of S.links){if(l.kind==='df'&&l.own||l.kind==='xp'||l.kind==='sat'||!S.pops[l.a]||!S.pops[l.b])continue;const k=[l.a,l.b].sort().join('|');(by[k]=by[k]||[]).push(l);}
return Object.entries(by).map(([k,ls])=>{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.

View file

@ -7,9 +7,9 @@ function renderDash(){checkLayer();
const tile=(l,v,sub)=>`<div class="tile"><div class="lbl">${l}</div><div class="val">${v}</div>${sub?`<div class="sub">${sub}</div>`:''}</div>`;
let h=`<div style="display:flex;align-items:center;gap:10px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)} · ${tierLabel()}</div><h2 style="font-size:28px">${tr('common.noc_dashboard')}</h2></div><button class="x" data-act="dashClose" aria-label="${tr('common.close')}">×</button></div>`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
<div class="dgrid">${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}</div>
<div class="dcols"><div class="panel2"><h3>${tr('dashboard.traffic_by_way_out')}</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}</div>
<div class="dcols"><div class="panel2"><h3>${tr('dashboard.traffic_by_way_out')}</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}</div>
<div class="panel2"><h3>${tr('dashboard.money_per_month')}</h3>${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}
<h3 style="margin-top:8px">${tr('dashboard.where_the_money_goes')}</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}</span><b>${tr('common.price_mo',{price:fmt$(v)})}</b></div>`).join('')}</div></div>`;
<h3 style="margin-top:8px">${tr('dashboard.where_the_money_goes')}</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.costs_row'),sat:tr('satellites.costs_row')}[k]||k}</span><b>${tr('common.price_mo',{price:fmt$(v)})}</b></div>`).join('')}</div></div>`;
const tT=(R.egT.t||0)||1;
const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0;
// The legend above the table picks which ways in count; "lost" still looks at everything the network gets.
@ -28,7 +28,7 @@ function renderDash(){checkLayer();
const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6);
if(DT==='infra')h+=`<div class="dcols" style="margin-top:12px"><div class="panel2"><h3>${tr('common.busiest_links')}</h3>${ls.length?ls.map(({l,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[l.a].name} ⇄ ${CITY[l.b].name} <span class="meta">${capName(l)} · ${linkLat(l).toFixed(1)} ms</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b>${btn(tr('common.open'),'dashLink',{id:l.id},'ghost sm')}</div>`).join(''):'<p class="empty">'+tr('common.no_links_yet')+'</p>'}</div>
<div class="panel2"><h3>${tr('common.router_load')}</h3>${rs.map(({c,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name} <span class="meta">${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b></div>`).join('')}
<h3 style="margin-top:10px">${tr('common.your_as')}</h3><div class="kv"><span>${tr('common.as_number')}</span><b>AS${S.asn}</b></div><div class="kv"><span>${tr('common.prefixes')}</span><b>${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>${tr('common.bgp_sessions')}</span><b>${R.sessions}</b></div><div class="kv"><span>${tr('common.upstreams')}</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>${tr('common.reach')}</span><b>${pct(R.reach)}</b></div><div class="kv"><span>${tr('common.customers')}</span><b>${tr('dashboard.n_businesses',{n:S.biz.length})}</b></div></div></div>`;
<h3 style="margin-top:10px">${tr('common.your_as')}</h3><div class="kv"><span>${tr('common.as_number')}</span><b>AS${S.asn}</b></div><div class="kv"><span>${tr('common.prefixes')}</span><b>${(ip4On()&&ip4Pfx())||Math.max(1,Math.ceil(Object.keys(S.pops).length/3))+' × /22'} IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>${tr('common.bgp_sessions')}</span><b>${R.sessions}</b></div><div class="kv"><span>${tr('common.upstreams')}</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>${tr('common.reach')}</span><b>${pct(R.reach)}</b></div><div class="kv"><span>${tr('common.customers')}</span><b>${tr('dashboard.n_businesses',{n:S.biz.length})}</b></div></div></div>`;
if(DT==='pops')h+=popsSection();
if(DT==='lease')h+=leaseTab();
if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);}

View file

@ -1,13 +1,14 @@
/* The NOC charts: legend entries switch a series on and off (the scale follows what is left), and hovering or
touching a chart shows every visible series on that day. View state only: UI.chartOff is never saved. */
const CHARTS={
traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'#1E2640':EGC[k][1]},
traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'var(--text)':EGC[k][1]},
mix:{stack:['c','p','ix','t'],lines:[],fmt:v=>fmtG(v),name:k=>EGC[k][0],col:k=>EGC[k][1]}, // the Traffic tab's table
money:{stack:[],lines:['rev','cost'],fmt:v=>fmt$(v),name:k=>k==='rev'?tr('common.revenue'):tr('common.costs'),col:k=>k==='rev'?'#16A866':'#FF4D5E'}
};
const chartKeys=C=>[...C.stack,...C.lines];
// The demand line's key is a dashed outline, in the line's own colour (dark ink by day, light text at night).
function chartLegend(id,label){const C=CHARTS[id],off=(UI.chartOff&&UI.chartOff[id])||{};
return `<div class="legend">${chartKeys(C).map(k=>`<button class="lg${off[k]?' off':''}" aria-pressed="${!off[k]}" data-act="chartToggle" data-args="${esc(JSON.stringify({c:id,k}))}"><i style="background:${k==='dem'?'#fff;border-style:dashed':C.col(k)}"></i>${C.name(k)}${label?label(k):''}</button>`).join('')}</div>`;}
return `<div class="legend">${chartKeys(C).map(k=>`<button class="lg${off[k]?' off':''}" aria-pressed="${!off[k]}" data-act="chartToggle" data-args="${esc(JSON.stringify({c:id,k}))}"><i style="background:${k==='dem'?`var(--paper);border-style:dashed;border-color:${C.col(k)}`:C.col(k)}"></i>${C.name(k)}${label?label(k):''}</button>`).join('')}</div>`;}
Object.assign(ACT,{
chartToggle:({c,k})=>{const C=CHARTS[c];if(!C||!chartKeys(C).includes(k))return;
const off=((UI.chartOff=UI.chartOff||{})[c]=UI.chartOff[c]||{});if(off[k])delete off[k];else off[k]=1;

View file

@ -21,7 +21,7 @@ function renderBank(){
h+=CT?`<div class="meta">${tr('bank.bank_picks_up_apr_apr_over',{bank:esc(BANKS[CT.bank].name),apr:(CT.apr*100).toFixed(1),n:CALL_MONTHS,limit:fmt$(lim)})}</div><div class="btns" style="margin-top:6px">${CALL_AMTS.map(a=>btn(fmt$(a),'callBank',{amount:a},'sm',a>lim)).join('')}</div>`:`<p class="empty">${tr('bank.get_to_an_aa_rating_and')}</p>`;}
h+=`<h3 style="font-size:18px;margin-top:14px">${tr('common.offers')}</h3>`;
if(!S.loanOffers.length)h+=`<p class="empty">${tr('bank.no_offers_right_now_banks_get')}</p>`;
for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}</div><div class="meta">${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}</div><div class="terms">${terms(o)}</div>${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(x=>x.sub).length}})}<div class="btns" style="margin-top:6px">${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}</div></div></div>`;}
for(const o of S.loanOffers){const B=BANKS[o.bank];h+=`<div class="loan"><span class="logo" style="--c:${B.col}">${initials(B)}</span><div class="grow"><div class="nm">${tr('bank.bank_offers_amount',{bank:esc(B.name),amount:fmt$(o.amount)})}</div><div class="meta">${esc(B.blurb)} · ${tr('bank.offer_ends_in_n_d',{n:o.exp-S.day})}</div><div class="terms">${terms(o)}</div>${covList({covs:o.covs,start:S.day,base:{sub:S.links.filter(seaLink).length}})}<div class="btns" style="margin-top:6px">${btn(tr('bank.take_the_money'),'takeLoan',{id:o.id},'pink')}${btn(tr('common.no_thanks'),'declineLoan',{id:o.id},'ghost sm')}</div></div></div>`;}
h+=`<h3 style="font-size:18px;margin-top:14px">${tr('common.your_loans')}</h3>`;
if(!S.loans.length)h+=`<p class="empty">${tr('bank.debt_free_your_accountant_is')}</p>`;
for(const l of S.loans){const B=BANKS[l.bank];const cost=repayCost(l,B);
@ -29,6 +29,6 @@ function renderBank(){
${B.equity?`<div class="meta">${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}</div>`:`<div class="kv"><span>${tr('common.still_owed')}</span><b>${fmt$(l.bal)}</b></div><div class="bar me"><i style="width:${Math.min(100,(1-l.bal/l.amount)*100)}%"></i></div><div class="meta">${loanLine(l)}</div>`}
${covList(l)}${l.breach>=1?`<div class="why">${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}</div>`:''}
<div class="btns" style="margin-top:6px">${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash<cost)}</div></div></div>`;}
h+=pieGovBank();
h+=pieGovBank()+ip4Bank();
if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;}
}

View file

@ -0,0 +1,22 @@
/* The bank's Address space section (#150, 33-address-space.js): what you hold and who uses it, the CGNAT ratio, your
blocks, and the transfer market. Phones: the boxes are full width, the dropdowns stack and every button row wraps. */
const ip4Pc=x=>(x*100).toFixed(1).replace(/\.0$/,'')+'%';
function ip4Bank(){if(!S||!ip4On())return '';const I=S.ip4,B=ip4Bill((R.rev&&R.rev.eyeballs)||0),u=B.u,len=ip4LenOk(UI.ip4Len)?UI.ip4Len:IP4_MAX,px=ip4Px(),full=ip4Full();
const kv=(l,v,bad)=>`<div class="kv"><span>${l}</span><b${bad?' style="color:var(--bad)"':''}>${v}</b></div>`,mo=v=>tr('common.price_mo',{price:fmt$(v)});
let h=`<section class="bank-gov bank-ip4"><h3 id="bankIp4" style="font-size:18px;margin-top:14px">🔢 ${tr('ip4.section')}</h3><p class="meta">${tr('ip4.note')}</p>`;
h+=`<div class="ops-o">${kv(tr('ip4.yours'),ip4N(u.T))}${kv(tr('ip4.business'),ip4N(u.B))}${kv(tr('ip4.homes'),u.cg?tr('ip4.homes_cgnat',{n:ip4N(u.H),p:pct(u.cg/u.H)}):ip4N(u.H))}${kv(tr('ip4.free'),ip4N(Math.max(0,u.free)),u.free<=0)}`;
if(u.over>0)h+=`<div class="why">${tr('ip4.squeezed',{p:pct(u.over),r:u.r})}</div>`;
if(B.lin>0)h+=kv(tr('ip4.leases_in'),mo(B.lin));if(B.box>=1)h+=kv(tr('ip4.cgnat_boxes'),mo(B.box));if(B.refund>=1)h+=kv(tr('ip4.refunds'),mo(B.refund));if(B.lout>0)h+=kv(tr('ip4.leases_out'),'+'+mo(B.lout));
h+=`<label class="ops-sel" style="margin-top:6px"><span>${tr('ip4.cgnat_ratio')}</span><select data-chg="ip4Nat">${IP4_NAT.map(r=>`<option value="${r}"${r===I.nat?' selected':''}>${trn('ip4.n_homes_per_address',r)}</option>`).join('')}</select></label>
<p class="meta">${tr('ip4.cgnat_note',{p:ip4Pc(IP4_ANNOY[I.nat])})}</p></div>`;
h+=`<div class="ops-o"><div class="nm">${tr('ip4.blocks')}</div>`;
for(const b of I.b){const n=ip4Sz(b.len),spare=u.free>=n,held=ip4Held(b),sure=UI.confirm===b.id;
const what=b.k==='in'?tr('ip4.leased_in_mo',{price:fmt$(b.mo||0)}):b.out?tr('ip4.leased_out_mo',{price:fmt$(b.mo||0)}):b.k==='buy'?tr('ip4.bought_on',{date:dateStr(b.d)}):tr('ip4.from_rir');
const btns=b.k==='in'?btn(tr('ip4.give_back'),'ip4Return',{id:b.id},'ghost sm',!spare):b.out?btn(tr('ip4.take_back'),'ip4Back',{id:b.id},'ghost sm')
:btn(tr('ip4.lease_out',{price:fmt$(ip4OutMo(b.len))}),'ip4Out',{id:b.id},'sm',!spare)+btn(sure?tr('ip4.really_sell',{price:fmt$(ip4Value(b.len))}):tr('ip4.sell',{price:fmt$(ip4Value(b.len))}),'ip4Sell',{id:b.id},sure?'red sm':'ghost sm',held||!spare);
// Greyed for want of room: say so (a disabled button never gets to show ip4Busy's toast).
h+=`<div class="row"><div class="grow"><div class="nm">/${b.len} · ${trn('ip4.n_addresses',n,{n:ip4N(n)})}</div><div class="meta">${what}${held&&!b.out?' · '+tr('ip4.movable_from',{date:dateStr(b.d+IP4_HOLD)}):''}</div>${!spare&&!b.out?`<div class="why">${tr('ip4.in_use')}</div>`:''}<div class="btns">${btns}</div></div></div>`;}
h+=`</div><div class="ops-o"><div class="nm">${tr('ip4.market')}</div><p class="meta">${tr('ip4.market_note',{px:fmt$(px),lin:'$'+(IP4_IN*px/IP4_PX).toFixed(2),lout:'$'+(IP4_OUT*px/IP4_PX).toFixed(2),p:pct(IP4_SELL)})}</p>
<label class="ops-sel"><span>${tr('ip4.block_size')}</span><select data-chg="ip4Pick">${Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MAX-i).map(l=>`<option value="${l}"${l===len?' selected':''}>/${l} · ${trn('ip4.n_addresses',ip4Sz(l),{n:ip4N(ip4Sz(l))})}</option>`).join('')}</select></label>
${full?`<div class="why">${tr('ip4.too_many',{n:IP4_BLK})}</div>`:''}<div class="btns">${btn(tr('ip4.buy',{price:fmt$(ip4Cost(len))}),'ip4Buy',{len},'pink sm',full||S.cash<ip4Cost(len))}${btn(tr('ip4.lease',{price:fmt$(ip4InMo(len))}),'ip4Lease',{len},'sm',full)}</div></div></section>`;
return h;}

View file

@ -22,7 +22,7 @@ function showTitle(){
${top?`<div class="btns tcont" style="margin-bottom:6px">${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}</div>`:''}
${many?slotsHtml():''}
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div>
${doorsHtml()}
${doorsHtml()}${MP_API?mpDoorHtml():''}
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
@ -43,9 +43,11 @@ function whatsNew(returning,force){
const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]];
const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'};
// The chosen preset in one line: its joke, then what actually changes.
const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)}</span>`;
const presetWhat=k=>`${esc(PRESETS[k].d)} <span class="meta">${esc(PRESETS[k].x)} ${PRESETS[k].ip4===false?tr('ip4.preset_plenty'):tr('ip4.preset_scarce')}</span>`;
// The Normal presets, one toggle each: on the title screen, and for a multiplayer session (48-multiplayer.js).
const presetBtns=pr=>`<label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p>`;
function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none';
return `<label class="f">${tr('title.pick_a_door')}</label><div class="doors">${DOORS.map(([k,i,n,d])=>`<button class="door${k===m?' on':''}" data-door="${k}" data-act="${doorAct[k]}" data-args='${k==='sandbox'||k==='normal'?`{"m":"${k}"}`:'{}'}'><i aria-hidden="true">${i}</i><b>${n}</b><span>${d}</span>${k==='puzzle'&&pzWkNew()||k==='scn'&&wsNew()?`<em class="pznew">${tr('puzzles.new_this_sunday')}</em>`:''}</button>`).join('')}</div>
<div id="doorNormal"${m==='normal'?'':' hidden'}><label class="f">${tr('title.how_much_trouble')}</label><div class="presets">${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return `<button class="preset${k===pr?' on':''}" data-preset="${k}" data-act="presetSet" data-args='{"p":"${k}"}' aria-pressed="${k===pr}"><i aria-hidden="true">${P.i}</i><b>${P.n}</b></button>`;}).join('')}</div><p class="note" id="presetWhat">${presetWhat(pr)}</p></div>
<div id="doorNormal"${m==='normal'?'':' hidden'}>${presetBtns(pr)}</div>
<div id="doorSandbox"${m==='sandbox'?'':' hidden'}><label class="f">${tr('title.chaos_in_your_sandbox')}</label><div class="chaos">${Object.entries(CHAOS).map(([k,C])=>`<button class="chs${k===ch?' on':''}" data-chaos="${k}" data-act="chaosSet" data-args='{"c":"${k}"}'><i aria-hidden="true">${C.i}</i><b>${C.n}</b><span>${C.d}</span></button>`).join('')}</div></div>
<p class="note lockn">🔒 ${tr('title.rules_are_picked_once_and_locked')}</p>`;}

View file

@ -5,7 +5,7 @@ const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?
// The network to continue: the most recent one that is not open in another window (or damaged).
function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;}
function slotLine(e){if(e.broken)return tr('slots.damaged_export_or_delete');
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);
const bits=[e.asn?'AS'+e.asn:'',e.name||e.gz?dateStr(e.day):''];if(e.mode==='scenario'&&e.scn)bits.push(esc(e.scn));else if(e.tier)bits.push(e.tier);if(MP_API&&e.mp)bits.push('🌐 '+mpShow(e.mp.slice(0,6)));
return bits.filter(Boolean).join(' · ');}
function slotRow(e,top){const busy=slotBusy(e.id),nm=esc(e.name||tr('common.unnamed_network'));
const tag=busy?`<span class="tag">${tr('slots.open_in_another_window')}</span>`:top?`<span class="tag">▶ ${tr('slots.continue')}</span>`:'';

View file

@ -0,0 +1,73 @@
/* Multiplayer on screen (89-multiplayer.js has the logic): the title screen's door, the start/join sheet, the session
panel (leaderboard, feed and chat, the code to share, the link to another device) and the HUD chip. Only ever drawn
when the build stamped MP_API. Everything another player wrote is escaped here. */
const MP_FEED_L={join:N_('mp.feed_join'),leave:N_('mp.feed_leave'),t2:N_('mp.feed_t2'),t1:N_('mp.feed_t1'),t1first:N_('mp.feed_t1first')};
const mpDoorHtml=()=>`<div class="mpdoor-row"><button class="door mpdoor" data-act="mpDoor"><i aria-hidden="true">🌐</i><b>${tr('mp.multiplayer')}</b><span>${tr('mp.door_d')}</span></button></div>`;
function mpStartHtml(){const pr=NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall';
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.multiplayer')}</div><h2 style="font-size:26px">${tr('mp.play_with_friends')}</h2></div><button class="x" data-act="mpBack" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('mp.intro')}</p>
<label class="f" for="mpName">${tr('title.name_your_network')}</label><input class="t" id="mpName" maxlength="24" value="${esc(UI.nm||'')}" autocomplete="off">
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="mpbox"><h3>${tr('mp.start_a_session')}</h3>${presetBtns(pr)}
<label class="f" for="mpTitle">${tr('mp.session_title')}</label><input class="t" id="mpTitle" maxlength="40" autocomplete="off">
<div class="btns">${btn(tr('mp.start_a_session'),'mpStart',{},'pink big mpgo')}</div></div>
<div class="mpbox"><h3>${tr('mp.join_a_session')}</h3><label class="f" for="mpCode">${tr('mp.code')}</label>
<div class="mpjoin"><input class="t" id="mpCode" maxlength="8" placeholder="K7Q-2XD" autocomplete="off" autocapitalize="characters" spellcheck="false">${btn(tr('mp.join'),'mpJoin',{},'big mpgo')}</div>
<p class="note">${tr('mp.join_note')}</p></div>
<p class="note" id="mpBusy" hidden>${tr('mp.talking')}</p>
<div class="btns cta">${btn(tr('common.back'),'mpBack',{},'ghost')}</div>`;}
function mpBusy(on){UI.mpBusy=on;document.querySelectorAll('.mpgo').forEach(b=>{b.disabled=on;});const b=$('mpBusy');if(b)b.hidden=!on;}
function mpErr(e){const st=e&&e.status;sfx('err');
toast(st===404?tr('mp.err_no_session'):st===409?tr('mp.err_full'):st===429?tr('mp.err_slow'):st===503?tr('mp.err_server_full'):st===400?tr('mp.err_refused'):tr('mp.err_offline'),'bad');}
const mpNameIn=()=>{const n=$('mpName'),v=String((n&&n.value)||UI.nm||randomNetworkName()).trim().slice(0,24)||randomNetworkName();UI.nm=v;return v;};
// The server said yes: the token goes to this browser's storage, the rest into a new game.
function mpBegin(j,nm,home,joined){const m=mpJoinOk(j);if(!m){toast(tr('mp.err_offline'),'bad');return;}
mpTokSet(m.code,m.pid,m.token);delete m.token;beginGame(nm,home,{mode:'normal',preset:m.preset,mp:{...m,joined}});}
// Called by beginGame just before its first save, which then pushes the day-0 save and the card: this player is on the
// leaderboard at once, and a link to another device works from the start.
function mpStarted(m){mpReset({day:-1,last:-1e9});mpHud();UI.mpLater={joined:!!(m&&m.joined)};}
// The code to share, with its buttons. A new Normal game asks for its charter first, on top of everything: the code
// waits until it is signed (ACT.charter), or its buttons could not be pressed.
function mpStartTell(){const b=UI.mpLater;if(!b||!mpIs())return;if(!$('modal').hidden&&$('modal').className==='charter')return;UI.mpLater=null;
const code=mpShow(S.mp.code),acts=[{l:tr('common.share'),act:'mpShare',args:{}},{l:tr('mp.session'),act:'mpOpen',args:{}}];
toast(b.joined?tr('mp.joined',{code}):tr('mp.session_live',{code}),'goal',acts);}
/* ---------- the session panel ---------- */
function mpBoardHtml(){const r=MP.roster;if(MP.gone)return `<p class="why">${tr('mp.not_in_session')}</p>`;
// Another device moved on: the toast with the choice is long gone, the choice stays here until it is made.
const st=MP.stale?`<p class="why">${tr('mp.moved_on_elsewhere')}</p><div class="btns">${btn(tr('mp.load_newer'),'mpNewer',{},'pink')}${btn(tr('mp.keep_mine'),'mpKeep',{},'')}</div>`:'';
if(st)return st;if(!r)return `<p class="note">${tr('mp.loading')}</p>`;const me=S&&S.mp&&S.mp.pid;
return mpRank(r.players).map((p,i)=>{const c=p.card,mine=p.pid===me;
const meta=c?[`AS${p.asn}`,c.t1?'Tier 1':c.tier==='t2'?'Tier 2':'Tier 3',trn('mp.n_pops',c.pops.length),fmtG(c.peak),trn('mp.n_customers',c.cust)].join(' · '):`AS${p.asn} · ${tr('mp.no_card')}`;
return `<div class="mprow${mine?' me':''}"><span class="mprk">${i+1}</span><i class="mpdot" style="background:${p.color}" aria-hidden="true"></i><div class="grow"><b>${esc(p.name)}</b>${mine?` <span class="tag">${tr('mp.you')}</span>`:''}<div class="meta">${meta}</div></div><small class="mpseen">${p.seen?slotAgo(p.seen):''}</small></div>`;}).join('');}
function mpFeedHtml(){const r=MP.roster;if(!r)return '';const f=r.feed.slice(-30).reverse();if(!f.length)return `<p class="note">${tr('mp.feed_empty')}</p>`;
const col=pid=>{const p=r.players.find(x=>x.pid===pid);return p?p.color:'#888888';};
return f.map(x=>{const who=`<b>${esc(x.name)}</b>`,t=x.k==='chat'?`${who}: ${esc(x.text)}`:tr(MP_FEED_L[x.k],{name:who});
return `<div class="mpf ${x.k}"><i class="mpdot" style="background:${col(x.pid)}" aria-hidden="true"></i><span class="grow">${t}</span><small>${x.at?slotAgo(x.at):''}</small></div>`;}).join('');}
function mpPanelHtml(){const m=S.mp,code=mpShow(m.code),link=mpLink(m);
return `<div class="mp-panel" id="mpPanel"><div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">🌐 ${tr('mp.session')} · ${esc(PRESETS[m.preset].n)}</div><h2 style="font-size:26px">${m.title?esc(m.title):tr('mp.session_code',{code})}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="mpcode"><div class="grow"><small>${tr('mp.code')}</small><b>${code}</b></div>${btn(tr('common.share'),'mpShare',{},'pink')}</div>
<p class="note">${tr('mp.share_note')}</p>
<h3>${tr('mp.leaderboard')}</h3><div class="mpboard" id="mpBoard">${mpBoardHtml()}</div>
<h3>${tr('mp.feed')}</h3><div class="mpchat"><input class="t" id="mpSay" maxlength="200" placeholder="${esc(tr('mp.say'))}" aria-label="${esc(tr('mp.say'))}" autocomplete="off">${btn(tr('mp.send'),'mpChat',{},'')}</div><div class="mpfeed" id="mpFeed">${mpFeedHtml()}</div>
${link?`<details class="mpmove"><summary>${tr('mp.move_device')}</summary><p class="note">${tr('mp.move_note')}</p><input class="t" id="mpLink" readonly value="${esc(link)}" aria-label="${esc(tr('mp.move_device'))}"><p class="why">${tr('mp.move_warn')}</p><div class="btns">${btn(tr('mp.copy_link'),'mpCopyLink',{},'')}</div></details>`:''}
<div class="btns cta">${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${btn(tr('mp.leave'),'mpLeaveAsk',{},'ghost')}</div></div>`;}
// The roster moved on: only the leaderboard and the feed are redrawn, so a chat line being typed stays.
function mpPanelUpdate(){const b=$('mpBoard'),f=$('mpFeed');if(!b||$('modal').hidden)return;b.innerHTML=mpBoardHtml();if(f)f.innerHTML=mpFeedHtml();}
// While the panel is open, the roster every 5 s; it stops by itself once the panel is gone.
function mpPoll(){clearInterval(MP.poll);MP.poll=null;if(!mpIs())return;mpRefresh();if(!window.__TUBES_TEST__)MP.poll=setInterval(mpPollTick,MP_POLL);}
function mpPollTick(){if($('modal').hidden||!$('mpPanel')||!mpIs()){clearInterval(MP.poll);MP.poll=null;return;}mpRefresh(true);}
/* The HUD chip: the session code and where you stand. A phone's top bar has no room for it (the menu has the session):
there, and on a tablet whose top bar is still too full (fitHud's last step), where you stand is a badge on the menu
button instead. Made the first time a session network is on screen. */
function mpHud(){let c=$('hMp');const on=mpIs();
if(!c){if(!on)return;c=document.createElement('button');c.className='chip mpchip hide-sm';c.id='hMp';c.dataset.act='mpOpen';
c.innerHTML='<span class="lbl" id="hMpCode"></span><span class="val num" id="hMpRank"></span>';const n=$('hNoc');n.parentNode.insertBefore(c,n.nextSibling);
const b=document.createElement('span');b.className='badge mpbadge num';b.id='hMpB';b.setAttribute('aria-hidden','true');const mb=document.querySelector('#hud .menubtn');if(mb)mb.appendChild(b);}
const b=$('hMpB');c.hidden=!on;if(b)b.hidden=!on;if(!on)return;
const r=MP.roster,i=r?mpRank(r.players).findIndex(p=>p.pid===S.mp.pid):-1,rk=i>=0?`#${i+1}/${r.players.length}`:'—';
c.setAttribute('aria-label',tr('mp.session'));c.title=tr('mp.session');c.style.borderColor=S.mp.color;
$('hMpCode').textContent=mpShow(S.mp.code);$('hMpRank').textContent='🌐 '+rk;if(b)b.textContent=i>=0?`#${i+1}`:'🌐';}
// Share text: the phone's share sheet, or the clipboard.
function mpSend(t){const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good');
if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}
try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}

View file

@ -1,14 +1,17 @@
function openLinkModal(a,b){
{const nt=noTalk(a,b);if(nt){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">${tr('common.not_happening')}</h2><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div><p class="lead" style="margin-top:8px">${tr(nt)}</p>`);return;}}
if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">${tr('link_modal.not_without_a_license')}</h2><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div><p class="lead" style="margin-top:8px">${tr('link_modal.building_into_mainland_china_needs_a',{city:CITY[cnCity(a)?a:b].name})}</p>`);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'&&l.kind!=='sat');
if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if(border)route+=`<p class="lead" style="margin-top:8px">${tr('link_modal.cross_border_circuits_into_mainland')}</p>${a==='hkg'||b==='hkg'?`<div class="seg">${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')}</div>`:`<p class="note">${tr('link_modal.premium_crossings_are_only_sold_in')}</p>`}`;
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+=`<p class="lead" style="margin-top:8px">${trn('link_modal.you_already_have_n_link_here',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}</p>
<div class="seg">${ts.length>1?ts.map((t,i)=>btn(`${i?tr('link_modal.diverse_route_n',{n:i}):tr('common.main_route')} <small>${esc(t.caps.join(', '))}${i?' · +40%':''}</small>`,'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')}</div>${ts.length>1?`<p class="note">${tr('link_modal.waves_on_the_same_route_share')}</p>`:''}`;}
const mode=UI.lmode==='df'?'df':'wave',tabs=`<div class="seg" style="margin-top:8px">${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')}</div>`;
// 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=`<div class="seg" style="margin-top:8px">${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'):''}</div>`;
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km</div><h2 style="font-size:26px">${CITY[a].name} → ${CITY[b].name}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>${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+`<p class="lead" style="margin-top:10px">${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(', ')})}</p>${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+`<p class="lead" style="margin-top:10px">${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}</p>`);return;}
if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`<p class="note" style="margin-top:8px">${landWhy(a,b)}</p>`;

View file

@ -0,0 +1,11 @@
/* The map's colours by theme (#80): the cartoon day, and a night under the same stickers (cities and markers keep
theirs; a dark outline round a white sticker reads on either). Both renderers read them when they paint: the 2D map
in drawFrame()/paintWorld(), the card in glBegin()/glFrame() (glPal()). Labels: the pill, its text and its edge.
What is only an outline turns light at night, or it would vanish into the dark land and sea: the tubes' casing
(casing) and a puzzle's stepping-stone ring (via). */
const MAP_PAL={
light:{sea:'#62CBEA',sea2:'#43AED6',wave:'rgba(255,255,255,.45)',cloud:'rgba(255,255,255,.55)',shadow:'rgba(20,90,130,.35)',sand:'#F8E6A8',land:'#9BDA6C',hill:'#86CB5B',shine:'rgba(255,255,255,.18)',coast:'#1E2640',
pill:'#FFFFFF',pillInk:'#1E2640',pillEdge:'#1E2640',halo:'rgba(255,255,255,.85)',casing:'#1E2640',via:'rgba(30,38,64,.7)'},
dark:{sea:'#173E5E',sea2:'#0B2440',wave:'rgba(160,210,255,.14)',cloud:'rgba(200,220,255,.1)',shadow:'rgba(0,0,0,.35)',sand:'#4E5440',land:'#2E5A3A',hill:'#284F31',shine:'rgba(255,255,255,.05)',coast:'#081020',
pill:'#1A2340',pillInk:'#E9EFFB',pillEdge:'#070B16',halo:'rgba(8,16,32,.85)',casing:'#A9B7D8',via:'rgba(233,239,251,.75)'}};
const MPAL=()=>THEME.dark?MAP_PAL.dark:MAP_PAL.light;

View file

@ -31,6 +31,7 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"
${seg(tr('settings.pause_on_outages_that_hurt'),'prefSet',cur('pauseIncident'),onoff('pauseIncident'),tr('settings.stops_the_game_when_a_failure'))}
${seg(tr('settings.quiet_notifications'),'prefSet',cur('quiet'),onoff('quiet'),tr('settings.only_trouble_and_milestones_pop_up'))}
<h3 class="sub4">${tr('settings.display_and_sound')}</h3>
${seg(tr('settings.theme'),'themeSet',THEME.pref,[['auto',tr('common.auto')],['light',tr('settings.light')],['dark',tr('settings.dark')]],tr('settings.auto_follows_your_device_s_light'))}
${seg(tr('common.animations'),'animSet',UI.anim||'auto',[['auto',tr('common.auto')],['on',tr('common.on')],['off',tr('common.off')]],tr('settings.auto_follows_your_device_s_reduce'))}
${seg(tr('settings.map_drawing'),'mapSet',GLX.want?'auto':'2d',[['auto',tr('common.auto')],['2d',tr('settings.always_2d')]],tr('settings.auto_draws_the_map_with_your')+(GLX.want&&!glCan()?' '+tr('settings.this_browser_cannot_so_the_map'):''))}
${seg(tr('common.sound'),'soundSet',UI.muted?'off':'on',[['on',tr('common.on')],['off',tr('common.off')]])}

Some files were not shown because too many files have changed in this diff Show more