The page stays free while big networks play: ambient map at 30 fps, saves in the worker, less to carry back

The game plays exactly as before; only what holds the page changes.

* mapStill() tells three cases apart: still (drawn once a second), ambient (only the animation clock moved: drawn at
  most every 29 ms, so 30 fps on 60 and 120 Hz screens) and moving (camera, pointer, selection, network: every frame).
  The animations follow the clock, so they keep their speed.
* save() skips the storage write when the text is the one the slot already holds (SLOT.txt) and no write is on its
  way; leaving the page still writes. A big autosave that moved on is packed, turned into text, stamped and
  compressed in the route worker (rwSave(), rwGzip()); the page only writes what comes back. A lost worker hands its
  pending saves back to the page (rwSaveBack(), rwGzBack()).
* Less crosses back from the worker: R.efg stays there while R is its own last answer (RW.wR, efg 0), R.egDesc comes
  as 0 or as the entries that changed (rwDescOut()/rwDescIn()), what crossed each link travels as typed arrays decoded
  on demand (rwLOut()/rwLIn()), and the full ports (hotMap) come along with R. Every message is read in order
  (rwMsg()), so both sides always hold the same last answer.
* Idle frames build the diverse-paths map and the latency floors a millisecond at a time (diversityWarm(),
  latWarm()), before the first offer asks.
* Diagnostic info shows how fast days really come: speed asked, speed held, how long a day takes (15-day-pace.js).
* perf-bench: "The NOC intern's shift: opsDay()" and, in Chromium, "One game day in play: page time only", a day
  played with the real route worker counting only the time it holds the page.

Tests: frame-pacing, day-pace, save-size, persist, route-worker (efg as typed arrays, hotMap from the worker),
day-steps (a second page plays the worker: answers without R.egDesc, with only its changes, posts without R.efg,
renewal haggles answered through the worker), intern-dark-fiber-worker, webgl-zoom-sprites, speed.
This commit is contained in:
Antoine 2026-11-07 22:21:22 +01:00
parent d03dde6fcd
commit b9d6319302
No known key found for this signature in database
GPG key ID: 728FF1CE15732B05
22 changed files with 517 additions and 86 deletions

View file

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

View file

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

View file

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

View 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))}`:'');}

View file

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

View file

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

View file

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

View file

@ -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){