Merge pull request #318 from antt0n/perf/page-stays-free
Big networks hold the page less: ambient map at 30 fps, saves and transfers handled by the worker
This commit is contained in:
commit
a1c0afbbbf
22 changed files with 517 additions and 86 deletions
|
|
@ -45,9 +45,10 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j
|
|||
or set state directly (`S.day=…`, `S.ev.x=…`).
|
||||
- **Force a specific random failure or event** by patching the picker:
|
||||
```js
|
||||
ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()");
|
||||
ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())");
|
||||
```
|
||||
Check the current source for the exact `pick` line first (`grep -rn "function fireFailure" src/game`); it may differ.
|
||||
`failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the
|
||||
exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`.
|
||||
- **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`.
|
||||
- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through
|
||||
`parseSave()`/`migrate()`, and test that an *old* save without the new field still loads.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ All notable changes to this project are documented here. The project follows
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed.
|
||||
- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds.
|
||||
- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before.
|
||||
|
||||
## [3.2.0] — 2026-11-07
|
||||
|
||||
- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic.
|
||||
|
|
|
|||
|
|
@ -120,6 +120,9 @@ the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routi
|
|||
sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's
|
||||
orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet
|
||||
notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker.
|
||||
A big autosave is packed, turned into text and compressed in the worker (`rwSave()`), the page only writes it. The
|
||||
diverse-paths map and the latency floors new offers need are worked out a millisecond a frame ahead (`diversityWarm()`,
|
||||
`latWarm()`). A rest waits for the next frame only when none was drawn just now (`rwLater()`).
|
||||
|
||||
The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected
|
||||
islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one.
|
||||
|
|
@ -206,7 +209,12 @@ network does not freeze the page once a day.
|
|||
saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every
|
||||
day with `dayTick()`.
|
||||
- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays
|
||||
transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page.
|
||||
transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. What crossed each
|
||||
link (`R.efp.L`) crosses as typed arrays with each exit key once (`rwLOut()`), and the page decodes a link only when
|
||||
something reads it (`rwLIn()`). Two parts are not sent again when they would be the same: `R.egDesc` comes back as 0
|
||||
when it is the last one key for key (the page keeps `RW.desc`), and `R.efg` is not posted back while R is the worker's
|
||||
own last answer (`RW.wR`; the worker keeps it in `RW.last`). Both sides read every message in order, so they always
|
||||
hold the same last one; `tests/day-steps.test.js` plays a second page as the worker and checks it all.
|
||||
- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's
|
||||
answer is stale: it is dropped and the day ends with the action's R.
|
||||
- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a
|
||||
|
|
@ -227,8 +235,11 @@ network does not freeze the page once a day.
|
|||
controlled by `renderTabbar()`.
|
||||
- These panels and the dashboard are rebuilt as HTML every tick and written with `morph()`, which
|
||||
patches only what changed. Buttons whose action changed are replaced, so taps stay safe (#44).
|
||||
- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses
|
||||
a simplified style; parallel waves are grouped by `linkGroups()`.
|
||||
- The map is a canvas drawn by `draw()` from `frame()`. Zoomed out (`lodFar()`) it uses
|
||||
a simplified style; parallel waves are grouped by `linkGroups()`. `mapStill()` decides whether a frame is drawn:
|
||||
when nothing changed (paused, animations off) it is not, except once a second; when only the animation clock moved
|
||||
(packets, waves, clouds, floaters) the map is ambient and drawn at most 30 times a second; anything else that moves
|
||||
(camera, pointer, selection, the network) gets every frame (`tests/frame-pacing.test.js`).
|
||||
|
||||
## The weekly puzzle
|
||||
|
||||
|
|
@ -273,7 +284,9 @@ back to the in-browser `weekly()`.
|
|||
- `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot
|
||||
(`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:<id>`, plain JSON or `gz:`-compressed above a million
|
||||
characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier,
|
||||
cash, last played, size, seq) is updated; the title screen lists networks from the index alone.
|
||||
cash, last played, size, seq) is updated; the title screen lists networks from the index alone. A save whose text is
|
||||
the one the slot already holds (`SLOT.txt`: a paused game, nothing changed) is not written again, unless the page is
|
||||
closing: on a big network the storage write costs more than making the text.
|
||||
- Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock
|
||||
(`sot-slot:<id>`) where supported, plus a heartbeat `sot-open:<id>`; BroadcastChannel `sot-slots` asks
|
||||
another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere
|
||||
|
|
|
|||
|
|
@ -43,6 +43,11 @@ const METRICS = [
|
|||
['panels', 'Side panel and left list', "for(const f of [true,false]){UI.sel={type:'city',id:f?'fra':'ams'};UI.tab=f?'peer':'up';UI.left=f?'nets':'noc';UI.leftOpen=true;renderPanel();renderLeft();}"],
|
||||
['dash', 'NOC dashboard tabs', "$('dash').hidden=false;for(const k of ['overview','conn','traffic','infra','cust']){UI.dtab=k;renderDash();}$('dash').hidden=true"],
|
||||
['map', 'Map at three zoom levels', "for(const z of [1,3.2,7]){cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=z;draw(0);}"],
|
||||
// The NOC intern runs every order, every day: one shift, its recomputes included (hired here if the save has none).
|
||||
['ops', "The NOC intern's shift: opsDay()", "if(!S.ops.intern){S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;}S.cash=1e9;opsDay(S.day)"],
|
||||
// A day as it is played: its routing in the route worker, and only the time it holds the page counted (what a player
|
||||
// feels as a hitch). Chromium only: jsdom has no Worker. See perf-browser.js.
|
||||
['play', 'One game day in play: page time only', null, { play: true }],
|
||||
];
|
||||
|
||||
function open(file) {
|
||||
|
|
@ -57,13 +62,14 @@ function open(file) {
|
|||
}
|
||||
|
||||
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; };
|
||||
const ms = (x) => x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
|
||||
const ms = (x) => x == null ? '–' : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
|
||||
|
||||
(async () => {
|
||||
const head = open(HEAD), base = BASE ? open(BASE) : null;
|
||||
const sameOutcome = base ? base.outcome() === head.outcome() : null;
|
||||
const res = {};
|
||||
for (const [k, , body] of METRICS) {
|
||||
for (const [k, , body, o] of METRICS) {
|
||||
if (o && o.play) { res[k] = { head: null, base: null, samples: null }; continue; }
|
||||
const h = [], b = [];
|
||||
for (const v of [head, base].filter(Boolean)) { v.time(body); v.time(body); } // warm up
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
|
|
@ -78,7 +84,7 @@ const browser = args.includes('--browser') ? await require('./perf-browser').run
|
|||
const { mannWhitneyP } = require('./perf-stats');
|
||||
const pOf = (r) => (r.samples && r.samples.base ? mannWhitneyP(r.samples.head, r.samples.base) : 1);
|
||||
const verdict = (r, noise = 2) => {
|
||||
if (r.base == null) return '';
|
||||
if (r.base == null || r.head == null) return '';
|
||||
const ratio = r.head / (r.base || 1e-9);
|
||||
if (Math.abs(r.head - r.base) < noise || pOf(r) >= 0.01) return '≈';
|
||||
if (ratio >= 1.5) return '🔴 slower';
|
||||
|
|
@ -86,8 +92,8 @@ const verdict = (r, noise = 2) => {
|
|||
if (ratio <= 0.85) return '🟢 faster';
|
||||
return '≈';
|
||||
};
|
||||
const pct = (r) => r.base == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
|
||||
const pTxt = (r) => { const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); };
|
||||
const pct = (r) => r.base == null || r.head == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
|
||||
const pTxt = (r) => { if (r.base == null || r.head == null) return ''; const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); };
|
||||
// One table per environment, all the same shape. `noise` is the absolute floor below which nothing counts.
|
||||
const table = (res, noise) => (base ? '| What | Base | This PR | Change | p | |\n|---|--:|--:|--:|--:|---|\n' : '| What | Time |\n|---|--:|\n') +
|
||||
METRICS.map(([k, label]) => { const r = res[k]; return base ? `| ${label} | ${ms(r.base)} | ${ms(r.head)} | ${pct(r)} | ${pTxt(r)} | ${verdict(r, noise)} |` : `| ${label} | ${ms(r.head)} |`; }).join('\n') + '\n';
|
||||
|
|
@ -95,7 +101,7 @@ const slowIn = (res, noise) => METRICS.filter(([k]) => /slower/.test(verdict(res
|
|||
|
||||
const s = head.size;
|
||||
let md = `## Performance on a big network\n\n${s.pops} POPs · ${s.links} links · ${s.pni} PNIs · ${s.caches} cache boxes · ${s.ix} IX ports · ${s.customers} customers. Median of ${RUNS} runs, in milliseconds.\n\n`;
|
||||
md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here.\n\n` + table(res, 2);
|
||||
md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here. It has no Worker either: a day in play is timed in Chromium only.\n\n` + table(res, 2);
|
||||
const slow = base ? slowIn(res, 2) : [];
|
||||
const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
|
||||
for (const p of PROFILES) {
|
||||
|
|
|
|||
|
|
@ -45,7 +45,23 @@ async function openPage(browser, profile, file, save, errors) {
|
|||
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 };
|
||||
// One game day as it is played: its steps on the page, its routing in the route worker (built from the page itself,
|
||||
// see 28-route-worker.js). Only the time it holds the page counts: starting the day, each answer from the worker and
|
||||
// each step that waited for a frame. Waiting for the worker does not count; the page is free meanwhile.
|
||||
// null when this page has no worker to play with.
|
||||
const play = async () => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(async () => {
|
||||
window.__TUBES_TEST__ = false;
|
||||
try {
|
||||
const w = typeof rwOn === 'function' && rwOn() && rwStart(); if (!w) return null;
|
||||
let busy = 0; const wrap = (f) => function (...a) { const t = performance.now(); try { return f.apply(this, a); } finally { busy += performance.now() - t; } };
|
||||
const om = w.onmessage, later = RW.later; w.onmessage = wrap(om); if (later) RW.later = (f) => later(wrap(f));
|
||||
S.nextFail = S.nextEvent = S.day + 99;
|
||||
try { const t = performance.now(); rwDay(); busy += performance.now() - t; while (RW.job) await new Promise((r) => setTimeout(r, 1)); }
|
||||
finally { w.onmessage = om; if (later) RW.later = later; }
|
||||
return RW.dead ? null : busy;
|
||||
} finally { window.__TUBES_TEST__ = true; }
|
||||
}); };
|
||||
return { ctx, time, play };
|
||||
}
|
||||
|
||||
// Returns {version, profiles: {desktop: {compute: {head, base}, ...}, phone: {...}}, errors}.
|
||||
|
|
@ -61,14 +77,17 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) {
|
|||
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 = [], 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 (const [k, , body, o] of metrics) {
|
||||
const H = [], B = [], run = (v) => (o && o.play ? v.play() : v.time(k, body));
|
||||
const go = async (v, into, m) => { const r = await run(v); if (o && o.play) into.push(r); else { into.push(r.ms); if (k === 'map') m.add(r.map); } };
|
||||
for (const v of [h, b].filter(Boolean)) { await run(v); await run(v); } // warm up (and the worker starts)
|
||||
for (let i = 0; i < runs; i++) {
|
||||
// Alternate who goes first, like the jsdom runs.
|
||||
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 } };
|
||||
// A version without a worker gives nothing to compare.
|
||||
const ok = (a) => a.every((x) => x != null);
|
||||
res[k] = { head: ok(H) ? median(H) : null, base: b && ok(B) ? median(B) : null, samples: { head: ok(H) ? H.map((x) => +x.toFixed(1)) : null, base: b && ok(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();
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const RW_IN=!!self.__TUBES_WORKER__;
|
|||
const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null;
|
||||
// RW_SLOW: a frame time (ms) above which the device does not keep up anyway, and a day may take longer slices (99-loop.js).
|
||||
const RW_SLOW=20;
|
||||
const RW={w:null,dead:false,seq:0,gen:0,job:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}};
|
||||
const RW={w:null,dead:false,seq:0,gz:0,gzq:new Map(),svq:new Map(),gen:0,job:null,desc:null,wR:null,wseq:0,last:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}};
|
||||
function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;}
|
||||
function rwStart(){if(RW.w)return RW.w;
|
||||
try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null';
|
||||
|
|
@ -23,12 +23,12 @@ if(${dict})self.I18N[${JSON.stringify(L)}]=${dict};
|
|||
`;
|
||||
const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'}));
|
||||
const w=RW.w=new Worker(url);URL.revokeObjectURL(url);
|
||||
w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();};
|
||||
w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwMsg(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();};
|
||||
}catch(e){console.error('[tubes] no route worker',e);rwKill();}
|
||||
return RW.w;}
|
||||
// Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker.
|
||||
// (A day resting between steps goes on by itself, on the page from then on.)
|
||||
function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;if(!j||j.rest)return;RW.job=null;
|
||||
function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;rwGzBack();rwSaveBack();const j=RW.job;if(!j||j.rest)return;RW.job=null;
|
||||
if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAgain(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);}
|
||||
// One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker.
|
||||
function rwDay(){rwGo(dayRun());}
|
||||
|
|
@ -45,7 +45,9 @@ function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);}
|
|||
const w=rwOn()&&rwStart();if(!w){try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;}
|
||||
const t=performance.now(),seq=++RW.seq;
|
||||
// The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths.
|
||||
try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg),...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});}
|
||||
// While R is the worker's own last answer (RW.wR), it keeps its R.efg rather than getting it back (efg 0, rwServe()).
|
||||
const mine=R===RW.wR;
|
||||
try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:mine?0:rwEfgOut(R.efg),wseq:mine?RW.wseq:0,...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});}
|
||||
catch(e){console.error('[tubes] route worker post',e);rwKill();try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;}
|
||||
const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,g,gen:RW.gen,t:t1,state:S,tr};return;}}
|
||||
/* Where a resting day goes on. A frame drawn moments ago leaves time before the next one: the day goes on in a task of
|
||||
|
|
@ -57,6 +59,15 @@ function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75)
|
|||
else requestAnimationFrame(()=>setTimeout(f,0));}
|
||||
// The day rests: it goes on after the next frame, still in flight meanwhile (no next day, no save).
|
||||
function rwRest(g,v){const j=RW.job={rest:true,g,state:S};RW.later(()=>{if(RW.job!==j)return;RW.job=null;if(j.state!==S){rwDayDone();return;}rwGo(g,v);});}
|
||||
// Every answer from the worker, in order.
|
||||
function rwMsg(m,t0){if(m.gz!==undefined){rwGzDone(m);return;}if(m.sv!==undefined){rwSaveDone(m);return;}if(m.R){const d=m.R.egDesc;if(d===0)m.R.egDesc=RW.desc;else RW.desc=m.R.egDesc=d&&d.dK!==undefined?rwDescIn(d,RW.desc):d;}rwDone(m,t0);}
|
||||
/* A changed R.egDesc comes as its keys, in order, and only the entries that changed (rwDescOut()): a few among thousands.
|
||||
The rest are yesterday's entries, so the page holds the same object, key for key and in the same order. */
|
||||
// dK 0: the keys are yesterday's, in yesterday's order (most days), so they do not come along either.
|
||||
function rwDescOut(d,old){if(!old)return d;const K=Object.keys(d),O=Object.keys(old),ch={};
|
||||
for(const k of K){const x=d[k],y=old[k];if(!y||x.lab!==y.lab||x.city!==y.city||x.k!==y.k)ch[k]=x;}
|
||||
let same=K.length===O.length;for(let i=0;same&&i<K.length;i++)same=K[i]===O[i];return {dK:same?0:K,ch};}
|
||||
function rwDescIn(m,old){const o={},{ch}=m,K=m.dK||Object.keys(old);for(const k of K)o[k]=Object.prototype.hasOwnProperty.call(ch,k)?ch[k]:old[k];return o;}
|
||||
function rwDone(m,t0){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now();
|
||||
// Another network was loaded meanwhile: the rest of that day belongs to nobody.
|
||||
if(j.state!==S){rwDayDone();return;}
|
||||
|
|
@ -65,26 +76,73 @@ function rwDone(m,t0){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;con
|
|||
// failed: the trial runs again here, checks included, on the game as it is now (dayAgain()).
|
||||
if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAgain(j.tr):j.tr.dark?!!m.ok:m.ok?j.tr.trial:null;}
|
||||
else if(m.err){console.error('[tubes] route worker',m.err);compute();}
|
||||
else if(RW.gen===j.gen){R=rwUnpack(m.R,m.ef);UI.hotMap=hotByCity();}
|
||||
// The worker's hotMap was worked out from this R and the game as it was sent, which nothing changed since (same gen).
|
||||
else if(RW.gen===j.gen){R=RW.wR=rwUnpack(m.R,m.ef);RW.wseq=m.seq;UI.hotMap=m.hot||hotByCity();}
|
||||
const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0;
|
||||
// Reading a big answer takes a few ms already: the day goes on after the next frame then, not in the same task.
|
||||
if(t0!==undefined&&t1-t0>RW.budget/2)rwRest(j.g,v);else rwGo(j.g,v);}
|
||||
function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}}
|
||||
function rwDayDone(){paceEnd(performance.now());UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}}
|
||||
/* A save's compression (91-save.js) runs in the worker too: deflating a big network held the page about as long as
|
||||
writing it plain. The text goes over as it is (a string is copied flat, without walking a game), the compressed
|
||||
text comes back. In order with the routings, so a save may wait for one. */
|
||||
function rwGzip(txt){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz;
|
||||
return new Promise((res,rej)=>{RW.gzq.set(k,{res,rej,txt});try{w.postMessage({gz:k,txt});}catch(e){RW.gzq.delete(k);rej(e);}});}
|
||||
function rwGzDone(m){const q=RW.gzq.get(m.gz);if(!q)return;RW.gzq.delete(m.gz);if(m.err)q.rej(new Error(m.err));else q.res(m.data);}
|
||||
/* A whole save in the worker (save(), 91-save.js): the game as it was when saved (the copy postMessage makes), packed,
|
||||
turned into text, stamped and compressed there. Back come the text (the slot keeps it, to spot an unchanged game) and
|
||||
what to write. The worker lost meanwhile: that save is gone, so the next frame saves again, here. */
|
||||
function rwSave(st,seq){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz;
|
||||
return new Promise((res,rej)=>{RW.svq.set(k,{res,rej});try{w.postMessage({sv:k,S:st,seq});}catch(e){RW.svq.delete(k);rej(e);}});}
|
||||
function rwSaveDone(m){const q=RW.svq.get(m.sv);if(!q)return;RW.svq.delete(m.sv);if(m.err)q.rej(new Error(m.err));else q.res({txt:m.txt,data:m.data});}
|
||||
function rwSaveBack(){const q=[...RW.svq.values()];RW.svq.clear();if(q.length)UI.lastSave=0;for(const x of q)x.rej(new Error('route worker lost'));}
|
||||
function rwSaveServe(m){let txt;try{txt=JSON.stringify(packSave(m.S));}catch(e){postMessage({sv:m.sv,err:String(e)});return;}
|
||||
const st=slotStamp(txt,m.seq);(txt.length>=GZ_BG?gzB64(st).then(b=>GZ+b):Promise.resolve(st)).then(data=>postMessage({sv:m.sv,txt,data}),e=>postMessage({sv:m.sv,err:String(e)}));}
|
||||
// The worker gone: what it was compressing is compressed here.
|
||||
function rwGzBack(){const q=[...RW.gzq.values()];RW.gzq.clear();for(const x of q)gzB64(x.txt).then(x.res,x.rej);}
|
||||
/* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild()
|
||||
and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an
|
||||
attack record names its attack in S by id. */
|
||||
const FL_COLS=['FREM','FCI','FNJ','FCA','FBZ','FGT','FGI','FGP','FGH','FTI','FII'];
|
||||
function rwPack(R){const o={};for(const k in R)o[k]=k==='ef'?0:k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];
|
||||
const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>({id:e.id}))},tr=[p.ACN.buffer,p.ACD.buffer];for(const k of FL_COLS)tr.push(c[k].buffer);
|
||||
return {o,p:{...p,flc:c},tr};}
|
||||
function rwUnpack(o,p){o.ef={};efBuild(o,p.L,p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc);
|
||||
const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>e.id)},L=rwLOut(p.L),tr=[p.ACN.buffer,p.ACD.buffer,...L.tr];for(const k of FL_COLS)tr.push(c[k].buffer);
|
||||
return {o,p:{...p,L:L.o,flc:c},tr};}
|
||||
function rwUnpack(o,p){o.ef={};p.flc.E=p.flc.E.map(id=>({id}));efBuild(o,rwLIn(p.L),p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc);
|
||||
const as=ddosAll(S,false);for(const m of o.ddos){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}return o;}
|
||||
/* What crossed each link (efp.L: [link id, edge index, t], t = {g: exit key → slot, v: sums by slot, n, d}) is the
|
||||
biggest part of R, and as plain objects it took longer to read on the page than all the rest. It crosses as typed
|
||||
arrays instead, the exit keys once each, and the page decodes a link's t only when something reads it: the link panel
|
||||
(R.ef) or a scenic circuit routed on the page (R.efg). Decoded, it is the same t, Map order included. */
|
||||
function rwLOut(L){const n=L.length,K=[],ki=new Map(),ID=new Array(n),EI=new Int32Array(n),OG=new Int32Array(n+1),ON=new Int32Array(n+1),OD=new Int32Array(n+1);
|
||||
let ng=0,nn=0,nd=0;for(const x of L){const t=x[2];ng+=t.g.size;nn+=t.n.length;nd+=t.d.length;}
|
||||
const G=new Int32Array(2*ng),V=new Float64Array(ng),N=new Int32Array(nn),D=new Int32Array(nd);ng=nn=nd=0;
|
||||
for(let j=0;j<n;j++){const [id,i,t]=L[j];ID[j]=id;EI[j]=i;
|
||||
for(const [k,sl] of t.g){let x=ki.get(k);if(x===undefined){ki.set(k,x=K.length);K.push(k);}G[2*ng]=x;G[2*ng+1]=sl;V[ng]=t.v[sl];ng++;}OG[j+1]=ng;
|
||||
for(const v of t.n)N[nn++]=v;ON[j+1]=nn;for(const v of t.d)D[nd++]=v;OD[j+1]=nd;}
|
||||
return {o:{K,ID,EI,OG,ON,OD,G,V,N,D},tr:[EI.buffer,OG.buffer,ON.buffer,OD.buffer,G.buffer,V.buffer,N.buffer,D.buffer]};}
|
||||
function rwLIn(X){const {K,ID,EI,OG,ON,OD,G,V,N,D}=X,L=new Array(ID.length);
|
||||
for(let j=0;j<ID.length;j++){let t=null;const T=()=>{if(!t){const g=new Map(),v=[];for(let a=OG[j];a<OG[j+1];a++){g.set(K[G[2*a]],G[2*a+1]);v[G[2*a+1]]=V[a];}
|
||||
t={g,v,n:Array.from(N.subarray(ON[j],ON[j+1])),d:Array.from(D.subarray(OD[j],OD[j+1]))};}return t;};
|
||||
L[j]=[ID[j],EI[j],{get g(){return T().g;},get v(){return T().v;},get n(){return T().n;},get d(){return T().d;}}];}
|
||||
return L;}
|
||||
// Yesterday's egress sums for scenic routing, as plain data (EgSums is a class; a clone would lose its get()).
|
||||
const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[k].t;return o;};
|
||||
const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;};
|
||||
// In the worker: route the state it was sent, answer with R.
|
||||
function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)});
|
||||
// A sales trial (offerTrial()): its answer only.
|
||||
/* R.egDesc names every exit that carried traffic (about two thirds of R on a big network) and only changes with the
|
||||
network. When it is yesterday's again, key for key, the worker sends 0 and the page keeps the one it has (RW.desc):
|
||||
every answer is read in order, the stale ones too, so both sides always hold the same last one. */
|
||||
function rwSameDesc(a,b){if(!a||!b)return false;const ka=Object.keys(a),kb=Object.keys(b);if(ka.length!==kb.length)return false;
|
||||
for(let i=0;i<ka.length;i++){const k=ka[i];if(k!==kb[i])return false;const x=a[k],y=b[k];if(x.lab!==y.lab||x.city!==y.city||x.k!==y.k)return false;}return true;}
|
||||
// R.efg (what crossed each link, by exit) is about a third of R and only routing reads it, here: the worker keeps the one
|
||||
// of its last answer, and the page sends it back only when it routed something of its own since (efg 0: keep yours).
|
||||
function rwServe(m){if(m.gz!==undefined){gzB64(m.txt).then(data=>postMessage({gz:m.gz,data}),e=>postMessage({gz:m.gz,err:String(e)}));return;}
|
||||
if(m.sv!==undefined){rwSaveServe(m);return;}
|
||||
try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};
|
||||
if(m.efg===0){if(!RW.last||RW.last.seq!==m.wseq)throw new Error('route worker: no R.efg for answer '+m.wseq);Object.defineProperty(R,'efg',{value:RW.last.efg});}
|
||||
else if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)});
|
||||
// A sales trial (offerTrial()) or the intern's fiber test (opsDarkTrial()): its answer only. What the worker keeps
|
||||
// for the next routing (RW.last, RW.desc) stays.
|
||||
if(m.trial){const t=performance.now(),ok=m.trial.dark?opsDarkTrial(m.trial):!!offerTrial(m.trial.b,m.trial.hx);postMessage({seq:m.seq,ok,ms:performance.now()-t});return;}
|
||||
const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);postMessage({seq:m.seq,R:o,ef:p,ms},tr);}
|
||||
const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);RW.last={seq:m.seq,efg:R.efg};
|
||||
if(rwSameDesc(RW.desc,o.egDesc))o.egDesc=0;else{const d=o.egDesc;o.egDesc=rwDescOut(d,RW.desc);RW.desc=d;}postMessage({seq:m.seq,R:o,ef:p,hot:UI.hotMap,ms},tr);}
|
||||
catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}}
|
||||
|
|
|
|||
|
|
@ -47,28 +47,35 @@ let diversityMap=null;
|
|||
function diversityPossible(a,b,state=S){
|
||||
if(!CITY[a]||!CITY[b]||a===b)return false;
|
||||
const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]);
|
||||
if(!diversityMap||diversityMap.key!==key){
|
||||
/* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with
|
||||
the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable
|
||||
on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the
|
||||
links were added, as a graph built from a list of them would. */
|
||||
if(!diversityMap||diversityMap.key!==key){if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!state.won)};
|
||||
for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;break;}}}
|
||||
const pair=[a,b].sort().join(':'),M=diversityMap;
|
||||
return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b)));
|
||||
}
|
||||
/* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with
|
||||
the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable
|
||||
on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the
|
||||
links were added, as a graph built from a list of them would. It only follows from the catalog and the key, so idle
|
||||
frames build it a few rows at a time (diversityWarm()) before the first offer asks; one that asks first finishes it. */
|
||||
let DIVW=null;
|
||||
function* diversityBuild(key,rules,won){
|
||||
const cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),N=cities.length,ix=new Map(cities.map((c,i)=>[c,i]));
|
||||
const cab=new Map();for(const c of CABLE_PAIRS){const k=c.a<c.b?c.a+'|'+c.b:c.b+'|'+c.a;let L=cab.get(k);if(!L)cab.set(k,L=[]);L.push(c);}
|
||||
const land=cities.map(landing),cn=cities.map(cnCity),fab=cities.map(c=>FABS.filter(f=>f.cities.includes(c))),ban=rules.banPairs||[];
|
||||
const adj=cities.map(()=>[]),grp=new Map();let n=0,k=0;const add=(i,j,g)=>{let r;if(g===undefined)r=k++;else{r=grp.get(g);if(r===undefined)grp.set(g,r=k++);}adj[i].push(j,r);adj[j].push(i,r);n++;};
|
||||
for(let i=0;i<N;i++)for(let j=i+1;j<N;j++){
|
||||
for(let i=0;i<N;i++){if(i%8===7)yield;for(let j=i+1;j<N;j++){
|
||||
const a=cities[i],b=cities[j],cs=cab.get(a<b?a+'|'+b:b+'|'+a),sub=!overland(CITY[a],CITY[b]);
|
||||
if(noTalk(a,b))continue;
|
||||
if(!sub){add(i,j);add(i,j);}
|
||||
if(cs)for(const c of cs)if(!ban.some(p=>p===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(i,j,'cab:'+c.cid);
|
||||
if(state.won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j);
|
||||
if(won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j);
|
||||
if(fab[i].length&&fab[j].length)for(const f of FABS)if(fab[i].includes(f)&&fab[j].includes(f))add(i,j,'fab:'+f.id);
|
||||
}
|
||||
diversityMap={key,ix,adj,links:n,answers:{}};
|
||||
}
|
||||
const pair=[a,b].sort().join(':'),M=diversityMap;
|
||||
return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b)));
|
||||
}
|
||||
}}
|
||||
return {key,ix,adj,links:n,answers:{}};}
|
||||
// A frame's spare time on it: at most ms, until it is built for the game's current rules.
|
||||
function diversityWarm(ms){if(!S||!S.pops)return;const rules=S.scn&&S.scn.rules||{},key=JSON.stringify([!!S.won,rules]);
|
||||
if(diversityMap&&diversityMap.key===key)return;if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!S.won)};
|
||||
const t=performance.now();for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;return;}if(performance.now()-t>ms)return;}}
|
||||
// disjointRoutes() on such a graph: a shortest path by hops, then another one that shares none of its risks.
|
||||
function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pl=new Int32Array(N),q=[a];prev[a]=a;
|
||||
for(let h=0;h<q.length;h++){const u=q[h];if(u===b)break;const L=adj[u];for(let k=0;k<L.length;k+=2){const v=L[k];if(prev[v]<0&&!(skip&&skip.has(L[k+1]))){prev[v]=u;pl[v]=L[k+1];q.push(v);}}}
|
||||
|
|
|
|||
|
|
@ -59,10 +59,17 @@ function bestLat(a,b,f){const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));con
|
|||
// design follows it at 0.9 or better). A sea route that no cable takes needs a survey, so it does not count.
|
||||
// Built from the map alone, so it is worked out once per city.
|
||||
const LATF=new Map();let LATC=null;
|
||||
function latFloor(a,b){let D=LATF.get(a);if(!D){LATF.set(a,D=latFloor0(a));}return D[CIDX[b]];}
|
||||
function latFloor0(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n);
|
||||
function latFloor(a,b){let D=LATF.get(a);if(!D){if(LATW&&LATW.a===a){for(;;){const s=LATW.g.next();if(s.done){D=s.value;break;}}LATW=null;}else D=latFloor0(a);LATF.set(a,D);}return D[CIDX[b]];}
|
||||
function latFloor0(a){const g=latFloorRun(a);for(;;){const s=g.next();if(s.done)return s.value;}}
|
||||
/* Each city's floor follows from the catalog alone, and costs a few milliseconds: idle frames work them out ahead, a
|
||||
few cities at a time (latWarm()), your POPs' first, then the financial centres latency customers ask about. */
|
||||
let LATW=null;const LAT_FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'];
|
||||
function latWarm(ms){if(!S||!S.pops)return;const t=performance.now();
|
||||
for(;;){if(!LATW){const a=Object.keys(S.pops).concat(LAT_FIN).find(c=>CITY[c]&&!LATF.has(c));if(!a)return;LATW={a,g:latFloorRun(a)};}
|
||||
const s=LATW.g.next();if(s.done){if(!LATF.has(LATW.a))LATF.set(LATW.a,s.value);LATW=null;}if(performance.now()-t>ms)return;}}
|
||||
function* latFloorRun(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n);let k=0;
|
||||
if(!LATC){LATC=new Map();for(const c of CABLE_PAIRS){const k=Math.min(CIDX[c.a],CIDX[c.b])*4096+Math.max(CIDX[c.a],CIDX[c.b]),w=c.km*Math.min(0.9,CAB[c.cid].lat||1);if(!(LATC.get(k)<=w))LATC.set(k,w);}}
|
||||
D[CIDX[a]]=0;for(;;){let u=-1,ud=Infinity;for(let i=0;i<n;i++)if(!done[i]&&D[i]<ud){u=i;ud=D[i];}if(u<0)break;done[u]=1;const U=CITIES[u];
|
||||
D[CIDX[a]]=0;for(;;){if((++k&15)===0)yield;let u=-1,ud=Infinity;for(let i=0;i<n;i++)if(!done[i]&&D[i]<ud){u=i;ud=D[i];}if(u<0)break;done[u]=1;const U=CITIES[u];
|
||||
for(let i=0;i<n;i++){if(done[i])continue;const V=CITIES[i],cw=LATC.get(Math.min(u,i)*4096+Math.max(u,i));
|
||||
let w=overland(U,V)&&!noTalk(U.id,V.id)?kmBetween(U.id,V.id)*1.1:Infinity;if(cw<w)w=cw;if(w<Infinity){const d=ud+w/200+0.05;if(d<D[i])D[i]=d;}}}
|
||||
return D;}
|
||||
|
|
|
|||
15
src/game/88-days/15-day-pace.js
Normal file
15
src/game/88-days/15-day-pace.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
/* ---------- the pace of days, as measured ----------
|
||||
How fast days really come with the route worker, for Settings › Diagnostic info: the speed asked, the speed held
|
||||
(from the starts of the last 12 days), how long a day takes from its start to its end, and the slowest of them.
|
||||
Measured only: a clock that started days on a steady beat was tried, and on big networks it cost a sixth of the
|
||||
speed without making the days any more regular (their spread comes from the long days themselves, a second routing
|
||||
for the intern's jobs or a failure, which no beat can hide). */
|
||||
const PACE={s:null,sp:0,st:[],d:[],t0:0};
|
||||
// A day starts (runClock(), 99-loop.js) / has ended (rwDayDone(), 28-route-worker.js). A new speed or another game:
|
||||
// the measure starts again.
|
||||
function paceStart(now){const P=PACE;if(P.s!==S||P.sp!==UI.speed){P.s=S;P.sp=UI.speed;P.st.length=0;P.d.length=0;}
|
||||
P.st.push(now);if(P.st.length>13)P.st.shift();P.t0=now;}
|
||||
function paceEnd(now){const P=PACE;if(!P.t0)return;P.d.push(now-P.t0);if(P.d.length>12)P.d.shift();P.t0=0;}
|
||||
function diagPace(){const P=PACE;if(!S||!UI.speed)return 'days: paused';if(P.s!==S||P.sp!==UI.speed||P.st.length<3)return `days: x${UI.speed} asked · measuring`;
|
||||
const gap=(P.st[P.st.length-1]-P.st[0])/(P.st.length-1),d=P.d.length?P.d.reduce((a,x)=>a+x,0)/P.d.length:0;
|
||||
return `days: x${UI.speed} asked · x${(DAY_MS/gap).toFixed(1)} held (one every ${Math.round(gap)} ms)`+(d?` · a day takes ${Math.round(d)} ms, slowest ${Math.round(Math.max(...P.d))}`:'');}
|
||||
|
|
@ -14,28 +14,39 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
|
|||
UI.lastSave=performance.now();
|
||||
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.
|
||||
if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return;
|
||||
/* A big network that moved on since its last save cannot be the same text: the route worker packs it, turns it into
|
||||
text and compresses it (rwSave()); the page only copies the game over and writes what comes back. */
|
||||
if(!force&&!failed&&st===S&&SLOT.day[id]!==undefined&&SLOT.day[id]!==st.day&&((SLOT.txt[id]||'').length>=GZ_BG||SLOT.big[id])&&gzOk()){
|
||||
const seq=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,p=rwSave(st,seq);
|
||||
if(p){SLOT.top[id]=seq;let tier=null;try{tier=tierLabel();}catch(e){}gzSave({id,s:st,txt:null,seq,day:st.day,meta:slotMeta(st,tier),p});return;}}
|
||||
const txt=JSON.stringify(packSave(st));
|
||||
// The very text the slot already holds (a paused game, nothing changed): writing a big network to storage costs more
|
||||
// than turning it into text, every 5 seconds, for nothing. Unless a write is still on its way, or the page is closing.
|
||||
if(!force&&!failed&&SLOT.txt[id]===txt&&(SLOT.top[id]||0)===(SLOT.sq[id]||0))return;
|
||||
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
|
||||
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
|
||||
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}
|
||||
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,day:st.day,meta:slotMeta(st,tier)};
|
||||
if(gzOk()&&(txt.length>=GZ_MIN||!force&&txt.length>=GZ_BG&&rwOn()))gzSave(j);else slotPut(j,slotStamp(txt,seq));}
|
||||
function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)};
|
||||
// Say so once per game (#176): a save that silently fails loses everything since the last one that worked.
|
||||
if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);}
|
||||
/* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage.
|
||||
Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save
|
||||
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
|
||||
const GZ='gz:',GZ_MIN=1e6,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
|
||||
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before.
|
||||
From GZ_BG up, the autosave is compressed too when the route worker does it: writing that much plain text held the
|
||||
page longer than everything else in a save (a save as the page closes stays plain below GZ_MIN: at once). */
|
||||
const GZ='gz:',GZ_MIN=1e6,GZ_BG=2e5,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
|
||||
async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below
|
||||
const r=stream.readable.getReader(),parts=[];let n=0;
|
||||
for(;;){const {done,value}=await r.read();if(done)break;parts.push(value);n+=value.length;}
|
||||
const out=new Uint8Array(n);let o=0;for(const p of parts){out.set(p,o);o+=p.length;}return out;}
|
||||
const b64=u=>{let s='';for(let i=0;i<u.length;i+=0x8000)s+=String.fromCharCode.apply(null,u.subarray(i,i+0x8000));return btoa(s);};
|
||||
const unb64=t=>{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u;};
|
||||
const gzip=async txt=>GZ+b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
|
||||
const gzB64=async txt=>b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
|
||||
const gzip=async txt=>GZ+await (rwGzip(txt)||gzB64(txt));
|
||||
const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip')));
|
||||
// Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then.
|
||||
function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true;
|
||||
gzip(slotStamp(j.txt,j.seq)).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
|
||||
(j.p?j.p.then(r=>{j.txt=r.txt;return r.data;}):gzip(slotStamp(j.txt,j.seq))).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
|
||||
.catch(e=>{console.error('[tubes] compressing the save failed',e);})
|
||||
.finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});}
|
||||
/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it.
|
||||
Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:<id>. */
|
||||
const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main';
|
||||
const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
|
||||
// txt: the text of each slot's last save that landed, before its stamp.
|
||||
const SLOT={sq:{},top:{},txt:{},day:{},big:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
|
||||
function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}}
|
||||
const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back
|
||||
const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}};
|
||||
|
|
@ -87,12 +88,14 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false;
|
|||
catch(e){// A migrated save the browser has no room to copy keeps living in the old key, as it always did.
|
||||
if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;}
|
||||
if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed
|
||||
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);
|
||||
SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);SLOT.txt[id]=j.txt;SLOT.day[id]=j.day;
|
||||
const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false}));
|
||||
slotIdxPut(list);return true;}
|
||||
function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}}
|
||||
// ---------- opening, leaving, losing ----------
|
||||
function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;
|
||||
function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;delete SLOT.txt[id];
|
||||
// The day the slot holds, and whether it is big (compressed, or long): the first save that moves on goes to the worker.
|
||||
{const raw=slotRaw(id);SLOT.day[id]=S?S.day:undefined;SLOT.big[id]=!!raw&&(raw.startsWith(GZ)||raw.length>=GZ_BG);}
|
||||
SLOT.sq[id]=Math.max(sv&&isFinite(sv.seq)?+sv.seq:0,e?e.seq:0);}
|
||||
function slotNew(){const id=slotRid();UI.slot=id;ssSet(SLOT_SS,id);SLOT.sq[id]=0;SLOT.no.delete(id);slotClaim(id,true,()=>{});return id;}
|
||||
// Leave this window's network (saved first); the slot is free for other windows once its last save has landed.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/* 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,
|
||||
frames, the time draw() takes, and the pace of days (asked and held). 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};
|
||||
|
|
@ -27,7 +27,7 @@ function diagShow(){const D=DIAG;let el=D.el;
|
|||
`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();}
|
||||
diagMap()+'\n'+diagPerf()+'\n'+diagPace();}
|
||||
// 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();}
|
||||
|
|
|
|||
|
|
@ -17,8 +17,11 @@ 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)){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(!(UI.mapHid=mapHidden())){const st=mapStill(t,now);if(st!==MAP_STILL&&!(st===MAP_AMBIENT&&now-(UI.drawnAt||0)<AMB_MS)){
|
||||
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);
|
||||
// The diverse-paths map and the latency floors new offers ask about, worked out a millisecond a frame ahead.
|
||||
if(S&&UI.started){diversityWarm(1);if(!DIVW)latWarm(1);}
|
||||
RW.lf=performance.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
|
||||
|
|
@ -26,9 +29,9 @@ function frame(now){
|
|||
function runClock(dt){acc+=dt*UI.speed;let n=0;
|
||||
// One day in flight at a time (its routing in the worker, or resting between steps): time does not pile up behind it.
|
||||
// The clock waits for the day, never the other way round: a machine that cannot keep up plays slower, it does not
|
||||
// freeze to catch up.
|
||||
// freeze to catch up. (Diagnostic info shows how fast days really come: 15-day-pace.js.)
|
||||
if(RW.job){acc=Math.min(acc,DAY_MS);return;}
|
||||
if(rwOn()){if(!RW.w)rwStart();if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
|
||||
if(rwOn()){if(!RW.w)rwStart();if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);paceStart(performance.now());try{rwDay();}catch(e){tickErr(e);}}}
|
||||
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
|
||||
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
|
||||
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
|
||||
|
|
@ -37,12 +40,17 @@ 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 (the WebGL map has none). */
|
||||
const FRAME=[];
|
||||
a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none).
|
||||
Playing, when only the animation clock moved (packets, waves, clouds, money floating up), the map is ambient: drawn
|
||||
at most 30 times a second, not at the screen's 60 or 120. The animations follow the clock, so they keep their speed
|
||||
and only lose frames nobody follows that closely; anything else that moves (the camera, a pointer, the network, a
|
||||
selection) gets every frame again at once. */
|
||||
const FRAME=[],MAP_MOVING=0,MAP_AMBIENT=1,MAP_STILL=2,AMB_MS=29;
|
||||
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,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&&(glOn()||!!(WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z)));}
|
||||
let same=v.length===FRAME.length,clock=same&&FRAME[0]!==v[0];for(let i=0;i<v.length;i++)if(FRAME[i]!==v[i]){if(i)clock=false;same=false;FRAME[i]=v[i];}
|
||||
if(!(glOn()||WL.cv&&WL.key===(cam.z*DPR).toFixed(4)&&wlCovers(cam.z)))return MAP_MOVING;
|
||||
return same?(now-(UI.drawnAt||0)<1000?MAP_STILL:MAP_MOVING):clock?MAP_AMBIENT:MAP_MOVING;}
|
||||
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){
|
||||
|
|
|
|||
35
tests/day-pace.test.js
Normal file
35
tests/day-pace.test.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// How fast days really come with the route worker (src/game/88-days/15-day-pace.js), for Settings › Diagnostic info:
|
||||
// the speed asked, the speed held from the starts of the last days, how long a day takes and the slowest. Measured
|
||||
// only: the clock starts days as it always did.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('Diagnostic info says the speed asked, the speed held and how long a day takes', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=8;");
|
||||
assert.equal(ev('diagPace()'), 'days: x8 asked · measuring');
|
||||
// A day every 400 ms (x8 asks one every 312.5), each taking 300 ms, one of them 700.
|
||||
ev('for(let i=0;i<14;i++){const t=1000+i*400;paceStart(t);paceEnd(t+(i===10?700:300));}');
|
||||
assert.equal(ev('diagPace()'), 'days: x8 asked · x6.3 held (one every 400 ms) · a day takes 333 ms, slowest 700');
|
||||
// Another speed: the measure starts again.
|
||||
ev('UI.speed=4;');
|
||||
assert.equal(ev('diagPace()'), 'days: x4 asked · measuring');
|
||||
ev('paceStart(9000);paceStart(9625);paceStart(10250);');
|
||||
assert.match(ev('diagPace()'), /^days: x4 asked · x4\.0 held \(one every 625 ms\)/);
|
||||
ev('UI.speed=0;');
|
||||
assert.equal(ev('diagPace()'), 'days: paused');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the clock with the worker feeds the measure and starts days as it always did', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();autoPause=()=>false;UI.speed=8;");
|
||||
// A stand-in worker day that ends at once: one day per 312.5 ms of clock, as before.
|
||||
ev(`window.__n=0;rwOn=()=>true;RW.w={postMessage(){},terminate(){}};rwDay=()=>{__n++;S.day++;rwDayDone();};
|
||||
for(let i=0;i<600;i++)runClock(1000/60);`);
|
||||
assert.equal(ev('__n'), Math.floor(600 * 1000 / 60 / 312.5), 'one day per 312.5 ms of clock');
|
||||
assert.equal(ev('PACE.st.length'), 13, 'the last days are measured');
|
||||
assert.match(ev('diagPace()'), /^days: x8 asked · x\d+\.\d held/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the
|
||||
// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
|
||||
// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
|
||||
// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day.
|
||||
// way must be the day dayTick() plays, move for move, R.egDesc left out of the answers that repeat it and R.efg out of
|
||||
// the posts that would only send the worker its own, and a frame let through in the middle of each day.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
|
@ -9,11 +10,12 @@ const path = require('node:path');
|
|||
const { load } = require('./harness');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic
|
||||
// routes, which read yesterday's R.efg. Ids come from Date.now(),
|
||||
// The big network with an intern running every order, a failure and an event due soon, its circuits on scenic
|
||||
// routes, which read yesterday's R.efg, and renewal haggles the sales desk answers (slRenRun() routes after them). Ids come from Date.now(),
|
||||
// so the clock stands still in every page.
|
||||
const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;
|
||||
S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;
|
||||
S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;S.slAuto.ren=true;window.__ren=0;{const f=slRenOne;slRenOne=function(){__ren++;return f.apply(this,arguments);};}
|
||||
for(const b of S.biz.filter(b=>clOn(b)&&!BIZ_T[b.type].fiber).slice(0,20)){b.te=S.day+28;b.hag={rate:Math.round(b.rate*0.7),until:S.day+28};}
|
||||
S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;
|
||||
S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`;
|
||||
const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
|
||||
|
|
@ -25,18 +27,22 @@ function played(t) {
|
|||
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
|
||||
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
|
||||
// Answers what is waiting, one message at a time; returns how many routings it served.
|
||||
let rests = 0, trials = 0;
|
||||
// kept: answers that left R.egDesc out, the page keeping the one it has; lean: posts that left R.efg out, the worker
|
||||
// keeping its own.
|
||||
let kept = 0, lean = 0, rests = 0, delta = 0, trials = 0;
|
||||
const pump = () => { let n = 0; for (;;) {
|
||||
if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; }
|
||||
if (!page.ev('__q.length')) break;
|
||||
if (page.ev('__q[0].efg===0')) lean++;
|
||||
if (page.ev('!!__q[0].trial')) trials++;
|
||||
wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out');
|
||||
page.ev('rwDone(__a)'); n++; } return n; };
|
||||
if (wk.ev('!!__out.R&&__out.R.egDesc===0')) kept++;
|
||||
if (wk.ev('!!(__out.R&&__out.R.egDesc&&__out.R.egDesc.dK!==undefined)')) delta++; page.ev('rwMsg(__a)'); n++; } return n; };
|
||||
// One message to the worker and its answer back (the trial test steps through a day with it).
|
||||
const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); };
|
||||
return { ...page, pump, pump1, rests: () => rests, trials: () => trials };
|
||||
const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); };
|
||||
return { ...page, pump, pump1, kept: () => kept, lean: () => lean, rests: () => rests, delta: () => delta, trials: () => trials };
|
||||
}
|
||||
// R.egDesc too, key for key and in order.
|
||||
// R.egDesc too, key for key and in order: the worker sends only what changed in it.
|
||||
const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})";
|
||||
// Equal states, or which of their fields differ.
|
||||
const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = [];
|
||||
|
|
@ -46,8 +52,8 @@ const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B =
|
|||
test('a day whose routings the worker answers is the day dayTick() plays', (t) => {
|
||||
const ref = open(t, 777), p = played(t);
|
||||
ref.ev(SETUP);
|
||||
// The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial())
|
||||
// included: they are steps like the others, routed by the worker.
|
||||
// The page itself never routes, the failure on day 3 (failureRun()), the sales desk's trials (offerTrial()) and its
|
||||
// renewal answers included: they are steps like the others, routed by the worker.
|
||||
p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
|
||||
let served = 0, extra = 0;
|
||||
for (let i = 0; i < 12; i++) {
|
||||
|
|
@ -63,7 +69,11 @@ test('a day whose routings the worker answers is the day dayTick() plays', (t) =
|
|||
assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened');
|
||||
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
|
||||
assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`);
|
||||
assert.ok(p.ev('__ren') > 0 && p.ev('__ren') === ref.ev('__ren'), `renewal haggles the desk answered: ${p.ev('__ren')}`);
|
||||
assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes');
|
||||
assert.ok(p.kept() > 0 && p.kept() < served, `answers without R.egDesc: ${p.kept()} of ${served}`);
|
||||
assert.ok(p.delta() > 0, `answers with only what changed in R.egDesc: ${p.delta()}`);
|
||||
assert.ok(p.lean() > 0 && p.lean() < served, `posts without R.efg: ${p.lean()} of ${served}`);
|
||||
// A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after
|
||||
// each job of an order (a generator's yields).
|
||||
const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length');
|
||||
|
|
|
|||
|
|
@ -1,8 +1,33 @@
|
|||
// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms.
|
||||
// The map's frame pacing (src/game/99-loop.js, mapStill()): while only the animation clock moves, the map is drawn at
|
||||
// most 30 times a second; anything else that moves gets every frame; paused, it is drawn about once a second.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A second of frames at 60 Hz (each() runs before every frame), and how many of them drew the map.
|
||||
const second = (ev, each = '') => ev(`(()=>{let n=0;const d=draw;draw=t=>{n++;return d(t);};
|
||||
try{for(let i=0;i<60;i++){window.__now=(window.__now||1000)+1000/60;${each};frame(__now);}}finally{draw=d;}return n;})()`);
|
||||
|
||||
test('ambient frames are drawn at most 30 times a second, the camera moving gets them all, paused about one', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;ACT.launchBB({city:'fra'});closeModal();UI.anim='on';UI.speed=1;autoPause=()=>false;");
|
||||
second(ev); // the land picture and the first frames settle
|
||||
const ambient = second(ev);
|
||||
assert.ok(ambient >= 28 && ambient <= 31, `ambient: ${ambient} draws`);
|
||||
assert.equal(second(ev, 'cam.x+=0.5'), 60, 'the camera moving');
|
||||
assert.equal(second(ev, "UI.hover=UI.hover==='fra'?null:'fra'"), 60, 'the pointer over a city and off it');
|
||||
ev('UI.speed=0');
|
||||
second(ev);
|
||||
const paused = second(ev);
|
||||
assert.ok(paused <= 2, `paused: ${paused} draws`);
|
||||
ev("UI.anim='off';UI.speed=1");
|
||||
second(ev);
|
||||
assert.ok(second(ev) <= 2, 'animations off: nothing moves, nothing to draw');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A day's steps on the page take half a frame at most before letting one through (RW.budget, rwGo()): 8 ms on a 60 Hz
|
||||
// screen, 3 ms on a 240 Hz one. One long frame (a big save, a tab switch) does not move it much.
|
||||
test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
|
||||
|
|
@ -29,3 +54,41 @@ test("a device that cannot hold 50 frames a second gives a day half its frame, 3
|
|||
});
|
||||
|
||||
// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one
|
||||
// asks: the very map one go would build. One that asks halfway finishes it at once.
|
||||
test('idle frames build the diverse-paths map in slices, the same map as in one go', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
|
||||
const sig = "JSON.stringify([diversityMap.key,diversityMap.links,diversityMap.adj])";
|
||||
ev('diversityMap=null;DIVW=null;diversityPossible("fra","ams");');
|
||||
const once = ev(sig);
|
||||
ev('diversityMap=null;DIVW=null;');
|
||||
let frames = 0;
|
||||
for (; frames < 2000 && ev('!diversityMap'); frames++) ev('window.__now=(window.__now||1000)+4;diversityWarm(0.05);');
|
||||
assert.ok(frames > 3, `built over several frames: ${frames}`);
|
||||
assert.equal(ev(sig), once, 'the same map');
|
||||
// Halfway, an offer asks: the rest is built at once, and it is still the same map.
|
||||
ev('diversityMap=null;DIVW=null;diversityWarm(0.05);');
|
||||
assert.equal(ev('!diversityMap&&!!DIVW'), true, 'half built');
|
||||
assert.equal(ev('typeof diversityPossible("fra","ams")'), 'boolean');
|
||||
assert.equal(ev(sig), once, 'finished at once, the same map');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// The latency floors latency customers are offered against (80-geography-and-latency.js) are worked out ahead too, a
|
||||
// few cities a frame, your POPs first: the same numbers as working one out when asked, even halfway through one.
|
||||
test('idle frames work the latency floors out ahead, the same numbers as when asked', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;ACT.buildPop({city:'ams'});");
|
||||
const ref = ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(latFloor0(c))))");
|
||||
ev('LATF.clear();LATW=null;');
|
||||
let n = 0;
|
||||
for (; n < 5000 && !(ev("LATF.has('fra')&&LATF.has('ams')&&LATF.has('nyc')")); n++) ev('latWarm(0.05)');
|
||||
assert.ok(n > 3, `over several frames: ${n}`);
|
||||
assert.equal(ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(LATF.get(c))))"), ref, 'the same floors');
|
||||
// Halfway through a city, an offer asks about it: finished at once, the same numbers.
|
||||
ev("LATF.clear();LATW=null;latWarm(0.01);");
|
||||
const a = ev('LATW&&LATW.a');
|
||||
assert.ok(a, 'a city half done');
|
||||
assert.equal(ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor('${a}',b)))`), ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor0('${a}')[CIDX[b]]))`));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
64
tests/intern-dark-fiber-worker.test.js
Normal file
64
tests/intern-dark-fiber-worker.test.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
// The intern's line system swap asks first whether a day without the fiber still serves everything (opsDark(),
|
||||
// 95-standing-orders.js). That test routes the whole network: in play the route worker answers it, like a sales trial,
|
||||
// so the shift never routes on the page. jsdom has no Worker: a second page plays it (rwServe()), messages cloned both
|
||||
// ways. The shift played that way is the shift opsDay() plays; an action while the worker routes makes the page test again.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// tests/intern-optical-upgrade.test.js's network: a full, hot fiber Frankfurt–Amsterdam and the long way round through
|
||||
// Paris on two waves, big enough (tier 4) to carry the day without the fiber, or not (tier 0).
|
||||
const base = tier => "Date.now=()=>1.7e12;ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
|
||||
"for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" +
|
||||
"S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" +
|
||||
"S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," +
|
||||
`{id:'w1',a:'fra',b:'par',kind:'wave',tier:${tier},km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:${tier},km:430,cut:0,mo:1}];compute();` +
|
||||
"ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap.optup=0;closeModal();S.ops.on.optup=true;S.ops.p.optup={at:80};R.load.f=dfCap(S.links[0])*0.9";
|
||||
const open = (t) => { const h = load(); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
|
||||
// The page with a stand-in worker (tests/day-steps.test.js): what it posts waits until pump() hands it to the other page.
|
||||
function played(t, tier) {
|
||||
const page = open(t), wk = open(t);
|
||||
page.ev(base(tier));
|
||||
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
|
||||
page.ev('window.__pc=0;{const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};}');
|
||||
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
|
||||
let dark = 0;
|
||||
const one = () => { if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) dark++; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); };
|
||||
const pump = () => { for (;;) { if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } if (!page.ev('__q.length')) break; one(); } };
|
||||
return { ...page, pump, one, dark: () => dark };
|
||||
}
|
||||
const STATE = "JSON.stringify({links:S.links,cash:S.cash,log:S.ops.log,spent:S.ops.spent,no:OPTUP_NO.get('f')??null,served:R.served})";
|
||||
|
||||
for (const [tier, sys] of [[4, 'roadm'], [0, 'lite']]) {
|
||||
test(`the dark fiber test goes to the worker and plays as on the page (waves of tier ${tier}: ${sys})`, (t) => {
|
||||
const ref = open(t), p = played(t, tier);
|
||||
ref.ev(base(tier));
|
||||
ref.ev('opsDay(S.day)');
|
||||
p.ev('rwGo(opsRun(S.day))');
|
||||
assert.equal(p.ev('!!(__q.length||__later.length)'), true, 'the shift waits for the worker');
|
||||
p.pump();
|
||||
assert.equal(p.ev('!!RW.job'), false, 'the shift is over');
|
||||
assert.equal(p.ev(STATE), ref.ev(STATE));
|
||||
assert.equal(p.ev('S.links[0].sys'), sys);
|
||||
assert.equal(p.dark(), 1, 'the worker tested the fiber dark');
|
||||
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
|
||||
assert.equal(p.ev("S.links[0].eqDown===undefined||S.links[0].eqDown>S.day"), true);
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
}
|
||||
|
||||
test('an action while the worker tests the fiber: the page tests it again on the game as it is', (t) => {
|
||||
const ref = open(t), p = played(t, 4);
|
||||
ref.ev(base(4));
|
||||
ref.ev('opsDay(S.day)');
|
||||
p.ev('rwGo(opsRun(S.day))');
|
||||
// Up to the dark fiber's trial, then an action (it routes on the page, as always), then the worker's stale answer.
|
||||
for (let i = 0; i < 50 && !p.ev('!!(__q[0]&&__q[0].trial&&__q[0].trial.dark)'); i++) { if (p.ev('__later.length')) p.ev('__later.shift()()'); else if (p.ev('__q.length')) p.one(); else break; }
|
||||
assert.equal(p.ev('!!(__q[0].trial&&__q[0].trial.dark)'), true, 'the trial is in flight');
|
||||
p.ev('__pc=0;after()');
|
||||
p.pump();
|
||||
assert.equal(p.ev('__pc'), 2, "the action's routing, and the test made again here");
|
||||
assert.equal(p.ev(STATE), ref.ev(STATE));
|
||||
assert.equal(p.ev('S.links[0].sys'), 'roadm');
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
|
@ -47,9 +47,11 @@ test('a save too big for the browser is not retried every few seconds, but leavi
|
|||
assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over');
|
||||
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
|
||||
assert.equal(a.ev('UI.saveFail'), null);
|
||||
a.ev('save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time');
|
||||
a.ev('__full=true;save();S=migrate(JSON.parse(JSON.stringify(S)));save()');
|
||||
a.ev('S.cash++;save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time the network changes');
|
||||
a.ev('save();save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'and writes nothing while nothing changes');
|
||||
a.ev('__full=true;S.cash++;save();S=migrate(JSON.parse(JSON.stringify(S)));S.cash++;save()');
|
||||
assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once');
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -15,11 +15,17 @@ const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.c
|
|||
// R with its lazy parts (R.ef, R.fl) read out, attacks by id.
|
||||
const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";
|
||||
|
||||
// R.efg, which the next day's routing reads: every link's sums, Map order included (they cross as typed arrays).
|
||||
const EFG = "JSON.stringify(Object.entries(R.efg).map(([k,e])=>[k,[...e.t.g],e.t.v,e.t.n,e.t.d]))";
|
||||
|
||||
test('R packed, cloned and unpacked is the same R, lazy parts and key order included', (t) => {
|
||||
const { ev, errors } = big(t);
|
||||
const want = ev(SIG);
|
||||
const want = ev(SIG), efg = ev(EFG);
|
||||
ev("{const {o,p,tr}=rwPack(R);const c=structuredClone({o,p},{transfer:tr});R=rwUnpack(c.o,c.p);UI.hotMap=hotByCity();}");
|
||||
assert.equal(ev(EFG), efg);
|
||||
assert.equal(ev(SIG), want);
|
||||
// Sent back to the worker after an action, a link's sums still clone whole.
|
||||
assert.equal(ev("JSON.stringify(Object.entries(structuredClone(rwEfgOut(R.efg))).map(([k,t])=>[k,[...t.g],t.v,t.n,t.d]))"), efg);
|
||||
assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -30,10 +36,13 @@ test('the worker side routes what it is sent: same R as routing on the page', (t
|
|||
ev("window.__got=null;window.postMessage=(m)=>{window.__got=m;};");
|
||||
ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}");
|
||||
ev("R=rwUnpack(structuredClone(__got.R),__got.ef)");
|
||||
const fromWorker = ev(SIG);
|
||||
const fromWorker = ev(SIG), hot = ev('JSON.stringify(structuredClone(__got.hot))');
|
||||
ev('R=__R0;S=JSON.parse(__S0);compute()');
|
||||
assert.equal(ev('JSON.stringify(S)'), ev('__S0'), 'routing does not change S');
|
||||
assert.equal(ev(SIG), fromWorker);
|
||||
// The full ports it found come along (the page no longer works them out again), key order included.
|
||||
assert.equal(hot, ev('JSON.stringify(UI.hotMap)'));
|
||||
assert.ok(Object.keys(JSON.parse(hot)).length > 5, 'some ports are full on the big network');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ const refuse = name => `window.__err=${lit(name)};{const P=Object.getPrototypeOf
|
|||
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError'));
|
||||
ev('save()');
|
||||
ev('S.cash++;save()');
|
||||
const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent));
|
||||
assert.equal(toasts().length, 1, 'one warning');
|
||||
assert.match(toasts()[0].textContent, /too big for this browser/);
|
||||
|
|
@ -31,7 +31,8 @@ test('#176 a save that does not fit tells the player once, with Export, and the
|
|||
|
||||
test('#176 storage that is blocked altogether gets its own advice', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()');
|
||||
// The game moves on first: a save of the very text the slot already holds writes nothing.
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';S.cash+=1;save()');
|
||||
assert.match(dom.window.document.body.textContent, /private window/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -126,3 +127,95 @@ test('#176 a damaged compressed save is kept, marked damaged, and the player is
|
|||
assert.equal(ev('!!UI.started'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A big network's autosave is compressed in the route worker (rwGzip()), not on the page: deflating it there held the
|
||||
// page about as long as writing it plain. jsdom has no Worker: a second page answers as the worker, messages cloned
|
||||
// both ways. A save as the page closes stays plain, and a worker lost mid-job leaves its job to the page.
|
||||
test('a big autosave is compressed in the route worker and loads back; a closing save stays plain', async () => {
|
||||
const a = load({ gzip: true }), w = load({ gzip: true });
|
||||
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
|
||||
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
|
||||
const len = a.ev('JSON.stringify(packSave(S)).length');
|
||||
assert.ok(len >= a.ev('GZ_BG') && len < a.ev('GZ_MIN'), `between the two thresholds: ${len}`);
|
||||
a.ev("window.__q=[];window.__pz=0;const gp=gzPipe;gzPipe=(...x)=>{__pz++;return gp(...x);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
|
||||
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
|
||||
const pump = async () => { for (let k = 0; k < 200; k++) {
|
||||
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
|
||||
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
|
||||
if (a.ev("(slotRaw(UI.slot)||'').startsWith(GZ)&&!UI.gzBusy")) return; await new Promise((r) => setTimeout(r, 5)); } };
|
||||
// Closing: plain text, at once.
|
||||
a.ev('save(true)');
|
||||
assert.equal(a.ev('slotRaw(UI.slot)[0]'), '{', 'a save as the page closes is written plain');
|
||||
// The autosave: compressed by the worker.
|
||||
a.ev("S.name='Worker Zip';save()");
|
||||
assert.equal(a.ev('__q.length'), 1, 'the text went to the worker');
|
||||
await pump();
|
||||
assert.ok(a.ev("slotRaw(UI.slot).startsWith(GZ)"), 'stored compressed');
|
||||
assert.equal(a.ev('__pz'), 0, 'nothing was deflated on the page');
|
||||
a.ev("gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length].join('|');})");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length].join('|')"));
|
||||
// The worker lost while it compresses: the page compresses that save itself.
|
||||
a.ev("__pz=0;S.name='Page Zip';save();rwKill()");
|
||||
await settle(a.ev, "!UI.gzBusy&&__pz>0", 'compressed on the page');
|
||||
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), 'Page Zip');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(w.errors, []);
|
||||
});
|
||||
|
||||
// A big network that moved on since its last save is packed, turned into text and compressed by the route worker
|
||||
// (rwSave()): the page copies the game over and writes what comes back. A paused game (same day) is still compared on
|
||||
// the page, so an unchanged one is not written again. The worker lost mid-save: the next frame saves again, here.
|
||||
test('a big game that moved on is saved by the route worker, a paused one is still compared on the page', async () => {
|
||||
const a = load({ gzip: true }), w = load({ gzip: true });
|
||||
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
|
||||
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
|
||||
a.ev("window.__q=[];window.__pk=0;const pk=packBiz;packBiz=b=>{__pk++;return pk(b);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
|
||||
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
|
||||
const pump = async (cond) => { for (let k = 0; k < 300; k++) {
|
||||
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
|
||||
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
|
||||
if (a.ev(cond)) return; await new Promise((r) => setTimeout(r, 5)); } assert.fail('never: ' + cond); };
|
||||
// The first save of the session is made here, and tells the slot which day it holds.
|
||||
a.ev('save()'); await pump("!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
// A day later: the whole save goes to the worker.
|
||||
a.ev("__pk=0;S.day++;S.name='Moved On';save()");
|
||||
assert.equal(a.ev('__q.length&&!!__q[0].sv&&!!__q[0].S'), true, 'the game went to the worker');
|
||||
await pump("!UI.gzBusy&&SLOT.day[UI.slot]===S.day");
|
||||
assert.equal(a.ev('__pk'), 0, 'nothing was packed on the page');
|
||||
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length,!!j.sv].join('|');})");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length,true].join('|')"), 'the slot holds the game, stamped');
|
||||
assert.equal(a.ev('SLOT.txt[UI.slot]===JSON.stringify(packSave(S))'), true, 'the slot knows its text');
|
||||
a.ev('__pk=0');
|
||||
// Paused, nothing changed: compared on the page and not written again.
|
||||
a.ev("__pk=0;window.__w=0;const sp=slotPut;slotPut=(...x)=>{__w++;return sp(...x);};save()");
|
||||
assert.equal(a.ev('__q.length'), 0, 'nothing went to the worker');
|
||||
assert.ok(a.ev('__pk') > 0, 'packed here, to compare');
|
||||
assert.equal(a.ev('__w'), 0, 'the same game is not written again');
|
||||
// The worker lost while it saves: the next frame saves again.
|
||||
a.ev("S.day++;save();rwKill()");
|
||||
await settle(a.ev, '!UI.gzBusy');
|
||||
assert.equal(a.ev('UI.lastSave'), 0, 'the next frame saves again');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(w.errors, []);
|
||||
});
|
||||
|
||||
// Loaded from a big slot, the game's first save once it moves on already goes to the worker: the slot knows its day.
|
||||
test('the first save after loading a big slot goes to the route worker once the game moves on', async () => {
|
||||
const a = load({ gzip: true });
|
||||
a.ev(bigBiz + ';' + huge);
|
||||
a.ev('save(true)');
|
||||
await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
const b = load({ gzip: true, storage: { 'sot-save-v1': a.ev('slotRaw(UI.slot)') } });
|
||||
await settle(b.ev, 'UI.started===true');
|
||||
b.dom.window.structuredClone = globalThis.structuredClone;
|
||||
b.ev("window.__q=[];rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){}});");
|
||||
assert.equal(b.ev('SLOT.big[UI.slot]===true&&SLOT.day[UI.slot]===S.day'), true, 'the slot knows its day and size');
|
||||
b.ev('S.day++;save()');
|
||||
assert.equal(b.ev('__q.length===1&&!!__q[0].sv'), true, 'the whole save went to the worker');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(b.errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -195,7 +195,9 @@ test('the map is only redrawn when something on it can have changed', () => {
|
|||
assert.ok(frame('', 1100) > 0, 'and once a second anyway');
|
||||
assert.ok(frame('WL.key=null') > 0, 'the land picture catching up after a zoom or resize redraws');
|
||||
ev('UI.speed=1');
|
||||
assert.ok(frame() > 0 && frame() > 0, 'with the clock running every frame moves');
|
||||
// Only the animation clock moves: ambient, drawn at most 30 times a second (tests/frame-pacing.test.js).
|
||||
const run = [frame(), frame(), frame(), frame()].filter((n) => n > 0).length;
|
||||
assert.ok(run >= 2 && run < 4, `with the clock running the map moves, every other frame at 60 Hz (${run} of 4)`);
|
||||
ev("ACT.animSet({v:'off'})");
|
||||
frame(); frame();
|
||||
assert.equal(frame(), 0, 'with animations off the running map stands still between days');
|
||||
|
|
|
|||
|
|
@ -68,14 +68,15 @@ test('a still map is drawn again when the zoom comes to rest, so the stretched p
|
|||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
// Animations off: the loop skips frames while nothing changes.
|
||||
// mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still.
|
||||
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');
|
||||
assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'nothing moved since the last frame');
|
||||
ev(`__T+=300`);
|
||||
assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
|
||||
assert.equal(ev('mapStill(0,__T)'), ev('MAP_MOVING'), '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.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'and then the map stays still again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue