Merge branch 'main' into unbuilt-pops
This commit is contained in:
commit
e62e4c7c98
69 changed files with 3199 additions and 145 deletions
|
|
@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows
|
|||
## [Unreleased]
|
||||
|
||||
- The NOC dashboard has a new tab listing every city where you have no POP yet, with its eyeballs, exchange and price. Sort it, filter by region, and jump to a city to build there.
|
||||
- A sales desk joins the NOC intern: from customer level 2 you can put one person in charge of sales, and each brings deals their own way. The engineer turned salesdroid books you into every network operators' meeting (you pay the ticket), brings more small and mid deals but never the huge ones, and only sells what your network can do, so their customers stay longer; they haggle badly. The shark lands bigger deals at a quarter more and takes a month of each as commission, but oversells promises your network does not keep yet, ignores technical customers and meetings, and makes peering desks want more traffic from you. Or the CEO runs sales himself, for free: a huge discounted deal on the golf course every couple of months, the odd offer you declined signed anyway, opinions, and no way to fire him short of asking the board for a VP of Sales.
|
||||
- Customers now sign contracts, and when one ends they renew, grow, haggle or leave, not always because of you (#178). Most renew at today's bandwidth price, which falls about 10% a year but rises when hardware is short; happy customers often take a bigger size, and some ask for a discount you can match, meet halfway or turn down in Deals. Others are acquired, go bust, build their own network, move away (they stay if you have a POP where they go), split their traffic with a second provider or end their project, and now and then one leaves for a stranger reason. Nothing changes during a customer's first contract, renewals in an old save are spread over the next year, your happiest long-time customers send you referrals, and the NOC dashboard shows customers won and lost each month and why.
|
||||
- Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities.
|
||||
- The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts.
|
||||
|
|
@ -14,8 +15,14 @@ All notable changes to this project are documented here. The project follows
|
|||
- Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in.
|
||||
- Clean traffic that a scrubbing center sends back to a customer under attack no longer shows as DDoS junk on your backbone links; a link now lists it as scrubbed clean traffic, so a small flood no longer looks like hundreds of gigabits of junk (#289).
|
||||
- Alien waves you rent out on your dark fiber are now priced against the fiber itself: a wave costs a share of what leasing and lighting that fiber would cost the buyer, and each wave sold between the same two cities goes a little cheaper than the last. A route sold out to its market now earns a few times its lease, not dozens, and contracts already signed keep their price (#203).
|
||||
- Leasing a dark fiber pair now costs about half as much again ($600 plus $1.50 per km a month, amplifiers as before), so it pays off once you light a couple of 400G waves on it. Leases you already hold keep their price (#203).
|
||||
- Extra crews can now cut a fiber build on land to half its planned time at most, since permits and rights of way do not speed up; the button shows the day it would be done (#203).
|
||||
- A link ordered by typing both ends (the AI tools) can no longer end in a city the map does not show (#203).
|
||||
- The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same, and zoomed out the card draws the coastlines with fewer points where the extra detail was smaller than a pixel, which helps phones most. Settings › Map drawing › Always 2D keeps the old drawing and frees what the graphics card held, and browsers without WebGL2 or without a usable graphics card keep it on their own. If the graphics card stops for a moment (on a phone, switching apps can do that), the map is drawn in 2D until it is back, and stays in 2D for a game where it keeps failing. (#281)
|
||||
- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the map also draws far fewer shapes each frame. (#281)
|
||||
- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in: its land picture now stays on the graphics card instead of being sent to it again on every frame. Firefox on Android keeps the old way, which avoids its drawing glitches. (#281)
|
||||
- Settings › Viewport info is now Diagnostic info: besides your screen's size, it shows how the map is drawn (by the graphics card or in 2D, and why) and how fast, ready to copy into a bug report. (#281)
|
||||
|
||||
## [2.9.1] — 2026-11-04
|
||||
|
||||
- Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten.
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
|
|||
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
|
||||
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
|
||||
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
|
||||
| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) |
|
||||
| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers) |
|
||||
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
|
||||
| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service |
|
||||
| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |
|
||||
|
|
@ -41,7 +41,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
|
|||
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), 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, `draw()`, the world layer, cities, input and click delegation |
|
||||
| `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 |
|
||||
| `99-loop.js` | `frame()` and `boot()` |
|
||||
|
||||
`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone.
|
||||
|
|
@ -75,6 +75,7 @@ Development runs on `npm run dev` (assembles the development page on every reque
|
|||
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
|
||||
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
|
||||
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
|
||||
| `scripts/gpu-bench.js`, `scripts/lib/gpu-bench-client.js` | `npm run bench:gpu -- --save FILE`: the map in your own browser on your own graphics card, 2D against WebGL, scenario by scenario; the table shows in the page and in the terminal |
|
||||
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client, headless or in the player's own tab ([MCP.md](MCP.md)) |
|
||||
| `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab |
|
||||
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@
|
|||
"page": "node scripts/lib/page.js",
|
||||
"serve": "npm run build && npx --yes serve@14.2.4 _site",
|
||||
"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"
|
||||
},
|
||||
|
|
|
|||
56
scripts/gpu-bench.js
Normal file
56
scripts/gpu-bench.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
#!/usr/bin/env node
|
||||
// The map's speed on your own graphics card, 2D against WebGL, in the browser you play in:
|
||||
//
|
||||
// npm run bench:gpu -- --save path/to/save.json (an exported save, or a plain one; default: the perf fixture)
|
||||
//
|
||||
// then open the printed address in Chrome, Edge or Firefox and press Start. Headless benchmarks (npm run perf) draw the
|
||||
// canvas in software, so they cannot say what a GPU does; this one runs where the GPU is. Each scenario plays a few
|
||||
// seconds with the 2D map and with the WebGL tubes, the table shows in the page, and the server prints it here when the
|
||||
// run ends. Options: --port N (8090), --secs N per scenario (6), --host 0.0.0.0 to open it from a phone on your network,
|
||||
// --out FILE to also write the table there. Under WSL, the Windows browser reaches http://localhost:PORT as it is.
|
||||
// In the address: ?only=gl or ?only=2d (one renderer), ?scen=x1-mid,pan (some scenarios), ?dpr=2 (a 4K screen's
|
||||
// pixels on a smaller one), ?auto (start at once). The game's clock keeps running: incidents do not pause it.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; };
|
||||
const PORT = +opt('port', 8090), HOST = opt('host', 'localhost'), SECS = +opt('secs', 6), OUT = opt('out', null);
|
||||
const SAVE = path.resolve(opt('save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')));
|
||||
const SITE = path.join(ROOT, 'site');
|
||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json' };
|
||||
|
||||
// An exported save is {app, version, S}; a plain one is S itself.
|
||||
const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })();
|
||||
const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8');
|
||||
const page = () => assemble().html.replace('</body>', `<script>window.__BENCH__=${JSON.stringify({ secs: SECS })};</script><script>${client}</script></body>`);
|
||||
|
||||
http.createServer((req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
try {
|
||||
if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); }
|
||||
if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); }
|
||||
if (url.pathname === '/__bench/results' && req.method === 'POST') {
|
||||
let body = ''; req.on('data', (c) => { body += c; }); req.on('end', () => {
|
||||
try { const r = JSON.parse(body); console.log('\n' + r.md + '\n'); if (OUT) { fs.writeFileSync(OUT, r.md + '\n\n```json\n' + JSON.stringify(r, null, 1) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results', e); }
|
||||
res.writeHead(204); res.end(); });
|
||||
return;
|
||||
}
|
||||
// The service worker would cache this page over the real one: none here.
|
||||
if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); }
|
||||
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
|
||||
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); }
|
||||
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
|
||||
fs.createReadStream(file).pipe(res);
|
||||
} catch (e) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); res.end(String(e && e.stack || e)); }
|
||||
}).listen(PORT, HOST, () => {
|
||||
const s = JSON.parse(save).S;
|
||||
console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`);
|
||||
console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`);
|
||||
if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`);
|
||||
console.log('Ctrl+C to stop.');
|
||||
});
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
// stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what
|
||||
// routing gave, as strings the driver compares.
|
||||
(() => {
|
||||
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
|
||||
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'mapSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
|
||||
'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu',
|
||||
'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare',
|
||||
// Leave the game or open what is not this game: the title screen, menus of other modes, AI helpers that fetch.
|
||||
|
|
@ -177,5 +177,6 @@
|
|||
if (keep) UI.rkR = R;
|
||||
return { a, b, c };
|
||||
};
|
||||
window.__fz = { direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen };
|
||||
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 };
|
||||
})();
|
||||
|
|
|
|||
155
scripts/lib/gpu-bench-client.js
Normal file
155
scripts/lib/gpu-bench-client.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// The benchmark panel that scripts/gpu-bench.js adds to the game page. It runs in your own browser, so it measures your
|
||||
// graphics card: the save is loaded, then each scenario plays for a few seconds with the 2D map and with the WebGL
|
||||
// tubes, and the frames are timed as they really reach the screen (requestAnimationFrame). Results show in the panel
|
||||
// and go back to the terminal that started the server. Nothing is saved: the page's save() is switched off.
|
||||
// What each number is: the frame rate and p95 frame are the cadence of requestAnimationFrame (what you see); draw() is
|
||||
// the main thread's time to build and submit a frame (CPU only: the card may still be drawing when it returns); GPU is
|
||||
// the card's own time for a WebGL frame, from EXT_disjoint_timer_query_webgl2 where the browser offers it (read back
|
||||
// frames later, never waited for, and thrown away when the card says its timing was disturbed).
|
||||
(() => {
|
||||
const CFG = window.__BENCH__ || {}, QS = new URLSearchParams(location.search);
|
||||
const SECS = CFG.secs || 6, WARM = CFG.warm ?? 1500, SETTLE = CFG.settleMs || 5000, SEED = CFG.seed || 777;
|
||||
const SCEN = [
|
||||
{ id: 'x1-far', label: 'Map at x1, zoomed out (0.6)', speed: 1, z: 0.6 },
|
||||
{ id: 'x1-mid', label: 'Map at x1 (zoom 1.4)', speed: 1, z: 1.4 },
|
||||
{ id: 'x1-near', label: 'Map at x1, zoomed in (3.2)', speed: 1, z: 3.2 },
|
||||
{ id: 'pan', label: 'Panning at x1 (zoom 1.4)', speed: 1, z: 1.4, pan: true },
|
||||
{ id: 'x8', label: 'Game at x8 (zoom 1.4)', speed: 8, z: 1.4 },
|
||||
];
|
||||
// ?only=gl or ?only=2d runs one renderer; ?scen=x1-mid,pan runs only those scenarios; ?reps=3 runs each one three
|
||||
// times (the renderers take turns going first, and the table shows the medians); ?dpr=2 below.
|
||||
const ONLY = QS.get('only'), PICK = QS.get('scen'), REPS = Math.max(1, Math.min(9, +QS.get('reps') || CFG.reps || 1));
|
||||
if (PICK) SCEN.splice(0, SCEN.length, ...SCEN.filter((s) => PICK.split(',').includes(s.id)));
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const box = document.createElement('div');
|
||||
box.style.cssText = 'position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:100000;background:rgba(30,38,64,.94);color:#fff;font:13px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:12px;max-width:94vw;max-height:80vh;overflow:auto;box-shadow:0 6px 24px rgba(0,0,0,.35)';
|
||||
box.innerHTML = '<b>Series of Tubes · GPU benchmark</b><div id="bst" style="margin:6px 0">Loading…</div><button id="bgo" disabled style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#22C47A;color:#fff;font-weight:700;cursor:pointer">Start</button> <button id="bcp" hidden style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#FF4F9A;color:#fff;font-weight:700;cursor:pointer">Copy results</button><div id="bout"></div>';
|
||||
const st = (t) => { box.querySelector('#bst').textContent = t; };
|
||||
let SAVE = null, MD = '', TRIAL = 0;
|
||||
|
||||
// Ends what the last trial left running before the next one starts, so nothing of one lands on the other: the clock
|
||||
// stops, its frame callback is cancelled (measure() does that, and TRIAL turns away one already queued), and a day
|
||||
// still being routed in the worker is waited for. Its answer runs dayPost() on the old save; one that never comes is
|
||||
// dropped (rwDone() ignores an answer to no job). Then the clock's leftovers are cleared.
|
||||
async function settle() {
|
||||
UI.speed = 0; TRIAL++;
|
||||
const t0 = performance.now();
|
||||
while (RW.job && performance.now() - t0 < SETTLE) await sleep(10);
|
||||
if (RW.job) { console.warn('[bench] the route worker did not answer: its day is dropped'); RW.job = null; }
|
||||
acc = 0; animT = 0;
|
||||
}
|
||||
// The save again, with the same random numbers every time (S.rng makes Math.random() follow it, as in a scenario).
|
||||
function fresh() {
|
||||
S = migrate(JSON.parse(SAVE)); S.rng = SEED; UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim();
|
||||
closeModal(); compute(); renderAll();
|
||||
const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y;
|
||||
}
|
||||
async function reset() { await settle(); fresh(); }
|
||||
const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0);
|
||||
async function measure(sc, hz, r) {
|
||||
await reset(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null;
|
||||
const trial = TRIAL;
|
||||
await sleep(WARM);
|
||||
const fr = [], dr = [], gpu = [], pend = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x, raf = 0, glF = 0, flatF = 0, disjoint = 0;
|
||||
// The card's own time, where the browser lets us read it: a timer around each WebGL draw(), read when it is ready.
|
||||
const gl = r === 'gl' ? GLX.gl : null; let tq = null; try { tq = gl && gl.getExtension('EXT_disjoint_timer_query_webgl2'); } catch (e) { /* none */ }
|
||||
const poll = () => { while (pend.length) { const x = pend[0]; if (!gl.getQueryParameter(x, gl.QUERY_RESULT_AVAILABLE)) break; pend.shift();
|
||||
const ns = gl.getQueryParameter(x, gl.QUERY_RESULT); gl.deleteQuery(x); if (gl.getParameter(tq.GPU_DISJOINT_EXT)) disjoint++; else gpu.push(ns / 1e6); } };
|
||||
const D0 = draw;
|
||||
draw = function (t) { let x = null; if (tq && GLX.gl === gl && pend.length < 16) { x = gl.createQuery(); gl.beginQuery(tq.TIME_ELAPSED_EXT, x); }
|
||||
const a = performance.now();
|
||||
try { return D0(t); } finally { dr.push(performance.now() - a); if (x) { gl.endQuery(tq.TIME_ELAPSED_EXT); pend.push(x); } if (GLX.shown) glF++; else flatF++; } };
|
||||
let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ }
|
||||
// Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are.
|
||||
const t00 = performance.now(), slow = [];
|
||||
const tick = (t) => { if (stop || trial !== TRIAL) return;
|
||||
if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true;
|
||||
if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; }
|
||||
if (tq) poll();
|
||||
raf = requestAnimationFrame(tick); };
|
||||
raf = requestAnimationFrame(tick);
|
||||
const t0 = performance.now(); await sleep(SECS * 1000); stop = true; cancelAnimationFrame(raf); const T = (performance.now() - t0) / 1000;
|
||||
draw = D0; if (po) po.disconnect(); UI.speed = 0;
|
||||
if (tq) { poll(); for (const x of pend) gl.deleteQuery(x); }
|
||||
const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), g = gpu.slice().sort((a, b) => a - b), budget = 1000 / hz;
|
||||
return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1),
|
||||
dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1),
|
||||
drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2),
|
||||
gpuMs: g.length ? +(g.reduce((a, x) => a + x, 0) / g.length).toFixed(2) : null, gpuP95: g.length ? +q(g, 0.95).toFixed(2) : null, gpuN: g.length, disjoint,
|
||||
// Which map really drew the frames: a WebGL run that fell back to 2D (or a 2D run on the card) is not what it says.
|
||||
drawn: glF && flatF ? 'mixed' : glF ? 'gl' : flatF ? '2d' : 'none', glFrames: glF, flatFrames: flatF,
|
||||
daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow };
|
||||
}
|
||||
// Several runs of one scenario: the median of each number; the flags and the stutters of all of them.
|
||||
function merge(ms) {
|
||||
if (ms.length === 1) return ms[0];
|
||||
const o = {}, med = (a) => { const s = a.slice().sort((x, y) => x - y); return s[(s.length - 1) >> 1]; };
|
||||
for (const k of Object.keys(ms[0])) {
|
||||
const v = ms.map((m) => m[k]);
|
||||
o[k] = k === 'slow' ? v.flat() : k === 'drawn' ? [...new Set(v)].join('+') : typeof v[0] === 'boolean' ? v.some(Boolean) : v.every((x) => typeof x === 'number') ? med(v) : v[0];
|
||||
}
|
||||
o.runs = ms.length; return o;
|
||||
}
|
||||
async function refresh() {
|
||||
const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); });
|
||||
a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]);
|
||||
}
|
||||
function table(res, env) {
|
||||
const gpu = res.gl && SCEN.some((sc) => res.gl[sc.id] && res.gl[sc.id].gpuMs != null);
|
||||
const rows = SCEN.map((sc) => { const a = res['2d'] && res['2d'][sc.id], b = res.gl && res.gl[sc.id];
|
||||
const f = (m, k, u = '') => (m && m[k] != null ? `${m[k]}${u}` : '-');
|
||||
return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |${gpu ? ` ${f(b, 'gpuMs', ' ms')} |` : ''}`; });
|
||||
// A run is only what it says if its frames were drawn by the map it names.
|
||||
const off = []; for (const [r, want] of [['2d', '2d'], ['gl', 'gl']]) for (const sc of SCEN) { const m = res[r] && res[r][sc.id]; if (m && m.drawn !== want && m.drawn !== 'none') off.push(`${sc.label} (${r === 'gl' ? 'WebGL' : '2D'}: ${m.flatFrames} frames in 2D, ${m.glFrames} on the card)`); }
|
||||
return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}${env.reps > 1 ? ` · median of ${env.reps} runs` : ''}`, '',
|
||||
`| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |${gpu ? ' WebGL GPU |' : ''}`,
|
||||
`|---|--:|--:|--:|--:|--:|--:|${gpu ? '--:|' : ''}`, ...rows,
|
||||
'', `<sub>fps and p95 frame: requestAnimationFrame's cadence (p95: the slowest 5% of frames). draw(): CPU time on the main thread to build and submit a frame; the card may still be working when it returns, so it is not the cost of drawing.${gpu ? ' WebGL GPU: the card\'s own time per frame (EXT_disjoint_timer_query_webgl2).' : ' No GPU timer in this browser: the card\'s own time is not measured.'}${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}</sub>`,
|
||||
...(off.length ? ['', `⚠️ Not drawn by the map they name: ${off.join('; ')}.`] : [])].join('\n');
|
||||
}
|
||||
async function run() {
|
||||
const go = box.querySelector('#bgo'); go.disabled = true;
|
||||
save = () => {};
|
||||
// An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything.
|
||||
autoPause = () => false;
|
||||
await reset(); st('Measuring the screen refresh…'); await sleep(500);
|
||||
const hz = await refresh();
|
||||
const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links`, reps: REPS };
|
||||
mapGl(false, false);
|
||||
const rends = (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY), all = {};
|
||||
// Scenario by scenario, both renderers in turn, the first one changing every time: neither always runs on a cold or
|
||||
// a tired browser.
|
||||
let n = 0;
|
||||
for (let rep = 0; rep < REPS; rep++) for (const [i, sc] of SCEN.entries()) for (const r of (rep + i) % 2 ? rends.slice().reverse() : rends) {
|
||||
mapGl(r === 'gl', false); n++;
|
||||
st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label}${REPS > 1 ? ` · run ${rep + 1}/${REPS}` : ''} (${SECS}s, ${n}/${REPS * SCEN.length * rends.length})… keep this tab in front`);
|
||||
const m = await measure(sc, hz, r); ((all[r] = all[r] || {})[sc.id] = all[r][sc.id] || []).push(m); if (m.hidden) env.invalid = true;
|
||||
}
|
||||
const res = { '2d': null, gl: null };
|
||||
for (const r of Object.keys(all)) { res[r] = {}; for (const id of Object.keys(all[r])) res[r][id] = merge(all[r][id]); }
|
||||
mapGl(want0, false); await reset();
|
||||
MD = table(res, env);
|
||||
st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).');
|
||||
box.querySelector('#bout').innerHTML = '<pre style="white-space:pre-wrap;font:11px/1.35 ui-monospace,monospace;margin:8px 0 0">' + MD.replace(/&/g, '&').replace(/</g, '<') + '</pre>';
|
||||
box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
|
||||
try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
|
||||
}
|
||||
// tests/gpu-bench.test.js drives the pieces without the panel.
|
||||
if (CFG.expose) { window.__bench = { settle, reset, measure, merge, table, setSave: (s) => { SAVE = s; } }; return; }
|
||||
addEventListener('load', async () => {
|
||||
document.body.appendChild(box);
|
||||
while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
|
||||
// A software renderer is measured too here (the game itself keeps the 2D map on one); the table names the renderer.
|
||||
GLX.soft = true;
|
||||
// ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
|
||||
const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
|
||||
await sleep(800);
|
||||
try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
|
||||
if (SAVE === 'null') { st('The save file has no game in it.'); return; }
|
||||
const runs = SCEN.length * (ONLY ? 1 : 2) * REPS;
|
||||
st(`Ready: ${SCEN.length} scenarios × ${ONLY ? 1 : 2} renderers${REPS > 1 ? ` × ${REPS}` : ''}, about ${Math.ceil(runs * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
|
||||
const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
|
||||
box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
|
||||
if (/[?&]auto\b/.test(location.search)) go.onclick();
|
||||
});
|
||||
})();
|
||||
|
|
@ -98,7 +98,10 @@ function playGame(pages, seed, opts = {}) {
|
|||
if (!div) compare('start');
|
||||
|
||||
// A screen's buttons on both pages; the same list or a divergence.
|
||||
const screen = (w) => { const [a, b] = both('screen', w); same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
|
||||
// Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have.
|
||||
let baseActs = null;
|
||||
const screen = (w) => { const [a, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
|
||||
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
|
||||
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
|
||||
// Answer whatever window opened, a few levels deep, then close it.
|
||||
const modal = (bias) => {
|
||||
|
|
|
|||
|
|
@ -98,7 +98,10 @@ md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its
|
|||
const slow = base ? slowIn(res, 2) : [];
|
||||
const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
|
||||
for (const p of PROFILES) {
|
||||
md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.\n\n` + table(browser.profiles[p.key], 2 * p.rate);
|
||||
// The map row is the whole frame, up to a pixel read back from the surface that drew it; say which one that was.
|
||||
const mp = browser.profiles[p.key].maps, mapName = (m) => (!m || !m.length ? 'no map' : m.map((x) => (x === 'gl' ? 'WebGL' : '2D canvas')).join(' then '));
|
||||
const drew = mp ? ` The map was drawn with ${base ? `${mapName(mp.base)} (base) and ${mapName(mp.head)} (this PR)` : mapName(mp.head)}; its row waits for that surface to finish.` : '';
|
||||
md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.${drew}\n\n` + table(browser.profiles[p.key], 2 * p.rate);
|
||||
if (base) slow.push(...slowIn(browser.profiles[p.key], 2 * p.rate).map((l) => `${l} (Chromium ${p.key})`));
|
||||
}
|
||||
if (base) {
|
||||
|
|
|
|||
|
|
@ -36,10 +36,15 @@ async function openPage(browser, profile, file, save, errors) {
|
|||
// One run of a workload, timed inside the page so the round trip to Node does not count. Garbage is collected
|
||||
// first, so a run never pays for the one before it (its own garbage still costs it, as in the game).
|
||||
// The browser leaves layout and canvas drawing for the next frame, so code that changes the DOM or draws the map
|
||||
// would look free: each run ends by forcing both (reading a size, and one pixel back from the map canvas).
|
||||
// would look free: each run ends by forcing both (reading a size, and one pixel back from the surface the map was
|
||||
// last drawn on: the WebGL canvas when the card drew it, which waits for the card to finish, else the 2D canvas).
|
||||
// A run also says which map drew (gl, 2d, or none when it drew nothing).
|
||||
const time = async (k, body) => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(([k, body]) => {
|
||||
const F = window.__fx || (window.__fx = {}); const f = F[k] || (F[k] = new Function(body)); const map = document.getElementById('map').getContext('2d');
|
||||
const t = performance.now(); f(); void document.documentElement.offsetHeight; map.getImageData(0, 0, 1, 1); return performance.now() - t; }, [k, body]); };
|
||||
const G = typeof GLX === 'object' ? GLX : null, px = window.__px || (window.__px = new Uint8Array(4));
|
||||
const t = performance.now(); f(); void document.documentElement.offsetHeight;
|
||||
const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1);
|
||||
return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); };
|
||||
return { ctx, time };
|
||||
}
|
||||
|
||||
|
|
@ -54,15 +59,18 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) {
|
|||
for (const p of PROFILES) {
|
||||
const h = await openPage(hb, p, head, save, errors), b = base ? await openPage(bb, p, base, save, errors) : null;
|
||||
const res = out.profiles[p.key] = {};
|
||||
// Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both).
|
||||
const maps = res.maps = { head: new Set(), base: new Set() };
|
||||
for (const [k, , body] of metrics) {
|
||||
const H = [], B = [];
|
||||
const H = [], B = [], go = async (v, into, m) => { const r = await v.time(k, body); into.push(r.ms); if (k === 'map') m.add(r.map); };
|
||||
for (const v of [h, b].filter(Boolean)) { await v.time(k, body); await v.time(k, body); } // warm up
|
||||
for (let i = 0; i < runs; i++) {
|
||||
// Alternate who goes first, like the jsdom runs.
|
||||
if (b && i % 2) { B.push(await b.time(k, body)); H.push(await h.time(k, body)); } else { H.push(await h.time(k, body)); if (b) B.push(await b.time(k, body)); }
|
||||
if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); }
|
||||
}
|
||||
res[k] = { head: median(H), base: b ? median(B) : null, samples: { head: H.map((x) => +x.toFixed(1)), base: b ? B.map((x) => +x.toFixed(1)) : null } };
|
||||
}
|
||||
res.maps = { head: [...maps.head], base: b ? [...maps.base] : null };
|
||||
await h.ctx.close(); if (b) await b.ctx.close();
|
||||
}
|
||||
} finally { await hb.close(); if (bb) await bb.close(); }
|
||||
|
|
|
|||
|
|
@ -1614,7 +1614,6 @@
|
|||
"common.vendor_tac":"Hersteller-TAC",
|
||||
"common.venus":"Venus",
|
||||
"common.via_rs":"über RS",
|
||||
"common.viewport_info":"Ansichtsinfo",
|
||||
"common.vigilante":"Selbstjustiz",
|
||||
"common.walk_away":"Aussteigen",
|
||||
"common.wave_lease":"Wave-Miete",
|
||||
|
|
@ -3904,6 +3903,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules}: Die Regeln sind für dieses Netz festgelegt.",
|
||||
"rules.the_real_thing_your_pager_has":"Das echte Spiel. Dein Pager hat Meinungen.",
|
||||
"rules.your_pager_never_sleeps":"Dein Pager schläft nie.",
|
||||
"sales.ask_vp":"Beim Vorstand einen VP Sales beantragen · {cost}",
|
||||
"sales.at_desk":"{name} leitet den Vertrieb",
|
||||
"sales.ceo_d":"Kostenlos, und überzeugt davon. Alle paar Monate unterschreibt er auf dem Golfplatz einen Riesendeal mit 30 % Rabatt, oft mit einem Versprechen, das niemand geprüft hat, und ab und zu ein Angebot, das du abgelehnt hast. Hat Meinungen. Kann nicht entlassen werden.",
|
||||
"sales.ceo_golf":"Der CEO hat {name} auf dem Golfplatz unterschrieben: {bw} in {city} für {price}/Monat, 30 % unter Liste.",
|
||||
"sales.ceo_n":"Der CEO, der besser verkauft als alle",
|
||||
"sales.ceo_override":"Du hast {name} abgelehnt, aber der CEO hatte schon eingeschlagen. Jetzt sind sie Kunde.",
|
||||
"sales.ceo_promised":"Er hat auch versprochen: {req}.",
|
||||
"sales.ceo_s":"der CEO",
|
||||
"sales.ceo_say_airport":"Gerade gelandet. Nichts unterschrieben, aber beim Lounge-WLAN hatte ich ein sehr gutes Gefühl.",
|
||||
"sales.ceo_say_blockchain":"Haben wir mal überlegt, die Routingtabelle auf eine Blockchain zu legen?",
|
||||
"sales.ceo_say_golf":"Die besten Deals passieren am neunten Loch. Das NOC sollte mehr Golf spielen.",
|
||||
"sales.ceo_say_mbps":"Warum verkaufen wir Gigabit? Megabit klingt nach mehr.",
|
||||
"sales.ceo_say_napkin":"Ich habe den nächsten Deal auf einer Serviette kalkuliert. Die Technik kann die Details klären.",
|
||||
"sales.ceo_say_synergy":"Wir verkaufen keine Bandbreite, wir verkaufen Synergie. Schreibt das auf die Website.",
|
||||
"sales.ceo_says":"Der CEO: „{say}“",
|
||||
"sales.ceo_took_over":"{name} hat den Vertrieb persönlich übernommen. Er ist sicher, dass er besser verkauft als alle.",
|
||||
"sales.commission":"{name} hat unterschrieben. Provision für den Hai: {cost}.",
|
||||
"sales.desk":"Vertrieb",
|
||||
"sales.eng_booked":"{name} hat dich für {conf} in {city} angemeldet ({cost}). Das Badge liegt schon bereit.",
|
||||
"sales.eng_d":"War Netzwerkingenieur und hat jetzt ein Badge von jeder NOG. Meldet dich zu jeder an (das Ticket zahlst du), bringt viele kleine und mittlere Deals, aber nie die richtig großen, und verkauft nur, was das Netz kann, also bleiben die Kunden. Die Nerds lieben Dave. Verhandelt schlecht.",
|
||||
"sales.eng_n":"Der Ingenieur, jetzt Salesdroide",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} hat den Schreibtisch geräumt. Der Vertrieb ist frei.",
|
||||
"sales.hire_sales":"Vertrieb einstellen",
|
||||
"sales.hired":"{name} ist jetzt im Vertrieb. Rechne mit Deals in diesem Stil.",
|
||||
"sales.intro":"Eine Person leitet den Vertrieb. Jede holt Deals auf ihre Art, und die Kunden, die sie abschließt, erinnern sich daran, wenn ihr Vertrag ausläuft.",
|
||||
"sales.let_ceo":"Den CEO machen lassen",
|
||||
"sales.locked":"Der Vertrieb öffnet ab Kundenstufe {lv}.",
|
||||
"sales.one_at_a_time":"Immer nur eine Person: Lass sie gehen, um jemand anderen einzustellen.",
|
||||
"sales.pitch":"Eine Person im Vertrieb holt Deals auf ihre eigene Art. Such sie aus.",
|
||||
"sales.shark_d":"Holt die größten Deals zu einem Viertel mehr und kassiert einen Monat jedes Deals als Provision. Verkauft zu viel: Die Hälfte kommt mit einem Versprechen, das dein Netz noch nicht hält, und diese Kunden gehen früher. Ignoriert die Nerds: keine technischen Kunden, keine Meetings, und Peering-Desks wollen ein Viertel mehr Verkehr von dir. Gewinnt die meisten Verhandlungen.",
|
||||
"sales.shark_n":"Der Hai",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"Der VP Sales hat angefangen, und der CEO ist zurück bei der Strategie. Der Vertrieb ist frei: Stell jemanden ein.",
|
||||
"sales.vp_asked":"Der Vorstand hat zugestimmt, nach dem Mittagessen. Ein VP Sales fängt in {n} Tagen an; bis dahin verkauft der CEO weiter.",
|
||||
"sales.vp_coming":"Ein VP Sales übernimmt in {n} Tagen.",
|
||||
"save.cash_in_the_bank":"{cash} auf der Bank",
|
||||
"save.import_failed_err":"<b>Import fehlgeschlagen.</b><br>{err}",
|
||||
"save.load_name":"{name} laden?",
|
||||
|
|
@ -3995,12 +4030,16 @@
|
|||
"settings.agent_api":"Agent-API",
|
||||
"settings.agent_relay_connected":"Agenten-Relay verbunden: Jetzt kann ein Tool dieses Spiel in diesem Tab spielen.",
|
||||
"settings.agent_s_clock":"Uhr des Agenten",
|
||||
"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_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.diagnostic_info":"Diagnoseinfos",
|
||||
"settings.display_and_sound":"Anzeige und Ton",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"Zum Melden von Layout-Fehlern: zeigt, was dein Bildschirm dem Spiel mitteilt.",
|
||||
"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.map_drawing":"Kartendarstellung",
|
||||
"settings.n_min":"{n} Min.",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Nur Ärger und Meilensteine poppen auf; alles andere landet still im NOC-Log. In Best Effort standardmäßig an.",
|
||||
|
|
@ -4013,6 +4052,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.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.",
|
||||
"share_card.build_the_internet_one_tube_at":"Bau das Internet, eine Röhre nach der anderen",
|
||||
|
|
|
|||
|
|
@ -1612,7 +1612,6 @@
|
|||
"common.vendor_tac":"TAC del fabricante",
|
||||
"common.venus":"Venus",
|
||||
"common.via_rs":"vía RS",
|
||||
"common.viewport_info":"Información del viewport",
|
||||
"common.vigilante":"Justiciero",
|
||||
"common.walk_away":"Marcharse",
|
||||
"common.wave_lease":"Alquiler de onda",
|
||||
|
|
@ -3902,6 +3901,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules}: las reglas están fijadas para esta red.",
|
||||
"rules.the_real_thing_your_pager_has":"El juego de verdad. Tu busca tiene opiniones.",
|
||||
"rules.your_pager_never_sleeps":"Tu busca no duerme nunca.",
|
||||
"sales.ask_vp":"Pedir al consejo un VP de Ventas · {cost}",
|
||||
"sales.at_desk":"{name} lleva las ventas",
|
||||
"sales.ceo_d":"Gratis, y convencido. Cada par de meses firma un trato enorme en el campo de golf con un 30 % de descuento, a menudo con una promesa que nadie comprobó, y de vez en cuando firma una oferta que tú rechazaste. Tiene opiniones. No se le puede despedir.",
|
||||
"sales.ceo_golf":"El CEO firmó a {name} en el campo de golf: {bw} en {city} por {price}/mes, un 30 % por debajo de tarifa.",
|
||||
"sales.ceo_n":"El CEO, que vende mejor que nadie",
|
||||
"sales.ceo_override":"Rechazaste a {name}, pero el CEO ya había dado la mano. Ahora son clientes.",
|
||||
"sales.ceo_promised":"También prometió: {req}.",
|
||||
"sales.ceo_s":"el CEO",
|
||||
"sales.ceo_say_airport":"Acabo de aterrizar. No he firmado nada, pero el Wi-Fi de la sala VIP me dio muy buena espina.",
|
||||
"sales.ceo_say_blockchain":"¿Hemos pensado en poner la tabla de rutas en una blockchain?",
|
||||
"sales.ceo_say_golf":"Los mejores tratos se cierran en el hoyo nueve. El NOC debería jugar más al golf.",
|
||||
"sales.ceo_say_mbps":"¿Por qué vendemos gigabits? Megabits suena a más.",
|
||||
"sales.ceo_say_napkin":"He calculado el próximo trato en una servilleta. Ingeniería puede resolver los detalles.",
|
||||
"sales.ceo_say_synergy":"No vendemos ancho de banda, vendemos sinergia. Ponedlo en la web.",
|
||||
"sales.ceo_says":"El CEO: «{say}»",
|
||||
"sales.ceo_took_over":"{name} se ha hecho cargo de las ventas en persona. Está seguro de que vende mejor que nadie.",
|
||||
"sales.commission":"{name} firmó. Comisión para el tiburón: {cost}.",
|
||||
"sales.desk":"Ventas",
|
||||
"sales.eng_booked":"{name} te apuntó a {conf} en {city} ({cost}). Ya tiene la acreditación.",
|
||||
"sales.eng_d":"Era ingeniero de redes y ahora tiene la acreditación de cada NOG. Te apunta a todas (la entrada la pagas tú), trae muchos tratos pequeños y medianos pero nunca los grandes de verdad, y solo vende lo que la red puede hacer, así que los clientes se quedan. Los nerds adoran a Dave. Negocia fatal.",
|
||||
"sales.eng_n":"El ingeniero convertido en vendedroide",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} ha vaciado su mesa. Ventas está libre.",
|
||||
"sales.hire_sales":"Contratar ventas",
|
||||
"sales.hired":"{name} se unió a ventas. Espera tratos a su estilo.",
|
||||
"sales.intro":"Una persona lleva las ventas. Cada una trae tratos a su manera, y los clientes que firma lo recuerdan cuando les toca renovar.",
|
||||
"sales.let_ceo":"Dejar que lo lleve el CEO",
|
||||
"sales.locked":"Ventas se abre en el nivel de clientes {lv}.",
|
||||
"sales.one_at_a_time":"Solo una a la vez: despídela para contratar a otra.",
|
||||
"sales.pitch":"Una persona de ventas trae tratos a su manera. Elige quién.",
|
||||
"sales.shark_d":"Consigue los tratos más grandes a un cuarto más, y se lleva un mes de cada trato de comisión. Vende de más: la mitad llega con una promesa que tu red aún no cumple, y esos clientes se van antes. Ignora a los nerds: nada de clientes técnicos ni de reuniones, y los equipos de peering te piden un cuarto más de tráfico. Gana casi todas las negociaciones.",
|
||||
"sales.shark_n":"El tiburón",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"El VP de Ventas ya empezó, y el CEO ha vuelto a la estrategia. Ventas está libre: contrata a alguien.",
|
||||
"sales.vp_asked":"El consejo aceptó, después de comer. Un VP de Ventas empieza en {n} días; hasta entonces el CEO sigue vendiendo.",
|
||||
"sales.vp_coming":"Un VP de Ventas toma el relevo en {n} días.",
|
||||
"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}?",
|
||||
|
|
@ -3993,12 +4028,16 @@
|
|||
"settings.agent_api":"API de agentes",
|
||||
"settings.agent_relay_connected":"Relay de agentes conectado: ahora una herramienta puede jugar esta partida en esta pestaña.",
|
||||
"settings.agent_s_clock":"Reloj del agente",
|
||||
"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_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.diagnostic_info":"Información de diagnóstico",
|
||||
"settings.display_and_sound":"Pantalla y sonido",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"Para informar de fallos de diseño: muestra lo que tu pantalla le dice al juego.",
|
||||
"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.map_drawing":"Dibujo del mapa",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Solo aparecen los problemas y los hitos; todo lo demás va en silencio al registro del NOC. Activado por defecto en Best Effort.",
|
||||
|
|
@ -4011,6 +4050,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.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.",
|
||||
"share_card.build_the_internet_one_tube_at":"Construye internet, un tubo a la vez",
|
||||
|
|
|
|||
|
|
@ -1612,7 +1612,6 @@
|
|||
"common.vendor_tac":"TAC du constructeur",
|
||||
"common.venus":"Vénus",
|
||||
"common.via_rs":"via RS",
|
||||
"common.viewport_info":"Infos viewport",
|
||||
"common.vigilante":"Justicier",
|
||||
"common.walk_away":"Laisser tomber",
|
||||
"common.wave_lease":"Location de longueur d’onde",
|
||||
|
|
@ -3902,6 +3901,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules} : les règles sont verrouillées pour ce réseau.",
|
||||
"rules.the_real_thing_your_pager_has":"Le vrai jeu. Ton bipeur a des opinions.",
|
||||
"rules.your_pager_never_sleeps":"Ton bipeur ne dort jamais.",
|
||||
"sales.ask_vp":"Demander un VP Ventes au conseil · {cost}",
|
||||
"sales.at_desk":"{name} gère les ventes",
|
||||
"sales.ceo_d":"Gratuit, et convaincu. Tous les deux mois, il signe un énorme contrat sur le terrain de golf à -30 %, souvent avec une promesse que personne n'a vérifiée, et de temps en temps une offre que vous aviez refusée. A des avis sur tout. Impossible à licencier.",
|
||||
"sales.ceo_golf":"Le PDG a signé {name} sur le terrain de golf : {bw} à {city} pour {price}/mois, 30 % sous le tarif.",
|
||||
"sales.ceo_n":"Le PDG, qui vend mieux que personne",
|
||||
"sales.ceo_override":"Vous avez refusé {name}, mais le PDG avait déjà topé. C'est maintenant un client.",
|
||||
"sales.ceo_promised":"Il a aussi promis : {req}.",
|
||||
"sales.ceo_s":"le PDG",
|
||||
"sales.ceo_say_airport":"Je viens d'atterrir. Rien signé, mais j'ai eu un très bon pressentiment avec le Wi-Fi du salon.",
|
||||
"sales.ceo_say_blockchain":"Avons-nous pensé à mettre la table de routage sur une blockchain ?",
|
||||
"sales.ceo_say_golf":"Les meilleurs contrats se signent au neuvième trou. Le NOC devrait jouer plus au golf.",
|
||||
"sales.ceo_say_mbps":"Pourquoi vendre des gigabits ? Des mégabits, ça fait plus.",
|
||||
"sales.ceo_say_napkin":"J'ai chiffré le prochain contrat sur une serviette. L'ingénierie réglera les détails.",
|
||||
"sales.ceo_say_synergy":"Nous ne vendons pas de la bande passante, nous vendons de la synergie. Mettez ça sur le site.",
|
||||
"sales.ceo_says":"Le PDG : « {say} »",
|
||||
"sales.ceo_took_over":"{name} a pris les ventes en main personnellement. Il est sûr de vendre mieux que personne.",
|
||||
"sales.commission":"{name} a signé. Commission du requin : {cost}.",
|
||||
"sales.desk":"Service commercial",
|
||||
"sales.eng_booked":"{name} vous a inscrit à {conf} à {city} ({cost}). Le badge est déjà prêt.",
|
||||
"sales.eng_d":"Ancien ingénieur réseau, il a un badge de chaque NOG. Il vous inscrit à toutes (vous payez le billet), apporte beaucoup de petits et moyens contrats mais jamais les très gros, et ne vend que ce que le réseau sait faire : les clients restent. Les geeks adorent Dave. Il négocie mal.",
|
||||
"sales.eng_n":"L'ingénieur devenu commercial-droïde",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} a vidé son bureau. Le service commercial est libre.",
|
||||
"sales.hire_sales":"Recruter un commercial",
|
||||
"sales.hired":"{name} rejoint le service commercial. Attendez-vous à des contrats dans son style.",
|
||||
"sales.intro":"Une seule personne gère les ventes. Chacune apporte des contrats à sa façon, et les clients qu'elle signe s'en souviennent à l'échéance.",
|
||||
"sales.let_ceo":"Laisser le PDG s'en charger",
|
||||
"sales.locked":"Le service commercial ouvre au niveau clients {lv}.",
|
||||
"sales.one_at_a_time":"Une seule à la fois : laissez-la partir pour en recruter une autre.",
|
||||
"sales.pitch":"Un commercial apporte des contrats à sa façon. Choisissez qui.",
|
||||
"sales.shark_d":"Décroche les plus gros contrats un quart plus cher, et prend un mois de chaque contrat en commission. Survend : la moitié arrive avec une promesse que votre réseau ne tient pas encore, et ces clients partent plus tôt. Ignore les geeks : pas de clients techniques, pas de NOG, et les équipes peering vous demandent un quart de trafic en plus. Gagne la plupart des négociations.",
|
||||
"sales.shark_n":"Le requin",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"Le VP Ventes a pris son poste, et le PDG est retourné à la stratégie. Le service commercial est libre : recrutez quelqu'un.",
|
||||
"sales.vp_asked":"Le conseil a dit oui, après le déjeuner. Un VP Ventes arrive dans {n} jours ; d'ici là, le PDG continue de vendre.",
|
||||
"sales.vp_coming":"Un VP Ventes prend le relais dans {n} jours.",
|
||||
"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} ?",
|
||||
|
|
@ -3993,12 +4028,16 @@
|
|||
"settings.agent_api":"API agent",
|
||||
"settings.agent_relay_connected":"Relais pour agents connecté : un outil peut maintenant jouer cette partie dans cet onglet.",
|
||||
"settings.agent_s_clock":"Horloge de l'agent",
|
||||
"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_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.diagnostic_info":"Infos de diagnostic",
|
||||
"settings.display_and_sound":"Affichage et son",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"Pour signaler des bugs de mise en page : montre ce que ton écran dit au jeu.",
|
||||
"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.map_drawing":"Dessin de la carte",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Seuls les problèmes et les étapes s'affichent ; tout le reste va discrètement dans le journal du NOC. Activé par défaut en Best Effort.",
|
||||
|
|
@ -4011,6 +4050,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.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.",
|
||||
"share_card.build_the_internet_one_tube_at":"Construis Internet, un tube à la fois",
|
||||
|
|
|
|||
|
|
@ -1612,7 +1612,6 @@
|
|||
"common.vendor_tac":"TAC del vendor",
|
||||
"common.venus":"Venere",
|
||||
"common.via_rs":"via RS",
|
||||
"common.viewport_info":"Info viewport",
|
||||
"common.vigilante":"Giustiziere",
|
||||
"common.walk_away":"Lascia perdere",
|
||||
"common.wave_lease":"Affitto della wave",
|
||||
|
|
@ -3902,6 +3901,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules}: le regole sono bloccate per questa rete.",
|
||||
"rules.the_real_thing_your_pager_has":"Il gioco vero. Il tuo cercapersone ha delle opinioni.",
|
||||
"rules.your_pager_never_sleeps":"Il tuo cercapersone non dorme mai.",
|
||||
"sales.ask_vp":"Chiedi al consiglio un VP vendite · {cost}",
|
||||
"sales.at_desk":"{name} gestisce le vendite",
|
||||
"sales.ceo_d":"Gratis, e convinto. Ogni paio di mesi firma un contratto enorme sul campo da golf con il 30% di sconto, spesso con una promessa che nessuno ha controllato, e ogni tanto firma un'offerta che avevi rifiutato. Ha opinioni. Non si può licenziare.",
|
||||
"sales.ceo_golf":"Il CEO ha firmato {name} sul campo da golf: {bw} a {city} per {price}/mese, il 30% sotto listino.",
|
||||
"sales.ceo_n":"Il CEO, che vende meglio di chiunque",
|
||||
"sales.ceo_override":"Hai rifiutato {name}, ma il CEO aveva già stretto la mano. Ora sono clienti.",
|
||||
"sales.ceo_promised":"Ha anche promesso: {req}.",
|
||||
"sales.ceo_s":"il CEO",
|
||||
"sales.ceo_say_airport":"Appena atterrato. Non ho firmato niente, ma il Wi-Fi della lounge mi ha dato ottime sensazioni.",
|
||||
"sales.ceo_say_blockchain":"Abbiamo pensato di mettere la tabella di routing su una blockchain?",
|
||||
"sales.ceo_say_golf":"I contratti migliori si chiudono alla nona buca. Il NOC dovrebbe giocare più a golf.",
|
||||
"sales.ceo_say_mbps":"Perché vendiamo gigabit? I megabit sembrano di più.",
|
||||
"sales.ceo_say_napkin":"Ho fatto il prezzo del prossimo contratto su un tovagliolo. L'ingegneria sistemerà i dettagli.",
|
||||
"sales.ceo_say_synergy":"Non vendiamo banda, vendiamo sinergia. Mettetelo sul sito.",
|
||||
"sales.ceo_says":"Il CEO: «{say}»",
|
||||
"sales.ceo_took_over":"{name} ha preso in mano le vendite di persona. È sicuro di vendere meglio di chiunque.",
|
||||
"sales.commission":"{name} ha firmato. Provvigione per lo squalo: {cost}.",
|
||||
"sales.desk":"Ufficio vendite",
|
||||
"sales.eng_booked":"{name} ti ha iscritto a {conf} a {city} ({cost}). Ha già il badge.",
|
||||
"sales.eng_d":"Era un ingegnere di rete e ora ha il badge di ogni NOG. Ti iscrive a tutti (il biglietto lo paghi tu), porta tanti contratti piccoli e medi ma mai quelli davvero grandi, e vende solo ciò che la rete sa fare, così i clienti restano. I nerd adorano Dave. Tratta male.",
|
||||
"sales.eng_n":"L'ingegnere diventato venditore-droide",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} ha svuotato la scrivania. L'ufficio vendite è libero.",
|
||||
"sales.hire_sales":"Assumi un venditore",
|
||||
"sales.hired":"{name} è entrato nelle vendite. Aspettati contratti nel suo stile.",
|
||||
"sales.intro":"Una persona alla volta gestisce le vendite. Ognuna porta contratti a modo suo, e i clienti che firma se ne ricordano alla scadenza.",
|
||||
"sales.let_ceo":"Lascia fare al CEO",
|
||||
"sales.locked":"L'ufficio vendite apre al livello clienti {lv}.",
|
||||
"sales.one_at_a_time":"Uno alla volta: lascialo andare per assumerne un altro.",
|
||||
"sales.pitch":"Un venditore porta contratti a modo suo. Scegli chi.",
|
||||
"sales.shark_d":"Porta i contratti più grandi a un quarto in più, e si prende un mese di ogni contratto come provvigione. Vende troppo: metà arriva con una promessa che la tua rete non mantiene ancora, e quei clienti se ne vanno prima. Ignora i nerd: niente clienti tecnici, niente incontri, e i peering desk ti chiedono un quarto di traffico in più. Vince quasi tutte le trattative.",
|
||||
"sales.shark_n":"Lo squalo",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"Il VP vendite ha iniziato, e il CEO è tornato alla strategia. L'ufficio vendite è libero: assumi qualcuno.",
|
||||
"sales.vp_asked":"Il consiglio ha detto sì, dopo pranzo. Un VP vendite inizia tra {n} giorni; fino ad allora il CEO continua a vendere.",
|
||||
"sales.vp_coming":"Un VP vendite subentra tra {n} giorni.",
|
||||
"save.cash_in_the_bank":"{cash} in cassa",
|
||||
"save.import_failed_err":"<b>Importazione fallita.</b><br>{err}",
|
||||
"save.load_name":"Caricare {name}?",
|
||||
|
|
@ -3993,12 +4028,16 @@
|
|||
"settings.agent_api":"API per agenti",
|
||||
"settings.agent_relay_connected":"Relay per agenti collegato: ora uno strumento può giocare questa partita in questa scheda.",
|
||||
"settings.agent_s_clock":"Orologio dell'agente",
|
||||
"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_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.diagnostic_info":"Info di diagnostica",
|
||||
"settings.display_and_sound":"Schermo e audio",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.",
|
||||
"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.map_drawing":"Disegno della mappa",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Compaiono solo i problemi e i traguardi; tutto il resto finisce in silenzio nel registro del NOC. Attivo di default in Best Effort.",
|
||||
|
|
@ -4011,6 +4050,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.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.",
|
||||
"share_card.build_the_internet_one_tube_at":"Costruisci internet, un tubo alla volta",
|
||||
|
|
|
|||
|
|
@ -1612,7 +1612,6 @@
|
|||
"common.vendor_tac":"TAC do fabricante",
|
||||
"common.venus":"Vênus",
|
||||
"common.via_rs":"via RS",
|
||||
"common.viewport_info":"Info do viewport",
|
||||
"common.vigilante":"Justiceiro",
|
||||
"common.walk_away":"Desistir",
|
||||
"common.wave_lease":"Aluguel da wave",
|
||||
|
|
@ -3902,6 +3901,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules}: as regras estão travadas para esta rede.",
|
||||
"rules.the_real_thing_your_pager_has":"O jogo de verdade. O seu pager tem opiniões.",
|
||||
"rules.your_pager_never_sleeps":"O seu pager nunca dorme.",
|
||||
"sales.ask_vp":"Pedir ao conselho um VP de Vendas · {cost}",
|
||||
"sales.at_desk":"{name} cuida das vendas",
|
||||
"sales.ceo_d":"De graça, e convicto. A cada dois meses fecha um contrato enorme no campo de golfe com 30% de desconto, muitas vezes com uma promessa que ninguém conferiu, e de vez em quando assina uma oferta que você recusou. Tem opiniões. Não pode ser demitido.",
|
||||
"sales.ceo_golf":"O CEO fechou com {name} no campo de golfe: {bw} em {city} por {price}/mês, 30% abaixo da tabela.",
|
||||
"sales.ceo_n":"O CEO, que vende melhor que ninguém",
|
||||
"sales.ceo_override":"Você recusou {name}, mas o CEO já tinha apertado a mão. Agora são clientes.",
|
||||
"sales.ceo_promised":"Ele também prometeu: {req}.",
|
||||
"sales.ceo_s":"o CEO",
|
||||
"sales.ceo_say_airport":"Acabei de pousar. Não assinei nada, mas tive um ótimo pressentimento com o Wi-Fi da sala VIP.",
|
||||
"sales.ceo_say_blockchain":"Já pensamos em colocar a tabela de rotas numa blockchain?",
|
||||
"sales.ceo_say_golf":"Os melhores negócios saem no nono buraco. O NOC devia jogar mais golfe.",
|
||||
"sales.ceo_say_mbps":"Por que vendemos gigabits? Megabits parecem mais.",
|
||||
"sales.ceo_say_napkin":"Fiz o preço do próximo contrato num guardanapo. A engenharia resolve os detalhes.",
|
||||
"sales.ceo_say_synergy":"Não vendemos banda, vendemos sinergia. Coloquem isso no site.",
|
||||
"sales.ceo_says":"O CEO: “{say}”",
|
||||
"sales.ceo_took_over":"{name} assumiu as vendas pessoalmente. Tem certeza de que vende melhor que ninguém.",
|
||||
"sales.commission":"{name} assinou. Comissão do tubarão: {cost}.",
|
||||
"sales.desk":"Vendas",
|
||||
"sales.eng_booked":"{name} inscreveu você no {conf} em {city} ({cost}). O crachá já está pronto.",
|
||||
"sales.eng_d":"Era engenheiro de redes e agora tem o crachá de cada NOG. Inscreve você em todas (o ingresso é por sua conta), traz muitos negócios pequenos e médios, mas nunca os realmente grandes, e só vende o que a rede consegue entregar, então os clientes ficam. Os nerds adoram o Dave. Negocia mal.",
|
||||
"sales.eng_n":"O engenheiro que virou vendedroide",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} esvaziou a mesa. Vendas está livre.",
|
||||
"sales.hire_sales":"Contratar vendas",
|
||||
"sales.hired":"{name} entrou em vendas. Espere negócios no estilo dele.",
|
||||
"sales.intro":"Uma pessoa por vez cuida das vendas. Cada uma traz negócios do seu jeito, e os clientes que ela fecha lembram disso quando o contrato vence.",
|
||||
"sales.let_ceo":"Deixar o CEO cuidar",
|
||||
"sales.locked":"Vendas abre no nível de clientes {lv}.",
|
||||
"sales.one_at_a_time":"Uma por vez: dispense para contratar outra.",
|
||||
"sales.pitch":"Uma pessoa de vendas traz negócios do jeito dela. Escolha quem.",
|
||||
"sales.shark_d":"Fecha os maiores negócios por um quarto a mais, e leva um mês de cada contrato de comissão. Vende demais: metade chega com uma promessa que sua rede ainda não cumpre, e esses clientes saem mais cedo. Ignora os nerds: nada de clientes técnicos nem de encontros, e as equipes de peering pedem um quarto a mais de tráfego. Ganha quase todas as negociações.",
|
||||
"sales.shark_n":"O tubarão",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"O VP de Vendas começou, e o CEO voltou para a estratégia. Vendas está livre: contrate alguém.",
|
||||
"sales.vp_asked":"O conselho aprovou, depois do almoço. Um VP de Vendas começa em {n} dias; até lá o CEO continua vendendo.",
|
||||
"sales.vp_coming":"Um VP de Vendas assume em {n} dias.",
|
||||
"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}?",
|
||||
|
|
@ -3993,12 +4028,16 @@
|
|||
"settings.agent_api":"API para agentes",
|
||||
"settings.agent_relay_connected":"Relay de agentes ligado: agora uma ferramenta pode jogar este jogo nesta aba.",
|
||||
"settings.agent_s_clock":"Relógio do agente",
|
||||
"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_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.diagnostic_info":"Informações de diagnóstico",
|
||||
"settings.display_and_sound":"Tela e som",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"Para reportar bugs de layout: mostra o que sua tela informa ao jogo.",
|
||||
"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.map_drawing":"Desenho do mapa",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Só aparecem problemas e marcos; todo o resto vai em silêncio para o registro do NOC. Ligado por padrão no Best Effort.",
|
||||
|
|
@ -4011,6 +4050,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.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.",
|
||||
"share_card.build_the_internet_one_tube_at":"Construa a internet, um tubo de cada vez",
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ const API_DOMAINS={
|
|||
metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']},
|
||||
egress:{table:'PREF',kind:'key'},
|
||||
routeMode:{table:'RT',kind:'key'},
|
||||
salesPersona:{table:'SALES',kind:'key'},
|
||||
site:{kind:'enum',values:['a','b','ab']},
|
||||
step:{kind:'enum',values:[1,-1]},
|
||||
connKind:{kind:'enum',values:['t','p','ix','c','nni']},
|
||||
|
|
|
|||
|
|
@ -218,6 +218,12 @@ const API_CMD={
|
|||
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.'},
|
||||
decline:{args:[['id','entityId']],
|
||||
doc:'Throw an offer away.'},
|
||||
salesHire:{args:[['id','salesPersona']],
|
||||
doc:'Put one salesperson at the sales desk: eng (engineer turned salesdroid: books every NOG at the usual ticket price, more small and mid deals, never the huge ones, customers stay longer), shark (bigger deals at higher prices plus a month of commission, oversells promises, no nerdy customers, peering desks want more traffic) or ceo (free, signs huge discounted deals on the golf course, sometimes signs what you declined, cannot be fired). One at a time; from customer level 2.'},
|
||||
salesFire:{args:[],confirm:'double',
|
||||
doc:'Let the salesperson go (not the CEO: ask the board for a VP of Sales instead).'},
|
||||
salesVp:{args:[],
|
||||
doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'},
|
||||
renewMatch:{args:[['id','entityId']],watch:['biz.#id'],
|
||||
doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'},
|
||||
renewMeet:{args:[['id','entityId']],watch:['biz.#id'],
|
||||
|
|
@ -469,6 +475,7 @@ const API_VIEW={
|
|||
keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'},
|
||||
routingOpen:{args:[],doc:'Open the Routing & DDoS window: 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.'},
|
||||
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.'},
|
||||
pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'},
|
||||
|
|
@ -560,6 +567,6 @@ const API_DENY={
|
|||
start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
|
||||
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
|
||||
slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
|
||||
animSet:'prefs',langSet:'prefs',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',vpSet:'prefs',
|
||||
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
|
||||
};
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ const API_STATE_DOC={
|
|||
nni:{type:'array',doc:'Fabric ports: city, provider, tier.'},
|
||||
biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'},
|
||||
offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'},
|
||||
sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them.'},
|
||||
cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'},
|
||||
done:{type:'map',doc:'Goals landed, by goal id → day.'},
|
||||
ach:{type:'map',doc:'Badges earned this game, by badge id → day.'},
|
||||
|
|
|
|||
|
|
@ -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={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,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={SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,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};}),
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ const OPT={
|
|||
tp16:{n:'Sienna WaveMagic 1.6T',g:1600,cost:70000,reach:4000,modes:[[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:2,lvl:4,sys:'roadm',blurb:tr('dark_fiber.big_shelf_big_reach_big_invoice')},
|
||||
tp32:{n:'Sienna WaveMagic 3.2T',g:3200,cost:130000,reach:1500,modes:[[3200,1500],[1600,4000],[1200,5500],[800,7000],[400,12000]],rg:4,lvl:8,sys:'roadm',blurb:tr('dark_fiber.twice_the_wavemagic_full_speed_only')},
|
||||
};
|
||||
const dfLeaseMo=km=>Math.round(400+km*1.0);
|
||||
// A leased fiber pair, per month. Dear enough that it pays off at a couple of 400G waves, as dark fiber does (#203);
|
||||
// a lease already signed keeps its price (l.mo).
|
||||
const dfLeaseMo=km=>Math.round(600+km*1.5);
|
||||
const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build'));
|
||||
const dfBuildDays=km=>leadDays(Math.round(120+km*0.25)),IRU_DAYS=30;
|
||||
const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY));
|
||||
|
|
|
|||
77
src/game/60-features/38-sales-desk.js
Normal file
77
src/game/60-features/38-sales-desk.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/* ---------- The sales desk: one salesperson, three kinds you meet in this industry ----------
|
||||
Next to the NOC intern, you can put one person in charge of sales. Each brings deals in their own way and leaves
|
||||
their mark on the customers they sign (b.by), which the contracts (75-customer-lifecycle.js) remember at renewal.
|
||||
- The engineer turned salesdroid goes to every network operators' meeting (you pay the ticket), brings plenty of
|
||||
small and mid deals and never the huge ones, and only sells what the network can do: their customers stay longer,
|
||||
the nerdy ones most of all. They haggle badly.
|
||||
- The shark brings the biggest deals at a higher price and takes a commission, but oversells: many come with a
|
||||
promise your network does not keep yet. Ignores the nerds: no technical customers, no meetings, and peering desks
|
||||
want more traffic from you. Wins most haggles.
|
||||
- The CEO runs sales himself, for free: now and then a huge deal signed on the golf course at a discount, with a
|
||||
promise nobody checked, the odd declined offer signed anyway, and opinions. He cannot be fired; the board can
|
||||
be asked for a VP of Sales instead.
|
||||
Every roll is a hash of the day and the deal, so a game without a salesperson keeps its random stream. */
|
||||
const SALES={
|
||||
eng:{i:'🤓',n:N_('sales.eng_n'),s:N_('sales.eng_s'),d:N_('sales.eng_d'),mo:9000},
|
||||
shark:{i:'🦈',n:N_('sales.shark_n'),s:N_('sales.shark_s'),d:N_('sales.shark_d'),mo:15000},
|
||||
ceo:{i:'👔',n:N_('sales.ceo_n'),s:N_('sales.ceo_s'),d:N_('sales.ceo_d'),mo:0},
|
||||
};
|
||||
const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30;
|
||||
// The ones the engineer never lands, and the nerds the shark never calls back.
|
||||
const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);};
|
||||
const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','dfpair'];
|
||||
const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')];
|
||||
const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null;
|
||||
const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';};
|
||||
// The short name at the start of a sentence: Dave, Chad, The CEO.
|
||||
const slCap=()=>{const t=slName();return t?t[0].toUpperCase()+t.slice(1):'';};
|
||||
const slR=q=>(hstr(((S&&S.asn)||0)+'|sales|'+q)%100000)/100000;
|
||||
// What a deal is, not its id: ids come from the clock, so a roll on them would differ every time the same game is played.
|
||||
const slKey=o=>[o.type,o.city,o.city2||'',o.name,o.bw,o.exp].join('|');
|
||||
const salesMo=()=>{const p=slP();return p?SALES[p].mo:0;};
|
||||
const salesCanHire=()=>lvl()>=SALES_LV;
|
||||
// How often offers come in: the engineer brings more, half as many again while a meeting's glow lasts.
|
||||
function salesSpawn(){const p=slP();if(p==='eng')return 1.4*(S.conf&&S.conf.until>S.day?1.5:1);if(p==='shark')return 1.2;return 1;}
|
||||
// What the salesperson does to the offers that just came in (from index n0): who brought them, which they drop,
|
||||
// and how the shark dresses them up.
|
||||
function salesShape(n0){const p=slP();if(!p)return;for(let i=S.offers.length-1;i>=n0;i--){const o=S.offers[i],T=BIZ_T[o.type];if(!T||o.ref)continue;
|
||||
if(p==='eng'&&salesBig(o.type)){S.offers.splice(i,1);continue;}
|
||||
if(p==='shark'&&SALES_NERDS.includes(o.type)){S.offers.splice(i,1);continue;}
|
||||
o.by=p;
|
||||
if(p==='shark'&&!T.event&&!T.cap){const up=(T.opts||[]).find(x=>x>o.bw);if(up&&!T.fiber)o.bw=up;o.rate=Math.round(o.rate*1.25);
|
||||
if(slR('over|'+slKey(o))<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}}
|
||||
// A promise nobody checked: a requirement this deal can have, that the network does not meet today.
|
||||
function salesPromise(o){const T=BIZ_T[o.type],pool=Object.keys(REQS).filter(k=>!(o.reqs||[]).includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,o)).sort();
|
||||
const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+slKey(o))*no.length)]:null;}
|
||||
// Their mark at renewal: how much likelier the customers they signed are to leave.
|
||||
function salesLeaveMul(b){if(b.by==='eng')return SALES_NERDS.includes(b.type)?0.5:0.75;if(b.by==='shark')return 1.5;if(b.by==='ceo')return 1.25;return 1;}
|
||||
// Haggles with whoever is at the desk now: how deep the discount they ask, and how often meeting halfway works.
|
||||
const salesAsk=()=>slP()==='eng'?0.72:0.8;
|
||||
const salesMeet=()=>({shark:0.9,eng:0.5,ceo:0.55})[slP()]||0.65;
|
||||
// Peering desks notice who you send to meetings: with the shark, selective networks want a quarter more traffic.
|
||||
const salesPeerMul=()=>slP()==='shark'?1.25:1;
|
||||
|
||||
/* A day at the sales desk: the engineer books the next meeting (30 days ahead, the same day the invitation comes),
|
||||
the CEO plays golf and has opinions, and a VP of Sales takes over from him when the board says so. */
|
||||
function salesDay(d){const L=S.sales;if(!L)return;
|
||||
if(L.vp&&d>=L.vp){L.p=null;L.vp=null;toast(tr('sales.vp_arrived'),'good',[{l:tr('sales.desk'),act:'salesOpen',args:{}}]);return;}
|
||||
const p=slP();if(!p)return;
|
||||
if(p==='eng')for(const cf of upcomingConfs(30)){if(cf.cap||cf.day-d!==30||(S.confReg||{})[cf.key])continue;
|
||||
if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}}
|
||||
if(p==='ceo'){if(!(L.golf>=d))L.golf=d+50+Math.floor(slR('golf|'+d)*30);else if(d===L.golf){salesGolf(d);L.golf=d+50+Math.floor(slR('golf|'+d)*30);}
|
||||
if(!(L.say>=d))L.say=d+20+Math.floor(slR('say|'+d)*15);else if(d===L.say){toast(tr('sales.ceo_says',{say:tr(SALES_SAY[Math.floor(slR('sayl|'+d)*SALES_SAY.length)])}),'');L.say=d+20+Math.floor(slR('say|'+d)*15);}}}
|
||||
// The golf course: the biggest internet customer this network can take, in its biggest city, at 30% off, signed on the spot.
|
||||
const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia'];
|
||||
function salesGolf(d){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 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;
|
||||
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;
|
||||
s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)};
|
||||
for(const x of [...s.biz,...s.offers])if(x.by!==undefined&&!own(SALES,x.by))delete x.by;}
|
||||
|
|
@ -16,7 +16,7 @@ function peerOk(id,via,city){
|
|||
if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]};
|
||||
if(n.pol==='open')return {ok:true};
|
||||
// In the Cogentle Spat, Goggle's peering desk wants eight times the usual traffic first, so cheap Cogentle-only transit really costs you Goggle (playtest).
|
||||
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};}
|
||||
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*salesPeerMul()*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};}
|
||||
if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')};
|
||||
if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')};
|
||||
if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};}
|
||||
|
|
|
|||
|
|
@ -361,7 +361,7 @@ function computeMoney(R2){
|
|||
C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0);
|
||||
C.caches=cachesMo();
|
||||
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0);
|
||||
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0);
|
||||
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0)+salesMo();
|
||||
V.eyeballs=0;V.business=0;V.ix=0;V.grant=grantOn(R2)?GRANT_MO:0;
|
||||
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))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);}
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ function sanitize(s){
|
|||
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;};
|
||||
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz);
|
||||
// Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally.
|
||||
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);
|
||||
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s);
|
||||
// Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked.
|
||||
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};}
|
||||
|
|
|
|||
|
|
@ -18,9 +18,11 @@ const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]};
|
|||
const clKind=t=>{const T=BIZ_T[t];if(!T||T.event||T.cap)return null;if(t==='dfpair'||t==='pairs')return 'iru';return T.l2||T.fiber||t==='isp'||t==='gpu'?'whole':'ip';};
|
||||
const clOn=b=>!!b&&!b.scripted&&!!clKind(b.type);
|
||||
// A stable roll in [0,1) for this customer, this term and this question.
|
||||
const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+b.id+'|'+b.te+'|'+q)%100000)/100000;
|
||||
// Who the customer is (names are unique), not its id: ids come from the clock and would differ every time a game is replayed.
|
||||
const clKey=b=>[b.type,b.city,b.city2||'',b.name].join('|');
|
||||
const clR=(b,q)=>(hstr(((S&&S.asn)||0)+'|'+clKey(b)+'|'+b.te+'|'+q)%100000)/100000;
|
||||
const clPick=(a,b,q)=>a[Math.floor(clR(b,q)*a.length)];
|
||||
function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{id:b.id,te:from},'term');return from+Math.round(m*365/12);}
|
||||
function clTerm(b,from){const m=clPick(CL_TERMS[clKind(b.type)],{type:b.type,city:b.city,city2:b.city2,name:b.name,te:from},'term');return from+Math.round(m*365/12);}
|
||||
// What this customer's contract would be priced at today: its price moved by the market since it was signed.
|
||||
// A renewal moves at most 25% down or 10% up at once, so an old save is not repriced in one go.
|
||||
const clFair=b=>rule('market')&&b.mk>0?Math.round(b.rate*clamp(mkt()/b.mk,0.75,1.1)):b.rate;
|
||||
|
|
@ -79,10 +81,10 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l
|
|||
if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;}
|
||||
if(d<b.te-30)continue;
|
||||
if(d<b.te){if(b.hr===b.te)continue;b.hr=b.te;const comp=clComp(b),cf=Math.min(1,comp/6);
|
||||
if(open<CL_HAG_MAX&&comp>=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(0.8+0.12*clR(b,'ask')));
|
||||
if(open<CL_HAG_MAX&&comp>=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(salesAsk()+0.12*clR(b,'ask')));
|
||||
if(ask>0&&ask<b.rate){b.hag={rate:ask,until:b.te};open++;clNote('hag');out.hag.push(b);}}
|
||||
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;
|
||||
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;}}
|
||||
clRenew(b,clFair(b));clNote('ren');out.ren++;}
|
||||
|
|
@ -102,7 +104,7 @@ const CL_REF=['dia','game','host','isp','stream','edu','scrub','provedor','gpu',
|
|||
function clReferral(d){if(d%45!==0||S.offers.length>=6)return;
|
||||
const b=S.biz.filter(x=>clOn(x)&&CL_REF.includes(x.type)&&x.mood>=90&&d-(x.since||0)>=365&&bizCity(x.city)&&lvl()>=(BIZ_T[x.type].lv||1)).sort((a,c)=>c.mood-a.mood||(a.since||0)-(c.since||0)||(a.id<c.id?-1:1))[0];
|
||||
if(!b||S.offers.some(o=>o.ref===b.id))return;const T=BIZ_T[b.type],list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));if(!list.length)return;
|
||||
const name=clPick(list,{id:b.id,te:d},'refname');useName(name);
|
||||
const name=clPick(list,{type:b.type,city:b.city,city2:b.city2,name:b.name,te:d},'refname');useName(name);
|
||||
S.offers.push({id:uid(),city:b.city,city2:null,name,type:b.type,bw:(T.opts||[1])[0],rate:Math.round((CITY[b.city].au?T.rate*AU_ARPU:T.rate)*mkt()),mk:mkt(),reqs:[],exp:d+40,ref:b.id,refN:b.name});}
|
||||
// New offers are priced at today's market (spawnOffer and friends price at 1; this moves them).
|
||||
function mktPrice(from){const m=mkt();for(let i=from;i<S.offers.length;i++){const o=S.offers[i];if(o.mk)continue;o.mk=m;if(m!==1){o.rate=Math.round(o.rate*m);if(o.fee)o.fee=Math.round(o.fee*m);}}}
|
||||
|
|
|
|||
|
|
@ -59,6 +59,8 @@ function dayPost(d){
|
|||
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
|
||||
// contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js)
|
||||
clDay(d);
|
||||
// the sales desk: meetings booked, golf played (38-sales-desk.js)
|
||||
salesDay(d);
|
||||
// own IX members join
|
||||
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
|
||||
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
|
||||
|
|
@ -69,7 +71,7 @@ function dayPost(d){
|
|||
// offers
|
||||
S.offers=S.offers.filter(o=>o.exp>d);
|
||||
brTick();
|
||||
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)){const n0=S.offers.length;spawnOffer();mktPrice(n0);}
|
||||
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);}
|
||||
// failures & events
|
||||
// Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never.
|
||||
let dirty=false;const cm=chaosMul();
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ const ACT={
|
|||
toast(B.equity?tr('interface.you_bought_out_bank_they_flew',{bank:esc(B.name)}):tr('interface.loan_from_bank_repaid_early',{bank:esc(B.name)}),'good');after();renderBank();},
|
||||
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=lvl()>=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();},
|
||||
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();},
|
||||
|
|
|
|||
|
|
@ -12,9 +12,11 @@ Object.assign(ACT,{
|
|||
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
|
||||
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
|
||||
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
|
||||
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;S.biz.push(clSign(customer));
|
||||
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer));
|
||||
// The shark's commission: one month of what the deal pays, on signing.
|
||||
if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}}
|
||||
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
|
||||
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
|
||||
decline:({id})=>{if(salesOverride(S.offers.find(x=>x.id===id))){after();return;}S.offers=S.offers.filter(x=>x.id!==id);after();},
|
||||
dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},
|
||||
});
|
||||
/* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times
|
||||
|
|
@ -23,7 +25,7 @@ function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;}
|
|||
Object.assign(ACT,{
|
||||
renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();},
|
||||
renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2);
|
||||
if(clR(b,'meet')<0.65){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');}
|
||||
if(clR(b,'meet')<salesMeet()){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');}
|
||||
else{clGone(b,'cheap');toast(tr('lifecycle.meet_no',{name:esc(b.name)}),'bad');sfx('err');}after();},
|
||||
renewLet:({id})=>{const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();},
|
||||
});
|
||||
|
|
|
|||
12
src/game/90-actions/52-sales.js
Normal file
12
src/game/90-actions/52-sales.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// The sales desk (38-sales-desk.js): hiring one salesperson, letting them go, and asking the board for a VP of Sales
|
||||
// when the CEO has taken over.
|
||||
Object.assign(ACT,{
|
||||
salesOpen:()=>{if(S)salesModal();},
|
||||
salesHire:({id})=>{if(!S||!own(SALES,id)||slP()||!salesCanHire()||!rule('clock'))return;const P=SALES[id];if(P.mo&&!spend(P.mo))return;
|
||||
S.sales=Object.assign(S.sales||{},{p:id,hired:S.day,vp:null,golf:null,say:null});UI.confirm=null;
|
||||
toast(id==='ceo'?tr('sales.ceo_took_over',{name:esc(slCap())}):tr('sales.hired',{name:esc(slCap())}),'good');sfx('coin');after();salesModal();},
|
||||
salesFire:()=>{const p=slP();if(!p||p==='ceo')return;if(UI.confirm!=='salesFire'){UI.confirm='salesFire';salesModal();return;}UI.confirm=null;const nm=slCap();S.sales.p=null;
|
||||
toast(tr('sales.fired',{name:esc(nm)}),'');after();salesModal();},
|
||||
// The CEO cannot be fired. A board meeting (and its catering) can get you a VP of Sales, who takes over a month later.
|
||||
salesVp:()=>{if(slP()!=='ceo'||S.sales.vp)return;if(!spend(SALES_VP))return;S.sales.vp=S.day+SALES_VP_DAYS;toast(tr('sales.vp_asked',{n:SALES_VP_DAYS}),'');after();salesModal();},
|
||||
});
|
||||
|
|
@ -35,7 +35,7 @@ Object.assign(ACT,{
|
|||
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},
|
||||
settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();},
|
||||
prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();},
|
||||
vpSet:({v})=>{vpOn(v==='on');refreshSettings();},
|
||||
vpSet:({v})=>{diagOn(v==='on');refreshSettings();},
|
||||
resetAsk:()=>openModal(`<h2 style="font-size:26px">${tr('game_and_settings.start_a_new_network')}</h2><p class="tagline">${tr('game_and_settings.name_and_everything_it_owns_will',{name:esc(S?S.name:tr('common.your_network'))})}</p><div class="btns">${btn(tr('game_and_settings.delete_and_start_over'),'newgame',{},'red big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}</div>`),
|
||||
whatsNewShow:()=>whatsNew(true,true),
|
||||
updateNow:()=>{save(true);location.reload();},
|
||||
|
|
|
|||
|
|
@ -58,6 +58,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','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','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);}
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ function renderLeft(){checkLayer();
|
|||
h+=badgeGrid();
|
||||
}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+=clDealsHtml()+confSection()+seatSection();
|
||||
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>`;}
|
||||
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);
|
||||
|
|
|
|||
17
src/game/93-ui/58-sales-panel.js
Normal file
17
src/game/93-ui/58-sales-panel.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// The sales desk in Deals, and its sheet: the three kinds of salesperson, who is at the desk, and what they cost.
|
||||
function salesCard(){if(!S||!rule('clock'))return '';const p=slP(),L=S.sales||{};
|
||||
return `<div class="ops-card"><div class="nm">${p?`${SALES[p].i} ${esc(tr('sales.at_desk',{name:slCap()}))}`:`💼 ${tr('sales.desk')}`}</div>
|
||||
<div class="meta">${p?(L.vp?tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)}):tr(SALES[p].d)):salesCanHire()?tr('sales.pitch'):tr('sales.locked',{lv:SALES_LV})}</div>
|
||||
<div class="btns">${btn(p?tr('sales.desk'):tr('sales.hire_sales'),'salesOpen',{},p?'sm':'pink sm',!p&&!salesCanHire())}</div></div>`;}
|
||||
function salesModal(){if(!S)return;const p=slP(),L=S.sales||{};
|
||||
let h=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.deals')}</div><h2 style="font-size:26px">${tr('sales.desk')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>`;
|
||||
h+=`<p class="tagline">${tr('sales.intro')}</p>`;
|
||||
if(!rule('clock'))h+=`<p class="why">${tr('ops.no_clock')}</p>`;else if(!salesCanHire()&&!p)h+=`<p class="why">${tr('sales.locked',{lv:SALES_LV})}</p>`;
|
||||
h+=Object.entries(SALES).map(([id,P])=>{const here=p===id;
|
||||
const act=here?(id==='ceo'?(L.vp?`<span class="tag st on">${tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)})}</span>`:btn(tr('sales.ask_vp',{cost:fmt$(SALES_VP)}),'salesVp',{},'ghost sm',S.cash<SALES_VP))
|
||||
:btn(UI.confirm==='salesFire'?tr('ops.really_fire'):tr('ops.fire'),'salesFire',{},'ghost sm'))
|
||||
:p?'':btn(id==='ceo'?tr('sales.let_ceo'):tr('ops.hire_mo',{price:fmt$(P.mo)}),'salesHire',{id},'pink sm',!salesCanHire()||!rule('clock')||S.cash<P.mo);
|
||||
return `<div class="ops-o${here?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${P.i}</span><div class="grow"><div class="nm">${tr(P.n)}</div>
|
||||
<div class="meta">${tr(P.d)}</div>${here&&id!=='ceo'?`<div class="meta">${tr('ops.salary',{price:fmt$(P.mo),d:dateStr(L.hired||0)})}</div>`:''}${act?`<div class="btns">${act}</div>`:''}</div></div></div>`;}).join('');
|
||||
if(p&&p!=='ceo')h+=`<p class="note">${tr('sales.one_at_a_time')}</p>`;
|
||||
openModal(h,'ops');}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
/* ================= CANVAS ================= */
|
||||
const cv=$('map'),ctx=cv.getContext('2d');
|
||||
// ctx is the 2D context draw() paints with: the map's own (CTX0), or with WebGL on the overlay above the card (56-webgl.js).
|
||||
const cv=$('map'),CTX0=cv.getContext('2d');let ctx=CTX0;
|
||||
const cam={x:1050,y:330,z:0.8};
|
||||
let CW=0,CH=0,DPR=1;
|
||||
/* Installed on an iPhone home screen with a translucent status bar, iOS can report a viewport one status bar
|
||||
|
|
@ -13,15 +14,5 @@ function fixStandaloneHeight(){const R0=document.documentElement;
|
|||
R0.classList.toggle('iosfix',on);if(on)R0.style.setProperty('--app-h',sh+'px');else R0.style.removeProperty('--app-h');return on?sh:0;}
|
||||
function resize(){const ah=fixStandaloneHeight();DPR=Math.min(2,window.devicePixelRatio||1);CW=innerWidth;CH=ah||innerHeight;cv.width=CW*DPR;cv.height=CH*DPR;}
|
||||
addEventListener('resize',()=>{resize();WL.key=null;renderLeft();fitHud();});resize();
|
||||
// Viewport readout for debugging phone layouts: open the game once with ?vp in the address (or the start URL).
|
||||
function vpDebug(){let el=document.getElementById('vpdbg');if(!el){el=document.createElement('pre');el.id='vpdbg';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none';document.body.appendChild(el);
|
||||
const pr=document.createElement('div');pr.id='vpprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';document.body.appendChild(pr);}
|
||||
const pr=document.getElementById('vpprobe'),cs=getComputedStyle(pr),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect();
|
||||
el.textContent=`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height}\nvv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\nstandalone ${navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches)} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}`;}
|
||||
let VP_T=null;const vpOn=on=>{clearInterval(VP_T);VP_T=null;const el=document.getElementById('vpdbg');if(el)el.remove();if(on){VP_T=setInterval(vpDebug,500);vpDebug();}try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}};
|
||||
if(/[?&]vp\b/.test(location.search))vpOn(true);else if(/[?&]novp\b/.test(location.search))vpOn(false);
|
||||
try{if(localStorage.getItem('sot-vp')==='1')vpOn(true);}catch(e){}
|
||||
// Inside an installed app there is no address bar: five quick taps on the date toggle the readout.
|
||||
{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];vpOn(!VP_T);}});}
|
||||
// iOS settles the standalone viewport a moment after launch and after rotating.
|
||||
for(const t of [300,1000])setTimeout(()=>{resize();WL.key=null;},t);addEventListener('pageshow',()=>{resize();WL.key=null;});
|
||||
|
|
|
|||
|
|
@ -30,9 +30,10 @@ function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"
|
|||
${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('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')]])}
|
||||
<div class="setline"><label for="langSel">${tr('common.language')}</label>${langPick('langSel')}</div>
|
||||
${seg(tr('common.viewport_info'),'vpSet',VP_T?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_reporting_layout_bugs_shows_what'))}
|
||||
${seg(tr('settings.diagnostic_info'),'vpSet',DIAG.on?'on':'off',[['on',tr('common.on')],['off',tr('common.off')]],tr('settings.for_bug_reports_shows_your_screen'))}
|
||||
${installRow()}<div class="btns" style="margin-top:12px">${btn(tr('common.done_8dd3'),'settingsClose',{},'pink')}</div>`;}
|
||||
const refreshSettings=()=>{if(UI.setOpen)openModal(settingsHtml());};
|
||||
function animOn(){const m=UI.anim||'auto';if(m==='on')return true;if(m==='off')return false;try{return !matchMedia('(prefers-reduced-motion: reduce)').matches;}catch(e){return true;}}
|
||||
|
|
|
|||
|
|
@ -30,8 +30,9 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const
|
|||
// Cable names are drawn in one font, so each width is measured once.
|
||||
const LBW=new Map(),labW=t=>{let w=LBW.get(t);if(w===undefined)LBW.set(t,w=ctx.measureText(t).width);return w;};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>LBW.clear());}catch(e){}
|
||||
function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab);
|
||||
if(!selC&&z<1.7&&cached)return;
|
||||
function drawCables(ks){const G=glOn(),z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab)&&!G;
|
||||
// On the card the cables are drawn by glBegin(); here only their labels are left.
|
||||
if(!selC&&z<1.7&&cached)return;if(G&&!selC&&z<1.7)return;
|
||||
ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';
|
||||
// Labels that would sit on another, or on a segment shorter than the name, are left out (a selected city's always show).
|
||||
// Placed labels go in a 64px grid, so each check only looks at its neighbours.
|
||||
|
|
@ -41,8 +42,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra
|
|||
for(let cx=c0;cx<=c1;cx++)for(let cy=r0;cy<=r1;cy++){const k=cx*8192+cy;let o=LG.get(k);if(!o)LG.set(k,o=[]);o.push(b);}return true;};
|
||||
const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C);
|
||||
for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}if(mx<-20||mn>CW+20)continue;
|
||||
if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
|
||||
if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);}
|
||||
if(!G&&(hot||!cached)){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);ctx.stroke();ctx.setLineDash([]);}
|
||||
if((hot||(z>=1.7&&!ar))&&lbOk(sp[Math.floor(sp.length/2)][0],sp[Math.floor(sp.length/2)][1]-8,labW(C.name),sp,hot)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;textStamp(C.name,ctx.font,10,labW(C.name),col,'rgba(255,255,255,.85)',3,m[0],m[1]-8);}
|
||||
ctx.globalAlpha=1;}}}
|
||||
function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit;
|
||||
const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;}
|
||||
|
|
|
|||
17
src/game/96-map/55-link-look.js
Normal file
17
src/game/96-map/55-link-look.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
/* How each tube on the map looks today, worked out once for both maps (the 2D canvas in drawFrame() and the card in
|
||||
58-webgl-links.js), so they cannot drift apart. */
|
||||
// Dash patterns, by number: none, cut, virtual circuit, being built, standby; 5 the fiber's dots, 6 an old cable.
|
||||
const LDASH=[[],[8,8],[2,7],[10,8],[4,6],[1,6],[6,5]];
|
||||
// A tube is a group of links drawn as one line: its capacity, load and state, its base width, colour and dash.
|
||||
function linkLook(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
|
||||
return {l,many,up,cap,load,u,df,bld,cut,dark,vx,idle,w0:vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)),
|
||||
col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),dash:cut?1:vx?2:bld?3:idle?4:0,
|
||||
pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0};} // packets on the line: more as it fills
|
||||
// The map's tubes as the picture needs them: the groups, their geometry and how each one looks. It changes with the
|
||||
// links and with the day's routing (R), not with the camera, so it is kept until one of those changes.
|
||||
let MLK=null;
|
||||
function mapLinks(day){const key=[S.links,S.links.length,R,day];
|
||||
if(MLK&&key.every((v,i)=>v===MLK.key[i]))return MLK;
|
||||
const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0]))));
|
||||
return MLK={key,PI,LG,GM,looks:LG.map(g=>linkLook(g,day))};}
|
||||
100
src/game/96-map/56-webgl.js
Normal file
100
src/game/96-map/56-webgl.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/* The map on the graphics card (WebGL2), wherever the browser can; Settings › Map drawing › Always 2D keeps the 2D
|
||||
canvas instead (a choice per device). A late-game map sends the 2D canvas several strokes per tube every frame (thousands on a
|
||||
big network) and repaints the land whenever you pan; here the card draws it all from buffers that change only with
|
||||
the network, so a frame costs the processor a few draws and uniforms.
|
||||
Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and
|
||||
packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for
|
||||
the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used.
|
||||
Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by
|
||||
the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs
|
||||
microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */
|
||||
const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''};
|
||||
try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){}
|
||||
// Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark).
|
||||
const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i;
|
||||
const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit();
|
||||
// Whether the card can draw the map, as far as is known without asking it: Settings says so without making a context
|
||||
// (on the title screen or in a puzzle that made the 64 MB atlas for a map drawn in 2D). A card not tried yet counts as able.
|
||||
const glCan=()=>!GLX.dead&&typeof WebGL2RenderingContext!=='undefined';
|
||||
// Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not.
|
||||
// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back.
|
||||
function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){}
|
||||
if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}}
|
||||
GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;}
|
||||
function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;}
|
||||
// Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame.
|
||||
function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;}
|
||||
function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.why=String(why&&why.message||why);GLX.dead=true;
|
||||
const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);}
|
||||
/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone
|
||||
64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go
|
||||
(WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps
|
||||
the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */
|
||||
function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf);
|
||||
const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){}
|
||||
GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;}
|
||||
/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and
|
||||
give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the
|
||||
same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card
|
||||
that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context)
|
||||
and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */
|
||||
const GL_LOSSES=2;
|
||||
// Forgets what was on the card (the context itself is kept): glInit() builds it all again.
|
||||
function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;}
|
||||
function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep())
|
||||
if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;}
|
||||
GLX.lost=true;glForget();}
|
||||
function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();}
|
||||
// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go).
|
||||
function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return;
|
||||
if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}}
|
||||
/* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for
|
||||
getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big
|
||||
uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never
|
||||
every frame: each read waits for the card. Up to four flags are read, as one call returns only one. */
|
||||
function glMem(gl,what){for(let i=0;i<4;i++){const e=gl.getError();if(!e||e===gl.CONTEXT_LOST_WEBGL)return;
|
||||
if(e===gl.OUT_OF_MEMORY)throw glErr(new Error('the graphics card is out of memory ('+what+')'));}}
|
||||
const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n';
|
||||
// Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing).
|
||||
const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n';
|
||||
function glProg(gl,vs,fs){const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error('shader: '+gl.getShaderInfoLog(x));return x;};
|
||||
const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,vs));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,fs));gl.linkProgram(p);
|
||||
if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error('link: '+gl.getProgramInfoLog(p));
|
||||
const u={},n=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;i<n;i++){const a=gl.getActiveUniform(p,i);u[a.name]=gl.getUniformLocation(p,a.name);}return {p,u};}
|
||||
// A vertex array and its buffer: attributes of the given sizes (in floats), interleaved, one record per instance
|
||||
// (div 1) or per vertex (div 0), filled with data if given.
|
||||
function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.createBuffer(),stride=sizes.reduce((a,x)=>a+x,0)*4;
|
||||
gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
|
||||
let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;});
|
||||
gl.bindVertexArray(null);return {v,b};}
|
||||
function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false;
|
||||
try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers');
|
||||
const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'});
|
||||
if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl;
|
||||
if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}}
|
||||
try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){}
|
||||
if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu);
|
||||
const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)};
|
||||
// The tubes' points for the packets: floats read with texelFetch, never filtered.
|
||||
const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST);
|
||||
glsInit(gl);
|
||||
// The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every
|
||||
// frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself.
|
||||
const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype;
|
||||
if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}}
|
||||
const V=s=>glVao(gl,s);
|
||||
Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;}
|
||||
catch(e){glKill(e);return false;}}
|
||||
// Colours as [r,g,b,a] from '#rrggbb', '#rgb' or 'rgba(r,g,b,a)', kept by string.
|
||||
const GLCOL=new Map();
|
||||
function glColor(s){let v=GLCOL.get(s);if(v)return v;let r=0,g=0,b=0,a=1;
|
||||
if(s[0]==='#'){let h=s.slice(1);if(h.length===3)h=h.replace(/./g,x=>x+x);r=parseInt(h.slice(0,2),16)/255;g=parseInt(h.slice(2,4),16)/255;b=parseInt(h.slice(4,6),16)/255;}
|
||||
else{const m=/rgba?\(([^)]*)\)/.exec(s);if(m){const p=m[1].split(',').map(x=>parseFloat(x));r=p[0]/255;g=p[1]/255;b=p[2]/255;a=p.length>3?p[3]:1;}}
|
||||
v=[r,g,b,a];GLCOL.set(s,v);return v;}
|
||||
// Sets a line or a point program's view for copy k of the map (wm: the line width multiplier).
|
||||
function glSet(gl,P,k,wm){gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.uniform1f(P.u.uWMul,wm);gl.uniform1f(P.u.uDpr,DPR);}
|
||||
// A full-screen fill, from one premultiplied colour at the bottom to another at the top (the sea), or of one colour
|
||||
// (the land and the clouds, through the stencil).
|
||||
const FILL_VS=GL_HEAD+`void main(){vec2 p=vec2((gl_VertexID&1)==0?-1.:1.,(gl_VertexID&2)==0?-1.:1.);gl_Position=vec4(p,0.,1.);}`;
|
||||
const FILL_FS=GL_HEAD+`uniform vec4 uTop,uBot;uniform float uH;out vec4 o;void main(){o=mix(uBot,uTop,gl_FragCoord.y/uH);}`;
|
||||
function glFill(gl,top,bot=top){const P=GLX.fill;gl.useProgram(P.p);gl.uniform4fv(P.u.uTop,top);gl.uniform4fv(P.u.uBot,bot);gl.uniform1f(P.u.uH,GLX.c.height);gl.bindVertexArray(GLX.empty);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);}
|
||||
126
src/game/96-map/57-webgl-background.js
Normal file
126
src/game/96-map/57-webgl-background.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
/* The background on the card, painted first each frame: the sea, the land, the waves, the clouds and the cables, as
|
||||
the 2D map paints them (drawFrame(), paintWorld()) and in the same colours. The land and the cables are geometry
|
||||
built once, so panning and zooming repaint nothing; only the waves and the clouds move. */
|
||||
const glPm=s=>{const [r,g,b,a]=glColor(s);return [r*a,g*a,b*a,a];}; // premultiplied, as the card blends
|
||||
const SEA_TOP=glPm('#62CBEA'),SEA_BOT=glPm('#43AED6'),CLOUD_COL=glPm('rgba(255,255,255,.55)');
|
||||
const LAND_SHADOW=glPm('rgba(20,90,130,.35)'),LAND_GRASS=glPm('#9BDA6C'),HILL_COL=glPm('#86CB5B'),HILL_SHINE=glPm('rgba(255,255,255,.18)');
|
||||
// The land's fill: a fan of triangles per coastline, counted in the stencil (how many times the coasts wind round each
|
||||
// pixel: glLandFill()), then one cover where the count is not zero. uOff shifts it in CSS px (the shadow).
|
||||
const FAN_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec2 aV;uniform vec2 uView,uOff;uniform vec3 uCam;
|
||||
void main(){gl_Position=clip((aV-uCam.xy)*uCam.z+uView*.5+uOff,uView,0.);}`;
|
||||
const FAN_FS=GL_HEAD+`out vec4 o;void main(){o=vec4(0.);}`;
|
||||
// Ellipses (the hills and their shine): centre and radii in map units, one premultiplied colour, smooth edges.
|
||||
const ELL_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aE;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out vec2 vr;
|
||||
void main(){vec2 c=(aE.xy-uCam.xy)*uCam.z+uView*.5,r=aE.zw*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m.x:m.x,(gl_VertexID&2)==0?-m.y:m.y);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
|
||||
const ELL_FS=GL_HEAD+`in vec2 vq;flat in vec2 vr;uniform vec4 uCol;uniform float uDpr;out vec4 o;
|
||||
void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);if(a<=0.)discard;o=uCol*a;}`;
|
||||
// Discs for the stencil only (the clouds' puffs): centre and radius in map units.
|
||||
const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr;
|
||||
void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
|
||||
const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`;
|
||||
/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does) and per zoom level
|
||||
lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each)
|
||||
for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its
|
||||
vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at
|
||||
the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched.
|
||||
Each level stays on the card once built (GLX.land, freed with the card): from 0.4 MB zoomed out to 3 MB at the
|
||||
closest zoom, about 15 MB if a game visits every zoom, so zooming back never builds one again mid-gesture. */
|
||||
const COAST_TOL=0.25,COASTP=[];
|
||||
// A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next,
|
||||
// through the corner between them), four segments per curve; the first point is repeated at the end.
|
||||
function coastPts(ri){let P=COASTP[ri];if(P)return P;const ring=COAST[ri],n=ring.length;P=[];
|
||||
const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m);
|
||||
for(let i=0;i<n;i++){const c=ring[i],e=mid(c,ring[(i+1)%n]);for(let j=1;j<=4;j++){const t=j/4,u=1-t;P.push([u*u*m[0]+2*u*t*c[0]+t*t*e[0],u*u*m[1]+2*u*t*c[1]+t*t*e[1]]);}m=e;}
|
||||
return COASTP[ri]=P;}
|
||||
// The points of P to keep so that none of the others is further than tol from the line kept (Douglas-Peucker).
|
||||
function coastSimplify(P,tol){const n=P.length;if(n<4||!(tol>0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1;
|
||||
while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2;
|
||||
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=t<0?0:t>1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}}
|
||||
if(m>=0){keep[m]=1;st.push(a,m,m,b);}}
|
||||
const o=[];for(let i=0;i<n;i++)if(keep[i])o.push(P[i]);return o;}
|
||||
// The zoom level the land is drawn at: 2^lv ≤ zoom < 2^(lv+1). Zooming in takes the finer level at once; zooming out
|
||||
// keeps the finer one (only more points, never less detail) until the zoom is 10 % under it, so a zoom that hovers
|
||||
// around a power of 2 does not switch back and forth.
|
||||
function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GLX.coastLv;
|
||||
if(cur===undefined||want>cur||z<Math.pow(2,cur)/1.1)GLX.coastLv=want;return GLX.coastLv;}
|
||||
/* A coastline as a fan of triangles from its first point, all turned the same way (anticlockwise on the map): summed
|
||||
with their signs, they count how many times the coast winds round each point. Every coast counts +1 inside, so where
|
||||
two coasts overlap (Timor is drawn twice) the land is 2, still land, as each coast filled on its own in 2D. */
|
||||
function coastFan(P,out){let a=0;const n=P.length;for(let i=0;i<n;i++){const p=P[i],q=P[(i+1)%n];a+=p[0]*q[1]-q[0]*p[1];}
|
||||
const s=a<0?1:0;for(let i=1;i+1<n;i++){const b=P[i+s],c=P[i+1-s];out.push(P[0][0],P[0][1],b[0],b[1],c[0],c[1]);}return out;}
|
||||
function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'+lv);let G=GLX.land[key];if(G)return G;
|
||||
const keep=far?new Set(LANDP_FAR):null,tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640');
|
||||
COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return;
|
||||
const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return;
|
||||
coastFan(P,fan);
|
||||
// Round ends make the joins round, as lineJoin='round' does; both lines are opaque, so the overlaps do not show.
|
||||
for(let i=0;i+1<P.length;i++){glSeg(sand,P[i],P[i+1],0,10,0,LINE_ROUND,SAND);glSeg(edge,P[i],P[i+1],0,2.5,0,LINE_ROUND,EDGE);}});
|
||||
const hills=[],shine=[];for(const [x,y,r] of HILLS){hills.push(x,y,r*1.4,r*.8);shine.push(x-r*.3,y-r*.25,r*.6,r*.3);}
|
||||
const F=a=>new Float32Array(a);
|
||||
G={fan:glVao(gl,[2],0,F(fan)).v,nFan:fan.length/2,sand:glVao(gl,[4,4,4],1,F(sand)).v,edge:glVao(gl,[4,4,4],1,F(edge)).v,nSeg:sand.length/LINE_STRIDE,
|
||||
hills:glVao(gl,[4],1,F(hills)).v,shine:glVao(gl,[4],1,F(shine)).v,nHill:HILLS.length};
|
||||
glMem(gl,'the land');return GLX.land[key]=G;}
|
||||
// Fills the land's shape (shifted by ox, oy CSS px) with one colour, for every copy of the map.
|
||||
// The stencil counts the coasts' windings (+1 for a triangle facing one way, -1 the other: coastFan()), as the 2D
|
||||
// canvas's nonzero rule does; counting only odd or even made two overlapping coasts cancel out into sea.
|
||||
function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST);
|
||||
gl.useProgram(P.p);gl.uniform2f(P.u.uView,CW,CH);gl.uniform2f(P.u.uOff,ox,oy);gl.bindVertexArray(G.fan);
|
||||
gl.colorMask(false,false,false,false);gl.stencilFunc(gl.ALWAYS,0,255);gl.stencilMask(255);
|
||||
gl.stencilOpSeparate(gl.FRONT,gl.KEEP,gl.KEEP,gl.INCR_WRAP);gl.stencilOpSeparate(gl.BACK,gl.KEEP,gl.KEEP,gl.DECR_WRAP);
|
||||
for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArrays(gl.TRIANGLES,0,G.nFan);}
|
||||
// The cover paints where the count is not zero and sets the stencil back to zero for the next user.
|
||||
gl.colorMask(true,true,true,true);gl.stencilFunc(gl.NOTEQUAL,0,255);gl.stencilOp(gl.ZERO,gl.ZERO,gl.ZERO);
|
||||
glFill(gl,col);gl.disable(gl.STENCIL_TEST);}
|
||||
function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col);
|
||||
for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}
|
||||
// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline.
|
||||
function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z));
|
||||
glLandFill(gl,G,ks,5,7,LAND_SHADOW);
|
||||
glLines(gl,G.sand,G.nSeg,ks);
|
||||
glLandFill(gl,G,ks,0,0,LAND_GRASS);
|
||||
glEllipses(gl,G.hills,G.nHill,ks,HILL_COL);glEllipses(gl,G.shine,G.nHill,ks,HILL_SHINE);
|
||||
glLines(gl,G.edge,G.nSeg,ks);}
|
||||
// The waves: each one two quadratic curves of four segments, swaying with the map's clock as in drawFrame(). They are
|
||||
// written into the same array every frame (no garbage for the collector to pick up while you play).
|
||||
const WAVE_COL=glColor('rgba(255,255,255,.45)');
|
||||
function glWaves(gl,now,ks){const A=GLX.wa||(GLX.wa=new Float32Array(WAVES.length*8*LINE_STRIDE)),ph0=now/900;let m=0;
|
||||
for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;
|
||||
// Two curves: up from x-9 to x, then down to x+9 (no array literals per wave: they were garbage every frame).
|
||||
for(let c=0;c<2;c++){const x0=x+o+(c?0:-9),cx=x0+4.5,cy=y+(c?4:-4),x1=x0+9;let px=x0,py=y;
|
||||
for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y;glSegAt(A,m++,px,py,qx,qy,0,2,0,0,WAVE_COL[3],WAVE_COL);px=qx;py=qy;}}}
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.wv.b);gl.bufferData(gl.ARRAY_BUFFER,A.subarray(0,m*LINE_STRIDE),gl.DYNAMIC_DRAW);glLines(gl,GLX.wv.v,m,ks);}
|
||||
// The clouds: their puffs are stencilled as one shape, then filled once, so overlapping puffs do not stack.
|
||||
function glClouds(gl,now,ks){const need=ks.length*CLOUDS.length*12;if(!need)return;
|
||||
// Written into one array kept from frame to frame, grown when more copies of the map show.
|
||||
if(!GLX.ca||GLX.ca.length<need)GLX.ca=new Float32Array(need);const A=GLX.ca;let n=0;
|
||||
for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y,s=c.s;
|
||||
A[n++]=x;A[n++]=y;A[n++]=16*s;A[n++]=0;A[n++]=x+18*s;A[n++]=y-8*s;A[n++]=20*s;A[n++]=0;A[n++]=x+40*s;A[n++]=y;A[n++]=15*s;A[n++]=0;}
|
||||
const F=A.subarray(0,n),P=GLX.circ;gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cl.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW);
|
||||
gl.enable(gl.STENCIL_TEST);gl.stencilFunc(gl.ALWAYS,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);gl.colorMask(false,false,false,false);
|
||||
gl.useProgram(P.p);gl.bindVertexArray(GLX.cl.v);gl.uniform2f(P.u.uView,CW,CH);gl.uniform3f(P.u.uCam,cam.x,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,F.length/4);
|
||||
gl.colorMask(true,true,true,true);gl.stencilFunc(gl.EQUAL,1,255);gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);glFill(gl,CLOUD_COL);gl.disable(gl.STENCIL_TEST);}
|
||||
// The cables, as drawCables() strokes them: rebuilt only when the highlighted city or the architect view changes.
|
||||
function glCables(gl,ks,selC,ar){const key=[selC,ar];
|
||||
if(!GLX.ckey||key.some((v,i)=>v!==GLX.ckey[i])){const A=[];
|
||||
for(const cp of CABLE_PAIRS){const hot=!!selC&&(cp.a===selC||cp.b===selC);if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;
|
||||
const C=CAB[cp.cid],[r,g,b]=glColor(cableCol(C)),col=[r,g,b,hot?.95:.4];let cum=0;
|
||||
for(let j=0;j+1<cp.pts.length;j++){const p=cp.pts[j],q=cp.pts[j+1];glSeg(A,p,q,cum,hot?3:1.6,C.age==='old'?6:0,0,col);cum+=Math.hypot(q[0]-p[0],q[1]-p[1]);}}
|
||||
const F=new Float32Array(A);gl.bindBuffer(gl.ARRAY_BUFFER,GLX.cb.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.STATIC_DRAW);glMem(gl,'the cables');GLX.cn=F.length/LINE_STRIDE;GLX.ckey=key;}
|
||||
if(GLX.cn)glLines(gl,GLX.cb.v,GLX.cn,ks);}
|
||||
// Starts a frame on the card: clears it and paints the background. The tubes come next (glFrame()), then the pictures
|
||||
// (glsFrameEnd()); draw() paints anything else on the overlay, which becomes ctx until the frame ends.
|
||||
function glBegin(now,ks){const gl=GLX.gl,c=GLX.c,f=GLX.f;glShow(true);GLS.frame=true;
|
||||
if(c.width!==cv.width||c.height!==cv.height){c.width=f.width=cv.width;c.height=f.height=cv.height;}
|
||||
// The 2D map under the card stays empty: it is cleared once, not every frame.
|
||||
if(!GLX.c0clean){CTX0.setTransform(1,0,0,1,0,0);CTX0.clearRect(0,0,cv.width,cv.height);GLX.c0clean=true;}
|
||||
gl.viewport(0,0,c.width,c.height);gl.clearColor(0,0,0,0);gl.clearDepth(1);gl.clearStencil(0);gl.colorMask(true,true,true,true);gl.depthMask(true);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT|gl.STENCIL_BUFFER_BIT);
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);gl.disable(gl.STENCIL_TEST);
|
||||
glFill(gl,SEA_TOP,SEA_BOT);
|
||||
glLand(gl,ks);
|
||||
glWaves(gl,now,ks);
|
||||
glClouds(gl,now,ks);
|
||||
const selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null);
|
||||
glCables(gl,ks,selC,arOn());
|
||||
const fx=GLX.fx;if(GLX.fxUsed){fx.setTransform(1,0,0,1,0,0);fx.clearRect(0,0,f.width,f.height);GLX.fxUsed=false;}
|
||||
ctx=fx;ctx.setTransform(DPR,0,0,DPR,0,0);}
|
||||
95
src/game/96-map/58-webgl-links.js
Normal file
95
src/game/96-map/58-webgl-links.js
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
/* The tubes on the card: every tube is one instanced draw per layer (halo, casing, colour, fiber dots, packets), and
|
||||
the packets travel their paths in the vertex shader, so a frame costs a few uniforms however many tubes there are.
|
||||
The buffers are rebuilt only when the network, the routing or the day change; a selection only rebuilds the halo,
|
||||
a buffer of the selected tube's own segments. Depth stands in for
|
||||
the 2D painting order: a later tube's casing still covers an earlier tube's colour and packets. */
|
||||
// The line program's passes: a tube's layers in drawFrame()'s order, and plain lines (coasts, waves, cables).
|
||||
const LP={halo:0,casing:1,colour:2,dots:3,plain:4};
|
||||
// A segment's flags: on the selected tube, lit fiber (its dots show), round ends for a plain line.
|
||||
const LINE_SEL=1,LINE_FIBER=2,LINE_ROUND=4;
|
||||
/* One segment is 12 floats: x0,y0,x1,y1 (map units) | the length before it, width (CSS px), dash (LDASH), flags |
|
||||
a, r,g,b, where a is the depth for a tube and the opacity for a plain line. */
|
||||
const LINE_STRIDE=12;
|
||||
function glSegAt(A,i,ax,ay,bx,by,cum,w,dash,fl,a,col){const o=i*LINE_STRIDE;
|
||||
A[o]=ax;A[o+1]=ay;A[o+2]=bx;A[o+3]=by;A[o+4]=cum;A[o+5]=w;A[o+6]=dash;A[o+7]=fl;A[o+8]=a;A[o+9]=col[0];A[o+10]=col[1];A[o+11]=col[2];}
|
||||
function glSeg(A,p,q,cum,w,dash,fl,col){A.push(p[0],p[1],q[0],q[1],cum,w,dash,fl,col[3],col[0],col[1],col[2]);}
|
||||
/* One instance per segment, a quad around it; the fragment keeps what lies within half the line width of the segment
|
||||
(or of a dash of it, both with round ends), which also gives round joins and caps. */
|
||||
const GL_LINE_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aSeg;layout(location=1) in vec4 aP;layout(location=2) in vec4 aC;
|
||||
uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uBusy;uniform int uPass;
|
||||
out vec2 vLoc;out float vLen,vS0,vHalf,vButt;flat out vec4 vCol;flat out vec2 vDash;
|
||||
vec2 dashOf(int k){${LDASH.map((d,i)=>d.length?`if(k==${i})return vec2(${d[0]}.,${d[1]}.);`:'').join('')}return vec2(0.);}
|
||||
void main(){vec2 h=uView*.5,a=(aSeg.xy-uCam.xy)*uCam.z+h,b=(aSeg.zw-uCam.xy)*uCam.z+h;
|
||||
float w=aP.y*uWMul,hw=w*.5;int fl=int(aP.w+.5);vec4 col=vec4(aC.yzw,1.);vec2 dash=dashOf(int(aP.z+.5));bool skip=false;
|
||||
if(uPass==${LP.halo}){hw=(w+14.)*.5;col=vec4(1.,79./255.,154./255.,.35);dash=vec2(0.);skip=(fl&${LINE_SEL})==0;}
|
||||
else if(uPass==${LP.casing}){hw=(w+4.)*.5;col=vec4(30./255.,38./255.,64./255.,1.);}
|
||||
else if(uPass==${LP.dots}){hw=max(1.,w*.25)*.5;col=vec4(1.,1.,1.,.75);dash=dashOf(5);skip=(fl&${LINE_FIBER})==0||uBusy>.5;}
|
||||
else if(uPass==${LP.plain})col.a=aC.x;
|
||||
if(skip){gl_Position=vec4(2.,2.,2.,1.);return;}
|
||||
vec2 d=b-a;float L=length(d);vec2 t=L>1e-4?d/L:vec2(1.,0.),n=vec2(-t.y,t.x);float m=hw+1./uDpr;
|
||||
float sx=(gl_VertexID&1)==0?-m:L+m,sy=(gl_VertexID&2)==0?-m:m;
|
||||
vLoc=vec2(sx,sy);vLen=L;vS0=aP.x*uCam.z;vHalf=hw;vCol=col;vDash=dash;vButt=uPass==${LP.plain}&&(fl&${LINE_ROUND})==0?1.:0.;
|
||||
gl_Position=clip(a+t*sx+n*sy,uView,(uPass==${LP.plain}?.9998:aC.x)*2.-1.);}`;
|
||||
const GL_LINE_FS=GL_HEAD+`in vec2 vLoc;in float vLen,vS0,vHalf,vButt;flat in vec4 vCol;flat in vec2 vDash;uniform float uDpr;out vec4 o;
|
||||
void main(){float x=vLoc.x,y=vLoc.y,d;
|
||||
if(vButt>.5&&(x<0.||x>vLen))discard;
|
||||
if(vDash.x<=0.){float c=clamp(x,0.,vLen);d=length(vec2(x-c,y));}
|
||||
else{float P=vDash.x+vDash.y,g=vS0+x,k=floor(g/P);d=1e9;
|
||||
for(int i=-1;i<=1;i++){float a0=(k+float(i))*P,lo=max(a0,vS0),hi=min(a0+vDash.x,vS0+vLen);if(lo<=hi){float c=clamp(g,lo,hi);d=min(d,length(vec2(g-c,y)));}}}
|
||||
float al=clamp((vHalf-d)*uDpr+.5,0.,1.);if(al<=0.)discard;o=vec4(vCol.rgb*vCol.a*al,vCol.a*al);}`;
|
||||
// Plain lines (coasts, waves, cables): colour and opacity from the data, flat ends unless LINE_ROUND, under the tubes.
|
||||
function glLines(gl,vao,n,ks){const L=GLX.line;gl.useProgram(L.p);gl.bindVertexArray(vao);gl.uniform1i(L.u.uPass,LP.plain);gl.uniform1f(L.u.uBusy,0);
|
||||
for(const k of ks){glSet(gl,L,k,1);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}
|
||||
/* Packets: one instance per packet; where it is on its tube comes from the tube's points (a float texture of x, y and
|
||||
the share of the length so far, GL_PTS_W texels a row), found by bisection the way polyAtXY() finds it. */
|
||||
const GL_PTS_W=2048;
|
||||
const GL_PK_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aK;layout(location=1) in vec4 aQ;
|
||||
uniform vec2 uView;uniform vec3 uCam;uniform float uWMul,uDpr,uT,uFar;uniform highp sampler2D uPts;
|
||||
out vec2 vLoc;flat out float vR,vLw;
|
||||
vec4 P(int i){return texelFetch(uPts,ivec2(i%${GL_PTS_W},i/${GL_PTS_W}),0);}
|
||||
void main(){float n=uFar>.5?max(1.,floor(aK.w*.5)):aK.w,i=aQ.x;if(i>=n){gl_Position=vec4(2.,2.,2.,1.);return;}
|
||||
float t=fract(uT*90./max(aK.z*uCam.z,40.)+i/n);if(mod(i,2.)>.5)t=1.-t;
|
||||
int o=int(aK.x+.5),lo=1,hi=int(aK.y+.5)-1;for(int s=0;s<16&&lo<hi;s++){int md=(lo+hi)/2;if(P(o+md).z<t)lo=md+1;else hi=md;}
|
||||
vec4 p0=P(o+lo-1),p1=P(o+lo);float f=p1.z>p0.z?(t-p0.z)/(p1.z-p0.z):0.;vec2 c=(mix(p0.xy,p1.xy,f)-uCam.xy)*uCam.z+uView*.5;
|
||||
float w=aQ.y*uWMul,r=uFar>.5?1.6:max(2.2,w*.42),lw=uFar>.5?1.:1.5,m=r+lw*.5+1./uDpr;
|
||||
vec2 q=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vLoc=q;vR=r;vLw=lw;
|
||||
gl_Position=clip(c+q,uView,aQ.z*2.-1.);}`;
|
||||
const GL_PK_FS=GL_HEAD+`in vec2 vLoc;flat in float vR,vLw;uniform float uDpr;out vec4 o;
|
||||
void main(){float d=length(vLoc),out_=clamp((vR+vLw*.5-d)*uDpr+.5,0.,1.);if(out_<=0.)discard;
|
||||
float inn=clamp((vR-vLw*.5-d)*uDpr+.5,0.,1.);vec3 c=mix(vec3(30./255.,38./255.,64./255.),vec3(1.),inn);o=vec4(c*out_,out_);}`;
|
||||
/* The tubes as instance data: their segments (see LINE_STRIDE; later tubes are nearer), their packets (first point,
|
||||
points, length, packets | which, base width, depth, -), and every tube's points in the texture. */
|
||||
const glDepth=(gi,N)=>1-(gi+1)/(N+2);
|
||||
function glBuild(LG,GM,looks){const gl=GLX.gl,N=LG.length;let ns=0,np=0,nk=0;
|
||||
for(let gi=0;gi<N;gi++){ns+=GM[gi].pts.length-1;np+=GM[gi].pts.length;nk+=looks[gi].pk;}
|
||||
const SEG=new Float32Array(ns*LINE_STRIDE),PK=new Float32Array(nk*8),TH=Math.max(1,Math.ceil(np/GL_PTS_W)),PT=new Float32Array(GL_PTS_W*TH*4);
|
||||
let si=0,ki=0,pi=0;
|
||||
for(let gi=0;gi<N;gi++){const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col);
|
||||
const fl=L.df&&!L.bld&&!L.dark?LINE_FIBER:0,p0=pi;
|
||||
for(let j=0;j<pts.length;j++){PT[pi*4]=pts[j][0];PT[pi*4+1]=pts[j][1];PT[pi*4+2]=cum[j];pi++;}
|
||||
for(let j=0;j+1<pts.length;j++)glSegAt(SEG,si++,pts[j][0],pts[j][1],pts[j+1][0],pts[j+1][1],cum[j]*len,L.w0,L.dash,fl,dep,col);
|
||||
for(let i=0;i<L.pk;i++){const o=ki*8;PK[o]=p0;PK[o+1]=pts.length;PK[o+2]=len;PK[o+3]=L.pk;PK[o+4]=i;PK[o+5]=L.w0;PK[o+6]=dep;ki++;}}
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.lv.b);gl.bufferData(gl.ARRAY_BUFFER,SEG,gl.DYNAMIC_DRAW);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER,GLX.pv.b);gl.bufferData(gl.ARRAY_BUFFER,PK,gl.DYNAMIC_DRAW);
|
||||
gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,GL_PTS_W,TH,0,gl.RGBA,gl.FLOAT,PT);glMem(gl,'the tubes');
|
||||
Object.assign(GLX,{nSeg:ns,nPk:nk});return {SEG,PK,PT};}
|
||||
// The selected tube's halo: its segments again, at its own depth (so later tubes still cover it), and nothing else.
|
||||
function glHalo(LG,GM,looks,selId){const gl=GLX.gl,N=LG.length,A=[];
|
||||
if(selId)for(let gi=0;gi<N;gi++){if(!LG[gi].some(x=>x.id===selId))continue;const L=looks[gi],{pts,cum,len}=GM[gi],dep=glDepth(gi,N),col=glColor(L.col);
|
||||
for(let j=0;j+1<pts.length;j++)A.push(pts[j][0],pts[j][1],pts[j+1][0],pts[j+1][1],cum[j]*len,L.w0,L.dash,LINE_SEL,dep,col[0],col[1],col[2]);}
|
||||
const F=new Float32Array(A);if(F.length){gl.bindBuffer(gl.ARRAY_BUFFER,GLX.hv.b);gl.bufferData(gl.ARRAY_BUFFER,F,gl.DYNAMIC_DRAW);}
|
||||
GLX.nHalo=F.length/LINE_STRIDE;return F;}
|
||||
// Draws the tubes and their packets over the background glBegin() painted (ML: mapLinks(), sc: the icon scale).
|
||||
function glFrame(ML,ks,far,busy,now,sc){const gl=GLX.gl;
|
||||
const selId=UI.sel&&UI.sel.type==='link'?UI.sel.id:'',net=GLX.key[0]!==ML;
|
||||
if(net)glBuild(ML.LG,ML.GM,ML.looks);
|
||||
if(net||GLX.key[1]!==selId){glHalo(ML.LG,ML.GM,ML.looks,selId);GLX.key=[ML,selId];}
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.depthMask(true);
|
||||
const L=GLX.line,K=GLX.pk,wm=sc*(far?0.5:1),lines=(pass,v=GLX.lv.v,n=GLX.nSeg)=>{gl.useProgram(L.p);gl.bindVertexArray(v);gl.uniform1f(L.u.uBusy,busy?1:0);gl.uniform1i(L.u.uPass,pass);
|
||||
for(const k of ks){glSet(gl,L,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}};
|
||||
if(GLX.nSeg)for(const pass of [LP.casing,LP.colour,LP.dots])lines(pass);
|
||||
if(GLX.nPk){gl.useProgram(K.p);gl.bindVertexArray(GLX.pv.v);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLX.tex);gl.uniform1i(K.u.uPts,0);
|
||||
gl.uniform1f(K.u.uT,now/1000);gl.uniform1f(K.u.uFar,far?1:0);for(const k of ks){glSet(gl,K,k,wm);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,GLX.nPk);}}
|
||||
// The selection's halo goes over earlier tubes but under its own line and later ones, as in 2D.
|
||||
if(GLX.nHalo){gl.depthFunc(gl.LESS);gl.depthMask(false);lines(LP.halo,GLX.hv.v,GLX.nHalo);gl.depthMask(true);}
|
||||
gl.bindVertexArray(null);}
|
||||
151
src/game/96-map/59-gl-sprites.js
Normal file
151
src/game/96-map/59-gl-sprites.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/* Pictures on the card. Cities, labels, markers and everything that bobs or pulses on them (cones, ships, offer
|
||||
bubbles, hot badges, floaters) are painted once with the 2D canvas, packed into one texture (the atlas), and drawn
|
||||
as instanced quads, with the small round things (lights, steam, glows) as discs, in one draw per frame after the
|
||||
tubes. Without WebGL the same calls draw the pictures with the 2D canvas, so the map's code does not care which. */
|
||||
const SPR_MAX=1400,SPR_STRIDE=13;
|
||||
// The card's pictures (SPRS) and the 2D map's (SPRC), by key; both at the screen's pixel density SPR_DPR.
|
||||
const SPRS=new Map(),SPRC=new Map();let SPR_DPR=0;
|
||||
/* The 2D map's pictures each keep a canvas, so they are also held to a size: a long zoom on a big network paints every
|
||||
city again at each step, and the list (only capped at SPR_MAX) held up to 180 MB of them where a frame shows 2 to
|
||||
23 MB. At the end of a frame over SPRC_BUDGET bytes, the pictures it did not use go, those unused the longest first,
|
||||
down to 3/4 of the budget (so this happens once in a while, not every frame). The frame's own are always kept: a
|
||||
screen that needs more than the budget keeps what it needs. A canvas let go is emptied (0×0) at once, which frees
|
||||
its pixels without waiting for the collector. The card's atlas has its own fixed size (GLS.size).
|
||||
SPR_F counts frames (draw()); finding or drawing a picture marks it as used in this one (e.f). */
|
||||
const SPRC_BUDGET=48*1048576;let SPRC_B=0,SPR_F=0;
|
||||
const sprFree=e=>{if(e.cv){e.cv.width=e.cv.height=0;e.cv=null;}};
|
||||
function sprcTrim(){if(SPRC_B<=SPRC_BUDGET)return;const old=[];for(const [k,e] of SPRC)if(e.f<SPR_F)old.push([e.f,k,e]);
|
||||
old.sort((a,b)=>a[0]-b[0]);const goal=SPRC_BUDGET*0.75;
|
||||
for(const [,k,e] of old){if(SPRC_B<=goal)break;SPRC.delete(k);SPRC_B-=e.pw*e.ph*4;sprFree(e);}}
|
||||
const GLS={prog:null,vao:null,buf:null,tex:null,size:4096,shx:0,shy:0,shh:0,frame:false,data:new Float32Array(SPR_STRIDE*2048),n:0,up:0,upq:false,memT:-1e9};
|
||||
/* One record is 13 floats: x,y,w,h (CSS px) | u0,v0,u1,v1 (atlas) | r,g,b,a | kind. A picture (kind 0) takes its
|
||||
colours from the atlas and a from the record; a disc (kind 1) is centred on x,y with radius w, in colour r,g,b,a. */
|
||||
const SPR_VS=GL_HEAD+`layout(location=0) in vec4 aP;layout(location=1) in vec4 aUV;layout(location=2) in vec4 aC;layout(location=3) in float aK;
|
||||
uniform vec2 uDev;uniform float uDpr;out vec2 vUV,vQ;out vec4 vC;flat out float vK,vR;
|
||||
void main(){vec2 c=vec2((gl_VertexID&1)==0?0.:1.,(gl_VertexID&2)==0?0.:1.),p;
|
||||
if(aK>.5){float m=aP.z+1./uDpr;vQ=(c*2.-1.)*m;vR=aP.z;vUV=vec2(0.);p=aP.xy+vQ;}
|
||||
else{vQ=vec2(0.);vR=0.;vUV=mix(aUV.xy,aUV.zw,c);p=aP.xy+c*aP.zw;}
|
||||
vC=aC;vK=aK;gl_Position=vec4(p.x*uDpr/uDev.x*2.-1.,1.-p.y*uDpr/uDev.y*2.,0.,1.);}`;
|
||||
const SPR_FS=GL_HEAD+`uniform sampler2D uTex;uniform float uDpr;in vec2 vUV,vQ;in vec4 vC;flat in float vK,vR;out vec4 o;
|
||||
void main(){if(vK>.5){float a=clamp((vR-length(vQ))*uDpr+.5,0.,1.)*vC.a;if(a<=0.)discard;o=vec4(vC.rgb*a,a);}
|
||||
else o=texture(uTex,vUV)*vC.a;}`;
|
||||
function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4,4,1]);GLS.vao=v;GLS.buf=b;
|
||||
// 4096 px square (64 MB), or what the card allows if that is less (some phones). A card that has not the memory for
|
||||
// it gets 2048 (16 MB: more resets of the atlas, the same map); without even that, the map stays 2D (glMem).
|
||||
GLS.tex=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);glMem(gl,'setup');
|
||||
for(GLS.size=Math.min(4096,gl.getParameter(gl.MAX_TEXTURE_SIZE)||4096);;GLS.size>>=1){
|
||||
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,GLS.size,GLS.size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
|
||||
try{glMem(gl,'the pictures');break;}catch(e){if(GLS.size<=2048)throw e;}}
|
||||
for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.LINEAR);
|
||||
for(const k of [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T])gl.texParameteri(gl.TEXTURE_2D,k,gl.CLAMP_TO_EDGE);
|
||||
GLS.shx=GLS.shy=GLS.shh=0;GLS.memT=-1e9;GLS.upq=false;}
|
||||
// Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it).
|
||||
function spritesReset(){glsDrawNow();for(const e of SPRC.values())sprFree(e);SPRS.clear();SPRC.clear();SPRC_B=0;GLS.shx=GLS.shy=GLS.shh=0;}
|
||||
// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten.
|
||||
function spritesDrop(){GLS.n=GLS.up=0;GLS.upq=false;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;}
|
||||
/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a
|
||||
canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context
|
||||
and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas.
|
||||
Each picture goes in with a clear border of GLS_GAP px: the card blends the texels around the point it reads, so a
|
||||
picture drawn off whole pixels or a little stretched read half a texel past its edge, and showed a thin line of its
|
||||
neighbour in the atlas (or of a picture from before the last reset, which leaves the texture as it was). */
|
||||
const GLS_GAP=1;
|
||||
const GLS_PAD={cv:null,g:null};
|
||||
function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;}
|
||||
if(P.cv.width<pw||P.cv.height<ph){P.cv.width=Math.max(P.cv.width,Math.ceil(pw/64)*64);P.cv.height=Math.max(P.cv.height,Math.ceil(ph/64)*64);P.g=null;}
|
||||
if(!P.g)P.g=P.cv.getContext('2d',{willReadFrequently:true});return P;}
|
||||
// Where this frame's pictures are kept: the card's or the 2D map's. A new pixel density starts both again.
|
||||
function sprMap(){if(DPR!==SPR_DPR){SPR_DPR=DPR;spritesReset();}return GLS.frame&&!!GLX.gl&&!!GLS.prog?SPRS:SPRC;}
|
||||
// The picture already painted under key, if any: callers ask first, so a picture drawn every frame costs no closure.
|
||||
const spriteHas=key=>{const e=sprMap().get(key);if(e)e.f=SPR_F;return e;};
|
||||
// A picture of w×h CSS px with its anchor at (ax,ay): painted once by paint(g) (the 2D canvas, at the screen's pixel
|
||||
// density), and kept by key in SPRS (the card's) or SPRC (the 2D map's).
|
||||
function spriteEntry(key,w,h,ax,ay,paint){const M=sprMap(),gpu=M===SPRS;let e=M.get(key);if(e){e.f=SPR_F;return e;}
|
||||
if(SPRS.size+SPRC.size>=SPR_MAX)spritesReset();
|
||||
const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx;
|
||||
e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1,f:SPR_F};
|
||||
const G=GLS_GAP;
|
||||
if(gpu&&pw+2*G<=GLS.size&&ph+2*G<=GLS.size){const P=glsPad(pw+2*G,ph+2*G),g=P.g;
|
||||
// Clipped to the picture, as its own canvas would be, so the border stays clear.
|
||||
g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw+2*G,ph+2*G);g.beginPath();g.rect(G,G,pw,ph);g.clip();ctx=g;
|
||||
try{g.setTransform(DPR,0,0,DPR,G,G);sprPen(g);paint(g);}finally{ctx=saved;g.restore();}
|
||||
// A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next.
|
||||
try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);}
|
||||
}else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g;
|
||||
try{g.setTransform(DPR,0,0,DPR,0,0);sprPen(g);paint(g);}finally{ctx=saved;}e.cv=cv;
|
||||
if(M===SPRC)SPRC_B+=pw*ph*4;}
|
||||
M.set(key,e);return e;}
|
||||
/* A picture starts with the pen the map's own canvas has when it draws cities and markers: the tubes leave it with
|
||||
round line ends and corners, the labels with text centred on its middle. Drawn straight on the map, the dashed rings,
|
||||
the cones' tips and a sleeping POP's "zzz" took those, and a new canvas has others (square ends, text on its baseline). */
|
||||
function sprPen(g){g.lineCap='round';g.lineJoin='round';g.textAlign='center';g.textBaseline='middle';}
|
||||
// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame.
|
||||
function glsEnsure(e){if(e.up)return true;const gl=GLX.gl,G=GLS_GAP;if(!gl||!GLS.prog||!e.cv)return false;
|
||||
if(e.pw+2*G>GLS.size||e.ph+2*G>GLS.size)return false;
|
||||
const P=glsPad(e.pw+2*G,e.ph+2*G),g=P.g;g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,e.pw+2*G,e.ph+2*G);g.drawImage(e.cv,G,G);
|
||||
try{return glsPut(gl,e,P.cv);}catch(x){throw glErr(x);}}
|
||||
// src holds the picture at (GLS_GAP,GLS_GAP), in a clear border that goes into the atlas with it.
|
||||
function glsPut(gl,e,src){const G=GLS_GAP,pw=e.pw+2*G,ph=e.ph+2*G,A=GLS.size;if(pw>A||ph>A)return false;
|
||||
if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;}
|
||||
if(GLS.shy+ph>A){spritesReset();return false;}
|
||||
const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph);
|
||||
gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true);
|
||||
// Only the picture's corner of the source (with its border): the pad is bigger than most pictures.
|
||||
gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false);
|
||||
GLS.up++;Object.assign(e,{up:true,u0:(x+G)/A,v0:(y+G)/A,u1:(x+pw-G)/A,v1:(y+ph-G)/A});return true;}
|
||||
// The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace.
|
||||
function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;}
|
||||
// Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas.
|
||||
function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data;
|
||||
d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;}
|
||||
else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);}
|
||||
// A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas.
|
||||
function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data;
|
||||
d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;}
|
||||
else{const sa=ctx.globalAlpha;if(a!==undefined)ctx.globalAlpha=a;ctx.fillStyle=col;ctx.beginPath();ctx.arc(x,y,r,0,7);ctx.fill();ctx.globalAlpha=sa;}}
|
||||
/* Pictures that grow with the zoom (cities, ships, badges) are painted at steps of 1/24 of their scale. On the card,
|
||||
while the zoom moves, they keep the step of the scale they had when it began, stretched by up to 1.25× either way
|
||||
(the card filters them smoothly), and are painted again at the right step once the zoom rests (ZOOM_REST ms): a
|
||||
pinch otherwise repainted every city at every step, hundreds of pictures a frame, and filled the atlas over and
|
||||
over. ZH.sc is the icon scale held, ZH.f how much a picture is painted smaller (<1) or bigger than it shows. */
|
||||
const CSPR_STEP=24,ZOOM_REST=250,ZH={z:0,t:-1e9,sc:0,f:1};
|
||||
function zoomHold(sc,G){const t=performance.now();if(cam.z!==ZH.z){ZH.z=cam.z;ZH.t=t;}
|
||||
if(!G||!ZH.sc||t-ZH.t>=ZOOM_REST||sc/ZH.sc>1.25||ZH.sc/sc>1.25)ZH.sc=sc;ZH.f=ZH.sc/sc;}
|
||||
// The zoom moved a moment ago: the pictures may be stretched, so a still map is drawn again once it rests (mapStill()).
|
||||
const zoomMoving=()=>performance.now()-ZH.t<ZOOM_REST;
|
||||
const sprQ=k=>Math.max(1/CSPR_STEP,Math.round(k*ZH.f*CSPR_STEP)/CSPR_STEP);
|
||||
// A small picture w×h px at scale k with its anchor at (ax,ay), painted once by paint(g) with the origin on the anchor
|
||||
// (k in steps of 1/24, as the cities; zoomed: k grows with the zoom, and is held while it moves, sprQ()), then drawn with
|
||||
// the anchor at (x,y). Things that bob or pulse are drawn as these at a moving place, so the overlay above the card
|
||||
// stays untouched (repainting it costs a whole screen of pixels).
|
||||
// The full key of a stamp at scale kq, kept per key: it was built again for every stamp on every frame.
|
||||
const STK=new Map();
|
||||
function stamp(key,w,h,ax,ay,k,x,y,paint,zoomed){const kq=zoomed?sprQ(k):Math.max(1/CSPR_STEP,Math.round(k*CSPR_STEP)/CSPR_STEP),r=k/kq;
|
||||
let m=STK.get(key);if(!m||m.kq!==kq){if(STK.size>4000)STK.clear();STK.set(key,m={kq,k:key+'|'+kq});}
|
||||
const e=spriteHas(m.k)||spriteEntry(m.k,Math.ceil(w*kq),Math.ceil(h*kq),ax*kq,ay*kq,g=>{g.translate(ax*kq,ay*kq);g.scale(kq,kq);paint(g);});
|
||||
blit(e,x-e.ax*r,y-e.ay*r,e.w*r,e.h*r);}
|
||||
// Text with an outline, centred on (x,y), as a picture placed on whole device pixels; tw is its width, px its size.
|
||||
function textStamp(t,font,px,tw,fill,stroke,lw,x,y){const W=Math.ceil(tw+lw+4),H=Math.ceil(px*1.5+lw+2);
|
||||
const e=spriteEntry(['txt',t,font,fill,stroke,lw].join('|'),W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.font=font;g.textAlign='center';g.textBaseline='middle';
|
||||
if(lw){g.lineWidth=lw;g.lineJoin='round';g.strokeStyle=stroke;g.strokeText(t,0,0);}g.fillStyle=fill;g.fillText(t,0,0);});
|
||||
blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);}
|
||||
// Sends the queued pictures to the card in one draw.
|
||||
function glsDrawNow(){const gl=GLX.gl,n=GLS.n;GLS.n=0;if(!gl||!GLS.prog||!n)return;
|
||||
try{glsDraw(gl,n);}catch(x){throw glErr(x);}}
|
||||
function glsDraw(gl,n){gl.useProgram(GLS.prog.p);gl.bindVertexArray(GLS.vao);gl.bindBuffer(gl.ARRAY_BUFFER,GLS.buf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER,GLS.data.subarray(0,n*SPR_STRIDE),gl.STREAM_DRAW);
|
||||
gl.uniform2f(GLS.prog.u.uDev,GLX.c.width,GLX.c.height);gl.uniform1f(GLS.prog.u.uDpr,DPR);gl.uniform1i(GLS.prog.u.uTex,0);
|
||||
gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);
|
||||
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);gl.disable(gl.DEPTH_TEST);
|
||||
gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);gl.bindVertexArray(null);}
|
||||
/* The end of a frame on the card: the pictures go up over the tubes. The frame is over even if that draw fails.
|
||||
Pictures sent are checked (did the card take them?): a card short of memory may refuse one without throwing, and the
|
||||
picture would be kept as sent. It then gives the map to 2D (glMem() throws, draw() draws the frame again there and
|
||||
glKill() forgets the card's pictures). Each read waits for the card to finish everything sent so far, so it is done
|
||||
at most once every GL_MEM_EVERY ms: the card keeps an error until it is read, so a later read still finds it, and a
|
||||
picture refused in between shows at worst as a dark box for that time. The first pictures sent into a new atlas are
|
||||
checked at once (a card that allocates it lazily refuses there). A frame that only reuses the atlas asks nothing. */
|
||||
const GL_MEM_EVERY=1000;
|
||||
function glsFrameEnd(){if(!GLS.frame)return;GLS.frame=false;if(GLS.up)GLS.upq=true;GLS.up=0;
|
||||
if(GLS.upq&&GLX.gl){const t=performance.now();if(t-GLS.memT>=GL_MEM_EVERY){GLS.memT=t;GLS.upq=false;glMem(GLX.gl,'the pictures');}}
|
||||
glsDrawNow();}
|
||||
|
|
@ -1,11 +1,25 @@
|
|||
function draw(now){DFC=new Map();try{drawFrame(now);}finally{DFC=null;}}
|
||||
/* A frame. An error from the card itself (glErr()) gives WebGL up for this session and draws the same frame again in
|
||||
2D, once; any other error goes on to the loop's tickErr(). Either way the 2D context and the sprite queue are reset. */
|
||||
function draw(now){for(let pass=0;;pass++){let err=null;DFC=new Map();SPR_F++;
|
||||
try{drawFrame(now);}catch(e){err=e;}
|
||||
try{glsFrameEnd();}catch(e){if(!err)err=e;}finally{DFC=null;GLS.frame=false;GLS.n=0;ctx=CTX0;sprcTrim();}
|
||||
if(!err)return;if(!err.glErr||pass)throw err;glKill(err);}}
|
||||
// Rectangles on a 64 px grid: a new one is compared only with the few that share its cells (a plain list made the
|
||||
// label placement quadratic in the number of cities).
|
||||
class RGrid{constructor(){this.m=new Map();}
|
||||
cells(r,f){for(let cx=Math.floor(r.x/64);cx<=Math.floor((r.x+r.w)/64);cx++)for(let cy=Math.floor(r.y/64);cy<=Math.floor((r.y+r.h)/64);cy++)f(cx*100003+cy);}
|
||||
push(r){this.cells(r,k=>{const a=this.m.get(k);if(a)a.push(r);else this.m.set(k,[r]);});}
|
||||
hits(r){let h=false;this.cells(r,k=>{if(h)return;const a=this.m.get(k);if(a)for(const q of a)if(r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h){h=true;return;}});return h;}}
|
||||
function drawFrame(now){
|
||||
if(!ctx)return;
|
||||
const ks=visibleKs(),z=cam.z,G=glOn();
|
||||
// WebGL on: the sea, land, waves, clouds and cables are on the card (glBegin); the 2D canvas below them stays empty.
|
||||
// Off (2D chosen, no game, a puzzle, the card given up), its layers are hidden here, before anything can return early.
|
||||
if(G){try{glBegin(now,ks);}catch(e){throw glErr(e);}}
|
||||
else{glShow(false);GLX.c0clean=false;const wl=worldLayer(z);
|
||||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||||
// sea
|
||||
const g=ctx.createLinearGradient(0,0,0,CH);g.addColorStop(0,'#62CBEA');g.addColorStop(1,'#43AED6');ctx.fillStyle=g;ctx.fillRect(0,0,CW,CH);
|
||||
const ks=visibleKs(),z=cam.z;
|
||||
const wl=worldLayer(z);
|
||||
for(const k of ks){
|
||||
ctx.setTransform(DPR*z,0,0,DPR*z,DPR*((k*W-cam.x)*z+CW/2),DPR*((-cam.y)*z+CH/2));
|
||||
// waves: one path, one stroke
|
||||
|
|
@ -19,43 +33,49 @@ function drawFrame(now){
|
|||
ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();
|
||||
for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100,y=c.y;ctx.moveTo(x+16*c.s,y);ctx.arc(x,y,16*c.s,0,7);ctx.moveTo(x+38*c.s,y-8*c.s);ctx.arc(x+18*c.s,y-8*c.s,20*c.s,0,7);ctx.moveTo(x+55*c.s,y);ctx.arc(x+40*c.s,y,15*c.s,0,7);}ctx.fill();
|
||||
}
|
||||
}
|
||||
ctx.setTransform(DPR,0,0,DPR,0,0);
|
||||
if(!S)return;
|
||||
const sc=iconScale(),day=S.day;
|
||||
const sc=iconScale(),day=S.day;zoomHold(sc,G);
|
||||
// cable systems
|
||||
drawCables(ks);
|
||||
// links
|
||||
AR_PILLS.length=0;
|
||||
const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY;
|
||||
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
|
||||
const far=lodFar(),ML=mapLinks(day),LG=ML.LG,GM=ML.GM,PI=ML.PI,busy=linesOnScreen(GM,ks)>MAP_BUSY;
|
||||
// WebGL on: the card draws every line and packet now, and the rest (labels, markers, cities…) goes on the overlay.
|
||||
if(G)try{glFrame(ML,ks,far,busy,now,sc);}catch(e){throw glErr(e);}
|
||||
for(let gi=0;gi<LG.length;gi++){const grp=LG[gi],{l,many,up,cap,load,df,bld,cut,dark,vx,w0,col,dash,pk}=ML.looks[gi],gm=GM[gi];
|
||||
const pz=pzOn(),arPz=pz&&!!S.ar,sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null;
|
||||
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length;
|
||||
// Only what sits at the middle of a line is still painted here when the card draws the lines.
|
||||
if(G&&!(bld||cut&&!vx||sel||z>0.9&&!busy))continue;
|
||||
const w=w0*sc*(far?0.5:1),np=gm.pts.length;
|
||||
if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);}
|
||||
for(const k of ks){
|
||||
// Off screen (with room for the widest line and the markers at its middle): nothing of it would show. The line's
|
||||
// box is kept on its cached geometry, so a link off screen is skipped without projecting its points.
|
||||
const bb=gm.bb||(gm.bb=(()=>{let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity;for(const p of gm.pts){if(p[0]<a)a=p[0];if(p[0]>b)b=p[0];if(p[1]<c)c=p[1];if(p[1]>d)d=p[1];}return [a,b,c,d];})());
|
||||
if((bb[1]+k*W-cam.x)*cam.z+CW/2<-40||(bb[0]+k*W-cam.x)*cam.z+CW/2>CW+40||(bb[3]-cam.y)*cam.z+CH/2<-40||(bb[2]-cam.y)*cam.z+CH/2>CH+40)continue;
|
||||
let mxx,my;
|
||||
if(G){const m=gm.mid||(gm.mid=polyAt(gm.pts,gm.cum,.5));mxx=(m[0]+k*W-cam.x)*cam.z+CW/2;my=(m[1]-cam.y)*cam.z+CH/2;}else{
|
||||
// Screen points as toS() gives them, kept in SX/SY.
|
||||
for(let i=0;i<np;i++){const p=gm.pts[i];SX[i]=(p[0]+k*W-cam.x)*cam.z+CW/2;SY[i]=(p[1]-cam.y)*cam.z+CH/2;}
|
||||
const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i<np;i++)ctx.lineTo(SX[i],SY[i]);};
|
||||
ctx.lineCap='round';ctx.lineJoin='round';
|
||||
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[]);path();ctx.stroke();
|
||||
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(LDASH[dash]);path();ctx.stroke();
|
||||
ctx.strokeStyle=col;ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||||
// Architect runs: tubes sharing one trench are drawn as strands of one bundle (one snip takes them all).
|
||||
if(pz&&many){ctx.strokeStyle='#1E2640';ctx.lineWidth=1.3;for(let j=1;j<grp.length;j++){const d=w*(j/grp.length-0.5);ctx.beginPath();for(let i=0;i<np;i++){const a=Math.max(0,i-1),b=Math.min(np-1,i+1),dx=SX[b]-SX[a],dy=SY[b]-SY[a],n=Math.hypot(dx,dy)||1,x=SX[i]-dy/n*d,y=SY[i]+dx/n*d;i?ctx.lineTo(x,y):ctx.moveTo(x,y);}ctx.stroke();}path();}
|
||||
// Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again.
|
||||
if(df&&!bld&&!dark&&!busy){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);}
|
||||
const at=t=>polyAtXY(SX,SY,gm.cum,t);
|
||||
if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12)>>(far?1:0)||1,len=gm.len*z,spd=90;
|
||||
if(pk){const n=pk>>(far?1:0)||1,len=gm.len*z,spd=90;
|
||||
ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=far?1:1.5;
|
||||
const rr2=far?1.6:Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i<n;i++){let t=(base+i/n)%1;if(i%2)t=1-t;const [px,py]=at(t);ctx.moveTo(px+rr2,py);ctx.arc(px,py,rr2,0,7);}ctx.fill();ctx.stroke();}
|
||||
const [mx2,my]=at(.5);const mxx=mx2;
|
||||
if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);}
|
||||
else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else if(!arPz)drawBackhoe(mxx,my,now,l.sub);}
|
||||
else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
|
||||
[mxx,my]=at(.5);}
|
||||
if(bld){if(far)stamp('bldfar',12,12,6,6,1,mxx,my,g=>{g.fillStyle='#FF8A3D';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,4,0,7);g.fill();g.stroke();});else drawCone(mxx,my,now);}
|
||||
else if(cut&&!vx){if(far)stamp('cutfar',14,14,7,7,1,mxx,my,g=>{g.fillStyle='#FF4D5E';g.strokeStyle='#1E2640';g.lineWidth=1.5;g.beginPath();g.arc(0,0,5,0,7);g.fill();g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText('!',0,0.5);});else if(!arPz)drawBackhoe(mxx,my,now,l.sub);}
|
||||
else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);pill(t,ctx.font,tw,17,8,'#fff','#1E2640','#1E2640',2,mxx,my-0.5,1.5);}
|
||||
// Every puzzle: say whether the tubes between two cities share one trench or take separate paths.
|
||||
if(pz&&!cut&&!bld&&(many||arPaths(l)>1)&&(many||lineIdx(l,PI.get(edgeKey(l)))===0))AR_PILLS.push([mxx,my+(sel||!S.ar?19:0),many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:arPaths(l)}),many]);
|
||||
}
|
||||
|
|
@ -76,9 +96,9 @@ function drawFrame(now){
|
|||
// cities
|
||||
UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}}
|
||||
// Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides.
|
||||
const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;if(pzHide(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}}
|
||||
const vis=[];for(const C of CITIES){const sy=(C.y-cam.y)*cam.z+CH/2;if(sy<-60||sy>CH+60)continue;if(C.off&&!cityOn(C.id))continue;if(pzHide(C.id))continue;for(const k of ks){const sx=(C.x+k*W-cam.x)*cam.z+CW/2;if(sx<-60||sx>CW+60)continue;vis.push({C,sx,sy});}}
|
||||
const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P);
|
||||
const rects=[],labs=[],hit=(r)=>rects.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h);
|
||||
const rects=new RGrid(),labs=new RGrid(),hit=(r)=>rects.hits(r);
|
||||
const farL=lodFar();
|
||||
// Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them.
|
||||
CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}}
|
||||
|
|
@ -93,10 +113,10 @@ function drawFrame(now){
|
|||
const h=farL?6:cityTop(v.C.id,p);const below=farL?v.sy+15:v.sy+16*csc+8,above=farL?v.sy-15:v.sy-h*csc-17*csc;let ly=null;
|
||||
for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
// Your POPs may sit over a city icon, but not over another name: that one waits until you zoom in.
|
||||
if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.some(q=>r.x<q.x+q.w&&q.x<r.x+r.w&&r.y<q.y+q.h&&q.y<r.y+r.h)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
if(ly===null&&prio(v)===1)for(const y of [below,above]){const r={x:v.sx-tw/2,y:y-10,w:tw,h:21};if(!labs.hits(r)){ly=y;rects.push(r);labs.push(r);break;}}
|
||||
if(ly===null&&(prio(v)===0||(prio(v)===1&&(v.C.id===S.home||UI.hover===v.C.id)))){ly=below;const r={x:v.sx-tw/2,y:below-10,w:tw,h:21};rects.push(r);labs.push(r);}
|
||||
v.ly=ly;}
|
||||
if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,csc,now);pzDrawMarks(ks,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);
|
||||
if(pzOn()){for(let i=vis.length-1;i>=0;i--)pzDrawCity(vis[i],csc,now);pzDrawMarks(ks,now);}else for(let i=vis.length-1;i>=0;i--){const v=vis[i];drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);}
|
||||
// cable ships at sea (88-cable-ships.js), over the city labels so a ship leaving port stays in sight
|
||||
drawShips(ks,now);
|
||||
// Architect runs: what the tubes between two cities are (one trench, or separate paths), above the cities.
|
||||
|
|
@ -105,7 +125,8 @@ function drawFrame(now){
|
|||
if(UI.mk)mkDraw(ks);else if(mkOn()&&!pzOn()&&CITY[S.monkey.c])mkStart(S.monkey.c);
|
||||
// floaters
|
||||
for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;}
|
||||
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}}
|
||||
const font='800 17px "Baloo 2", sans-serif';if(f.w===undefined){ctx.font=font;f.w=ctx.measureText(f.text).width;}
|
||||
for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;textStamp(f.text,font,17,f.w,f.col,'#fff',4,sx,sy-a*40);ctx.globalAlpha=1;}}
|
||||
}
|
||||
/* A map with more than MAP_BUSY lines on screen (huge late-game networks) is a tangle where nobody reads thousands of
|
||||
overlapping labels or fiber dots, and painting them took about half of every frame. They come back once fewer lines
|
||||
|
|
@ -116,7 +137,7 @@ function linesOnScreen(GM,ks){let n=0;for(const gm of GM){const b=gm.box||(gm.bo
|
|||
for(const k of ks){const x0=(b[0]+k*W-cam.x)*cam.z+CW/2,x1=(b[2]+k*W-cam.x)*cam.z+CW/2,y0=(b[1]-cam.y)*cam.z+CH/2,y1=(b[3]-cam.y)*cam.z+CH/2;
|
||||
if(!(x1<-40||x0>CW+40||y1<-40||y0>CH+40))n++;}}return n;}
|
||||
function ptsBox(pts){let a=Infinity,b=Infinity,c=-Infinity,d=-Infinity;for(const p of pts){if(p[0]<a)a=p[0];if(p[1]<b)b=p[1];if(p[0]>c)c=p[0];if(p[1]>d)d=p[1];}return [a,b,c,d];}
|
||||
function drawCone(x,y,now){const b=Math.sin(now/300)*1.5;ctx.save();ctx.translate(x,y-12+b);ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();ctx.restore();}
|
||||
function drawCone(x,y,now){stamp('cone',26,28,13,13,1,x,y-12+Math.sin(now/300)*1.5,()=>{ctx.strokeStyle='#1E2640';ctx.lineWidth=2;ctx.fillStyle='#FF8A3D';ctx.beginPath();ctx.moveTo(-7,9);ctx.lineTo(0,-10);ctx.lineTo(7,9);ctx.closePath();ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.fillRect(-4,-1,8,3);ctx.fillStyle='#1E2640';rr(-10,8,20,4,2);ctx.fill();});}
|
||||
// Static land + cable map, rendered once per zoom bucket into an offscreen canvas.
|
||||
function paintWorld(c,z,withCables){const LANDP=lodFar()?LANDP_FAR:LANDP_ALL;
|
||||
for(const o of [0,W,-W]){c.save();c.translate(o+5/z,7/z);c.fillStyle='rgba(20,90,130,.35)';for(const p of LANDP)c.fill(p);c.restore();}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@
|
|||
GPU canvas implementations (Firefox on Android) garble big paths (#43). It is painted into an offscreen image
|
||||
instead: the whole world when that fits in MAXPX, otherwise the visible area plus a margin, repainted when you
|
||||
pan out of it. While a zoom gesture is still moving, the last image is scaled rather than repainted. */
|
||||
const SOFT_CANVAS=/Firefox\//.test(navigator.userAgent);
|
||||
/* Only Firefox on Android gets that image as a software canvas (willReadFrequently). Firefox on a computer drew it
|
||||
fine on the graphics card, and a software canvas there is sent to the card again on every frame, a cost that grows
|
||||
with the image: zoomed in, the 2D map ran at half its speed. */
|
||||
const softCanvas=ua=>/Android.*Firefox\//.test(ua),SOFT_CANVAS=softCanvas(navigator.userAgent);
|
||||
function wlCovers(z){if(WL.full)return true;const hw=CW/2/z,hh=CH/2/z,w=WL.cv.width/WL.sc,h=WL.cv.height/WL.sc;
|
||||
return cam.x-hw>=WL.ox&&cam.x+hw<=WL.ox+w&&cam.y-hh>=WL.oy&&cam.y+hh<=WL.oy+h;}
|
||||
function worldLayer(z){
|
||||
|
|
@ -21,14 +24,12 @@ function worldLayer(z){
|
|||
function drawWorldLayer(wl,k,z,k0){if(!wl.full&&k!==k0)return;const f=z*DPR/wl.sc,ox=(wl.full?k*W:wl.ox);
|
||||
ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(wl.cv,Math.round(DPR*((ox-cam.x)*z+CW/2)),Math.round(DPR*((wl.oy-cam.y)*z+CH/2)),wl.cv.width*f,wl.cv.height*f);}
|
||||
function cableCol(C){return C.price<=0.85?'#14A88C':C.price<=1.1?'#2F7BEA':'#A05AE0';}
|
||||
function drawBackhoe(x,y,now,sub){
|
||||
const b=Math.sin(now/180)*2;ctx.save();ctx.translate(x,y-14+b);
|
||||
function drawBackhoe(x,y,now,sub){stamp('hoe|'+(sub?1:0),38,32,15,16,1,x,y-14+Math.sin(now/180)*2,()=>{
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=2.2;
|
||||
if(sub){ // shark fin
|
||||
ctx.fillStyle='#6B7C99';ctx.beginPath();ctx.moveTo(-12,8);ctx.quadraticCurveTo(-2,-14,10,-12);ctx.quadraticCurveTo(4,-2,12,8);ctx.closePath();ctx.fill();ctx.stroke();
|
||||
}else{
|
||||
ctx.fillStyle='#FFD23F';rr(-12,-4,18,12,3);ctx.fill();ctx.stroke();rr(-8,-12,10,9,2);ctx.fillStyle='#BDE8FF';ctx.fill();ctx.stroke();
|
||||
ctx.beginPath();ctx.moveTo(6,0);ctx.lineTo(14,-10);ctx.lineTo(19,2);ctx.stroke();ctx.fillStyle='#1E2640';ctx.beginPath();ctx.arc(-7,10,3,0,7);ctx.arc(2,10,3,0,7);ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
}});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,32 @@
|
|||
// Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow.
|
||||
const LBLW={},LINKW=new Map(),LBLF=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;});}catch(e){}
|
||||
const LBLW={},LINKW=new Map(),LBLF=new Map(),FKEY=new Map(),QKEY=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;spritesReset();});}catch(e){}
|
||||
// A label on a pill: its text and look never change, so it is painted once (spriteEntry) and drawn as a picture. The
|
||||
// centre is x, y; the text sits at y+ty. The pill's box is w×h with corners r; the picture also takes the outline.
|
||||
// Keys are kept by text (PILLK), one per look: joining them for every label on every frame was most of the map's garbage.
|
||||
const PILLK=new Map();
|
||||
function pill(t,font,w,h,r,fill,ink,stroke,lw,x,y,ty){
|
||||
const pad=lw+2,W=Math.ceil(w+pad*2),H=Math.ceil(h+pad*2);let L=PILLK.get(t),m=null;
|
||||
if(L)for(let i=0;i<L.length;i++){const q=L[i];if(q.font===font&&q.w===w&&q.h===h&&q.r===r&&q.fill===fill&&q.ink===ink&&q.stroke===stroke&&q.lw===lw&&q.ty===ty){m=q;break;}}
|
||||
if(!m){if(!L){if(PILLK.size>4000)PILLK.clear();PILLK.set(t,L=[]);}L.push(m={font,w,h,r,fill,ink,stroke,lw,ty,k:['pill',t,font,w,h,r,fill,ink,stroke,lw,ty].join('|')});}
|
||||
const e=spriteHas(m.k)||spriteEntry(m.k,W,H,W/2,H/2,g=>{g.translate(W/2,H/2);g.fillStyle=fill;g.strokeStyle=stroke;g.lineWidth=lw;
|
||||
rr(-w/2,-h/2,w,h,r);g.fill();g.stroke();g.fillStyle=ink;g.font=font;g.textAlign='center';g.textBaseline='middle';g.fillText(t,0,ty);});
|
||||
// Whole device pixels, so the text stays as sharp as before.
|
||||
blit(e,Math.round((x-e.w/2)*DPR)/DPR,Math.round((y-e.h/2)*DPR)/DPR,e.w,e.h);}
|
||||
// Zoomed out a city is a small picture (a dot, or your POP's box), kept as a sprite; a POP in trouble glows under it.
|
||||
function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
ctx.save();ctx.translate(sx,sy);ctx.strokeStyle='#1E2640';
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.strokeStyle='#1E2640';}
|
||||
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)dot(sx,sy,12,'rgba(255,77,94,1)',.35+.25*Math.sin(now/200));
|
||||
const t=cTier(C.id),ph=sel?Math.floor(now/40)%8:-1,f=(p?1:0)|(down?2:0)|(p&&p.site2?4:0)|(p&&(p.routers||1)>=2?8:0)|(hov?16:0)|(hasIxAt(C.id)?32:0)|(CM.off.has(C.id)?64:0)|(CM.inc.has(C.id)?128:0);
|
||||
// The key, kept per city and built again only when the picture changes.
|
||||
let m=FKEY.get(C.id);if(!m||m.f!==f||m.t!==t||m.ph!==ph)FKEY.set(C.id,m={f,t,ph,k:'far|'+t+'|'+f+'|'+ph});
|
||||
stamp(m.k,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph));
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
|
||||
pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);}
|
||||
}
|
||||
function cityFarStatic(C,p,down,sel,hov,ph){ctx.strokeStyle='#1E2640';
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=2.5;ctx.setLineDash([4,4]);ctx.lineDashOffset=-ph;ctx.beginPath();ctx.arc(0,0,p?14:9,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;ctx.strokeStyle='#1E2640';}
|
||||
if(p){
|
||||
if(!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){ctx.fillStyle=`rgba(255,77,94,${.35+.25*Math.sin(now/200)})`;ctx.beginPath();ctx.arc(0,0,12,0,7);ctx.fill();}
|
||||
const col=down?'#8A91A8':'#FF4F9A';ctx.lineWidth=1.8;
|
||||
if(p.site2){ctx.setLineDash([2,2]);ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(9,6);ctx.stroke();ctx.setLineDash([]);ctx.fillStyle=col;rr(5,3,9,7,3);ctx.fill();ctx.stroke();}
|
||||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-6,-7,15,10,4);ctx.fill();ctx.stroke();}
|
||||
|
|
@ -15,26 +35,26 @@ function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
|||
const t=cTier(C.id),r=FAR_R[t]*(hov?1.3:1);if(t===4){ctx.fillStyle='rgba(255,255,255,.55)';ctx.beginPath();ctx.arc(0,0,r+4.5,0,7);ctx.fill();}
|
||||
ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.lineWidth=t>=3?1.6:1.3;ctx.beginPath();ctx.arc(0,0,r,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.off.has(C.id)){ctx.fillStyle='#16A866';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?9:5,p?-7:-5,3,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}
|
||||
ctx.restore();
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;rr(sx-tw/2,ly-8,tw,16,8);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);}
|
||||
}
|
||||
function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
||||
if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
const hot=(UI.hotMap||{})[C.id];
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
// No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom).
|
||||
if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc;ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;ctx.beginPath();ctx.arc(sx,sy+2*sc,r,0,7);ctx.fill();ctx.stroke();return;}
|
||||
const t=cTier(C.id),cs=p?1:CSC[t];
|
||||
const k=sc*(hov?1.15:1);
|
||||
ctx.save();ctx.translate(sx,sy);
|
||||
if(UI.feed&&UI.feed.has(C.id)){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-now/40;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
// A flood is filling ports here: they pulse until it is over (#242).
|
||||
if(p&&R.ddosHot&&R.ddosHot[C.id]){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=now/30;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(p&&!down&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9){const a=.35+.25*Math.sin(now/200);ctx.fillStyle=`rgba(255,77,94,${a})`;ctx.beginPath();ctx.arc(0,-6*k,26*k,0,7);ctx.fill();}
|
||||
if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}}
|
||||
// A city's picture is painted once per state and kept as a sprite (citySprite). What moves every frame is painted on top
|
||||
// (cityMoving): the lights, the steam, a flashing IX, the hot badges and the offer bubble. The rings and the glow move too,
|
||||
// but in steps (cityPhase), so their sprite changes only at a step; so does its scale (sprQ(), 59-gl-sprites.js).
|
||||
// dd is -1 without an attack: the attack's ring at step 0 must not share a sprite with no ring at all.
|
||||
function cityPhase(C,p,sel,now){const ph={sel:0,dd:-1,gl:-1};
|
||||
if(sel)ph.sel=Math.floor(now/40)%12; // dash period 12 px, lineDashOffset -now/40
|
||||
if(p&&R.ddosHot&&R.ddosHot[C.id])ph.dd=Math.floor(now/30)%8; // dash period 8 px, lineDashOffset now/30
|
||||
if(p&&!(p.down>S.day)&&R.cityDem[C.id]>0&&sfOf(R,C.id)<0.9)ph.gl=Math.round((Math.sin(now/200)+1)*3.5); // 8 levels of .35+.25·sin
|
||||
return ph;}
|
||||
// The IX badge. Hot (a flood or a fault) it flashes: cityMoving() then draws it from two pictures, one per colour.
|
||||
function cityIX(C,p,t,h,hot,now){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),q=!p&&!hot&&ixQuiet(C.id),Rr=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4);
|
||||
ctx.fillStyle=hot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+Rr*Math.cos(a),-h+2+Rr*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke();
|
||||
ctx.fillStyle=mine||hot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);}
|
||||
// Everything about the city that does not move, in the city's own frame (origin on the city). Drawn into a sprite, so
|
||||
// it reads only what citySprite() puts in the key.
|
||||
function cityStatic(C,p,t,cs,k,ph,st){const down=st.down;
|
||||
if(st.feed){ctx.strokeStyle='#FF8A3D';ctx.lineWidth=4;ctx.setLineDash([3,5]);ctx.beginPath();ctx.arc(0,-6*k,36*k,0,7);ctx.stroke();ctx.setLineDash([]);}
|
||||
if(st.sel){ctx.strokeStyle='#FF4F9A';ctx.lineWidth=3;ctx.setLineDash([6,6]);ctx.lineDashOffset=-ph.sel;ctx.beginPath();ctx.arc(0,-6*k,30*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;}
|
||||
if(ph.dd>=0){ctx.strokeStyle='#FF4D5E';ctx.lineWidth=3;ctx.setLineDash([4,4]);ctx.lineDashOffset=ph.dd;ctx.beginPath();ctx.arc(0,-6*k,33*k,0,7);ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;}
|
||||
ctx.scale(k*cs,k*cs);
|
||||
ctx.fillStyle='rgba(30,38,64,.2)';ctx.beginPath();ctx.ellipse(0,9,p?20:SKY_W[t]/2+5,5,0,0,7);ctx.fill();
|
||||
const h=p?18:SKY_H[t];
|
||||
|
|
@ -56,30 +76,64 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
|||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-13,-13,34,16,6);ctx.fill();ctx.stroke();}
|
||||
if(p.gen){ctx.fillStyle='#FFD23F';rr(-27,-1,9,11,2);ctx.fill();ctx.stroke();}
|
||||
ctx.fillStyle=down?'#8A91A8':'#FF4F9A';rr(-17,-7,34,16,6);ctx.fill();ctx.stroke();
|
||||
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const t=(now/700+i/3)%1;ctx.fillStyle=`rgba(90,98,130,${0.55*(1-t)})`;ctx.beginPath();ctx.arc(6+i*3,-12-t*18,3+t*4,0,7);ctx.fill();}}
|
||||
if((p.rgen||0)>0){const G=RG[p.rgen||0];ctx.fillStyle=G.badge?'#7CFFB2':'#FFD23F';ctx.beginPath();ctx.arc(17,-7,6,0,7);ctx.fill();ctx.lineWidth=1.8;ctx.stroke();ctx.fillStyle='#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(G.badge||String(G.cls+1),17,-6.5);ctx.lineWidth=2.2;}
|
||||
const sf=sfOf(R,C.id);
|
||||
for(let i=0;i<4;i++){const on=down?false:(((now/(160+i*37))|0)+i)%3!==0;ctx.fillStyle=down?'#3B4260':on?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';ctx.beginPath();ctx.arc(-10+i*6.6,1,2.1,0,7);ctx.fill();}
|
||||
if(down){ctx.fillStyle='#fff';ctx.font='900 14px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.fillText('zzz',20,-14);}
|
||||
if(flip)ctx.restore();
|
||||
ctx.translate(0,-2);
|
||||
}
|
||||
const ixn=ixName(C.id);
|
||||
// The IX badge sits at the skyline's top right, whatever its width.
|
||||
if(ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov)){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id),ixHot=hot&&hot.ix,q=!p&&!ixHot&&ixQuiet(C.id),R=q?6.5:8.5,ix=p?19:SKY_W[t]/2+(q?2:4);
|
||||
ctx.fillStyle=ixHot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(ix+R*Math.cos(a),-h+2+R*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=q?1.4:2;ctx.stroke();
|
||||
ctx.fillStyle=mine||ixHot?'#fff':'#1E2640';ctx.font=`900 ${q?6.5:8}px Nunito, sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',ix,-h+2.5);}
|
||||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const k of ['r','t','p','c']){if(!hot[k])continue;ctx.globalAlpha=pulse;ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-29,y,6.5,0,7);ctx.fill();ctx.globalAlpha=1;ctx.lineWidth=2;ctx.strokeStyle='#1E2640';ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(HOTL[k],-29,y+0.5);y+=14;}}
|
||||
const off=CM.off.has(C.id);
|
||||
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=CM.big.has(C.id);ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
|
||||
const inc=CM.inc.has(C.id);
|
||||
if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||||
ctx.restore();
|
||||
if(st.ixDraw&&!st.ixHot)cityIX(C,p,t,h,false,0);
|
||||
if(st.inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||||
}
|
||||
// The picture of a city in a given state, at the quantised scale kq: painted once and kept until it is not needed.
|
||||
// Its key is kept per city (CKEY) and joined again only when one of its parts changes: the yes/no parts are bits of f.
|
||||
const CKEY=new Map();
|
||||
function citySprite(C,p,t,cs,kq,ph,st){const id=C.id,
|
||||
f=(st.down?1:0)|(p?2:0)|(p&&p.site2?4:0)|(p&&p.site2&&siteDown(id,'b')?8:0)|(p&&p.ringcut>S.day?16:0)|(p&&p.gen?32:0)|(C.au?64:0)|(st.ixDraw?128:0)|
|
||||
(st.ixHot?256:0)|(S.myIx[id]?512:0)|(hasIxAt(id)?1024:0)|(!p&&ixQuiet(id)?2048:0)|(st.feed?4096:0)|(st.inc?8192:0),
|
||||
ro=p?(p.routers||1):0,rg=p?(p.rgen||0):0,ix=ixName(id)||'',sp=st.sel?ph.sel:-1,dd=ph.dd;
|
||||
let m=CKEY.get(id);
|
||||
if(!m||m.t!==t||m.kq!==kq||m.f!==f||m.ro!==ro||m.rg!==rg||m.ix!==ix||m.sp!==sp||m.dd!==dd)CKEY.set(id,m={t,kq,f,ro,rg,ix,sp,dd,k:['city',id,t,kq,f,ro,rg,ix,sp,dd].join('|')});
|
||||
const e=spriteHas(m.k);if(e)return e;
|
||||
const W=Math.ceil(92*kq),H=Math.ceil(84*kq),ax=45*kq,ay=46*kq;
|
||||
return spriteEntry(m.k,W,H,ax,ay,g=>{g.translate(ax,ay);cityStatic(C,p,t,cs,kq,ph,st);});}
|
||||
// The parts that move, in the city's frame at the true scale k.
|
||||
function cityMoving(C,p,t,cs,k,sx,sy,now,h,st,hot){const down=st.down,K=k*cs;
|
||||
if(p){// The POP's own frame is shifted 2 down, and mirrored Down Under (C.au): mp() takes a point of that frame to the city's.
|
||||
// A point (x,y) of that frame is at sx+(fl?-x:x)*K, sy+(fl?-y-2:y+2)*K (written out: no array per light per frame).
|
||||
const fl=!!C.au,sf=sfOf(R,C.id);
|
||||
if(!down&&(R.nodeLoad[C.id]||0)>=(R.nodeCap[C.id]||1e12)*0.95){for(let i=0;i<3;i++){const tt=(now/700+i/3)%1,x=6+i*3,y=-12-tt*18;dot(sx+(fl?-x:x)*K,sy+(fl?-y-2:y+2)*K,(3+tt*4)*K,'rgba(90,98,130,1)',0.55*(1-tt));}}
|
||||
// The four lights: a disc each, lit or not.
|
||||
for(let i=0;i<4;i++){const lit=down?false:(((now/(160+i*37))|0)+i)%3!==0,x=-10+i*6.6,col=down?'#3B4260':lit?(sf<0.9?'#FF4D5E':'#7CFFB2'):'#2A3150';dot(sx+(fl?-x:x)*K,sy+(fl?-3:3)*K,2.1*K,col,1);}
|
||||
}
|
||||
// A flashing IX: two pictures, one per colour.
|
||||
if(st.ixDraw&&st.ixHot){const on=Math.sin(now/180)>0,ix=p?19:SKY_W[t]/2+4;stamp('ixhot'+(on?1:0),22,22,11,11,K,sx+ix*K,sy+(2-h)*K,()=>{ctx.translate(-ix,h-2);ctx.strokeStyle='#1E2640';cityIX(C,p,t,h,true,on?1:-1);},true);}
|
||||
// Hot badges: the red disc pulses, the ring and the letter over it stay.
|
||||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const kk of ['r','t','p','c']){if(!hot[kk])continue;const bx=sx-29*K,by=sy+y*K;dot(bx,by,6.5*K,'#FF4D5E',pulse);
|
||||
stamp('hotb|'+HOTL[kk],18,18,9,9,K,bx,by,g=>{g.lineWidth=2;g.strokeStyle='#1E2640';g.beginPath();g.arc(0,0,6.5,0,7);g.stroke();g.fillStyle='#fff';g.font='900 8px Nunito, sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(HOTL[kk],0,0.5);},true);y+=14;}}
|
||||
// The offer bubble bobs over the city.
|
||||
if(st.off)stamp('offer|'+(st.big?2:1),30,28,15,12,K,sx-2*K,sy+(-h-16+Math.sin(now/250)*3)*K,g=>{g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=2.2;g.beginPath();g.ellipse(0,0,11,9,0,0,7);g.fill();g.stroke();
|
||||
g.beginPath();g.moveTo(-3,8);g.lineTo(-5,14);g.lineTo(2,8);g.fill();g.fillStyle=st.big?'#FF4F9A':'#16A866';g.font='900 13px "Baloo 2", sans-serif';g.textAlign='center';g.textBaseline='middle';g.fillText(st.big?'$$':'$',0,1);},true);}
|
||||
function drawCity(C,sx,sy,sc,now,lyOverride,dem){
|
||||
if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
const hot=(UI.hotMap||{})[C.id];
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
// No room for its skyline here: a quiet dot, a little bigger for bigger cities, until you zoom in (cityRoom).
|
||||
if(dem&&!p&&!sel&&!hov){const r=(2.6+cTier(C.id)*0.35)*sc,rq=Math.round(r*4)/4,fill=hasIxAt(C.id)?'#FFD23F':'#FFFFFF',S2=Math.ceil(rq*2+4);
|
||||
const qk=rq*8+(fill==='#FFFFFF'?0:1);let key=QKEY.get(qk);if(!key)QKEY.set(qk,key=['quiet',rq,fill].join('|'));
|
||||
const e=spriteHas(key)||spriteEntry(key,S2,S2,S2/2,S2/2,g=>{g.translate(S2/2,S2/2);g.fillStyle=fill;g.strokeStyle='#1E2640';g.lineWidth=1.6;g.beginPath();g.arc(0,0,rq,0,7);g.fill();g.stroke();});
|
||||
blit(e,sx-e.ax,sy+2*sc-e.ay,e.w,e.h);return;}
|
||||
const t=cTier(C.id),cs=p?1:CSC[t],k=sc*(hov?1.15:1),kq=sprQ(k);
|
||||
const ixn=ixName(C.id),ixDraw=!!ixn&&(ixShown(C.id,p)||(hot&&hot.ix)||sel||hov),ixHot=!!(ixDraw&&hot&&hot.ix);
|
||||
const st={down:!!down,feed:!!(UI.feed&&UI.feed.has(C.id)),sel:!!sel,inc:CM.inc.has(C.id),ixDraw,ixHot,off:CM.off.has(C.id),big:CM.big.has(C.id)};
|
||||
const ph=cityPhase(C,p,sel,now),spr=citySprite(C,p,t,cs,kq,ph,st),r=k/kq;
|
||||
// The glow of a city in trouble pulses: a disc each frame, under the picture (as it was under the skyline).
|
||||
if(ph.gl>=0)dot(sx,sy-6*k,26*k,'rgba(255,77,94,1)',.35+.25*(2*ph.gl/7-1));
|
||||
blit(spr,sx-spr.ax*r,sy-spr.ay*r,spr.w*r,spr.h*r);
|
||||
cityMoving(C,p,t,cs,k,sx,sy,now,p?18:SKY_H[t],st,hot);
|
||||
// label
|
||||
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
|
||||
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
|
||||
pill(t,ctx.font,tw,19,9,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',2,sx,ly+0.5,0.5);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,13 +24,13 @@ function shipAt(s,T){const f=S.fleet&&S.fleet[s.id],H=shipHomePt(s);if(!f||T>=f.
|
|||
else{p=1-(T-f.done)/Math.max(0.01,f.back-f.done);mode='back';}
|
||||
p=clamp(p,0,1);const [x,y]=polyAt(r.pts,r.cum,p),[x2]=polyAt(r.pts,r.cum,clamp(p+(mode==='back'?-0.01:0.01),0,1));return {x,y,m:mode,dx:x2-x||1};}
|
||||
// A cartoon cable ship: red hull, white bridge, the yellow bow sheave cable ships are known by; a wake when under way.
|
||||
function shipSprite(x,y,face,sc,col,now,mode){const c=ctx;c.save();c.translate(x,y+Math.sin(now/420+x*0.05)*1.2*sc);c.scale(face*sc,sc);
|
||||
function shipSprite(x,y,face,sc,col,now,mode){const bl=mode==='work'&&Math.floor(now/350)%2;
|
||||
stamp(['ship',col,face,mode,bl?1:0].join('|'),52,32,26,18,sc,x,y+Math.sin(now/420+x*0.05)*1.2*sc,c=>{c.scale(face,1);
|
||||
if(mode!=='port'&&mode!=='work'){c.strokeStyle='rgba(255,255,255,.85)';c.lineWidth=1.6;c.beginPath();c.moveTo(-10,3);c.quadraticCurveTo(-16,1,-22,4);c.moveTo(-10,5);c.quadraticCurveTo(-15,8,-21,9);c.stroke();}
|
||||
c.fillStyle=col;c.strokeStyle='#1E2640';c.lineWidth=1.6;c.lineJoin='round';c.beginPath();c.moveTo(-11,0);c.lineTo(11,0);c.lineTo(8,6);c.lineTo(-9,6);c.closePath();c.fill();c.stroke();
|
||||
c.fillStyle='#fff';c.beginPath();c.rect(-7,-7,8,7);c.fill();c.stroke();c.fillStyle='#1E2640';c.fillRect(-5,-5,4,2);
|
||||
c.beginPath();c.arc(9,-2,2.6,0,7);c.fillStyle='#FFD23F';c.fill();c.stroke();
|
||||
if(mode==='work'&&Math.floor(now/350)%2){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}
|
||||
c.restore();}
|
||||
if(bl){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}},true);}
|
||||
function drawShips(ks,now){SHIP_HITS.length=0;if(!S||pzOn()||!S.fleet)return;
|
||||
const T=S.day+(UI.speed?clamp(acc/DAY_MS,0,0.999):0),z=cam.z,sc=Math.max(0.85,Math.min(1.5,Math.sqrt(z)))*(lodFar()?0.9:1.05),list=[];
|
||||
for(const s of SHIPS){const p=shipAt(s,T);if(p.m==='port'&&z<1.1)continue;list.push({p,s,col:s.club==='prv'?'#7A5CFF':'#FF4D5E'});}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,5 @@ let PD={t:0,b:null};
|
|||
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
|
||||
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
|
||||
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||||
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
|
||||
|
||||
|
|
|
|||
37
src/game/96-map/97-diagnostics.js
Normal file
37
src/game/96-map/97-diagnostics.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/* Settings › Diagnostic info: one readout in a corner, for bug reports. What the screen tells the game (for phone
|
||||
layouts), how the map is drawn (the graphics card or 2D, and why), and how fast: frames per second, the slowest
|
||||
frames, the time draw() takes. It is also opened with ?vp or ?fps in the address (?novp, ?nofps close it), and,
|
||||
inside an installed app where there is no address bar, with five quick taps on the date. Its words are technical on
|
||||
purpose and stay in English: they are pasted into bug reports. */
|
||||
const DIAG={on:false,el:null,t:null,fr:[],dr:[],last:0,dms:-1};
|
||||
// One frame of the loop (99-loop.js): its interval, and the time draw() took if the map was drawn.
|
||||
function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now;if(D.dms>=0){D.dr.push(D.dms);D.dms=-1;}
|
||||
if(D.fr.length>600)D.fr.splice(0,300);if(D.dr.length>600)D.dr.splice(0,300);}
|
||||
// What draws the map, and why it is the 2D canvas when it is.
|
||||
function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)';
|
||||
if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';if(GLX.lost)return 'map: 2D (graphics context lost, waiting for it back)';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';}
|
||||
// Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. The loop runs at
|
||||
// the screen's rate even when a still map is not drawn again (mapStill()), so how often it was drawn is shown too.
|
||||
function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0),
|
||||
q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead;
|
||||
return `${sum?(f.length*1000/sum).toFixed(0):'-'} fps · map drawn ${sum?(d.length*1000/sum).toFixed(0):'-'}/s · p95 ${q(.95)} ms · max ${q(1)} ms\ndraw ${d.length?(d.reduce((a,x)=>a+x,0)/d.length).toFixed(1):'-'} ms · x${UI.speed||0} · zoom ${cam.z.toFixed(2)}`+
|
||||
(gl?` · ${GLX.nSeg} segments · ${GLX.nPk} packets`:'');}
|
||||
function diagShow(){const D=DIAG;let el=D.el;
|
||||
if(!el){el=D.el=document.createElement('pre');el.id='diag';el.style.cssText='position:fixed;left:8px;bottom:calc(var(--tabbar,0px) + 8px);z-index:99;margin:0;padding:6px 8px;max-width:calc(100vw - 32px);background:rgba(30,38,64,.85);color:#7CFFB2;font:11px/1.35 ui-monospace,monospace;border-radius:8px;pointer-events:none;white-space:pre-wrap;overflow-wrap:anywhere';
|
||||
// A hidden probe reads the safe areas (the notch, the home bar) as CSS gives them.
|
||||
const pr=document.createElement('div');pr.id='diagprobe';pr.style.cssText='position:fixed;visibility:hidden;padding:env(safe-area-inset-top,0px) 0 env(safe-area-inset-bottom,0px)';el.appendChild(pr);
|
||||
D.txt=document.createTextNode('');el.appendChild(D.txt);document.body.appendChild(el);}
|
||||
const cs=getComputedStyle(document.getElementById('diagprobe')),vv=window.visualViewport,de=document.documentElement,tb=document.getElementById('tabbar').getBoundingClientRect(),
|
||||
sa=navigator.standalone===true||!!(window.matchMedia&&matchMedia('(display-mode: standalone)').matches);
|
||||
D.txt.data=`Series of Tubes ${APP_VERSION} · ${LANG}\n`+
|
||||
`inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height} · dpr ${window.devicePixelRatio||1}\n`+
|
||||
`vv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\n`+
|
||||
`standalone ${sa} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}\n`+
|
||||
diagMap()+'\n'+diagPerf();}
|
||||
// Shows or hides the readout, and remembers it on this device.
|
||||
function diagOn(on){const D=DIAG;clearInterval(D.t);D.t=null;if(D.el){D.el.remove();D.el=null;}D.on=!!on;D.fr.length=D.dr.length=0;D.last=0;D.dms=-1;
|
||||
if(on){D.t=setInterval(diagShow,500);diagShow();}
|
||||
try{on?localStorage.setItem('sot-vp','1'):localStorage.removeItem('sot-vp');}catch(e){}}
|
||||
{const q=location.search;let on=false;try{on=localStorage.getItem('sot-vp')==='1';}catch(e){}
|
||||
if(/[?&](vp|fps)\b/.test(q))on=true;else if(/[?&]no(vp|fps)\b/.test(q))on=false;diagOn(on);}
|
||||
{let taps=[];document.getElementById('hDate').closest('.chip,div').addEventListener('click',()=>{const t=performance.now();taps=taps.filter(x=>t-x<1500).concat(t);if(taps.length>=5){taps=[];diagOn(!DIAG.on);}});}
|
||||
|
|
@ -12,7 +12,8 @@ function frame(now){
|
|||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt);
|
||||
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||
const t=animOn()?animT:0;
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;}
|
||||
if(DIAG.on)diagFrame(now);
|
||||
}
|
||||
// dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames
|
||||
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
|
||||
|
|
@ -27,12 +28,12 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c
|
|||
const r=c.getBoundingClientRect();if(r.top<=1&&r.left<=1&&r.right>=innerWidth-1&&r.bottom>=innerHeight-1)return true;}return false;}
|
||||
/* Paused, or with animations off, the map only changes when you move it, point at something or the network changes.
|
||||
Until then the last frame is still right, so it is not drawn again (phones keep cool). It is redrawn at least once
|
||||
a second anyway, and every frame while the land picture is still catching up with a zoom. */
|
||||
a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none). */
|
||||
const FRAME=[];
|
||||
function mapStill(t,now){const sl=UI.sel,dr=UI.drag;
|
||||
const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0];
|
||||
const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0,zoomMoving()];
|
||||
let same=v.length===FRAME.length;for(let i=0;i<v.length;i++)if(FRAME[i]!==v[i]){same=false;FRAME[i]=v[i];}
|
||||
return same&&now-(UI.drawnAt||0)<1000&&!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z));}
|
||||
return same&&now-(UI.drawnAt||0)<1000&&(glOn()||!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z)));}
|
||||
function tickErr(e){console.error('[tubes] tick failed',e);if(UI.tickErr)return;UI.tickErr=true;track('tick_error',true);
|
||||
toast(tr('loop.something_in_the_noc_glitched_the'),'bad');}
|
||||
function boot(data){
|
||||
|
|
|
|||
|
|
@ -1613,7 +1613,6 @@
|
|||
"common.vendor_tac":"Vendor TAC",
|
||||
"common.venus":"Venus",
|
||||
"common.via_rs":"via RS",
|
||||
"common.viewport_info":"Viewport info",
|
||||
"common.vigilante":"Vigilante",
|
||||
"common.walk_away":"Walk away",
|
||||
"common.wave_lease":"Wave lease",
|
||||
|
|
@ -3903,6 +3902,42 @@
|
|||
"rules.rules_are_locked_for_this_network":"{rules}: rules are locked for this network.",
|
||||
"rules.the_real_thing_your_pager_has":"The real thing. Your pager has opinions.",
|
||||
"rules.your_pager_never_sleeps":"Your pager never sleeps.",
|
||||
"sales.ask_vp":"Ask the board for a VP of Sales · {cost}",
|
||||
"sales.at_desk":"{name} runs sales",
|
||||
"sales.ceo_d":"Free, and sure of it. Every couple of months signs a huge deal on the golf course at 30% off, often with a promise nobody checked, and now and then signs an offer you declined. Has opinions. Cannot be fired.",
|
||||
"sales.ceo_golf":"The CEO signed {name} on the golf course: {bw} in {city} for {price}/mo, 30% off list.",
|
||||
"sales.ceo_n":"The CEO, who sells better than anyone",
|
||||
"sales.ceo_override":"You declined {name}, but the CEO had already shaken hands on it. They are now a customer.",
|
||||
"sales.ceo_promised":"He also promised: {req}.",
|
||||
"sales.ceo_s":"the CEO",
|
||||
"sales.ceo_say_airport":"Just landed. Signed nothing, but I had a very good feeling about the lounge Wi-Fi.",
|
||||
"sales.ceo_say_blockchain":"Have we thought about putting the routing table on a blockchain?",
|
||||
"sales.ceo_say_golf":"The best deals happen on the ninth hole. The NOC should play more golf.",
|
||||
"sales.ceo_say_mbps":"Why do we sell gigabits? Megabits sound like more.",
|
||||
"sales.ceo_say_napkin":"I priced the next deal on a napkin. Engineering can work out the details.",
|
||||
"sales.ceo_say_synergy":"We don't sell bandwidth, we sell synergy. Put that on the website.",
|
||||
"sales.ceo_says":"The CEO: “{say}”",
|
||||
"sales.ceo_took_over":"{name} has taken over sales personally. He is sure he sells better than anyone.",
|
||||
"sales.commission":"{name} signed. Commission for the shark: {cost}.",
|
||||
"sales.desk":"Sales desk",
|
||||
"sales.eng_booked":"{name} registered you for {conf} in {city} ({cost}). They already have the lanyard.",
|
||||
"sales.eng_d":"Was a network engineer, now has a lanyard for every NOG. Books you into each one (you pay the ticket), brings plenty of small and mid deals but never the really big ones, and only sells what the network can do, so customers stay. The nerds love Dave. Haggles badly.",
|
||||
"sales.eng_n":"The engineer turned salesdroid",
|
||||
"sales.eng_s":"Dave",
|
||||
"sales.fired":"{name} has cleared their desk. The sales desk is free.",
|
||||
"sales.hire_sales":"Hire sales",
|
||||
"sales.hired":"{name} joined sales. Expect deals in their style.",
|
||||
"sales.intro":"One person runs sales at a time. Each brings deals in their own way, and the customers they sign remember it when their contract comes up.",
|
||||
"sales.let_ceo":"Let the CEO run it",
|
||||
"sales.locked":"The sales desk opens at customer level {lv}.",
|
||||
"sales.one_at_a_time":"One at a time: let them go to hire someone else.",
|
||||
"sales.pitch":"One salesperson brings in deals their own way. Pick who.",
|
||||
"sales.shark_d":"Lands the biggest deals at a quarter more, and takes a month of each deal as commission. Oversells: half of them come with a promise your network does not keep yet, and those customers leave sooner. Ignores the nerds: no technical customers, no meetings, and peering desks want a quarter more traffic from you. Wins most haggles.",
|
||||
"sales.shark_n":"The shark",
|
||||
"sales.shark_s":"Chad",
|
||||
"sales.vp_arrived":"The VP of Sales has started, and the CEO has gone back to strategy. The sales desk is free: hire someone.",
|
||||
"sales.vp_asked":"The board agreed, after lunch. A VP of Sales starts in {n} days; until then the CEO keeps selling.",
|
||||
"sales.vp_coming":"A VP of Sales takes over in {n} days.",
|
||||
"save.cash_in_the_bank":"{cash} in the bank",
|
||||
"save.import_failed_err":"<b>Import failed.</b><br>{err}",
|
||||
"save.load_name":"Load {name}?",
|
||||
|
|
@ -3994,12 +4029,16 @@
|
|||
"settings.agent_api":"Agent API",
|
||||
"settings.agent_relay_connected":"Agent relay connected: a tool can now drive this game in this tab.",
|
||||
"settings.agent_s_clock":"Agent's clock",
|
||||
"settings.always_2d":"Always 2D",
|
||||
"settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.",
|
||||
"settings.auto_draws_the_map_with_your":"Auto draws the map with your graphics card when the browser allows it, which keeps big networks smooth. Always 2D works everywhere but is slower on big maps.",
|
||||
"settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.",
|
||||
"settings.customers_and_alerts":"Customers and alerts",
|
||||
"settings.diagnostic_info":"Diagnostic info",
|
||||
"settings.display_and_sound":"Display and sound",
|
||||
"settings.for_reporting_layout_bugs_shows_what":"For reporting layout bugs: shows what your screen tells the game.",
|
||||
"settings.for_bug_reports_shows_your_screen":"For bug reports: shows in a corner your screen's size, how the map is drawn (graphics card or 2D, and why) and how fast.",
|
||||
"settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game",
|
||||
"settings.map_drawing":"Map drawing",
|
||||
"settings.n_min":"{n} min",
|
||||
"settings.n_sec":"{n} s",
|
||||
"settings.only_trouble_and_milestones_pop_up":"Only trouble and milestones pop up; everything else goes quietly into the NOC log. On by default in Best Effort.",
|
||||
|
|
@ -4012,6 +4051,7 @@
|
|||
"settings.the_agent_moves_it":"The agent moves it",
|
||||
"settings.the_clock_while_an_agent_plays":"The clock while an agent plays",
|
||||
"settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.",
|
||||
"settings.this_browser_cannot_so_the_map":"This browser cannot, so the map is drawn in 2D.",
|
||||
"settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy",
|
||||
"settings.while_agent_mode_is_on_the":"While agent mode is on, the clock is not yours. With a pace it runs by itself and cannot be paused by hand, not even by an open window (yours included), and it waits while no agent is connected. Or the agent moves it, and nothing happens until it asks for days. The page connects to the local agent relay (npm run dev hosts one), so tools like the MCP server can drive this game while you watch.",
|
||||
"share_card.build_the_internet_one_tube_at":"Build the internet, one tube at a time",
|
||||
|
|
|
|||
|
|
@ -102,6 +102,7 @@
|
|||
</div>
|
||||
</noscript>
|
||||
<canvas id="map" aria-label="World map of your network" data-i18n-aria-label="page.world_map_of_your_network"></canvas>
|
||||
<canvas id="mapgl" aria-hidden="true" hidden></canvas><canvas id="mapfx" aria-hidden="true" hidden></canvas>
|
||||
|
||||
<header id="hud">
|
||||
<button class="chip brand menubtn" data-act="menu" aria-label="Network menu: save, load or start over" data-i18n-aria-label="page.network_menu_save_load_or_start">
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ body{margin:0}
|
|||
body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased}
|
||||
#map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab}
|
||||
#map.linking{cursor:crosshair}
|
||||
/* The WebGL tubes and the 2D overlay above them (58-webgl-links.js): pictures only, the map underneath takes the pointer. */
|
||||
#mapgl,#mapfx{position:fixed;inset:0;width:100%;height:100%;pointer-events:none}
|
||||
.num{font-variant-numeric:tabular-nums}
|
||||
h2,h3,h4{font-family:var(--display);margin:0;text-wrap:balance;line-height:1.1}
|
||||
button{font:inherit;color:inherit}
|
||||
|
|
|
|||
|
|
@ -65,3 +65,17 @@ test('#203 a dark fiber, cable or wave cannot be ordered to a city the map does
|
|||
assert.equal(ev(`S.links.some(l=>l.b==='${off}'||l.a==='${off}')`), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#203 a dark fiber lease costs more, and a lease already signed keeps its price', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const c of ['fra','ams'])if(!S.pops[c])ACT.buildPop({city:c})");
|
||||
assert.equal(ev('dfLeaseMo(1000)'), 2100);
|
||||
ev("UI.pending={a:'fra',b:'ams'};UI.dfSrc='lease';UI.dfSys='lite';ACT.orderDf()");
|
||||
const km = ev("S.links.find(l=>l.kind==='df').km");
|
||||
assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), Math.round(600 + km * 1.5));
|
||||
// An old save's lease, signed at the old price, keeps it.
|
||||
const old = Math.round(400 + km);
|
||||
ev(`S.links.find(l=>l.kind==='df').mo=${old};S=migrate(JSON.parse(JSON.stringify(S)))`);
|
||||
assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), old);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ const { load } = require('./harness');
|
|||
// land on another is left out, unless the cable touches the selected city.
|
||||
const labels = (ev, sel) => JSON.parse(ev(`(()=>{ACT.start({});S.nextFail=1e9;S.nextEvent=1e9;UI.sel=${sel ? `{type:'city',id:'${sel}'}` : 'null'};
|
||||
cam.x=(CITY.mnl.x+CITY.dvo.x)/2;cam.y=(CITY.mnl.y+CITY.dvo.y)/2;cam.z=4.5;const out=[];
|
||||
ctx.fillText=(t,x,y)=>out.push({t,x,y,w:ctx.measureText(t).width});ctx.strokeText=()=>{};drawCables([0]);return JSON.stringify(out);})()`));
|
||||
const ts=textStamp;textStamp=(t,f,px,w,c,sk,lw,x,y)=>out.push({t,x,y,w});try{drawCables([0]);}finally{textStamp=ts;}return JSON.stringify(out);})()`));
|
||||
|
||||
test('cable names never sit on top of each other', () => {
|
||||
const { ev, errors } = load();
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@ const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const
|
|||
const sign = (ev, o) => ev(`(()=>{const b=clSign(offerCustomer(Object.assign({id:'c'+Math.random().toString(36).slice(2),city:'ams',city2:null,name:'Test Co',type:'dia',bw:5,rate:600,reqs:[],exp:S.day+40},${JSON.stringify(o || {})})));S.biz.push(b);return b.id;})()`);
|
||||
const B = (ev, id, k) => ev(`S.biz.find(b=>b.id===${JSON.stringify(id)})${k ? '.' + k : ''}`);
|
||||
// An id whose roll for question q (at term end te) is below p, or at least p when above is true.
|
||||
const idFor = (ev, q, p, te, above = false) => ev(`(()=>{for(let i=0;i<20000;i++){const id='x'+i,r=clR({id,te:${te}},'${q}');if(${above ? 'r>=' : 'r<'}${p})return id;}})()`);
|
||||
// The rolls hash who the customer is, so the id found here is also its name (a Enterprise DIA in Amsterdam).
|
||||
const idFor = (ev, q, p, te, above = false) => ev(`(()=>{for(let i=0;i<20000;i++){const id='x'+i,r=clR({type:'dia',city:'ams',name:id,te:${te}},'${q}');if(${above ? 'r>=' : 'r<'}${p})return id;}})()`);
|
||||
|
||||
test('every customer signs for a term that fits what it buys; events and scripted customers have none', () => {
|
||||
const { ev, errors } = load();
|
||||
|
|
@ -31,7 +32,7 @@ test('nothing happens during a first term, and a renewal reprices to the market
|
|||
ev(start);
|
||||
const te = ev('S.day') + 365;
|
||||
const id = idFor(ev, 'leave', 0.9, te, true);
|
||||
ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'Steady Co',type:'dia',bw:5,rate:600,reqs:[],mood:100,since:S.day,te:${te},mk:2})`);
|
||||
ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:5,rate:600,reqs:[],mood:100,since:S.day,te:${te},mk:2})`);
|
||||
ev(`for(let i=0;i<364;i++)clDay(S.day+i)`);
|
||||
assert.equal(B(ev, id, 'rate'), 600, 'first term: same price, still here');
|
||||
ev(`S.biz.find(b=>b.id==='${id}').mood=100;clDay(${te})`);
|
||||
|
|
@ -49,6 +50,9 @@ test('the lifecycle never draws from Math.random, so seeded games keep their str
|
|||
ev('for(const b of S.biz)b.te=S.day+31');
|
||||
ev('window.__r=0;const r0=Math.random;Math.random=()=>{__r++;return r0();};for(let i=0;i<40;i++)clDay(S.day+i);Math.random=r0');
|
||||
assert.equal(ev('__r'), 0);
|
||||
// Nor from the clock: offer and customer ids come from Date.now(), so a roll must not depend on them.
|
||||
assert.equal(ev("clR({id:'a1',type:'dia',city:'ams',name:'Same Co',te:400},'leave')"), ev("clR({id:'zz9',type:'dia',city:'ams',name:'Same Co',te:400},'leave')"));
|
||||
assert.equal(ev("slR('over|'+slKey({id:'a1',type:'dia',city:'ams',name:'Same Co',bw:5,exp:40}))"), ev("slR('over|'+slKey({id:'zz9',type:'dia',city:'ams',name:'Same Co',bw:5,exp:40}))"));
|
||||
assert.ok(ev("S.cl.mo.reduce((a,e)=>a+e.ren+e.grew+Object.values(e.lost).reduce((x,y)=>x+y,0),0)") > 0, 'contracts did end');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -57,7 +61,7 @@ test('happy customers renew or grow; an unhappy one leaves, and says it was the
|
|||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
const te = ev('S.day') + 10;
|
||||
const stay = idFor(ev, 'leave', 0.5, te, true), grow = ev(`(()=>{for(let i=0;i<20000;i++){const id='g'+i;if(clR({id,te:${te}},'leave')>=0.5&&clR({id,te:${te}},'grow')<0.3)return id;}})()`);
|
||||
const stay = idFor(ev, 'leave', 0.5, te, true), grow = ev(`(()=>{for(let i=0;i<20000;i++){const id='g'+i,b={type:'dia',city:'ams',name:id,te:${te}};if(clR(b,'leave')>=0.5&&clR(b,'grow')<0.3)return id;}})()`);
|
||||
const sad = idFor(ev, 'leave', 0.3, te);
|
||||
for (const [id, mood] of [[stay, 100], [grow, 100], [sad, 20]]) ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:2,rate:600,reqs:[],mood:${mood},since:S.day-400,te:${te},mk:1})`);
|
||||
ev(`clDay(${te})`);
|
||||
|
|
@ -82,7 +86,7 @@ test('leaving that is not your fault: only reasons that fit the customer, and th
|
|||
assert.ok(!(r.moved || []).some(t => t === 'l2vpn' || t === 'dfpair'), 'circuits and fiber do not move away');
|
||||
assert.ok(!(r.bust || []).includes('dfpair'));
|
||||
// The odd reasons: never twice within 60 days.
|
||||
const gaps = JSON.parse(ev(`(()=>{S.day=5000;S.cl={odd:-1e9,mo:[]};const days=[];for(let d=0;d<400;d++){for(let i=0;i<6;i++){const b={id:'o'+d+'_'+i,city:'ams',city2:null,name:'O',type:'dia',bw:1,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1};S.biz=[b];const o=S.cl.odd;clDay(S.day);if(S.cl.odd!==o)days.push(S.day);}S.day++;}return JSON.stringify(days);})()`));
|
||||
const gaps = JSON.parse(ev(`(()=>{S.day=5000;S.cl={odd:-1e9,mo:[]};const days=[];for(let d=0;d<400;d++){for(let i=0;i<6;i++){const b={id:'o'+d+'_'+i,city:'ams',city2:null,name:'O'+d+'_'+i,type:'dia',bw:1,rate:100,reqs:[],mood:90,since:0,te:S.day,mk:1};S.biz=[b];const o=S.cl.odd;clDay(S.day);if(S.cl.odd!==o)days.push(S.day);}S.day++;}return JSON.stringify(days);})()`));
|
||||
assert.ok(gaps.length >= 3, `odd reasons do come (${gaps.length} in 400 days)`);
|
||||
assert.ok(gaps.every((d, i) => !i || d - gaps[i - 1] >= 60), 'at most one every 60 days');
|
||||
assert.deepEqual(errors, []);
|
||||
|
|
@ -93,7 +97,7 @@ test('a haggle: 30 days ahead, in Deals; match, meet halfway, let go, or no answ
|
|||
ev(start);
|
||||
const te = ev('S.day') + 30;
|
||||
const id = idFor(ev, 'hag', 0.05, te);
|
||||
ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'Haggle Co',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`);
|
||||
ev(`S.biz.push({id:'${id}',city:'ams',city2:null,name:'${id}',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:${te},mk:1})`);
|
||||
ev(`clDay(S.day)`);
|
||||
const hag = JSON.parse(ev(`JSON.stringify(S.biz.find(b=>b.id==='${id}').hag)`));
|
||||
assert.ok(hag && hag.rate < 600 && hag.rate >= 480 && hag.until === te, `asks 8–20% off until the term ends (${JSON.stringify(hag)})`);
|
||||
|
|
|
|||
109
tests/diagnostic-info.test.js
Normal file
109
tests/diagnostic-info.test.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// Settings › Diagnostic info (src/game/96-map/97-diagnostics.js): one readout for bug reports, which replaced the
|
||||
// separate viewport readout and frame meter. It shows the screen, what draws the map (and why it is 2D), and how fast;
|
||||
// the setting, ?vp/?fps and five taps on the date open it, and it is remembered on the device.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open(opts = {}) {
|
||||
const h = load({ seed: 777, ...opts });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();console.warn=()=>{};`);
|
||||
// The readout refreshes on an interval: closing the window stops it, so the test process can end.
|
||||
h.done = () => h.dom.window.close();
|
||||
return h;
|
||||
}
|
||||
const text = (ev) => ev('(()=>{const e=document.getElementById("diag");return e?e.textContent:null;})()');
|
||||
|
||||
test('the setting shows one readout with the screen, the map and its speed, and remembers it', () => {
|
||||
const h = open();
|
||||
const { ev, errors } = h;
|
||||
try {
|
||||
assert.equal(text(ev), null, 'off by default');
|
||||
ev('ACT.settings()');
|
||||
assert.match(ev('$("modal").innerHTML'), new RegExp(ev('tr("settings.diagnostic_info")')));
|
||||
ev('ACT.vpSet({v:"on"})');
|
||||
const t = text(ev);
|
||||
for (const part of ['Series of Tubes', 'inner ', 'screen ', 'safe top', 'tabbar', 'map: ', 'fps', 'draw ']) assert.ok(t.includes(part), `shows "${part}"`);
|
||||
assert.equal(ev('document.querySelectorAll("#diag").length'), 1, 'one readout');
|
||||
assert.equal(ev('localStorage.getItem("sot-vp")'), '1');
|
||||
ev('ACT.vpSet({v:"off"})');
|
||||
assert.equal(text(ev), null);
|
||||
assert.equal(ev('localStorage.getItem("sot-vp")'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { h.done(); }
|
||||
});
|
||||
|
||||
test('it says what draws the map, and why it is the 2D canvas', () => {
|
||||
const h = open();
|
||||
const { ev, errors } = h;
|
||||
try {
|
||||
ev('diagOn(true)');
|
||||
const map = () => ev('diagMap()');
|
||||
ev('mapGl(false,false)');
|
||||
assert.equal(map(), 'map: 2D (Always 2D)');
|
||||
ev('mapGl(true,false);glKill(new Error("the graphics card is out of memory (the pictures)"))');
|
||||
assert.equal(map(), 'map: 2D (the graphics card is out of memory (the pictures))');
|
||||
ev('GLX.dead=false;GLX.lost=true');
|
||||
assert.equal(map(), 'map: 2D (graphics context lost, waiting for it back)');
|
||||
ev('GLX.lost=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"');
|
||||
assert.equal(map(), 'map: WebGL2 · ANGLE (NVIDIA GeForce GTX 980)');
|
||||
ev('const s=S;S=null;window.__S=s');
|
||||
assert.equal(map(), 'map: none (title screen)');
|
||||
ev('S=__S;GLX.gl=null;GLX.shown=false');
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { h.done(); }
|
||||
});
|
||||
|
||||
test('it measures frames per second, the slowest frames and draw()', () => {
|
||||
const h = open();
|
||||
const { ev, errors } = h;
|
||||
try {
|
||||
ev('diagOn(true)');
|
||||
// 60 frames, so 59 intervals: 58 of 16 ms and a last one of 50 ms (978 ms in all); the map drawn on every other
|
||||
// one (a still map is not drawn again), in 2 ms: 30 in 978 ms, 31 a second.
|
||||
ev('let t=1000;for(let i=0;i<60;i++){t+=i===59?50:16;if(i%2)DIAG.dms=2;diagFrame(t);}diagShow();');
|
||||
const t = text(ev);
|
||||
assert.match(t, /\b60 fps · map drawn 31\/s · p95 16 ms · max 50 ms/);
|
||||
assert.match(t, /draw 2\.0 ms · x0 · zoom /);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { h.done(); }
|
||||
});
|
||||
|
||||
test('?fps and ?vp open it, ?nofps closes it, and it stays open on this device', () => {
|
||||
for (const [url, storage, want] of [['?fps', {}, true], ['?vp', {}, true], ['?nofps', { 'sot-vp': '1' }, false], ['', { 'sot-vp': '1' }, true], ['', {}, false]]) {
|
||||
const h = load({ seed: 777, url: 'https://tests.invalid/' + url, storage });
|
||||
try {
|
||||
assert.equal(h.ev('!!document.getElementById("diag")'), want, `${url || 'no flag'} ${JSON.stringify(storage)}`);
|
||||
assert.equal(h.ev('localStorage.getItem("sot-vp")'), want ? '1' : null, 'remembered as one setting');
|
||||
} finally { h.dom.window.close(); }
|
||||
}
|
||||
});
|
||||
|
||||
test('five quick taps on the date toggle it (an installed app has no address bar)', () => {
|
||||
const h = open();
|
||||
const { ev, errors } = h;
|
||||
try {
|
||||
const tap = () => ev('document.getElementById("hDate").click()');
|
||||
for (let i = 0; i < 5; i++) tap();
|
||||
assert.equal(ev('DIAG.on'), true);
|
||||
for (let i = 0; i < 5; i++) tap();
|
||||
assert.equal(ev('DIAG.on'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { h.done(); }
|
||||
});
|
||||
|
||||
test('on a 360 px phone the readout wraps inside the screen instead of running off it', () => {
|
||||
const h = open();
|
||||
const { ev } = h;
|
||||
try {
|
||||
ev('diagOn(true)');
|
||||
const st = ev('document.getElementById("diag").style.cssText');
|
||||
assert.match(st, /max-width: calc\(100vw - 32px\)/);
|
||||
assert.match(st, /white-space: pre-wrap/);
|
||||
assert.match(st, /pointer-events: none/, 'it never takes a tap meant for the map');
|
||||
} finally { h.done(); }
|
||||
});
|
||||
80
tests/gpu-bench.test.js
Normal file
80
tests/gpu-bench.test.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// The GPU benchmark's panel (scripts/lib/gpu-bench-client.js): one trial must never reach into the next. A day the route
|
||||
// worker is still routing lands on the save it was routed for, a pan's frame callback stops with its trial, every
|
||||
// trial starts from the same random numbers, and the table says which map really drew each run.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
const CLIENT = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'gpu-bench-client.js'), 'utf8');
|
||||
|
||||
function open(cfg = {}) {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`window.__BENCH__=${JSON.stringify({ expose: true, secs: 0.15, warm: 0, settleMs: 300, ...cfg })};`);
|
||||
h.ev(CLIENT);
|
||||
h.ev(`__bench.setSave(${JSON.stringify(SAVE)});save=()=>{};`);
|
||||
return h;
|
||||
}
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes.
|
||||
const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[];
|
||||
dayPost=function(d){__posts.push({d,old:S===__old});};`;
|
||||
|
||||
test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => {
|
||||
const { ev, errors } = open();
|
||||
await ev('__bench.reset()');
|
||||
ev(IN_FLIGHT);
|
||||
ev('setTimeout(()=>rwDone({seq:41}),60)');
|
||||
await ev('__bench.reset()');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [{ d: 201, old: true }], 'its day ran on the old save, before the new one was loaded');
|
||||
assert.equal(ev('S!==__old&&RW.job===null'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an answer that never comes is dropped, and coming late it changes nothing', async () => {
|
||||
const { ev, errors } = open();
|
||||
await ev('__bench.reset()');
|
||||
ev(IN_FLIGHT);
|
||||
ev('console.warn=()=>{}');
|
||||
await ev('__bench.reset()');
|
||||
assert.equal(ev('RW.job'), null, 'the next trial does not wait for it forever');
|
||||
ev('rwDone({seq:41})');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__posts)')), [], 'nothing ran on the new save');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a pan stops with its trial: the next trial’s camera is left alone', async () => {
|
||||
const { ev, errors } = open();
|
||||
const m = JSON.parse(await ev('__bench.measure({id:"pan",pan:true,z:1.4,speed:0},60,"2d").then(JSON.stringify)'));
|
||||
assert.ok(m.fps > 0, 'the pan ran');
|
||||
ev('cam.x=0');
|
||||
await wait(120);
|
||||
assert.equal(ev('cam.x'), 0, 'no frame of the pan came after it');
|
||||
const x8 = await ev('(async()=>{const p=__bench.measure({id:"x8",z:1.4,speed:8},60,"2d");await new Promise(r=>setTimeout(r,20));const x=cam.x;await p;return [x,cam.x];})()');
|
||||
assert.equal(x8[0], x8[1], 'the next scenario keeps its camera where it put it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every trial starts from the same random numbers and an empty clock', async () => {
|
||||
const { ev, errors } = open();
|
||||
const draws = async () => { await ev('acc=12345;animT=999;__bench.reset()'); return ev('JSON.stringify([acc,animT,Math.random(),Math.random(),Math.random()])'); };
|
||||
const a = await draws(), b = await draws();
|
||||
assert.equal(a, b);
|
||||
assert.deepEqual(JSON.parse(a).slice(0, 2), [0, 0]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the table says which map drew each run, and what each column measures', () => {
|
||||
const { ev } = open();
|
||||
const md = ev(`(()=>{const m=(drawn,gl,flat,gpu)=>({fps:60,p95:17,drawMs:1,drawn,glFrames:gl,flatFrames:flat,gpuMs:gpu});
|
||||
const res={'2d':{'x1-mid':m('2d',0,300,null)},gl:{'x1-mid':m('mixed',12,288,0.8)}};
|
||||
return __bench.table(res,{gpu:'stub',ua:'ua',w:1,h:1,dpr:1,hz:60,cores:1,save:'s',reps:1});})()`);
|
||||
assert.match(md, /WebGL GPU/, 'a GPU column when the card timed its frames');
|
||||
assert.match(md, /CPU time on the main thread/, 'draw() is said to be CPU time');
|
||||
assert.match(md, /Not drawn by the map they name: Map at x1 \(zoom 1\.4\) \(WebGL: 288 frames in 2D/, 'a run that fell back to 2D is flagged');
|
||||
const merged = JSON.parse(ev(`JSON.stringify(__bench.merge([{fps:50,drawn:'gl',hidden:false,slow:[1]},{fps:70,drawn:'gl',hidden:true,slow:[2]},{fps:60,drawn:'2d',hidden:false,slow:[]}]))`));
|
||||
assert.deepEqual(merged, { fps: 60, drawn: 'gl+2d', hidden: true, slow: [1, 2], runs: 3 });
|
||||
});
|
||||
68
tests/map-2d-sprite-budget.test.js
Normal file
68
tests/map-2d-sprite-budget.test.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
// The 2D map keeps a canvas per picture (59-gl-sprites.js). A long zoom on a big network paints every city again at
|
||||
// each step, and the list, capped only by its length, held up to 180 MB of pictures where a frame shows at most 23 MB.
|
||||
// It is now held to SPRC_BUDGET bytes: past it, the pictures no frame used since the one before are let go, and those
|
||||
// in use are always kept. The page's clock is set by hand, so nothing depends on how fast the test runs.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
// The big network on a 1280×800 screen at 2× in 2D. Canvases are counted as they are made; their contexts take any call.
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false,false);
|
||||
DPR=2;CW=1280;CH=800;cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=0.6;window.__cv=0;
|
||||
const ce=document.createElement.bind(document);document.createElement=function(t){const e=ce(t);if(String(t).toLowerCase()==='canvas')__cv++;return e;};
|
||||
HTMLCanvasElement.prototype.getContext=function(){return this.__c||(this.__c=new Proxy({},{get(t,k){if(k in t)return t[k];
|
||||
if(k==='measureText')return s=>({width:String(s).length*7});if(k==='createLinearGradient')return ()=>({addColorStop(){}});return ()=>{};},set(t,k,v){t[k]=v;return true;}}));};
|
||||
window.__bytes=()=>{let b=0;for(const e of SPRC.values())b+=e.pw*e.ph*4;return b;};
|
||||
// What the last frame drew: its pictures and their bytes.
|
||||
window.__used=()=>{let n=0,b=0;for(const e of SPRC.values())if(e.f===SPR_F){n++;b+=e.pw*e.ph*4;}return {n,b};};`);
|
||||
return h;
|
||||
}
|
||||
// A pinch from 0.6 to 3.2 and back in 180 frames of 16 ms: the most bytes held, and the most a frame used.
|
||||
const PINCH = `(()=>{let held=0,used=0,drift=0;for(let i=0;i<=180;i++){const f=i<=90?i/90:(180-i)/90;cam.z=0.6*Math.pow(3.2/0.6,f);__T+=16;draw(__T);
|
||||
const b=__bytes();held=Math.max(held,b);used=Math.max(used,__used().b);drift=Math.max(drift,Math.abs(b-SPRC_B));}return JSON.stringify({held,used,drift});})()`;
|
||||
|
||||
test('a long zoom on the 2D map holds its pictures to the budget, plus what one frame needs', () => {
|
||||
const { ev, errors } = open();
|
||||
const r = JSON.parse(ev(PINCH));
|
||||
const MB = 1048576, budget = ev('SPRC_BUDGET');
|
||||
assert.equal(r.drift, 0, 'the bytes counted are the bytes held');
|
||||
assert.ok(r.used > 5 * MB, `a frame uses a real share of it (${(r.used / MB).toFixed(1)} MB)`);
|
||||
// After a frame, over the budget only if that frame alone needs more.
|
||||
assert.ok(r.held <= Math.max(budget, r.used), `held ${(r.held / MB).toFixed(1)} MB, budget ${budget / MB} MB`);
|
||||
assert.ok(r.held < 80 * MB, `far under the 180 MB it held before (${(r.held / MB).toFixed(1)} MB)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the pictures a frame uses are never let go, and a still map paints nothing new', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(PINCH);
|
||||
// Every picture the last frame drew is still kept (it was used, so it cannot have been let go).
|
||||
ev('window.__keep=[];const b0=blit;blit=function(e,...a){__keep.push(e);return b0(e,...a);};__T+=16;draw(__T);blit=b0;');
|
||||
assert.ok(ev('__keep.length') > 50);
|
||||
assert.equal(ev('__keep.every(e=>[...SPRC.values()].includes(e))'), true, 'every picture of the frame is kept');
|
||||
// The same view again and again: everything comes from the kept pictures.
|
||||
ev('window.__c0=__cv;for(let i=0;i<5;i++){__T+=16;draw(__T);}');
|
||||
assert.equal(ev('__cv-__c0'), 0, 'no picture painted again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('under the budget nothing is let go', () => {
|
||||
const { ev, errors } = open();
|
||||
ev('cam.z=1.1;__T+=16;draw(__T);window.__n=SPRC.size;window.__b=SPRC_B;');
|
||||
assert.ok(ev('__b') < ev('SPRC_BUDGET'));
|
||||
// A small pan: new pictures come in, none goes.
|
||||
ev('for(let i=0;i<10;i++){cam.x+=4;__T+=16;draw(__T);}');
|
||||
assert.ok(ev('SPRC.size') >= ev('__n'), 'the list only grew');
|
||||
assert.equal(ev('SPRC_B'), ev('__bytes()'));
|
||||
// A reset (a new pixel density) forgets the bytes with the pictures.
|
||||
ev('DPR=1;__T+=16;draw(__T);');
|
||||
assert.equal(ev('SPRC_B'), ev('__bytes()'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
308
tests/map-2d.test.js
Normal file
308
tests/map-2d.test.js
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
// The 2D map, for players who keep it (Settings › Map drawing › Always 2D, or no usable graphics card). The WebGL work
|
||||
// changed it too: cities, labels and markers are painted once as pictures and reused (59-gl-sprites.js), and each
|
||||
// tube's look is worked out once per day's routing (mapLinks(), 55-link-look.js). These tests hold the 2D map to what
|
||||
// it drew before:
|
||||
// - a frame drawn with the pictures kept from earlier states is, call for call, the frame painted from scratch: no
|
||||
// picture is ever shown for a state it was not painted for (on the big network, and in seeded random games);
|
||||
// - every tube's width, colour, dash and packets follow the formulas main's 2D map used, after every move and day;
|
||||
// - the 2D map never asks for WebGL, never draws a picture it has no canvas for, and keeps one canvas per picture;
|
||||
// - every picture starts with the pen main's map had when it drew the same thing straight on the map (round line
|
||||
// ends, centred text), or its dashed rings and markers would come out differently.
|
||||
// The page's clock is set by hand, so nothing depends on how fast the test runs. Comparing pixels with main needs a real
|
||||
// browser, which npm test does not use: that was done by hand, in Chromium, for this change.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const page = require('../scripts/lib/page');
|
||||
const { openPage, playGame, rng } = require('../scripts/lib/route-fuzz');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
/* In the page: every canvas made from now on records what is drawn on it, and the map's own context records the
|
||||
frame. A picture is known by what was painted on it (a hash of its calls), so a frame's calls say which picture went
|
||||
where. WebGL is not there (getContext gives null for it), and every request for it is counted. */
|
||||
const KIT = `window.__M2D=(()=>{
|
||||
const N=v=>typeof v==='number'?String(Math.round(v*1000)/1000):v==null?String(v):typeof v==='function'?'fn':
|
||||
v instanceof HTMLCanvasElement?v.__cid():Array.isArray(v)?'['+v.map(N).join(',')+']':typeof v==='object'?'obj':String(v);
|
||||
const M=['arc','arcTo','beginPath','bezierCurveTo','clearRect','clip','closePath','drawImage','ellipse','fill','fillRect','fillText',
|
||||
'lineTo','moveTo','quadraticCurveTo','rect','resetTransform','restore','rotate','roundRect','save','scale','setLineDash','setTransform',
|
||||
'stroke','strokeRect','strokeText','transform','translate'];
|
||||
// With each call that paints, the state of the context it uses (a picture does not care about the font, say).
|
||||
const IMG=['globalAlpha','globalCompositeOperation'],FILL=[...IMG,'fillStyle'],LINE=[...IMG,'strokeStyle','lineWidth','lineDashOffset','lineJoin','lineCap'],
|
||||
TXT=['font','textAlign','textBaseline'];
|
||||
const PAINT={drawImage:IMG,clearRect:[],fill:FILL,fillRect:FILL,stroke:LINE,strokeRect:LINE,fillText:[...FILL,...TXT],strokeText:[...LINE,...TXT]};
|
||||
const DEF={globalAlpha:1,fillStyle:'#000000',strokeStyle:'#000000',lineWidth:1,font:'10px sans-serif',lineDashOffset:0,lineJoin:'miter',lineCap:'butt',
|
||||
textAlign:'start',textBaseline:'alphabetic',globalCompositeOperation:'source-over'};
|
||||
function rec(c,keep){const Q={h:2166136261,n:0,log:keep?[]:null};
|
||||
const add=s=>{for(let i=0;i<s.length;i++)Q.h=Math.imul(Q.h^s.charCodeAt(i),16777619)>>>0;Q.n++;if(Q.log)Q.log.push(s);};
|
||||
for(const m of M)c[m]=function(...a){let s=m+'('+a.map(N).join(',')+')';for(const k of PAINT[m]||[])s+=' '+N(this[k]);add(s);};
|
||||
Object.assign(c,DEF);c.__Q=Q;return c;}
|
||||
const blank=()=>new Proxy({},{get(t,k){if(k in t)return t[k];if(k==='measureText')return s=>({width:String(s).length*7});
|
||||
if(k==='createLinearGradient'||k==='createRadialGradient'||k==='createPattern')return ()=>({addColorStop(){}});
|
||||
if(k==='getImageData')return ()=>({data:new Uint8ClampedArray(4)});if(k==='canvas')return null;return ()=>{};},set(t,k,v){t[k]=v;return true;}});
|
||||
const asked=[];
|
||||
HTMLCanvasElement.prototype.getContext=function(type){asked.push(type);if(type!=='2d')return null;return this.__ctx||(this.__ctx=rec(blank(),false));};
|
||||
HTMLCanvasElement.prototype.__cid=function(){const q=this.__ctx&&this.__ctx.__Q;return q?'cv:'+q.h.toString(36)+'.'+q.n:'cv:?';};
|
||||
rec(CTX0,true);
|
||||
// A picture drawn in a 2D frame without a canvas of its own would simply not show.
|
||||
let lost=0;const blit0=blit;blit=function(e,...a){if(!GLS.frame&&!e.cv)lost++;return blit0(e,...a);};
|
||||
// One frame's calls on the map's canvas, from a known state of the context.
|
||||
function frame(t){const Q=CTX0.__Q;Q.log.length=0;Q.h=2166136261;Q.n=0;Object.assign(CTX0,DEF);draw(t);return Q.log.slice();}
|
||||
function inv(){let dup=0,bad=0;const seen=new Set();
|
||||
for(const e of SPRC.values()){if(!e.cv){bad++;continue;}if(seen.has(e.cv))dup++;seen.add(e.cv);if(e.cv.width!==e.pw||e.cv.height!==e.ph)bad++;}
|
||||
return {webgl:asked.filter(x=>x!=='2d').length,sprs:SPRS.size,glsFrame:GLS.frame,ctx0:ctx===CTX0,glShown:!document.getElementById('mapgl').hidden,
|
||||
pad:!!GLS_PAD.cv,shared:dup,badCanvas:bad,lost};}
|
||||
// Without the cache: every picture is painted again for every call, as if nothing were kept, even within a frame.
|
||||
let nocache=false;const none={get(){},set(){},has:()=>false,size:0},sprMap0=sprMap;sprMap=function(){const m=sprMap0();return nocache?none:m;};
|
||||
/* The same state drawn twice: with the pictures kept from every state before (kept), then painting every picture
|
||||
again (fresh). The land picture is settled first, so both frames find it as it is. */
|
||||
function pair(t){__T+=1000;if(S)worldLayer(cam.z);lost=0;
|
||||
const kept=frame(t),had=SPRC.size;nocache=true;let fresh;try{fresh=frame(t);}finally{nocache=false;}
|
||||
let d=-1;for(let i=0,n=Math.max(kept.length,fresh.length);i<n;i++)if(kept[i]!==fresh[i]){d=i;break;}
|
||||
return {calls:fresh.length,had,diff:d<0?null:{at:d,kept:kept.slice(Math.max(0,d-2),d+2),fresh:fresh.slice(Math.max(0,d-2),d+2)},...inv()};}
|
||||
// How main's 2D map worked out a tube's look, frame by frame (its drawFrame() before this change), word for word.
|
||||
function ref(grp,day){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby);
|
||||
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)));
|
||||
return {w,dash:cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[],col:bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u),
|
||||
pk:!cut&&load>0.01?clamp(Math.round(2+u*10),2,12):0,cut,bld,dark,vx,cap,load,up:up&&up.map(x=>x.id)};}
|
||||
// The kept looks (mapLinks) against groups, geometry and looks worked out again now, the way main did.
|
||||
function looks(){if(!S||!R)return [];const ML=mapLinks(S.day),PI=pairIdx(),LG=linkGroups(),bad=[];
|
||||
if(JSON.stringify(ML.LG.map(g=>g.map(l=>l.id)))!==JSON.stringify(LG.map(g=>g.map(l=>l.id))))return ['the tubes are not grouped as now'];
|
||||
LG.forEach((g,i)=>{const gm=linkGeom(g[0],PI.get(edgeKey(g[0])));if(JSON.stringify(gm.pts)!==JSON.stringify(ML.GM[i].pts))bad.push('geometry of '+g[0].id);
|
||||
const n=ML.looks[i],o=JSON.stringify(ref(g,S.day)),m=JSON.stringify({w:n.w0,dash:LDASH[n.dash],col:n.col,pk:n.pk,cut:n.cut,bld:n.bld,dark:n.dark,vx:n.vx,cap:n.cap,load:n.load,up:n.up&&n.up.map(x=>x.id)});
|
||||
if(o!==m)bad.push(g[0].id+': main '+o+' kept '+m);});
|
||||
return bad.slice(0,3);}
|
||||
/* A view of the map: the camera on a city at a zoom, maybe a city or a tube selected, maybe a city under the
|
||||
pointer, at clock t. u: numbers in [0,1) from the test's own seeded generator. */
|
||||
function view(u){if(!S)return null;const pops=Object.keys(S.pops),at=pops.length&&u[0]<.7?pops[Math.floor(u[1]*pops.length)]:CITIES[Math.floor(u[1]*CITIES.length)].id,C=CITY[at];
|
||||
cam.x=C.x+(u[2]-.5)*80;cam.y=C.y+(u[3]-.5)*60;cam.z=[.45,.7,1,1.6,3.2][Math.floor(u[4]*5)];
|
||||
UI.sel=u[5]<.35?null:u[5]<.6?{type:'city',id:at}:S.links.length?{type:'link',id:S.links[Math.floor(u[6]*S.links.length)].id}:null;
|
||||
UI.hover=u[7]<.3?at:null;return Math.floor(u[8]*20000);}
|
||||
function check(u){const keep={x:cam.x,y:cam.y,z:cam.z,sel:UI.sel,hov:UI.hover};
|
||||
try{const t=view(u);if(t===null)return null;const r=pair(t);r.looks=looks();r.view={at:UI.sel,z:cam.z,t};return r;}
|
||||
finally{cam.x=keep.x;cam.y=keep.y;cam.z=keep.z;UI.sel=keep.sel;UI.hover=keep.hov;}}
|
||||
return {frame,pair,inv,looks,check,view,asked};})();0`;
|
||||
|
||||
// What a check returned, as the problems it shows (none: an empty list).
|
||||
function problems(r, where) {
|
||||
if (!r) return [];
|
||||
const out = [];
|
||||
if (r.diff) out.push(`${where}: a kept picture differs from a fresh one at call ${r.diff.at}\n kept: ${r.diff.kept.join('\n ')}\n fresh: ${r.diff.fresh.join('\n ')}`);
|
||||
for (const l of r.looks || []) out.push(`${where}: ${l}`);
|
||||
if (r.webgl) out.push(`${where}: WebGL asked for ${r.webgl} times`);
|
||||
if (r.lost) out.push(`${where}: ${r.lost} pictures drawn without a canvas`);
|
||||
if (r.shared || r.badCanvas) out.push(`${where}: ${r.shared} pictures share a canvas, ${r.badCanvas} have none or one of the wrong size`);
|
||||
if (r.pad) out.push(`${where}: the card's shared canvas was made`);
|
||||
if (r.sprs || r.glsFrame || !r.ctx0 || r.glShown) out.push(`${where}: card state leaked into 2D ${JSON.stringify({ sprs: r.sprs, glsFrame: r.glsFrame, ctx0: r.ctx0, glShown: r.glShown })}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
// A card that records what it is asked (jsdom has no WebGL), as in tests/webgl-zoom-sprites.test.js.
|
||||
const GLSTUB = `window.__GLSTUB=(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push(k);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
const fx=document.createElement('canvas').getContext('2d');
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx,line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
|
||||
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})();0`;
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);`);
|
||||
h.ev(KIT);
|
||||
return h;
|
||||
}
|
||||
|
||||
test('the 2D map draws the same frame from kept pictures as from fresh ones, whatever happens to a POP', () => {
|
||||
const { ev, errors } = open();
|
||||
const found = [];
|
||||
assert.ok(ev('CW>300&&CH>300'), 'the map has a size');
|
||||
// One city goes through every state its picture can show. After each change the map is looked at from the same
|
||||
// views (every zoom, plain, under the pointer, selected), so a picture kept from an earlier state is found under its
|
||||
// key whenever the key leaves out what changed.
|
||||
const STEPS = [
|
||||
'0',
|
||||
'S.pops[S.home].down=S.day+3',
|
||||
'S.pops[S.home].down=0;S.pops[S.home].routers=2',
|
||||
'S.pops[S.home].gen=1',
|
||||
'S.pops[S.home].rgen=1',
|
||||
'S.pops[S.home].site2=S.pops[S.home].site2||{}',
|
||||
'S.pops[S.home].ringcut=S.day+2',
|
||||
"S.inc.push({id:'t-site',type:'site',ref:S.home,site:'b',until:S.day+5})",
|
||||
'R.ddosHot=Object.assign({},R.ddosHot,{[S.home]:1})',
|
||||
'UI.hotMap={[S.home]:{r:1,t:1,ix:1}}',
|
||||
"S.myIx[S.home]=S.myIx[S.home]||{name:'Test-IX',members:[],next:S.day+4}",
|
||||
'S.pops[S.home].routers=3;S.pops[S.home].rgen=0;S.pops[S.home].gen=0',
|
||||
'delete R.ddosHot[S.home];UI.hotMap=null;S.pops[S.home].ringcut=0',
|
||||
'S.pops[S.home].down=S.day+1',
|
||||
// A city without a POP next to it: an incident there, then an exchange.
|
||||
"S.inc.push({id:'t-x',type:'cut',ref:__OTHER,until:S.day+3})",
|
||||
"S.myIx[__OTHER]={name:'Other-IX',members:[],next:S.day+4}",
|
||||
];
|
||||
// The other city: the nearest one without a POP.
|
||||
ev("window.__OTHER=CITIES.filter(c=>!S.pops[c.id]&&!c.off).sort((a,b)=>Math.hypot(a.x-CITY[S.home].x,a.y-CITY[S.home].y)-Math.hypot(b.x-CITY[S.home].x,b.y-CITY[S.home].y))[0].id;0");
|
||||
let checks = 0;
|
||||
// u (see view()): centred on the home POP or on the other city, at zoom index z; nothing selected, the city under
|
||||
// the pointer, or selected.
|
||||
const VIEWS = [];
|
||||
for (const city of ['pop', 'other']) for (let z = 0; z < 5; z++) for (const [sel, hov] of [[0.1, 0.9], [0.1, 0.1], [0.5, 0.9]]) VIEWS.push({ city, u: [city === 'pop' ? 0 : 0.9, 0, 0.5, 0.5, z / 5 + 0.01, sel, 0, hov, (z + 1) / 7] });
|
||||
for (const step of STEPS) {
|
||||
ev(step);
|
||||
// Each change is looked at from the city it touches (both at the start).
|
||||
const on = step === '0' ? null : step.includes('__OTHER') ? 'other' : 'pop';
|
||||
VIEWS.forEach(({ city, u }, v) => {
|
||||
if (on && city !== on) return;
|
||||
const at = city === 'pop' ? 'Object.keys(S.pops).indexOf(S.home)/Object.keys(S.pops).length' : 'CITIES.findIndex(c=>c.id===__OTHER)/CITIES.length';
|
||||
ev(`window.__U=${JSON.stringify(u)};__U[1]=${at}+1e-9;0`);
|
||||
found.push(...problems(JSON.parse(ev('JSON.stringify(__M2D.check(__U))')), `after "${step}", view ${v} (${city})`));
|
||||
checks++;
|
||||
});
|
||||
}
|
||||
assert.ok(checks >= 250);
|
||||
assert.deepEqual(found.slice(0, 5), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the 2D map draws the same from kept pictures as from fresh ones, and tubes as main did, over random views of the big network', () => {
|
||||
const { ev, errors } = open();
|
||||
const r = rng(99), found = [];
|
||||
for (let i = 0; i < 60; i++) {
|
||||
// Now and then a day passes (failures and events on), so cuts, builds, floods and offers come and go.
|
||||
if (i % 6 === 5) ev('S.nextFail=S.day;S.nextEvent=S.day;dayTick();compute();');
|
||||
const u = Array.from({ length: 9 }, () => r());
|
||||
found.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `view ${i} (day ${ev('S.day')})`));
|
||||
}
|
||||
assert.deepEqual(found.slice(0, 5), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('in seeded random games, after every move and day, the 2D map draws the same from kept pictures and tubes as main did', () => {
|
||||
const file = path.join(os.tmpdir(), `tubes-map2d-${process.pid}.html`);
|
||||
fs.writeFileSync(file, page.assemble().html);
|
||||
try {
|
||||
// A normal game, a sandbox, a scenario and a puzzle (the seeds of tests/route-fuzz.test.js). The big network is the
|
||||
// test above: a whole game of it, routed again after every move on two pages, takes a minute.
|
||||
for (const seed of [20, 23, 27, 26]) {
|
||||
// Two pages of this checkout play the game in lockstep (scripts/lib/route-fuzz.js): drawing the map on both, between
|
||||
// moves, must not make them part (the 2D map must not change the game).
|
||||
const P = { base: openPage(file, 'a'), head: openPage(file, 'b') };
|
||||
for (const p of [P.base, P.head]) p.ev(`window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});mapGl(false);${KIT}`);
|
||||
const r = rng(seed * 7919), found = [];
|
||||
let checks = 0;
|
||||
const g = playGame(P, seed, { moves: 40, maxDays: 4, onMove: () => {
|
||||
const u = Array.from({ length: 9 }, () => r());
|
||||
for (const p of [P.base, P.head]) {
|
||||
const out = JSON.parse(p.ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`));
|
||||
if (out) checks++;
|
||||
found.push(...problems(out, `seed ${seed}, page ${p.label}`));
|
||||
}
|
||||
} });
|
||||
assert.equal(g.div, null, `seed ${seed}: the two pages parted: ${JSON.stringify(g.div && { where: g.div.where, last: g.div.last })}`);
|
||||
assert.ok(checks >= 20, `seed ${seed}: the map was checked (${checks})`);
|
||||
assert.deepEqual(found.slice(0, 5), [], `seed ${seed}`);
|
||||
assert.deepEqual(g.errors, [], `seed ${seed}`);
|
||||
}
|
||||
} finally { fs.rmSync(file, { force: true }); }
|
||||
});
|
||||
|
||||
test('a 2D map without WebGL2 never asks for it again, and its pictures each keep their own canvas', () => {
|
||||
const h = load({ seed: 777 });
|
||||
// Auto mode, in a browser where WebGL2 is not there.
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
|
||||
h.ev(KIT);
|
||||
h.ev('mapGl(true,false);draw(__T);');
|
||||
const first = JSON.parse(h.ev('JSON.stringify({asked:__M2D.asked.filter(x=>x!=="2d").length,gl:!!GLX.gl,glOn:glOn()})'));
|
||||
assert.equal(first.gl, false);
|
||||
assert.equal(first.glOn, false, 'auto mode draws in 2D');
|
||||
for (let i = 0; i < 20; i++) h.ev(`cam.z=${0.5 + i * 0.15};__T+=16;draw(__T);`);
|
||||
const inv = JSON.parse(h.ev('JSON.stringify(__M2D.inv())'));
|
||||
assert.ok(inv.webgl <= first.asked, `WebGL was asked for again (${inv.webgl} after ${first.asked})`);
|
||||
assert.deepEqual(problems({ ...inv, webgl: 0 }, 'zoom'), []);
|
||||
assert.ok(h.ev('SPRC.size') > 50, 'the pictures are kept');
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('the 2D map after the card is given up, or switched off, draws as a 2D map that never had one', () => {
|
||||
const { ev, errors } = open();
|
||||
// A card (a recording stand-in) draws a few frames and fills its own pictures.
|
||||
ev(GLSTUB);
|
||||
const views = (tag) => {
|
||||
const out = [];
|
||||
for (let v = 0; v < 8; v++) {
|
||||
const u = [0.2, v / 8, 0.5, 0.5, (v % 5) / 5 + 0.01, v / 8, 0.3, v % 2 ? 0.1 : 0.9, v / 8];
|
||||
out.push(...problems(JSON.parse(ev(`JSON.stringify(__M2D.check(${JSON.stringify(u)}))`)), `${tag}, view ${v}`));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
// Switched off in the settings, with the card's pictures still kept.
|
||||
for (let i = 0; i < 6; i++) ev(`cam.z=${0.5 + i * 0.4};__T+=16;draw(__T);`);
|
||||
assert.ok(ev('SPRS.size') > 20, 'the card painted its pictures');
|
||||
ev('mapGl(false)');
|
||||
// pad and sprs: the card's own, left from its frames; what matters is that the 2D frames never use them.
|
||||
const off = views('switched off').filter((p) => !/card's shared canvas|card state leaked/.test(p) || /ctx0":false|glShown":true|glsFrame":true/.test(p));
|
||||
assert.deepEqual(off.slice(0, 5), []);
|
||||
// Back on, then the card fails: the session's map stays 2D.
|
||||
ev('mapGl(true);__T+=16;draw(__T);glKill(new Error("test"));');
|
||||
assert.equal(ev('SPRS.size'), 0, 'the card’s pictures are forgotten');
|
||||
const dead = views('given up').filter((p) => !/card's shared canvas/.test(p));
|
||||
assert.deepEqual(dead.slice(0, 5), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the 2D map paints its pictures again for a new pixel density', () => {
|
||||
const { ev, errors } = open();
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.ok(ev('SPRC.size') > 20);
|
||||
ev('DPR=2;__T+=16;draw(__T);');
|
||||
const bad = JSON.parse(ev('JSON.stringify([...SPRC.values()].filter(e=>e.pw!==Math.ceil(e.w*2)||e.ph!==Math.ceil(e.h*2)).length)'));
|
||||
assert.equal(bad, 0, 'every picture is at the new density');
|
||||
const r = JSON.parse(ev('JSON.stringify(__M2D.check([0,0,0.5,0.5,0.5,0.1,0,0.9,0.3]))'));
|
||||
assert.deepEqual(problems(r, 'at 2×'), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('money pop-ups on the 2D map fade out as before', () => {
|
||||
const { ev, errors } = open();
|
||||
const C = 'CITY[S.home]';
|
||||
ev(`cam.x=${C}.x;cam.y=${C}.y;cam.z=1;__T+=16;FLOATS.push({x:${C}.x,y:${C}.y,text:'+$1,234',col:'#16A866',t:__T});`);
|
||||
// At 0, 40% and 80% of its life: drawn at opacity 1-a².
|
||||
const alphas = [];
|
||||
for (const a of [0, 0.4, 0.8]) {
|
||||
const log = JSON.parse(ev(`JSON.stringify(__M2D.frame(FLOATS[FLOATS.length-1].t+${a * 1600}))`));
|
||||
const last = log.filter((s) => s.startsWith('drawImage(')).pop();
|
||||
alphas.push(+last.split(' ')[1]);
|
||||
}
|
||||
assert.deepEqual(alphas, [1, 0.84, 0.36]);
|
||||
ev(`__M2D.frame(FLOATS[FLOATS.length-1].t+1700)`);
|
||||
assert.equal(ev('FLOATS.length'), 0, 'gone after its life');
|
||||
// The same text in two colours at once: two pictures, each in its own colour.
|
||||
ev(`FLOATS.push({x:${C}.x,y:${C}.y,text:'+$500',col:'#16A866',t:5000},{x:${C}.x+40,y:${C}.y,text:'+$500',col:'#FF4D5E',t:5000});`);
|
||||
const r = JSON.parse(ev('JSON.stringify(__M2D.pair(5400))'));
|
||||
assert.deepEqual(problems(r, 'two pop-ups'), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every picture starts with the pen the map had when it drew them itself: round line ends and corners, centred text', () => {
|
||||
const { ev, errors } = open();
|
||||
// Drawn straight on the map, main's dashed rings, cones and "zzz" took the state the tubes and labels left there.
|
||||
let n = 0;
|
||||
const pen = (spoil) => JSON.parse(ev(`(()=>{let o;spriteEntry('t-pen|${n++}',10,10,5,5,g=>{o={cap:g.lineCap,join:g.lineJoin,align:g.textAlign,base:g.textBaseline};
|
||||
${spoil ? "g.lineCap='butt';g.lineJoin='miter';g.textAlign='start';g.textBaseline='alphabetic';" : ''}});return JSON.stringify(o);})()`));
|
||||
const want = { cap: 'round', join: 'round', align: 'center', base: 'middle' };
|
||||
assert.deepEqual(pen(true), want, 'a 2D picture');
|
||||
assert.deepEqual(pen(false), want, 'the next 2D picture');
|
||||
// On the card one canvas is reused for every picture: each starts from that pen again, whatever the last one did.
|
||||
ev(GLSTUB);
|
||||
ev('GLS.frame=true;');
|
||||
try {
|
||||
assert.deepEqual(pen(true), want, 'a picture on the card');
|
||||
assert.deepEqual(pen(false), want, 'the next picture on the card, on the same canvas');
|
||||
assert.ok(ev('!!GLS_PAD.cv&&SPRS.size>=2'), 'the card’s pictures went through its shared canvas');
|
||||
} finally { ev('GLS.frame=false;'); }
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1010,7 +1010,8 @@ test('Down Under: routers upside down, BrisVegas, Next-Door-DC and everything tr
|
|||
assert.equal(ev("S.log.filter(e=>/Router installed/.test(e.t)).length"), 2, 'one note per Australian POP');
|
||||
ev("ACT.buildPop({city:'lon'})");
|
||||
assert.equal(ev("S.log.filter(e=>/Router installed/.test(e.t)).length"), 2, 'London routers stay the right way up');
|
||||
const turns = c => ev(`(()=>{let n=0;const r=ctx.rotate;ctx.rotate=a=>{if(Math.abs(a-Math.PI)<1e-9)n++;return r.call(ctx,a);};try{const C=CITY['${c}'];drawCity(C,100,100,1,0);}finally{ctx.rotate=r;}return n;})()`);
|
||||
// The picture of a city is painted once per state (citySprite), so the turn is checked on its static part.
|
||||
const turns = c => ev(`(()=>{let n=0;const r=ctx.rotate;ctx.rotate=a=>{if(Math.abs(a-Math.PI)<1e-9)n++;return r.call(ctx,a);};try{const C=CITY['${c}'],t=cTier(C.id);cityStatic(C,S.pops[C.id],t,1,1,{sel:0,dd:0,gl:-1},{down:false,feed:false,sel:false,inc:false,ixDraw:false,ixHot:false});}finally{ctx.rotate=r;}return n;})()`);
|
||||
assert.equal(turns('syd'), 1, 'Sydney: upside down');
|
||||
assert.equal(turns('lon'), 0, 'London: the right way up');
|
||||
// BrisVegas, Megapork's home town, and the data centres
|
||||
|
|
|
|||
|
|
@ -16,10 +16,11 @@ function pages() {
|
|||
let base = head;
|
||||
try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {}
|
||||
let P = { base: openPage(base, 'base'), head: openPage(head, 'head') };
|
||||
// A change to the world itself (cities, networks, cables) cannot route like main: there is no same game to compare.
|
||||
// Then the base is this checkout too, and the cache on/off check still runs; equivalence with main resumes once it lands.
|
||||
const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])])])");
|
||||
if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world differs from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; }
|
||||
// A change to the world itself (cities, networks, cables) or to what links cost cannot route like main: there is no
|
||||
// same game to compare. Then the base is this checkout too, and the cache on/off check still runs; equivalence with
|
||||
// main resumes once it lands.
|
||||
const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)])])");
|
||||
if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; }
|
||||
return P;
|
||||
}
|
||||
|
||||
|
|
|
|||
118
tests/sales-desk.test.js
Normal file
118
tests/sales-desk.test.js
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
// The sales desk: one salesperson at a time, three kinds (the engineer turned salesdroid, the shark, the CEO), each
|
||||
// bringing deals their own way and leaving their mark on the customers they sign.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par','fra','nyc','ash'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=3;compute()";
|
||||
// Offers as the day brings them, shaped by whoever is at the desk.
|
||||
const offers = (ev, n = 600) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();mktPrice(0);salesShape(0);out.push(...S.offers.map(o=>({t:o.type,by:o.by||null,bw:o.bw,rate:o.rate,reqs:(o.reqs||[]).length})));}return JSON.stringify(out);})()`));
|
||||
|
||||
test('one salesperson at a time, from customer level 2, with a salary; the CEO is free and cannot be fired', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.lvl=1;ACT.salesHire({id:'eng'})");
|
||||
assert.equal(ev('slP()'), null, 'level 1: the desk is not open yet');
|
||||
ev("S.lvl=4;ACT.salesHire({id:'eng'})");
|
||||
assert.equal(ev('slP()'), 'eng');
|
||||
ev("ACT.salesHire({id:'shark'})");
|
||||
assert.equal(ev('slP()'), 'eng', 'one at a time');
|
||||
assert.equal(ev('salesMo()'), 9000, 'on the payroll');
|
||||
ev('compute()');
|
||||
assert.ok(ev('R.cost.extras') >= 9000);
|
||||
ev('ACT.salesFire()'); ev('ACT.salesFire()');
|
||||
assert.equal(ev('slP()'), null, 'let go after a confirmation');
|
||||
ev("ACT.salesHire({id:'ceo'})");
|
||||
assert.equal(ev('slP()'), 'ceo');
|
||||
assert.equal(ev('salesMo()'), 0);
|
||||
ev('ACT.salesFire()'); ev('ACT.salesFire()');
|
||||
assert.equal(ev('slP()'), 'ceo', 'nobody fires the CEO');
|
||||
const cash = ev('S.cash');
|
||||
ev('ACT.salesVp()');
|
||||
assert.equal(ev('S.cash'), cash - ev('SALES_VP'), 'a board meeting costs');
|
||||
ev('for(let i=0;i<SALES_VP_DAYS;i++)salesDay(S.day+i+1)');
|
||||
assert.equal(ev('slP()'), null, 'a month later the VP of Sales frees the desk');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the engineer: more offers, never the huge deals, books every NOG at the usual price, and their customers stay', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("ACT.salesHire({id:'eng'})");
|
||||
const o = offers(ev);
|
||||
assert.ok(o.length > 300);
|
||||
assert.ok(o.every(x => !ev(`salesBig('${x.t}')`)), 'no mega AI, hyperscaler or AGI deals');
|
||||
assert.ok(o.every(x => x.by === 'eng'), 'every offer is theirs');
|
||||
assert.ok(ev('salesSpawn()') > 1, 'more offers come in');
|
||||
// A meeting 30 days out: they register you and you pay the ticket.
|
||||
const r = JSON.parse(ev(`(()=>{const cf=upcomingConfs(400).find(c=>!c.cap);S.day=cf.day-30;const cash=S.cash;salesDay(S.day);const n=upcomingConfs(30).filter(c=>!c.cap&&c.day===cf.day).length;return JSON.stringify({reg:!!S.confReg[cf.key],paid:cash-S.cash,n});})()`));
|
||||
assert.equal(r.reg, true);
|
||||
assert.equal(r.paid, r.n * ev('CONF_COST'), 'every meeting that day, each at the usual ticket price: not for free');
|
||||
assert.equal(ev("salesLeaveMul({by:'eng',type:'hft'})"), 0.5, 'the nerds love them');
|
||||
assert.ok(ev("salesLeaveMul({by:'eng',type:'dia'})") < 1);
|
||||
assert.ok(ev('salesAsk()') < 0.8, 'and they haggle badly');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the shark: bigger deals at a quarter more, oversold promises, no nerds, a commission, tougher peering', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
const plain = offers(ev);
|
||||
ev("ACT.salesHire({id:'shark'})");
|
||||
const o = offers(ev);
|
||||
assert.ok(o.every(x => !ev(`SALES_NERDS.includes('${x.t}')`)), 'no technical customers');
|
||||
const avg = (l, t) => { const x = l.filter(y => y.t === t); return x.reduce((a, y) => a + y.rate, 0) / Math.max(1, x.length); };
|
||||
assert.ok(avg(o, 'dia') > avg(plain, 'dia') * 1.15, `priced higher (${avg(o, 'dia')} vs ${avg(plain, 'dia')})`);
|
||||
const oversold = o.filter(x => x.reqs > 0).length / o.length, before = plain.filter(x => x.reqs > 0).length / plain.length;
|
||||
assert.ok(oversold > before + 0.15, `oversold: ${Math.round(oversold * 100)}% with promises, ${Math.round(before * 100)}% without the shark`);
|
||||
assert.equal(ev('salesPeerMul()'), 1.25);
|
||||
assert.equal(ev('salesMeet()'), 0.9, 'wins most haggles');
|
||||
assert.equal(ev("salesLeaveMul({by:'shark',type:'dia'})"), 1.5, 'and their customers leave sooner');
|
||||
// Signing one of theirs pays the commission.
|
||||
ev("S.offers=[];for(let i=0;i<200&&!S.offers.some(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);i++){spawnOffer();salesShape(0);}");
|
||||
const r = JSON.parse(ev("(()=>{const o=S.offers.find(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);const cash=S.cash;ACT.accept({id:o.id});const b=S.biz.find(b=>b.id===o.id);return JSON.stringify({by:b&&b.by,paid:cash-S.cash,mo:b?bizMo(b):0});})()"));
|
||||
assert.equal(r.by, 'shark', 'the customer remembers who signed it');
|
||||
assert.equal(r.paid, Math.round(r.mo), 'a month of the deal as commission');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the CEO: golf deals at 30% off, the odd declined offer signed anyway, opinions; all from hashes, not Math.random', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("ACT.salesHire({id:'ceo'})");
|
||||
ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};');
|
||||
const n0 = ev('S.biz.length');
|
||||
ev('for(let i=1;i<=200;i++)salesDay(S.day+i)');
|
||||
ev('Math.random=__r0');
|
||||
assert.equal(ev('__r'), 0, 'no draws from the game\'s random stream');
|
||||
const golf = JSON.parse(ev(`JSON.stringify(S.biz.slice(${n0}).map(b=>({by:b.by,t:b.type,bw:b.bw,rate:b.rate,list:BIZ_T[b.type].rate})))`));
|
||||
assert.ok(golf.length >= 2 && golf.length <= 4, `a golf deal every 50–80 days (${golf.length} in 200 days)`);
|
||||
for (const g of golf) {
|
||||
assert.equal(g.by, 'ceo');
|
||||
assert.ok(g.rate <= Math.round(g.list * 0.7 * ev('mkt()')) + 1, '30% off list');
|
||||
}
|
||||
assert.ok(ev("S.log.some(e=>/The CEO: /.test(e.t))"), 'and opinions');
|
||||
// Declining: about one in three, he already shook hands.
|
||||
const r = JSON.parse(ev(`(()=>{let over=0,n=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>bHas(o)&&!BIZ_T[o.type].event);if(!o)continue;n++;const b0=S.biz.length;ACT.decline({id:o.id});if(S.biz.length>b0)over++;}return JSON.stringify({over,n});})()`));
|
||||
assert.ok(r.n > 50 && r.over / r.n > 0.2 && r.over / r.n < 0.45, `${r.over} of ${r.n} declines signed anyway`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the desk in Deals and its sheet, and saves that remember who is at the desk', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("UI.left='deals';renderLeft()");
|
||||
assert.match(ev("document.getElementById('left').innerHTML"), /data-act="salesOpen"/);
|
||||
ev('ACT.salesOpen()');
|
||||
const m = ev("document.getElementById('modal').innerHTML");
|
||||
for (const id of ['eng', 'shark', 'ceo']) assert.match(m, new RegExp(`data-act="salesHire" data-args="\\{"id":"${id}"\\}"`));
|
||||
ev("ACT.salesHire({id:'shark'})");
|
||||
const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
|
||||
s.offers = [{ id: 'o1', city: 'ams', name: 'X', type: 'dia', bw: 1, rate: 600, reqs: [], exp: 99, by: 'pirate' }];
|
||||
const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`));
|
||||
assert.equal(out.sales.p, 'shark');
|
||||
assert.equal(out.offers[0].by, undefined, 'only real salespeople');
|
||||
s.sales = { p: 'intern', hired: 'yesterday' };
|
||||
assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).sales)`)).p, null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -109,9 +109,9 @@ test('the map keeps fiber capacities for one frame only, and skips links above o
|
|||
const cap = ev("dfCap(S.links.find(l=>l.id==='dfT'))");
|
||||
ev("S.links.find(l=>l.id==='dfT').ch.push('zr4');draw(0)");
|
||||
assert.equal(ev("dfCap(S.links.find(l=>l.id==='dfT'))"), 2 * cap, 'a new channel counts on the next frame');
|
||||
ev("ctx.fillText=()=>{throw new Error('boom')}");
|
||||
ev("window.__ds=drawShips;drawShips=()=>{throw new Error('boom')}");
|
||||
assert.throws(() => ev('draw(0)'));
|
||||
ev('delete ctx.fillText');
|
||||
ev('drawShips=window.__ds');
|
||||
assert.equal(ev('DFC'), null, 'not even after a frame that failed');
|
||||
// The whole network far above the screen: the links cost nothing, as if there were none.
|
||||
const calls = (body) => ev(`(()=>{cam.x=CITY.fra.x;cam.y=CITY.fra.y+${'2000'};cam.z=2;${body};const n=ctx.calls.n;draw(0);return ctx.calls.n-n;})()`);
|
||||
|
|
@ -125,7 +125,7 @@ test('a map with more than MAP_BUSY lines on screen leaves out link labels and f
|
|||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
// Spy on the two things that go: the dotted line on lit fiber and the link labels.
|
||||
ev("window.__dots=0;window.__labels=[];ctx.setLineDash=d=>{if(d.length===2&&d[0]===1&&d[1]===6)__dots++;};ctx.fillText=t=>{if(/ DF$/.test(t))__labels.push(t);}");
|
||||
ev("window.__dots=0;window.__labels=[];ctx.setLineDash=d=>{if(d.length===2&&d[0]===1&&d[1]===6)__dots++;};const __pill=pill;pill=(t,...a)=>{if(/ DF$/.test(t))__labels.push(t);return __pill(t,...a);}");
|
||||
const frame = () => ev("__dots=0;__labels=[];draw(0);JSON.stringify([__dots,__labels.length])");
|
||||
const view = "cam.x=(CITY.fra.x+CITY.lon.x)/2;cam.y=(CITY.fra.y+CITY.lon.y)/2;cam.z=1.6;";
|
||||
const lines = () => ev("(()=>{const PI=pairIdx();return linesOnScreen(linkGroups().map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),visibleKs());})()");
|
||||
|
|
|
|||
120
tests/webgl-coast.test.js
Normal file
120
tests/webgl-coast.test.js
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
// The land on the card per zoom level (src/game/96-map/57-webgl-background.js): zoomed out, the coastlines are
|
||||
// simplified so that no point moves more than COAST_TOL px on screen at that level, which takes most of the card's
|
||||
// vertices away. The coastlines themselves (COAST, onLand()) and the 2D map stay as they were.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
|
||||
|
||||
test('a simplified coastline never strays more than the tolerance from the full one', () => {
|
||||
const { ev, errors } = open();
|
||||
const r = JSON.parse(ev(`(()=>{const out=[];let worst=0,rings=0,kept=0,all=0;
|
||||
for(const lv of [-2,-1,0,1,3]){const tol=COAST_TOL/Math.pow(2,lv);
|
||||
COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastPts(ri),Q=coastSimplify(P,tol),at=new Map(P.map((p,i)=>[p,i]));rings++;kept+=Q.length;all+=P.length;
|
||||
if(Q[0]!==P[0]||Q[Q.length-1]!==P[P.length-1])out.push('ends '+ri);
|
||||
for(let j=0;j+1<Q.length;j++){const a=at.get(Q[j]),b=at.get(Q[j+1]);if(!(b>a))out.push('order '+ri);
|
||||
const ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;
|
||||
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=Math.max(0,Math.min(1,t));const d=Math.hypot(ax+t*dx-P[i][0],ay+t*dy-P[i][1])/tol;if(d>worst)worst=d;}}});}
|
||||
return JSON.stringify({bad:out.slice(0,5),worst,rings,share:kept/all});})()`));
|
||||
assert.deepEqual(r.bad, [], 'each ring keeps its ends and its order');
|
||||
assert.ok(r.worst <= 1 + 1e-9, `no point further than the tolerance (worst ${r.worst.toFixed(3)} of it)`);
|
||||
assert.ok(r.rings > 50);
|
||||
assert.ok(r.share < 0.6, `points are left out (${(r.share * 100).toFixed(0)} % kept)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('zoomed out the land has a few times fewer segments, and the closer the zoom the more it keeps', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const full=glLandGeo(GLX.gl,false),n=lv=>glLandGeo(GLX.gl,false,lv).nSeg;
|
||||
return JSON.stringify({full:full.nSeg,fullFan:full.nFan,l_1:n(-1),l0:n(0),l1:n(1),l3:n(3),far:glLandGeo(GLX.gl,true,-1).nSeg,once:glLandGeo(GLX.gl,false,0)===glLandGeo(GLX.gl,false,0),
|
||||
fan:glLandGeo(GLX.gl,false,-1).nFan});})()`));
|
||||
assert.ok(r.l_1 * 3 < r.full, `zoom 0.5–1: ${r.l_1} segments, ${r.full} in full`);
|
||||
assert.ok(r.l_1 < r.l0 && r.l0 < r.l1 && r.l1 <= r.l3 && r.l3 <= r.full, JSON.stringify(r));
|
||||
assert.ok(r.far < r.l_1, 'the far view still leaves out the islets');
|
||||
assert.ok(r.fan * 3 < r.fullFan, 'the fill’s fan shrinks as much');
|
||||
assert.equal(r.once, true, 'each level is built once');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the zoom level takes the finer level at once and keeps it a little while zooming out', () => {
|
||||
const { ev, errors } = open();
|
||||
const lv = JSON.parse(ev(`(()=>{delete GLX.coastLv;return JSON.stringify([1.5,2.1,1.95,1.85,1.8,0.9,0.95,0.4].map(coastLevel));})()`));
|
||||
assert.deepEqual(lv, [0, 1, 1, 1, 0, -1, -1, -2]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('each frame on the card fills the land from its zoom level’s geometry; the coastlines and the 2D map stay as they were', () => {
|
||||
const { ev, errors } = open();
|
||||
const coast = ev('JSON.stringify(COAST)');
|
||||
ev(STUB);
|
||||
const fans = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;delete GLX.coastLv;const o=[];
|
||||
for(const z of [0.6,1.4,3.2]){cam.z=z;GLX.gl.calls.length=0;draw(1000);const want=glLandGeo(GLX.gl,lodFar(),coastLevel(z)).nFan;
|
||||
o.push(GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').every(c=>c[3]===want));}return JSON.stringify(o);})()`));
|
||||
assert.deepEqual(fans, [true, true, true]);
|
||||
assert.equal(ev('JSON.stringify(COAST)'), coast, 'COAST is never changed (onLand() reads it)');
|
||||
let built = 0;
|
||||
ev(`mapGl(false);window.__lg=glLandGeo;glLandGeo=function(){__built++;return __lg.apply(this,arguments);};window.__built=0;cam.z=0.6;draw(1016);cam.z=3.2;draw(1032);`);
|
||||
built = ev('__built');
|
||||
assert.equal(built, 0, 'the 2D map does not use it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
/* Where two coastlines overlap, the land stays land, as the 2D map fills each coast on its own (nonzero). Timor is drawn
|
||||
twice (COAST[58] and the finer COAST[154], with Dili): the card counted only odd or even coverings over all the coasts,
|
||||
so the two cancelled out and most of the island was sea, its shadow too. The fan now winds every coast the same way
|
||||
and the stencil counts windings. w(x,y) is the winding the card counts at a point: the fan's triangles that cover it,
|
||||
+1 or -1 by the way they turn. */
|
||||
const WIND = `window.__wind=(fan,x,y)=>{let w=0;const s=(ax,ay,bx,by)=>(bx-ax)*(y-ay)-(by-ay)*(x-ax);
|
||||
for(let i=0;i<fan.length;i+=6){const [ax,ay,bx,by,cx,cy]=fan.slice(i,i+6),d1=s(ax,ay,bx,by),d2=s(bx,by,cx,cy),d3=s(cx,cy,ax,ay);
|
||||
if(d1>0&&d2>0&&d3>0)w++;else if(d1<0&&d2<0&&d3<0)w--;}return w;};`;
|
||||
|
||||
test('two overlapping coastlines leave their overlap filled (Timor), at every zoom', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(WIND);
|
||||
const r = JSON.parse(ev(`(()=>{const pt=[1692,600],o={both:[58,154].map(i=>inPoly(...pt,coastPts(i)))};
|
||||
for(const lv of [undefined,-1,0,1,2,3,4,5]){const tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[];
|
||||
COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastSimplify(coastPts(ri),tol);if(P.length>=4)coastFan(P,fan);});
|
||||
o['lv'+lv]=__wind(fan,...pt);}
|
||||
return JSON.stringify(o);})()`));
|
||||
assert.deepEqual(r.both, [true, true], 'the point is inside both of Timor’s coastlines');
|
||||
for (const lv of [undefined, -1, 0, 1, 2, 3, 4, 5]) assert.equal(r['lv' + lv], 2, `level ${lv}: counted twice, so land (an odd/even count gave 0, sea)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('every coastline counts +1 inside, whichever way it was drawn', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(WIND);
|
||||
const r = JSON.parse(ev(`(()=>{const sq=(x,y,s,cw)=>{const p=[[x,y],[x+s,y],[x+s,y+s],[x,y+s]];return cw?p.reverse():p;};
|
||||
const fan=[];coastFan(sq(0,0,10,false),fan);coastFan(sq(5,5,10,true),fan);
|
||||
return JSON.stringify({a:__wind(fan,2,1),both:__wind(fan,8,6),b:__wind(fan,12,13),out:__wind(fan,20,20)});})()`));
|
||||
assert.deepEqual(r, { a: 1, both: 2, b: 1, out: 0 }, 'one square turned each way: the overlap is 2, not 0');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the card fills the land where the winding count is not zero, and leaves the stencil at zero', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const c = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;GLX.gl.calls.length=0;draw(1000);
|
||||
return JSON.stringify(GLX.gl.calls.filter(c=>/^stencil/.test(c[0])).map(c=>c.join(' ')));})()`));
|
||||
assert.ok(c.includes('stencilOpSeparate FRONT KEEP KEEP INCR_WRAP') && c.includes('stencilOpSeparate BACK KEEP KEEP DECR_WRAP'), 'counts windings, +1 one way and -1 the other');
|
||||
assert.ok(c.includes('stencilFunc NOTEQUAL 0 255'), 'fills where the count is not zero, on all 8 bits');
|
||||
assert.ok(c.includes('stencilOp ZERO ZERO ZERO'), 'and sets it back to zero');
|
||||
assert.ok(!c.some(s => /INVERT/.test(s)), 'no odd/even count left');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
163
tests/webgl-context-restore.test.js
Normal file
163
tests/webgl-context-restore.test.js
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
// A WebGL context can be lost and given back: a driver reset, or on a phone sometimes just leaving the app. The map
|
||||
// gave the card up for the session at the first loss, so a phone that went to another app came back to the slower 2D
|
||||
// map until the page was reloaded. It now draws in 2D while the context is away, and builds everything on the card
|
||||
// again when the browser gives it back (webglcontextrestored), up to GL_LOSSES times a session. Settings › Map drawing
|
||||
// › Always 2D lets the context go the same way (WEBGL_lose_context), and Auto asks for it back, so a map drawn in 2D
|
||||
// does not hold 64 MB of atlas on the card. Switching for the GPU benchmark (mapGl(on,false)) keeps the context.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's. It can be lost by the "browser"
|
||||
(__browserLose(), __browserRestore()) or through WEBGL_lose_context (counted in __LOST and __RESTORE; without it when
|
||||
window.__noExt). Events come at once, which the real ones do not: the code must not rely on either order. Textures
|
||||
made are counted (__TEX), so a rebuild shows. */
|
||||
const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__LOST=0;window.__RESTORE=0;window.__TEX=0;
|
||||
let lost=false;const c=document.getElementById('mapgl'),fire=t=>c.dispatchEvent(new window.Event(t,{cancelable:true}));
|
||||
window.__browserLose=()=>{lost=true;fire('webglcontextlost');};window.__browserRestore=()=>{lost=false;fire('webglcontextrestored');};
|
||||
const ext={loseContext:()=>{__LOST++;if(lost)return;lost=true;fire('webglcontextlost');},restoreContext:()=>{__RESTORE++;if(!lost)return;lost=false;fire('webglcontextrestored');}};
|
||||
const gl=new Proxy({},{get(t,k){
|
||||
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?(window.__noExt?null:ext):{UNMASKED_RENDERER_WEBGL:'REN'};
|
||||
if(k==='isContextLost')return ()=>lost;
|
||||
if(k==='createTexture')return ()=>{__TEX++;return {};};
|
||||
if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096;
|
||||
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
|
||||
if(k==='getError')return ()=>0;
|
||||
return ()=>({});}});
|
||||
c.getContext=(t)=>t==='webgl2'?gl:null;})()`;
|
||||
|
||||
function open(storage) {
|
||||
const h = load({ seed: 777, storage });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
|
||||
const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`);
|
||||
h.ev(GL);
|
||||
return h;
|
||||
}
|
||||
const frame = (ev) => ev('__T+=16;draw(__T);JSON.stringify({gl:!!GLX.gl&&GLX.shown,dead:GLX.dead,lost:GLX.lost,sprs:SPRS.size,sprc:SPRC.size,err:!!UI.tickErr})');
|
||||
|
||||
test('a context the browser loses draws the map in 2D, then on the card again once it is back', () => {
|
||||
const { ev, errors } = open();
|
||||
assert.equal(JSON.parse(frame(ev)).gl, true, 'drawn on the card');
|
||||
ev('UI.tickErr=false;__browserLose();');
|
||||
let f = JSON.parse(frame(ev));
|
||||
assert.deepEqual([f.gl, f.dead, f.lost, f.err], [false, false, true, false], 'in 2D while it is away, without a glitch');
|
||||
assert.equal(f.sprs, 0, 'the card’s pictures are forgotten (its atlas went with the context)');
|
||||
assert.ok(f.sprc > 0, 'the 2D map paints its own');
|
||||
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
|
||||
ev('window.__t0=__TEX;window.__built=0;const gb=glBuild;glBuild=function(){__built++;return gb.apply(this,arguments);};__browserRestore();');
|
||||
f = JSON.parse(frame(ev));
|
||||
assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'back on the card');
|
||||
assert.ok(ev('__TEX-__t0') >= 2, 'the atlas and the tubes’ points are made again');
|
||||
assert.equal(ev('__built'), 1, 'the tubes are built again');
|
||||
assert.ok(f.sprs > 0, 'the pictures are sent again');
|
||||
assert.equal(ev('GLX.losses'), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`a card lost more than GL_LOSSES times is given up for the session`, () => {
|
||||
const { ev, errors } = open();
|
||||
frame(ev);
|
||||
const n = ev('GL_LOSSES');
|
||||
for (let i = 0; i < n; i++) { ev('__browserLose()'); frame(ev); ev('__browserRestore()'); assert.equal(JSON.parse(frame(ev)).gl, true, `back after loss ${i + 1}`); }
|
||||
ev('__browserLose()');
|
||||
let f = JSON.parse(frame(ev));
|
||||
assert.equal(f.dead, true, 'given up');
|
||||
assert.match(ev('GLX.why'), /lost 3 times/);
|
||||
assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did');
|
||||
// A late restore does not bring it back.
|
||||
ev('__browserRestore()');
|
||||
f = JSON.parse(frame(ev));
|
||||
assert.deepEqual([f.gl, f.dead], [false, true]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Always 2D lets the context go, Auto takes it back, and neither counts as a loss', () => {
|
||||
const { ev, errors } = open();
|
||||
frame(ev);
|
||||
ev("ACT.mapSet({v:'2d'})");
|
||||
assert.equal(ev('__LOST'), 1, 'the context is let go');
|
||||
assert.equal(ev('GLX.gl===null&&GLS.tex===null&&SPRS.size===0'), true, 'nothing on the card is held');
|
||||
let f = JSON.parse(frame(ev));
|
||||
assert.deepEqual([f.gl, f.dead], [false, false]);
|
||||
assert.equal(ev('localStorage.getItem("sot-map")'), '2d');
|
||||
ev("ACT.mapSet({v:'auto'})");
|
||||
assert.equal(ev('__RESTORE'), 1, 'asked back');
|
||||
f = JSON.parse(frame(ev));
|
||||
assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'on the card again');
|
||||
assert.equal(ev('GLX.losses'), 0, 'the player’s choice is not a failure');
|
||||
// Back and forth: still fine, still not counted.
|
||||
for (let i = 0; i < 4; i++) { ev("ACT.mapSet({v:'2d'})"); frame(ev); ev("ACT.mapSet({v:'auto'})"); }
|
||||
assert.equal(JSON.parse(frame(ev)).gl, true);
|
||||
assert.equal(ev('GLX.losses'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a context the browser gives back after the player chose Always 2D is let go again', () => {
|
||||
const { ev, errors } = open();
|
||||
frame(ev);
|
||||
ev('__browserLose()');
|
||||
ev("ACT.mapSet({v:'2d'})");
|
||||
assert.equal(ev('__LOST'), 0, 'already lost: nothing to let go yet');
|
||||
ev('__browserRestore()');
|
||||
assert.equal(ev('__LOST'), 1, 'let go as soon as it is back');
|
||||
assert.equal(JSON.parse(frame(ev)).gl, false);
|
||||
ev("ACT.mapSet({v:'auto'})");
|
||||
assert.equal(JSON.parse(frame(ev)).gl, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the GPU benchmark switches maps without letting the context go', () => {
|
||||
const { ev, errors } = open();
|
||||
frame(ev);
|
||||
ev('mapGl(false,false)');
|
||||
assert.equal(JSON.parse(frame(ev)).gl, false);
|
||||
ev('mapGl(true,false)');
|
||||
assert.equal(JSON.parse(frame(ev)).gl, true);
|
||||
assert.equal(ev('__LOST+__RESTORE'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('without WEBGL_lose_context, Always 2D keeps the context, as before', () => {
|
||||
const { ev, errors } = open();
|
||||
ev('window.__noExt=true');
|
||||
frame(ev);
|
||||
ev("ACT.mapSet({v:'2d'})");
|
||||
assert.equal(JSON.parse(frame(ev)).gl, false);
|
||||
assert.equal(ev('!!GLX.gl'), true, 'kept for later');
|
||||
ev("ACT.mapSet({v:'auto'})");
|
||||
assert.equal(JSON.parse(frame(ev)).gl, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a game started with Always 2D never makes a context', () => {
|
||||
const { ev, errors } = open({ 'sot-map': '2d' });
|
||||
ev('window.__made=0;const gc=document.getElementById("mapgl").getContext;document.getElementById("mapgl").getContext=t=>{__made++;return gc(t);};');
|
||||
frame(ev);
|
||||
ev("ACT.settings({})");
|
||||
assert.equal(ev('__made'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Settings said whether the card could draw the map by setting it up: opening them on the title screen or in a puzzle
|
||||
// made the context and its 64 MB atlas for a map drawn in 2D. It now says what is known without asking the card.
|
||||
test('opening Settings never makes a context, and still says when the card cannot', () => {
|
||||
const { ev, errors } = open();
|
||||
ev('window.WebGL2RenderingContext=function(){};window.__made=0;const c=document.getElementById("mapgl"),gc=c.getContext;c.getContext=t=>{__made++;return gc(t);};');
|
||||
const note = () => ev("settingsHtml().includes(tr('settings.this_browser_cannot_so_the_map'))");
|
||||
ev('const s=S;S=null;window.__S=s;');
|
||||
assert.equal(note(), false, 'title screen: a card not tried yet counts as able');
|
||||
ev('S=__S;');
|
||||
assert.equal(note(), false);
|
||||
assert.equal(ev('__made'), 0, 'no context made by Settings');
|
||||
ev('glKill(new Error("no graphics card, only SwiftShader"))');
|
||||
assert.equal(note(), true, 'a card given up: Settings says so');
|
||||
ev('delete window.WebGL2RenderingContext;GLX.dead=false;');
|
||||
assert.equal(note(), true, 'no WebGL2 in this browser: Settings says so');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
89
tests/webgl-frame-garbage.test.js
Normal file
89
tests/webgl-frame-garbage.test.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// A frame on the card makes little garbage (src/game/96-map/57-webgl-background.js, 59-gl-sprites.js, 80-cities.js):
|
||||
// the keys of the pictures are kept per city and per label and built again only when the picture changes, and the
|
||||
// waves and the clouds are written into arrays kept from frame to frame. What is drawn stays the same.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
|
||||
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
|
||||
|
||||
// Counts the keys joined during one frame (Array#join with '|', as the picture keys are), but the ships' (a handful).
|
||||
const JOINS = (body) => `(()=>{let n=0;const j=Array.prototype.join;Array.prototype.join=function(s){if(s==='|'&&this[0]!=='ship')n++;return j.apply(this,arguments);};
|
||||
try{${body}}finally{Array.prototype.join=j;}return n;})()`;
|
||||
|
||||
for (const [view, z] of [['near', 1.4], ['far', 0.6]]) {
|
||||
test(`an unchanged frame on the card joins no picture key again (${view} view)`, () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=${z};UI.sel=null;draw(1000);draw(1016);`);
|
||||
const first = ev(JOINS(`SPRS.clear();CKEY.clear();PILLK.clear();FKEY.clear();QKEY.clear();draw(1032);`));
|
||||
const again = ev(JOINS('draw(1048);'));
|
||||
assert.ok(first > 20, `a first frame builds its keys (${first})`);
|
||||
assert.equal(again, 0, 'the next one builds none');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('a city whose state changes gets a new picture, and its old one back after', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id],p=S.pops[id];cam.x=C.x;cam.y=C.y;cam.z=1.4;UI.sel=null;
|
||||
const pic=()=>{draw(1000);return CKEY.get(id).k;};const a=pic();const was=p.down;p.down=S.day+3;const b=pic();p.down=was;const c=pic();
|
||||
UI.sel={type:'city',id};const d=pic();UI.sel=null;
|
||||
const before=CKEY.get(id).k,gen=p.gen;p.gen=!gen;const e=pic();p.gen=gen;
|
||||
return JSON.stringify({a,b,c,d,e,before});})()`));
|
||||
assert.notEqual(r.b, r.a, 'down: another picture');
|
||||
assert.equal(r.c, r.a, 'back up: the same picture');
|
||||
assert.notEqual(r.d, r.a, 'selected: another picture');
|
||||
assert.notEqual(r.e, r.before, 'a generator: another picture');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('labels with the same text but another look are other pictures', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;const f='800 12px "Baloo 2", sans-serif';
|
||||
pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FF4F9A','#FFFFFF','#1E2640',2,10,10,.5);pill('Lagos',f,50,19,9,'#FFFFFF','#1E2640','#1E2640',2,10,10,.5);
|
||||
const n=GLS.n,L=PILLK.get('Lagos').length,u=new Set([0,1,2].map(i=>GLS.data[i*SPR_STRIDE+4]+','+GLS.data[i*SPR_STRIDE+5])).size;GLS.frame=false;GLS.n=0;ctx=CTX0;
|
||||
return JSON.stringify({n,L,u});})()`));
|
||||
assert.equal(r.n, 3);
|
||||
assert.equal(r.L, 2, 'two looks kept for one text');
|
||||
assert.equal(r.u, 2, 'two pictures in the atlas, the third label reuses the first');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the waves and the clouds are what they were, written into arrays kept from frame to frame', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const ks=[-1,0,1],now=12345,gl=GLX.gl;
|
||||
glWaves(gl,now,ks);const wa=GLX.wa,ph0=now/900,want=[];let m=0,bad=0;
|
||||
for(const [x,y,ph] of WAVES){const o=Math.sin(ph0+ph*6)*3;for(const [x0,cx,cy,x1] of [[x-9+o,x-4.5+o,y-4,x+o],[x+o,x+4.5+o,y+4,x+9+o]]){let px=x0,py=y;
|
||||
for(let j=1;j<=4;j++){const t=j/4,u=1-t,qx=u*u*x0+2*u*t*cx+t*t*x1,qy=u*u*y+2*u*t*cy+t*t*y,o2=m*LINE_STRIDE;
|
||||
if(wa[o2]!==Math.fround(px)||wa[o2+1]!==Math.fround(py)||wa[o2+2]!==Math.fround(qx)||wa[o2+3]!==Math.fround(qy))bad++;m++;px=qx;py=qy;}}}
|
||||
glWaves(gl,now+16,ks);const sameW=GLX.wa===wa;
|
||||
glClouds(gl,now,ks);const ca=GLX.ca,A=[];for(const k of ks)for(const c of CLOUDS){const x=((c.x+now/1000*c.v)%(W+200))-100+k*W,y=c.y;A.push(x,y,16*c.s,0, x+18*c.s,y-8*c.s,20*c.s,0, x+40*c.s,y,15*c.s,0);}
|
||||
const sent=gl.calls.filter(c=>c[0]==='bufferData').pop()[2],cbad=A.filter((v,i)=>sent[i]!==Math.fround(v)).length;
|
||||
glClouds(gl,now+16,ks);
|
||||
return JSON.stringify({bad,m,sameW,cbad,clen:sent.length,alen:A.length,sameC:GLX.ca===ca});})()`));
|
||||
assert.equal(r.bad, 0, `every wave segment where it was (${r.m} segments)`);
|
||||
assert.equal(r.sameW, true);
|
||||
assert.equal(r.clen, r.alen, 'one record per puff');
|
||||
assert.equal(r.cbad, 0, 'every puff where it was');
|
||||
assert.equal(r.sameC, true, 'the clouds’ array is kept');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
333
tests/webgl-map.test.js
Normal file
333
tests/webgl-map.test.js
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
// The WebGL map (src/game/96-map/56-webgl.js to 59-gl-sprites.js): jsdom has no WebGL, so these tests check what can be checked
|
||||
// without a graphics card. A browser without WebGL2 keeps the 2D map; the instance data the card would draw says the
|
||||
// same as the 2D map (points, colours, dashes, packets, painting order, selection); with a stand-in context the map
|
||||
// sends its lines to the card and paints the rest on the overlay, and goes back to its own canvas afterwards.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
|
||||
return h;
|
||||
}
|
||||
|
||||
// A WebGL2 stand-in that records draws: enough for glBuild() and glFrame() to run.
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
|
||||
|
||||
test('without WebGL2 the map stays 2D, and asking for WebGL changes nothing', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(`mapGl(true);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
|
||||
assert.equal(ev('GLX.dead'), true, 'a context that cannot compile shaders is given up');
|
||||
assert.equal(ev('glOn()'), false);
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'the layer stays hidden');
|
||||
assert.ok(ev('ctx===CTX0'), 'the map draws on its own canvas');
|
||||
assert.ok(ev(`cv.getContext('2d').calls.n`) > 1000, 'the 2D map drew its lines');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the instance data says what the 2D map draws: points, colours, dashes, packets and painting order', () => {
|
||||
const { ev } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0]))));
|
||||
const sel=LG[3][0].id,looks=LG.map(g=>linkLook(g,S.day)),{SEG,PK,PT}=glBuild(LG,GM,looks),H=glHalo(LG,GM,looks,sel);let si=0,ki=0,pi=0,hi=0,bad=[];const deps=[];
|
||||
for(let gi=0;gi<LG.length;gi++){const gm=GM[gi],L=looks[gi],[r,g,b]=glColor(L.col),hot=LG[gi].some(x=>x.id===sel);
|
||||
for(let j=0;j<gm.pts.length;j++){if(PT[pi*4]!==Math.fround(gm.pts[j][0])||PT[pi*4+2]!==Math.fround(gm.cum[j]))bad.push('pt '+gi);pi++;}
|
||||
for(let j=0;j+1<gm.pts.length;j++){const o=si*12;
|
||||
if(SEG[o]!==Math.fround(gm.pts[j][0])||SEG[o+3]!==Math.fround(gm.pts[j+1][1]))bad.push('seg '+gi);
|
||||
if(SEG[o+6]!==L.dash||SEG[o+5]!==Math.fround(L.w0)||SEG[o+9]!==Math.fround(r)||SEG[o+11]!==Math.fround(b))bad.push('look '+gi);
|
||||
if((SEG[o+7]&1)===1||((SEG[o+7]&2)===2)!==(L.df&&!L.bld&&!L.dark))bad.push('flags '+gi);
|
||||
if(hot){const h=hi*12;for(let x=0;x<12;x++)if(H[h+x]!==(x===7?1:SEG[o+x]))bad.push('halo '+gi);hi++;}
|
||||
if(j===0)deps.push(SEG[o+8]);si++;}
|
||||
const n=!L.cut&&L.load>0.01?clamp(Math.round(2+L.u*10),2,12):0;for(let i=0;i<n;i++){if(PK[ki*8+3]!==n||PK[ki*8+4]!==i)bad.push('pk '+gi);ki++;}}
|
||||
return JSON.stringify({bad:bad.slice(0,5),si,segs:SEG.length/12,ki,pks:PK.length/8,groups:LG.length,
|
||||
order:deps.every((d,i)=>!i||d<deps[i-1]),inRange:deps.every(d=>d>0&&d<1),sel:hi>0&&hi===GLX.nHalo,moving:looks.filter(L=>!L.cut&&L.load>0.01).length});})()`));
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.equal(r.si, r.segs, 'one instance per segment');
|
||||
assert.equal(r.ki, r.pks, 'one instance per packet');
|
||||
assert.ok(r.groups > 50 && r.moving > 20, 'a big map with traffic');
|
||||
assert.ok(r.order && r.inRange, 'later tubes are nearer, so they paint over earlier ones as in 2D');
|
||||
assert.equal(r.sel, true, 'the selected tube, and only it, gets its halo: its own segments at its own depth');
|
||||
});
|
||||
|
||||
test('with WebGL the lines go to the card, the rest to the overlay, and the map gets its canvas back', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
|
||||
const flat = ev(`cv.getContext('2d').calls.n`);
|
||||
ev(STUB);
|
||||
ev(`cv.getContext('2d').calls.n=0;document.getElementById('mapfx').getContext('2d').calls.n=0;draw(1000);`);
|
||||
assert.equal(ev('glOn()'), true);
|
||||
const main = ev(`cv.getContext('2d').calls.n`), over = ev(`document.getElementById('mapfx').getContext('2d').calls.n`);
|
||||
assert.ok(main < flat / 2, `the map's own canvas only paints sea, land and cables (${main} calls, ${flat} in 2D)`);
|
||||
assert.ok(over > 100, 'labels and cities go on the 2D overlay');
|
||||
assert.ok(ev('ctx===CTX0'), 'draw() hands the 2D context back');
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden`), false, 'the WebGL layer shows');
|
||||
const draws = JSON.parse(ev(`JSON.stringify(GLX.gl.calls.filter(c=>c[0]==='drawArraysInstanced').map(c=>c[4]))`));
|
||||
assert.ok(draws.includes(ev('GLX.nSeg')) && draws.includes(ev('GLX.nPk')), 'every segment and every packet in instanced draws');
|
||||
// Nothing changed: the next frame reuses the buffers. A cut link changes routing, and the tubes are rebuilt.
|
||||
// The tubes' own buffers (segments, packets, points) are what must not be sent again on an ordinary frame; the waves and clouds move every frame by design.
|
||||
const uploads = () => ev(`GLX.gl.calls.filter(c=>c[0]==='bufferData'&&c[2]&&c[2].length===GLX.nSeg*12).length`);
|
||||
const u0 = uploads(); ev('draw(1016)'); assert.equal(uploads(), u0, 'a frame alone uploads no tube data');
|
||||
const id = ev(`(()=>{const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));l.cut=S.day+5;compute();draw(1032);return l.id;})()`);
|
||||
assert.ok(uploads() > u0, 'a cut rebuilds the tubes');
|
||||
assert.equal(ev(`linkLook(linkGroups().find(g=>g.some(x=>x.id===${JSON.stringify(id)})),S.day).dash`), 1, 'drawn dashed like a cut');
|
||||
ev('mapGl(false);draw(1048)');
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'switching back hides the layers');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a label sits at the middle of its line whichever way the middle is found', () => {
|
||||
const { ev } = open();
|
||||
const d = ev(`(()=>{let m=0;const PI=pairIdx();for(const g of linkGroups()){const gm=linkGeom(g[0],PI.get(edgeKey(g[0]))),X=gm.pts.map(p=>(p[0]-cam.x)*cam.z+CW/2),Y=gm.pts.map(p=>(p[1]-cam.y)*cam.z+CH/2);
|
||||
const a=polyAtXY(X,Y,gm.cum,.5),w=polyAt(gm.pts,gm.cum,.5),b=[(w[0]-cam.x)*cam.z+CW/2,(w[1]-cam.y)*cam.z+CH/2];m=Math.max(m,Math.hypot(a[0]-b[0],a[1]-b[1]));}return m;})()`);
|
||||
assert.ok(d < 1e-6, `midpoints agree (${d})`);
|
||||
});
|
||||
|
||||
test('the labels and cities stay on the 2D overlay; the card draws the background and the tubes', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`cv.getContext('2d').calls.n=0;document.getElementById('mapfx').getContext('2d').calls.n=0;draw(1000);`);
|
||||
assert.ok(ev(`document.getElementById('mapfx').getContext('2d').calls.n`) > 100, 'labels and cities are painted on the 2D overlay');
|
||||
assert.ok(ev(`GLX.gl.calls.filter(c=>c[0]==='drawArraysInstanced').length`) > 0, 'the tubes are still drawn on the card');
|
||||
assert.equal(ev(`document.getElementById('mapfx').hidden`), false, 'the 2D overlay shows');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the land is geometry on the card: one fan per coastline, its outlines, its hills; the far view leaves out islets', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const all=glLandGeo(GLX.gl,false),far=glLandGeo(GLX.gl,true);
|
||||
const pts=COAST.reduce((a,p)=>a+p.length,0);
|
||||
GLX.gl.calls.length=0;cam.z=1.4;draw(1000);
|
||||
const fans=GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').map(c=>c[3]);
|
||||
const lv=glLandGeo(GLX.gl,false,coastLevel(1.4));
|
||||
return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,lvFan:lv.nFan,
|
||||
wl:GLX.gl.calls.some(c=>c[0]==='texImage2D'&&c[6]===WL.cv)});})()`));
|
||||
assert.equal(r.nFan % 3, 0, 'whole triangles');
|
||||
assert.equal(r.nSeg, r.pts * 4, 'each curve of the coast in four segments');
|
||||
assert.ok(r.farSeg < r.nSeg, 'zoomed out, the islets are left out as in 2D');
|
||||
assert.equal(r.hills, ev('HILLS.length'));
|
||||
assert.ok(r.again, 'built once');
|
||||
assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.lvFan), 'shadow and grass are filled each frame from the same fan (the zoom level’s)');
|
||||
assert.equal(r.wl, false, 'no picture of the land is uploaded');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the 2D layers are cleared only when something was painted on them', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`(()=>{const f=GLX.fx,c=CTX0,cr=(x)=>{const o=x.clearRect;x.__n=0;x.clearRect=function(){x.__n++;return o.apply(this,arguments);};};cr(f);cr(c);})()`);
|
||||
ev('cam.z=1.4;draw(1000);draw(1016)');
|
||||
assert.equal(ev('CTX0.__n'), 1, 'the empty map canvas under the card is cleared once');
|
||||
ev('GLX.fxUsed=false;GLX.fx.__n=0;draw(1032)');
|
||||
assert.equal(ev('GLX.fx.__n'), 0, 'an overlay nothing was painted on is left alone');
|
||||
ev('GLX.fxUsed=true;draw(1048)');
|
||||
assert.equal(ev('GLX.fx.__n'), 1, 'one that was painted on is cleared');
|
||||
assert.equal(ev('GLX.fxUsed'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('things that bob, pulse or float are pictures on the card, not shapes on the overlay', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{GLS.prog={p:{},u:{}};GLS.frame=true;GLS.n=0;const fx=document.getElementById('mapfx').getContext('2d'),n0=fx.calls.n,c0=CTX0.calls.n;ctx=fx;
|
||||
drawCone(100,100,0);drawCone(100,100,500);drawBackhoe(200,100,0,true);shipSprite(300,100,1,1,'#FF4D5E',0,'sail');
|
||||
ctx.globalAlpha=.5;textStamp('+$1,000','800 17px "Baloo 2", sans-serif',17,60,'#16A866','#fff',4,50,50);ctx.globalAlpha=1;
|
||||
const n=GLS.n,size=SPRS.size,alpha=GLS.data[4*SPR_STRIDE+11];GLS.frame=false;GLS.n=0;ctx=CTX0;
|
||||
return JSON.stringify({n,size,alpha,fx:fx.calls.n-n0,main:CTX0.calls.n-c0});})()`));
|
||||
assert.equal(r.n, 5, 'one picture each');
|
||||
assert.equal(r.fx, 0, 'nothing painted on the overlay');
|
||||
assert.equal(r.alpha, 0.5, 'a fading floater keeps its fade');
|
||||
assert.ok(r.size >= 4, 'a bobbing cone is the same picture at another place');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a frame on the card is a handful of draws, whatever the size of the network', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const draws = (body) => ev(`(()=>{${body};const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);GLX.gl.calls.length=0;draw(1016);
|
||||
return GLX.gl.calls.filter(c=>/^draw(Arrays|ArraysInstanced)$/.test(c[0])).length;})()`);
|
||||
const big = draws(''), links = ev('S.links.length');
|
||||
ev('S.links.length=0;compute()');
|
||||
const none = draws('');
|
||||
assert.ok(links > 100, 'a big network');
|
||||
assert.ok(big < 50, `${big} draws for ${links} links`);
|
||||
assert.ok(big - none <= 8, `the tubes add their passes, not one draw per link (${none} without links, ${big} with)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('panning on the card repaints no land and sends no geometry again', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{let paints=0;const pw=paintWorld;paintWorld=function(){paints++;return pw.apply(this,arguments);};
|
||||
const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);GLX.gl.calls.length=0;
|
||||
for(let i=1;i<=30;i++){cam.x+=25;draw(1000+i*16);}
|
||||
paintWorld=pw;const c=GLX.gl.calls,static_=c.filter(x=>x[0]==='bufferData'&&x[3]==='STATIC_DRAW').length;
|
||||
return JSON.stringify({paints,tex:c.filter(x=>x[0]==='texImage2D').length,static_});})()`));
|
||||
assert.equal(r.paints, 0, 'the land is never painted with the 2D canvas');
|
||||
assert.equal(r.tex, 0, 'no picture of the land, no tube points uploaded again');
|
||||
assert.equal(r.static_, 0, 'the land and the cables were built once');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('Settings › Map drawing: Auto uses the card, Always 2D keeps the 2D map and is remembered', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev('ACT.settings({})');
|
||||
assert.match(ev(`document.getElementById('modal').innerHTML`), /data-act="mapSet"/, 'the setting is in Settings');
|
||||
ev(`ACT.mapSet({v:'2d'});draw(1000)`);
|
||||
assert.equal(ev(`localStorage.getItem('sot-map')`), '2d');
|
||||
assert.equal(ev('glOn()'), false);
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden`), true, 'the card is hidden');
|
||||
ev(`ACT.mapSet({v:'sideways'})`);
|
||||
assert.equal(ev(`localStorage.getItem('sot-map')`), '2d', 'a value it does not know changes nothing');
|
||||
ev(`ACT.mapSet({v:'auto'});draw(1016)`);
|
||||
assert.equal(ev(`localStorage.getItem('sot-map')`), null);
|
||||
assert.equal(ev('glOn()'), true);
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden`), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a sprite record that makes the queue grow is kept, for pictures and for discs', () => {
|
||||
const { ev, errors } = open();
|
||||
// Pictures and discs alternate, so both cross a growth (2048, then 4096 records); each record says which one it is.
|
||||
const bad = JSON.parse(ev(`(()=>{const e={up:true,u0:.1,v0:.2,u1:.3,v1:.4,cv:null};GLS.frame=true;GLS.n=0;GLS.data=new Float32Array(SPR_STRIDE*2048);
|
||||
for(let i=0;i<4100;i++){ctx.globalAlpha=(i%7+1)/8;if(i%2)dot(i,i*2,3+i%5,'#FF4D5E',(i%3+1)/4);else blit(e,i,i*2,10+i%9,20+i%11);}
|
||||
ctx.globalAlpha=1;const D=GLS.data,n=GLS.n,cap=D.length/SPR_STRIDE,bad=[];GLS.frame=false;GLS.n=0;
|
||||
for(let i=0;i<n;i++){const o=i*SPR_STRIDE,want=i%2?[i,i*2,3+i%5,1,(i%3+1)/4]:[i,i*2,10+i%9,0,(i%7+1)/8];
|
||||
const got=i%2?[D[o],D[o+1],D[o+2],D[o+12],D[o+11]]:[D[o],D[o+1],D[o+2],D[o+12],D[o+11]];
|
||||
if(i%2===0&&(D[o+3]!==20+i%11||D[o+4]!==Math.fround(.1)||D[o+7]!==Math.fround(.4)))bad.push(i);
|
||||
else if(i%2&&D[o+8]!==1)bad.push(i);
|
||||
else if(want.some((v,j)=>Math.fround(v)!==got[j]))bad.push(i);}
|
||||
return JSON.stringify({n,cap,bad:bad.slice(0,8),edges:[2047,2048,2049,4096,4097].filter(i=>bad.includes(i))});})()`));
|
||||
assert.equal(bad.n, 4100);
|
||||
assert.ok(bad.cap >= 4100, 'the queue grew past 4096 records');
|
||||
assert.deepEqual(bad.edges, [], 'the records at each growth are where they were drawn');
|
||||
assert.deepEqual(bad.bad, [], 'and so is every other record');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a city under attack never reuses its picture without the attack ring, and gets it back after', () => {
|
||||
const { ev, errors } = open();
|
||||
const r = JSON.parse(ev(`(()=>{const id=Object.keys(S.pops).find(c=>!S.pops[c].down||S.pops[c].down<=S.day),C=CITY[id],p=S.pops[id],t=cTier(id);
|
||||
const st={down:false,feed:false,sel:false,inc:false,ixDraw:false,ixHot:false,off:false,big:false};
|
||||
const spr=now=>{const ph=cityPhase(C,p,false,now);return [ph.dd,citySprite(C,p,t,1,1,ph,st)];};
|
||||
R.ddosHot={};const [d0,quiet]=spr(0);
|
||||
R.ddosHot={[id]:1};const [d1,hit0]=spr(0),[d2,hit3]=spr(90);
|
||||
R.ddosHot={};const [d3,after]=spr(0);
|
||||
// Animations off: the map's clock stays at 0, so the attack is always at step 0.
|
||||
R.ddosHot={[id]:1};const [d4,still]=spr(0);
|
||||
return JSON.stringify({dd:[d0,d1,d2,d3,d4],sameAtZero:quiet===hit0,step:hit0===hit3,back:after===quiet,still:still===hit0});})()`));
|
||||
assert.deepEqual(r.dd, [-1, 0, 3, -1, 0]);
|
||||
assert.equal(r.sameAtZero, false, 'step 0 of an attack is not the picture without one');
|
||||
assert.equal(r.step, false, 'the ring turns');
|
||||
assert.equal(r.back, true, 'once over, the plain picture is back');
|
||||
assert.equal(r.still, true, 'with animations off the attack keeps its own picture');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('leaving a game hides the card’s layers, and the next game shows them again', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const shown = () => JSON.parse(ev(`JSON.stringify([GLX.shown,!document.getElementById('mapgl').hidden,!document.getElementById('mapfx').hidden])`));
|
||||
ev('draw(1000)');
|
||||
assert.deepEqual(shown(), [true, true, true], 'a game on the card');
|
||||
ev('ACT.toTitle();draw(1016)');
|
||||
assert.deepEqual(shown(), [false, false, false], 'back to the title: the old network is not left behind it');
|
||||
assert.ok(ev('ctx===CTX0'));
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;compute();draw(1032)`);
|
||||
assert.deepEqual(shown(), [true, true, true], 'the next game is on the card again');
|
||||
ev(`slotBroke(UI.slot||'x');draw(1048)`);
|
||||
assert.deepEqual(shown(), [false, false, false], 'a damaged save leaves the title with an empty map too');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Faults injected into the card at each step of a frame: WebGL is given up once, the same frame is drawn in 2D, the
|
||||
// layers are hidden, and the next frames are 2D without another try or another error.
|
||||
for (const [where, inject] of [
|
||||
['the start of a frame', `GLX.gl.clear=()=>{throw new Error('boom')};`],
|
||||
['an upload of the tubes', `GLX.key=[];GLX.gl.texImage2D=()=>{throw new Error('boom')};`],
|
||||
['the pictures’ draw', `GLS.prog={p:{},u:{}};GLS.vao={};GLS.tex={};glsDraw=()=>{throw new Error('boom')};`],
|
||||
['a picture going into the atlas', `GLS.prog={p:{},u:{}};GLS.vao={};GLS.tex={};SPRS.clear();GLX.gl.texSubImage2D=()=>{throw new Error('boom')};`],
|
||||
]) {
|
||||
test(`a fault in ${where} falls back to 2D once and for all`, () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`draw(1000);${inject}window.__tries=0;const gb=glBegin;glBegin=function(){__tries++;return gb.apply(this,arguments);};
|
||||
window.__warn=0;console.warn=function(){__warn++;};`);
|
||||
const c0 = ev('CTX0.calls.n');
|
||||
ev('draw(1016);draw(1032);draw(1048)');
|
||||
assert.equal(ev('GLX.dead'), true, 'WebGL is given up');
|
||||
assert.equal(ev('__tries'), 1, 'and not tried again every frame');
|
||||
assert.equal(ev('__warn'), 1, 'said once');
|
||||
assert.ok(ev('ctx===CTX0'), 'the 2D context is back');
|
||||
assert.equal(ev('GLS.frame'), false);
|
||||
assert.equal(ev('GLS.n'), 0);
|
||||
assert.equal(ev(`document.getElementById('mapgl').hidden&&document.getElementById('mapfx').hidden`), true, 'the layers are hidden');
|
||||
assert.ok(ev('CTX0.calls.n') - c0 > 1000, 'the 2D map is drawn, from the frame that failed on');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('an error outside the card still reaches the loop, and leaves the frame clean', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`draw(1000);window.__dc=drawCity;drawCity=function(){throw new Error('not the card');};`);
|
||||
assert.throws(() => ev('draw(1016)'), /not the card/);
|
||||
assert.equal(ev('GLX.dead'), false, 'WebGL stays on: the card did nothing wrong');
|
||||
assert.ok(ev('ctx===CTX0'));
|
||||
assert.equal(ev('GLS.frame'), false);
|
||||
ev('drawCity=__dc;draw(1032)');
|
||||
assert.equal(ev('GLX.shown'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('selecting a tube sends its halo to the card, not the network again', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);const c=GLX.gl.calls,nSeg=GLX.nSeg;
|
||||
const sent=()=>{const b=c.filter(x=>x[0]==='bufferData').map(x=>x[2]&&x[2].length||0),t=c.filter(x=>x[0]==='texImage2D').length;c.length=0;return {b,t};};
|
||||
sent();const l=S.links.find(l=>l.kind!=='vxc'&&!linkDown(l));UI.sel={type:'link',id:l.id};draw(1016);const on=sent(),halo=GLX.nHalo;
|
||||
UI.sel=null;draw(1032);const off=sent();
|
||||
return JSON.stringify({nSeg,on,off,halo,haloDraw:GLX.nHalo});})()`));
|
||||
const tubes = r.nSeg * 12;
|
||||
assert.ok(r.halo > 0, 'the halo has the selected tube’s segments');
|
||||
assert.ok(!r.on.b.includes(tubes) && r.on.t === 0, 'selecting sends no tube, packet or point again');
|
||||
assert.ok(r.on.b.includes(r.halo * 12), 'only the halo goes up');
|
||||
assert.ok(!r.off.b.includes(tubes) && r.off.t === 0, 'nor does unselecting');
|
||||
assert.equal(r.haloDraw, 0, 'and the halo is gone');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A WebGL2 context that compiles everything and names its renderer: enough for glInit() to run to the end.
|
||||
const FAKE_GL = (name) => `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};const c=document.getElementById('mapgl');c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
|
||||
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
if(k==='getExtension')return ()=>({UNMASKED_RENDERER_WEBGL:'REN'});
|
||||
if(k==='getParameter')return (p)=>p==='REN'?${JSON.stringify(name)}:p==='ACTIVE_UNIFORMS'?0:4096;
|
||||
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
|
||||
return ()=>({});}});})()`;
|
||||
|
||||
test('a graphics card drawn by the processor keeps the 2D map; a real one gets the card', () => {
|
||||
for (const [name, gl] of [['ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)', false],
|
||||
['llvmpipe (LLVM 17.0.6, 256 bits)', false], ['Microsoft Basic Render Driver', false],
|
||||
['ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 Direct3D11 vs_5_0 ps_5_0, D3D11)', true], ['Apple M2', true], ['Mali-G78', true]]) {
|
||||
const { ev } = open();
|
||||
ev(FAKE_GL(name));
|
||||
ev('console.warn=()=>{}');
|
||||
assert.equal(ev('glInit()'), gl, name);
|
||||
assert.equal(ev('GLX.dead'), !gl, name);
|
||||
assert.equal(ev('GLX.gpu'), name, 'the renderer is still named');
|
||||
}
|
||||
const { ev } = open();
|
||||
ev(FAKE_GL('SwiftShader driver'));
|
||||
ev('GLX.soft=true');
|
||||
assert.equal(ev('glInit()'), true, 'the GPU benchmark can still measure it');
|
||||
});
|
||||
168
tests/webgl-out-of-memory.test.js
Normal file
168
tests/webgl-out-of-memory.test.js
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// A graphics card short of memory may refuse a texture or a buffer without throwing: the call only leaves
|
||||
// OUT_OF_MEMORY for getError(), and the atlas then drew every picture as a black box while the map stayed on the card.
|
||||
// The big uploads now read it (glMem(), src/game/96-map/56-webgl.js): the atlas tries 2048 px before giving up, and
|
||||
// any other refusal gives the card up for 2D in the same frame, or for a picture within a second. getError() is never
|
||||
// read on an ordinary frame, and at most once a second while pictures are sent (each read waits for the card).
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's, and that refuses memory as asked in
|
||||
window.__FAIL: atlas (the texture sizes refused), land (the first static buffer after setup), tubes (the tubes'
|
||||
points), sprites (every picture sent into the atlas). A refusal sets OUT_OF_MEMORY, read once by getError(); the
|
||||
reads are counted. It also counts the pictures sent (__SUB), what is deleted (__DEL) and the context let go (__LOST). */
|
||||
const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__GE=0;window.__ERR=0;window.__SUB=0;window.__DEL=[];window.__LOST=0;window.__LOSTEV=0;
|
||||
const F=window.__FAIL;let setup=true,lost=false;const c=document.getElementById('mapgl');c.addEventListener('webglcontextlost',()=>{__LOSTEV++;});
|
||||
c.getContext=(t)=>t!=='webgl2'?null:new Proxy({},{get(t,k){
|
||||
if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?{loseContext:()=>{__LOST++;lost=true;c.dispatchEvent(new window.Event('webglcontextlost'));}}:{UNMASKED_RENDERER_WEBGL:'REN'};
|
||||
if(k==='isContextLost')return ()=>lost||!!window.__lostNow;
|
||||
if(k==='deleteTexture'||k==='deleteBuffer')return (x)=>{__DEL.push(x);};
|
||||
if(k==='texSubImage2D')return ()=>{__SUB++;if(F.sprites)__ERR='OUT_OF_MEMORY';};
|
||||
if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096;
|
||||
if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true;
|
||||
if(k==='getError')return ()=>{__GE++;const e=__ERR;__ERR=0;return e;};
|
||||
if(k==='texImage2D')return (...a)=>{if(a[2]==='RGBA'&&(F.atlas||[]).includes(a[3]))__ERR='OUT_OF_MEMORY';if(a[2]==='RGBA32F'&&F.tubes)__ERR='OUT_OF_MEMORY';};
|
||||
if(k==='bufferData')return (...a)=>{if(a[2]==='STATIC_DRAW'&&F.land&&!setup){F.land=false;__ERR='OUT_OF_MEMORY';}};
|
||||
if(k==='useProgram')return ()=>{setup=false;};
|
||||
return ()=>({});}});})()`;
|
||||
|
||||
function open(fail) {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{};
|
||||
window.__FAIL=${JSON.stringify(fail)};`);
|
||||
h.ev(GL);
|
||||
return h;
|
||||
}
|
||||
|
||||
test('a card without memory for a 4096 px atlas gets a 2048 px one, and keeps the map', () => {
|
||||
const { ev, errors } = open({ atlas: [4096] });
|
||||
assert.equal(ev('glInit()'), true);
|
||||
assert.equal(ev('GLS.size'), 2048);
|
||||
assert.equal(ev('GLX.dead'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a card without memory for either atlas leaves the map in 2D', () => {
|
||||
const { ev, errors } = open({ atlas: [4096, 2048] });
|
||||
assert.equal(ev('glInit()'), false);
|
||||
assert.equal(ev('GLX.dead'), true);
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.equal(ev('glOn()'), false, 'the map is drawn in 2D');
|
||||
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
for (const what of ['land', 'tubes']) {
|
||||
test(`a card that refuses the ${what} without throwing gives the map to 2D in the same frame`, () => {
|
||||
const { ev, errors } = open({ [what]: true });
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('UI.tickErr=false;__T+=16;draw(__T);');
|
||||
assert.equal(ev('GLX.dead'), true, 'the card is given up');
|
||||
assert.equal(ev('glOn()'), false);
|
||||
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
|
||||
assert.equal(ev('ctx===CTX0&&!GLS.frame'), true);
|
||||
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player: the frame is drawn again in 2D');
|
||||
// The next frames are plain 2D ones.
|
||||
ev('__T+=16;draw(__T);__T+=16;draw(__T);');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('an ordinary frame never asks the card for its errors', () => {
|
||||
const { ev, errors } = open({});
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.equal(ev('GLX.dead'), false);
|
||||
assert.ok(ev('__GE') > 0, 'the first frame checked its uploads');
|
||||
// Panning brings new cities into view, whose pictures are sent: they are checked at most once a second (each read
|
||||
// waits for the card), the first time a second after the first frame's check.
|
||||
const pan = JSON.parse(ev(`(()=>{let sent=0,reads=0,most=0,at=[];for(let i=0;i<120;i++){const s=__SUB,g=__GE;cam.x+=3;__T+=16;draw(__T);
|
||||
if(__SUB>s)sent++;if(__GE>g){reads++;at.push(i);}most=Math.max(most,__GE-g);}return JSON.stringify({sent,reads,most,at});})()`));
|
||||
assert.ok(pan.sent > 5, 'frames send pictures');
|
||||
assert.ok(pan.reads >= 1 && pan.reads <= 2, `about two seconds of panning read the errors once or twice, not once per frame that sends (${JSON.stringify(pan)})`);
|
||||
assert.ok(pan.most <= 4, 'one check reads at most four flags');
|
||||
// The pan's last pictures are still to be checked: once, on the next frame a second on. Then a still map reads nothing.
|
||||
ev('__GE=0;__T+=1100;draw(__T);');
|
||||
assert.ok(ev('__GE') <= 4, 'the pictures left over are checked once');
|
||||
ev('__GE=0;for(let i=0;i<10;i++){__T+=1100;draw(__T);}');
|
||||
assert.equal(ev('__GE'), 0, 'a still map reads nothing');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
/* A picture the card refused without throwing (texSubImage2D only leaves OUT_OF_MEMORY) was kept as sent, and drawn
|
||||
from an atlas that never got it. The frame now checks its new pictures before drawing them, and gives the map to 2D
|
||||
in that same frame: no picture is kept as sent. */
|
||||
test('a picture the card refuses without throwing gives the map to 2D in the same frame', () => {
|
||||
const { ev, errors } = open({ sprites: true });
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);');
|
||||
assert.ok(ev('__SUB') > 0, 'pictures were sent');
|
||||
assert.equal(ev('GLX.dead'), true, 'the card is given up');
|
||||
assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent to the card');
|
||||
assert.equal(ev('glOn()'), false);
|
||||
assert.equal(ev('document.getElementById("mapgl").hidden'), true);
|
||||
assert.ok(ev('SPRC.size') > 0, 'the same frame was drawn again in 2D, with its own pictures');
|
||||
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player');
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// The card keeps an error until it is read: a picture refused between two checks is found by the next one.
|
||||
test('a picture refused after the first check gives the map to 2D within a second', () => {
|
||||
const { ev, errors } = open({});
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('UI.tickErr=false;const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;__T+=16;draw(__T);');
|
||||
assert.equal(ev('GLX.dead'), false);
|
||||
ev('__FAIL.sprites=true;');
|
||||
const n = ev('(()=>{let i=0;for(;i<120&&!GLX.dead;i++){cam.x+=5;__T+=16;draw(__T);}return i;})()');
|
||||
assert.equal(ev('GLX.dead'), true, 'given up');
|
||||
assert.ok(n * 16 <= 1000 + 32, `within a second (${n} frames)`);
|
||||
assert.equal(ev('SPRS.size'), 0, 'no picture is kept as sent');
|
||||
assert.equal(ev('!!UI.tickErr'), false, 'no glitch for the player');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
/* Given up for good while the context still lives (memory refused), the card kept the atlas (64 MB at 4096 px) and the
|
||||
rest while the 2D map began painting its own pictures. glKill() now deletes the biggest and lets the context go. */
|
||||
test('giving the card up for good frees what it holds and lets the context go, and the frame is drawn in 2D', () => {
|
||||
const { ev, errors } = open({ tubes: true });
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('window.__atlas=GLS.tex;window.__tubes=GLX.tex;window.__buf=GLS.buf;');
|
||||
ev('UI.tickErr=false;__T+=16;draw(__T);');
|
||||
assert.equal(ev('GLX.dead'), true);
|
||||
assert.equal(ev('__DEL.includes(__atlas)&&__DEL.includes(__tubes)&&__DEL.includes(__buf)'), true, 'the atlas, the tubes’ points and the pictures’ buffer are deleted');
|
||||
assert.equal(ev('__LOST'), 1, 'the context is let go');
|
||||
assert.equal(ev('__LOSTEV'), 1, 'its loss event came once');
|
||||
assert.equal(ev('GLS.tex===null&&GLS.buf===null&&GLX.tex===null&&GLX.gl===null&&GLX.ctx===null'), true, 'nothing on the card is referenced');
|
||||
assert.equal(ev('GLX.why'), 'the graphics card is out of memory (the tubes)', 'the loss it caused does not replace the reason');
|
||||
assert.equal(ev('!!UI.tickErr'), false, 'the frame was drawn again in 2D');
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a setup that fails half-way lets its context go too', () => {
|
||||
const { ev, errors } = open({ atlas: [4096, 2048] });
|
||||
assert.equal(ev('glInit()'), false);
|
||||
assert.equal(ev('__LOST'), 1);
|
||||
assert.equal(ev('GLX.ctx'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A context the browser lost may come back (tests/webgl-context-restore.test.js): it is waited for, not let go.
|
||||
test('a context the browser lost is not let go a second time', () => {
|
||||
const { ev, errors } = open({});
|
||||
assert.equal(ev('glInit()'), true);
|
||||
ev('__T+=16;draw(__T);');
|
||||
ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost",{cancelable:true}));');
|
||||
assert.equal(ev('GLX.dead'), false, 'waiting for it to come back');
|
||||
assert.equal(ev('GLX.lost&&!glOn()'), true, 'the 2D map draws meanwhile');
|
||||
assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did');
|
||||
ev('__T+=16;draw(__T);');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
153
tests/webgl-sprites.test.js
Normal file
153
tests/webgl-sprites.test.js
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
// The card's pictures (src/game/96-map/59-gl-sprites.js): painted on one reused canvas and sent to the atlas at once, so
|
||||
// a long zoom does not leave the browser holding a canvas per picture (it lost the graphics context and fell back to 2D).
|
||||
// The 2D map keeps a canvas per picture. jsdom has no WebGL: a stand-in context records what would go to the card.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
|
||||
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;
|
||||
// Counts the canvases the page makes from here on.
|
||||
const ce=document.createElement.bind(document);window.__canvases=0;document.createElement=function(t){if(String(t).toLowerCase()==='canvas')__canvases++;return ce.apply(document,arguments);};
|
||||
return gl;})()`;
|
||||
|
||||
// Frames over a zoom from far to near and back, as a player pinching would.
|
||||
const ZOOM = `(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;for(let i=0;i<=40;i++){cam.z=0.5*Math.pow(9,(1-Math.cos(i/40*Math.PI*2))/2);draw(1000+i*16);}})()`;
|
||||
|
||||
test('on the card, pictures are painted on one canvas and each goes into the atlas as it is painted', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(ZOOM);
|
||||
const r = JSON.parse(ev(`(()=>{const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D'),es=[...SPRS.values()];
|
||||
return JSON.stringify({canvases:__canvases,subs:subs.length,sprites:es.length,mine:es.filter(e=>e.cv).length,
|
||||
allUp:es.every(e=>e.up),rect:subs.every(c=>c.length===10&&c[9]===GLS_PAD.cv&&c[5]>0&&c[6]>0),
|
||||
fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length>0&&SPRC.size===0});})()`));
|
||||
assert.ok(r.sprites > 50, `a zoom paints many pictures (${r.sprites})`);
|
||||
assert.ok(r.canvases <= 1, `one canvas for all of them, not one each (${r.canvases} made)`);
|
||||
assert.equal(r.mine, 0, 'no picture keeps a canvas of its own');
|
||||
assert.equal(r.allUp, true, 'every picture is in the atlas');
|
||||
assert.ok(r.subs >= r.sprites, 'each was sent once, when painted');
|
||||
assert.equal(r.rect, true, 'only its corner of the pad, from the pad');
|
||||
assert.equal(r.fit, true);
|
||||
assert.equal(r.keys, true, 'kept apart from the 2D map’s pictures');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// The card blends the texels around the point it reads: a picture drawn off whole pixels, or stretched while a zoom
|
||||
// moves, read half a texel past its edge, and the map showed thin coloured lines around cities (its neighbour in the
|
||||
// atlas, or a picture from before the last reset). So each picture goes in with a clear border, and never touches another.
|
||||
test('on the card, every picture sits in the atlas in a clear border of its own', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
// What the pad is asked to do for each picture: cleared, clipped to the picture, painted inside the border.
|
||||
ev(`(()=>{const P=glsPad(1,1),g=P.g;window.__pad=[];for(const k of ['clearRect','rect','setTransform'])g[k]=(...a)=>__pad.push([k,...a]);})()`);
|
||||
ev(ZOOM);
|
||||
const r = JSON.parse(ev(`(()=>{const A=GLS.size,G=GLS_GAP,es=[...SPRS.values()].filter(e=>e.up);
|
||||
const R=es.map(e=>({x0:Math.round(e.u0*A),y0:Math.round(e.v0*A),x1:Math.round(e.u1*A),y1:Math.round(e.v1*A),e}));
|
||||
const exact=R.every(q=>q.x1-q.x0===q.e.pw&&q.y1-q.y0===q.e.ph);
|
||||
const inside=R.every(q=>q.x0>=G&&q.y0>=G&&q.x1+G<=A&&q.y1+G<=A);
|
||||
let touch=0;for(let i=0;i<R.length;i++)for(let j=i+1;j<R.length;j++){const a=R[i],b=R[j];
|
||||
if(a.x0<b.x1+2*G&&b.x0<a.x1+2*G&&a.y0<b.y1+2*G&&b.y0<a.y1+2*G)touch++;}
|
||||
const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D').slice(-es.length);
|
||||
const sent=subs.every(c=>R.some(q=>c[3]===q.x0-G&&c[4]===q.y0-G&&c[5]===q.e.pw+2*G&&c[6]===q.e.ph+2*G));
|
||||
// Each picture: clearRect(0,0,W,H), then rect(G,G,W-2G,H-2G) for the clip, then the transform that paints inside it.
|
||||
const at=__pad.flatMap((c,i)=>c[0]==='clearRect'?[i]:[]),nx=(i,k)=>__pad[i+k]||[];
|
||||
return JSON.stringify({n:es.length,exact,inside,touch,sent,G,
|
||||
cleared:at.length>=es.length&&at.every(i=>nx(i,0)[1]===0&&nx(i,0)[2]===0),
|
||||
clipped:at.every(i=>{const c=nx(i,0),q=nx(i,1);return q[0]==='rect'&&q[1]===G&&q[2]===G&&q[3]===c[3]-2*G&&q[4]===c[4]-2*G;}),
|
||||
offset:at.every(i=>{const q=nx(i,2);return q[0]==='setTransform'&&q[5]===G&&q[6]===G;})});})()`));
|
||||
assert.ok(r.n > 50, `a zoom paints many pictures (${r.n})`);
|
||||
assert.ok(r.G >= 1, 'a border of at least one texel');
|
||||
assert.equal(r.exact, true, 'the picture’s own texels are read, no more');
|
||||
assert.equal(r.inside, true, 'with room for its border inside the atlas');
|
||||
assert.equal(r.touch, 0, 'no two pictures (with their borders) overlap or touch');
|
||||
assert.equal(r.sent, true, 'each was sent with its border');
|
||||
assert.equal(r.cleared, true, 'the pad is cleared from its corner, border included');
|
||||
assert.equal(r.clipped, true, 'painting is clipped to the picture, so the border stays clear');
|
||||
assert.equal(r.offset, true, 'and starts inside the border');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a picture with its own canvas goes into the atlas in a clear border too', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const e=spriteEntry('own',20,10,10,5,g=>{g.fillRect(0,0,20,10);});
|
||||
const P=glsPad(1,1),g=P.g,log=[];g.clearRect=(...a)=>log.push(['clear',...a]);g.drawImage=(cv,x,y)=>log.push(['draw',cv===e.cv,x,y]);
|
||||
const ok=glsEnsure(e),A=GLS.size,G=GLS_GAP,s=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D').pop();
|
||||
return JSON.stringify({cv:!!e.cv,ok,log,G,u0:e.u0*A,v0:e.v0*A,u1:e.u1*A,v1:e.v1*A,pw:e.pw,ph:e.ph,sent:s.slice(3,7),pad:s[9]===P.cv});})()`));
|
||||
assert.equal(r.cv, true, 'painted outside a card frame, so with its own canvas');
|
||||
assert.equal(r.ok, true);
|
||||
assert.deepEqual(r.log, [['clear', 0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G], ['draw', true, r.G, r.G]], 'copied into a cleared pad, inside the border');
|
||||
assert.deepEqual([r.u0, r.v0, r.u1, r.v1], [r.G, r.G, r.G + r.pw, r.G + r.ph]);
|
||||
assert.deepEqual(r.sent, [0, 0, r.pw + 2 * r.G, r.ph + 2 * r.G]);
|
||||
assert.equal(r.pad, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a full atlas starts again and the picture that did not fit goes into the new one at once', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.shy=GLS.size-4;GLS.shx=GLS.size-2;GLS.shh=4;
|
||||
const before=SPRS.size;let draws=0;const gd=glsDraw;glsDraw=function(){draws++;};
|
||||
const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40);
|
||||
glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`));
|
||||
assert.equal(r.up, true, 'the picture is in the atlas');
|
||||
assert.equal(r.u0, 1 / 4096, 'at the start of the new atlas, past its clear border'); assert.equal(r.v0, 1 / 4096);
|
||||
assert.equal(r.kept, true, 'and kept under its key after the restart');
|
||||
assert.equal(r.size, 1, 'the old pictures are gone');
|
||||
assert.equal(r.n, 1, 'drawn this frame');
|
||||
assert.equal(r.cv, false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the 2D map keeps a canvas per picture, and its pictures are not the card’s', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
|
||||
const r = JSON.parse(ev(`(()=>{const es=[...SPRC.entries()];return JSON.stringify({n:es.length,cv:SPRS.size===0&&es.every(([k,e])=>e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`));
|
||||
assert.ok(r.n > 10);
|
||||
assert.equal(r.cv, true, 'each with its own canvas, at its size');
|
||||
assert.equal(r.up, false, 'nothing went to a card');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('giving the card up drops its pictures; the 2D map paints its own', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`);
|
||||
assert.ok(ev('SPRS.size') > 10);
|
||||
ev(`window.__warn=0;console.warn=function(){__warn++;};glKill('test')`);
|
||||
assert.equal(ev('SPRS.size'), 0, 'no picture without a canvas is left behind');
|
||||
assert.equal(ev('GLS.shx+GLS.shy+GLS.shh'), 0, 'the atlas is forgotten');
|
||||
ev('draw(1016)');
|
||||
assert.ok(ev('SPRC.size') > 10);
|
||||
assert.equal(ev(`[...SPRC.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas');
|
||||
assert.ok(ev('ctx===CTX0'));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a picture too big for the atlas keeps its own canvas and is painted on the overlay', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.size=64;const n0=GLX.fx.calls.n;
|
||||
const e=spriteEntry('huge',200,30,100,15,g=>{g.fillRect(0,0,200,30);});blit(e,0,0,200,30);
|
||||
const r={cv:!!e.cv,up:e.up,n:GLS.n,fx:GLX.fx.calls.n-n0};GLS.frame=false;GLS.n=0;ctx=CTX0;GLS.size=4096;return JSON.stringify(r);})()`));
|
||||
assert.equal(r.cv, true);
|
||||
assert.equal(r.up, false);
|
||||
assert.equal(r.n, 0, 'not queued for the card');
|
||||
assert.ok(r.fx >= 1, 'drawn on the overlay instead');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
91
tests/webgl-zoom-sprites.test.js
Normal file
91
tests/webgl-zoom-sprites.test.js
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// While the zoom moves, the card keeps the pictures of cities at the scale they had when it began (stretched by up to
|
||||
// 1.25× either way) and paints them again at the right step once the zoom rests (src/game/96-map/59-gl-sprites.js,
|
||||
// sprQ()). A pinch used to repaint every city at every 1/24 step of its scale. The 2D map is unchanged.
|
||||
// The page's clock is set by hand, so whether the zoom "rests" never depends on how fast the test runs.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();
|
||||
window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});
|
||||
GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;return gl;})()`;
|
||||
|
||||
// One POP's city pictures painted during frames from zoom z0 to z1 (the clock moving 16 ms a frame), by scale.
|
||||
const ZOOM = (z0, z1, n) => `(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const seen=new Set(),bad=[];
|
||||
for(let i=0;i<=${n};i++){cam.z=${z0}+(${z1}-${z0})*i/${n};__T+=16;draw(__T);
|
||||
for(const k of SPRS.keys()){const p=k.split('|');if(p[0]==='city'&&p[1]===id)seen.add(+p[3]);}
|
||||
const k=cityScale(iconScale()),kq=[...SPRS.keys()].filter(x=>x.split('|')[0]==='city'&&x.split('|')[1]===id).map(x=>+x.split('|')[3]);
|
||||
if(kq.length&&!kq.some(q=>Math.max(q/k,k/q)<=1.25*(1+.5/24/0.7)))bad.push(i);}
|
||||
return JSON.stringify({steps:[...seen].sort(),bad});})()`;
|
||||
|
||||
test('on the card a zoom keeps each city’s picture for a while, and paints it at the right step once it rests', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
ev(`cam.z=0.6;draw(__T);__T+=1000;draw(__T)`);
|
||||
const r = JSON.parse(ev(ZOOM(0.6, 1.6, 60)));
|
||||
// Without the hold, every 1/24 step between the two scales gets a picture.
|
||||
const plain = ev(`(()=>{const s=new Set();for(let i=0;i<=60;i++){cam.z=0.6+i/60;s.add(Math.round(cityScale(iconScale())*24)/24);}return s.size;})()`);
|
||||
assert.ok(plain >= 10, `the zoom crosses many steps (${plain})`);
|
||||
assert.ok(r.steps.length <= 4, `the city was painted at ${r.steps.length} scales during the zoom (${r.steps}), not ${plain}`);
|
||||
assert.deepEqual(r.bad, [], 'a picture is never stretched more than 1.25× either way (and half a step)');
|
||||
assert.equal(ev('zoomMoving()'), true);
|
||||
ev('__T+=300;draw(__T)');
|
||||
const rest = JSON.parse(ev(`(()=>{const id=S.home,want=Math.round(cityScale(iconScale())*24)/24;
|
||||
return JSON.stringify({f:ZH.f,want,has:[...SPRS.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}),moving:zoomMoving()});})()`));
|
||||
assert.equal(rest.moving, false);
|
||||
assert.equal(rest.f, 1, 'at rest nothing is stretched');
|
||||
assert.equal(rest.has, true, 'the city is painted again at its own step');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the 2D map paints cities at their own step on every frame of a zoom, as before', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(`mapGl(false);cam.z=0.8;draw(__T);`);
|
||||
const r = JSON.parse(ev(`(()=>{const id=S.home,C=CITY[id];cam.x=C.x;cam.y=C.y;const bad=[];
|
||||
for(let i=0;i<=30;i++){cam.z=0.8+i/30;__T+=16;SPRC.clear();draw(__T);const want=Math.round(cityScale(iconScale())*24)/24;
|
||||
if(ZH.f!==1||![...SPRC.keys()].some(k=>{const p=k.split('|');return p[0]==='city'&&p[1]===id&&+p[3]===want;}))bad.push(i);}
|
||||
return JSON.stringify({bad});})()`));
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a still map is drawn again when the zoom comes to rest, so the stretched pictures do not stay', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
// Animations off: the loop skips frames while nothing changes.
|
||||
ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`);
|
||||
ev(`__T+=16`);
|
||||
assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame');
|
||||
ev(`__T+=300`);
|
||||
assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
|
||||
ev(`draw(__T);UI.drawnAt=__T;__T+=16`);
|
||||
assert.equal(ev('ZH.f'), 1);
|
||||
assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('pictures that keep their size whatever the zoom (far-view cities, cones, diggers) are never held or stretched', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{cam.z=1;draw(__T);__T+=1000;cam.z=1;draw(__T);cam.z=1.4;__T+=16;draw(__T);GLS.frame=true;GLS.n=0;ctx=GLX.fx;
|
||||
const f=ZH.f;drawCone(100,100,0);drawBackhoe(200,100,0,false);const D=GLS.data,o=[D[2],D[3],D[SPR_STRIDE+2],D[SPR_STRIDE+3]];
|
||||
const keys=[...SPRS.keys()].filter(k=>['cone','hoe'].includes(k.split('|')[0]));GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify({f,o,keys});})()`));
|
||||
assert.notEqual(r.f, 1, 'the zoom is moving and city pictures are held');
|
||||
assert.deepEqual(r.o, [26, 28, 38, 32], 'drawn at their own size');
|
||||
assert.ok(r.keys.length >= 2 && r.keys.every(k => k.endsWith('|1')), 'painted at scale 1: ' + r.keys);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
36
tests/world-layer-firefox.test.js
Normal file
36
tests/world-layer-firefox.test.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// The 2D map's land picture (src/game/96-map/70-world-layer.js) is a software canvas (willReadFrequently) only in
|
||||
// Firefox on Android, which garbled big paths on its graphics card (#43). Firefox on a computer had it too, and sent
|
||||
// the whole picture to the card again on every frame: measured in Firefox on Windows, full screen 2560x1440, zoomed in
|
||||
// the 2D map ran at a third of its speed (zoom 3.2 on the big network: 26 fps, 78 without it).
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
test('only Firefox on Android gets the land as a software canvas', () => {
|
||||
const { ev } = load({ seed: 777 });
|
||||
const soft = (ua) => ev(`softCanvas(${JSON.stringify(ua)})`);
|
||||
// Firefox on Android, phone and tablet.
|
||||
assert.equal(soft('Mozilla/5.0 (Android 14; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0'), true);
|
||||
assert.equal(soft('Mozilla/5.0 (Android 13; Tablet; rv:128.0) Gecko/128.0 Firefox/128.0'), true);
|
||||
// Firefox on a computer, and the other browsers.
|
||||
assert.equal(soft('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:159.0) Gecko/20100101 Firefox/159.0'), false);
|
||||
assert.equal(soft('Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0'), false);
|
||||
assert.equal(soft('Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:131.0) Gecko/20100101 Firefox/131.0'), false);
|
||||
assert.equal(soft('Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36'), false);
|
||||
assert.equal(soft('Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/130.0 Mobile/15E148 Safari/605.1.15'), false);
|
||||
});
|
||||
|
||||
test('elsewhere the land picture is an ordinary canvas, which the browser may keep on the graphics card', () => {
|
||||
const { ev, errors } = load({ seed: 777 });
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();mapGl(false,false);
|
||||
window.__opts=[];const gc=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(t,o){__opts.push(o||null);return gc.call(this,t,o);};
|
||||
WL.cv=null;WL.key=null;cam.z=1.6;worldLayer(cam.z);`);
|
||||
assert.equal(ev('SOFT_CANVAS'), false);
|
||||
assert.ok(ev('!!WL.cv'), 'the land was painted');
|
||||
assert.equal(ev('__opts.some(o=>o&&o.willReadFrequently)'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue