Merge perf/3-worker: each day's routing runs in a Web Worker built from the page's own script, identical results
This commit is contained in:
commit
167e2a715b
9 changed files with 161 additions and 16 deletions
56
src/game/80-simulation/28-route-worker.js
Normal file
56
src/game/80-simulation/28-route-worker.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/* Routing off the main thread. The worker is this page's own game script run a second time
|
||||
from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert
|
||||
stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code.
|
||||
Only the day uses it: dayPre(), then S goes to the worker, the day waits (no next day starts) and dayPost() runs
|
||||
when R is back, so a day sees exactly the routing it would have had in one go. An action in between routes
|
||||
synchronously as always (compute() bumps RW.gen); then the worker's answer is stale and the action's R stands.
|
||||
Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */
|
||||
const RW_IN=!!self.__TUBES_WORKER__;
|
||||
const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null;
|
||||
const RW={w:null,dead:false,seq:0,gen:0,job:null,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';
|
||||
const pre=`'use strict';self.__TUBES_WORKER__=1;self.window=self;
|
||||
const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true});
|
||||
const _st={getItem:()=>null,setItem(){},removeItem(){},key:()=>null,length:0};
|
||||
Object.assign(self,{document:_n,localStorage:_st,sessionStorage:_st,requestAnimationFrame:()=>0,cancelAnimationFrame(){},innerWidth:1280,innerHeight:800,devicePixelRatio:1,
|
||||
matchMedia:()=>({matches:false,addEventListener(){},addListener(){}}),Image:_n,Audio:_n,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},SOT_LANG:${JSON.stringify(L)},SOT_LANGS:{},I18N:{}});
|
||||
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);};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 day it was routing is routed here instead.
|
||||
function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;RW.job=null;if(j){try{compute();dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}}
|
||||
// One day in play: the first half here, the routing in the worker, the second half when it answers.
|
||||
function rwDay(){const d=dayPre();if(d===false)return;const w=rwStart();
|
||||
if(!w){compute();dayPost(d);rwDayDone();return;}
|
||||
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)});}catch(e){console.error('[tubes] route worker post',e);rwKill();compute();dayPost(d);rwDayDone();return;}
|
||||
const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,d,gen:RW.gen,t:t1};}
|
||||
function rwDone(m){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now();
|
||||
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();}
|
||||
const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0;
|
||||
try{dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}
|
||||
function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}}
|
||||
/* 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 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;}
|
||||
// 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)});
|
||||
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);}
|
||||
catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}}
|
||||
|
|
@ -8,7 +8,18 @@ function flbGrow(){const c=Math.max(4096,FLB.cap*2),g=(A,o)=>{const a=new A(c);i
|
|||
FLB.rem=g(Float64Array,FLB.rem);FLB.ci=g(Int32Array,FLB.ci);FLB.nj=g(Int32Array,FLB.nj);FLB.ca=g(Uint8Array,FLB.ca);FLB.bz=g(Uint8Array,FLB.bz);FLB.cap=c;}
|
||||
// R.efg[link]: what each egress put on that link, read by scenic routing the next day (t.g gives each egress its slot in t.v).
|
||||
class EgSums{constructor(t){this.t=t;}get(k){const s=this.t.g.get(k);return s===undefined?undefined:this.t.v[s];}}
|
||||
function compute(){
|
||||
/* R.ef and R.efg from what routing added up per edge (L: [link id, edge index, its sums t]), and R.fl from the flow
|
||||
columns (c). Also how a route worker's answer is put back together (28-route-worker.js): getters do not cross
|
||||
threads, so it sends these plain pieces (R.efp, R.flc) and the page rebuilds the same lazy R. */
|
||||
function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,t] of L){let rec=null;efg[id]=new EgSums(t);
|
||||
Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s];
|
||||
for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});}
|
||||
Object.defineProperty(R2,'efg',{value:efg});Object.defineProperty(R2,'efp',{value:{L,ACN,ACD,NKN,NC,NN}});}
|
||||
// R.fl: the flows as objects, made only when something asks (38-pni-value.js). E: the exits FTI and FII point into.
|
||||
function flDefine(R2,c){const {NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E,CNB,NCN}=c;let fl=null;Object.defineProperty(R2,'flc',{value:c});
|
||||
Object.defineProperty(R2,'fl',{get(){if(!fl){fl=new Array(NF);for(let i=0;i<NF;i++){const ci=FCI[i],j=FNJ[i];
|
||||
fl[i]={c:CITIES[ci].id,n:NET_IDS[j],rem:FREM[i],cache:FCA[i]===1,junk:false,bz:FBZ[i]===1,ci,cn:CNB[ci],ncn:NCN[j],nj:j,nr:j,gt:FGT[i],gi:FGI[i],gp:FGP[i],gh:FGH[i],ti:FTI[i]<0?null:E[FTI[i]].id,ii:FII[i]<0?null:E[FII[i]].id};}}return fl;}});}
|
||||
function compute(){RW.gen++;
|
||||
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
|
||||
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
|
||||
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
|
||||
|
|
@ -302,10 +313,7 @@ function compute(){
|
|||
for(const o of G.values()){const c=CITIES[o.src].id,cur=R2.latFar[c];if(!cur||o.g>cur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}}
|
||||
// R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic
|
||||
// routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same).
|
||||
{const efg={};for(const l of EL){const t=l.tr,i=l.i;let rec=null;efg[l.id]=new EgSums(t);
|
||||
Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s];
|
||||
for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});}
|
||||
Object.defineProperty(R2,'efg',{value:efg});}
|
||||
efBuild(R2,EL.map(l=>[l.id,l.i,l.tr]),ACN,ACD,NKN,NC,NN);
|
||||
// Active links fill first, by capacity; standby links take what is left over.
|
||||
for(const k in edges){const e=edges[k],ld=e.ld||0,ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;for(const l of e.links){const c=capOf(l);R2.load[l.id]=l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0);}}
|
||||
for(const e of TORD){const m=R2.tNet[e.id]={},b=e.ts*NN;for(const j of TNK[e.ts])m[NET_IDS[j]]=TNA[b+j];}
|
||||
|
|
@ -330,8 +338,7 @@ function compute(){
|
|||
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix);
|
||||
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
|
||||
R2.revMo=V.eyeballs+V.business+V.ix+V.grant;
|
||||
// R.fl: the flows as objects, made only when something asks (38-pni-value.js), from this call's own columns.
|
||||
{let fl=null;Object.defineProperty(R2,'fl',{get(){if(!fl){fl=new Array(NF);for(let i=0;i<NF;i++){const ci=FCI[i],j=FNJ[i];
|
||||
fl[i]={c:CITIES[ci].id,n:NET_IDS[j],rem:FREM[i],cache:FCA[i]===1,junk:false,bz:FBZ[i]===1,ci,cn:CNB[ci],ncn:NCN[j],nj:j,nr:j,gt:FGT[i],gi:FGI[i],gp:FGP[i],gh:FGH[i],ti:FTI[i]<0?null:E[FTI[i]].id,ii:FII[i]<0?null:E[FII[i]].id};}}return fl;}});}
|
||||
// R.fl: from this call's own columns, made into objects only when something asks.
|
||||
flDefine(R2,{NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E,CNB,NCN});
|
||||
R=R2;UI.hotMap=hotByCity();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
/* ---------- daily tick ---------- */
|
||||
function dayTick(){
|
||||
if(!S||S.lost||!rule('clock'))return; // no clock (puzzles): no days, no bills, nothing fires
|
||||
/* A day is two halves around its routing: dayPre() (the world moves on), compute(), dayPost() (bills, moods, offers).
|
||||
In play the routing can run in a worker in between (28-route-worker.js); tests and the fallback run it in one go. */
|
||||
function dayTick(){const d=dayPre();if(d===false)return;compute();dayPost(d);}
|
||||
function dayPre(){
|
||||
if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires
|
||||
S.day++;
|
||||
const d=S.day;
|
||||
dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
|
||||
|
|
@ -27,7 +30,8 @@ function dayTick(){
|
|||
for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c);
|
||||
if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);}
|
||||
else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));}
|
||||
compute();
|
||||
return d;}
|
||||
function dayPost(d){
|
||||
ddosNews();ddosTrack();
|
||||
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
|
||||
S.cash+=(R.revMo-R.costMo)/30;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@
|
|||
/* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set
|
||||
aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */
|
||||
function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
|
||||
// Half a day (its routing still in the worker) is never saved: the day's end saves instead.
|
||||
if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;}
|
||||
if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return;
|
||||
if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
|
||||
if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,11 @@ function frame(now){
|
|||
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
|
||||
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
|
||||
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;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;}}
|
||||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;
|
||||
// With the route worker one day is in flight at a time; time does not pile up behind it.
|
||||
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);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;}}}
|
||||
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
|
||||
const t=animOn()?animT:0;
|
||||
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
|
||||
|
|
@ -47,4 +50,4 @@ function boot(data){
|
|||
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
|
||||
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
|
||||
}
|
||||
slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
|
||||
if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue