Merge pull request #313: every routing a day needs runs in the route worker, and a long day lets frames through

Conflicts with main resolved: the intern's chosen router model, optical upgrades and personas are generators like the
other orders, with a rest after each job. The optical upgrade's fiber test is a step the day answers, in the route
worker in play (opsDark(), {dark}), like the sales desk's trial; the renewal desk's reroute is a step too (slRenRun()).
This commit is contained in:
Frederic Jung 2026-11-06 22:47:54 +01:00
commit 410eb81544
No known key found for this signature in database
28 changed files with 612 additions and 141 deletions

View file

@ -24,18 +24,28 @@ function slWeekLine(x,last){const parts=[];if(x.n)parts.push(trn('sales.w_signed
const v={name:tr(SALES[x.p].s),list:parts.join(', ')};return last?tr('sales.w_last',v):tr('sales.w_now',v);}
// An orbit offer fits where its dish has room for it; used: what this shift already signed on each dish.
function slSkyOk(o,used){const L=pieServe(o.city,o.type);if(!L)return null;const k=L.cr+'|'+L.k;return slP()==='shark'||L.left-(used.get(k)||0)>=o.bw?k:null;}
function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7);
// Like a day, the desk is a generator: a routing trial is a step the day answers (in play, the route worker does).
const slAutoDay=d=>dayGo(slAutoRun(d),(g,v)=>g.next(v));
function* slAutoRun(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7);
// A new week: last week's tally becomes the report, and the one notice of the week.
if(!A.wk||A.wk.w!==w){if(slWkAny(A.wk)&&A.wk.w<w){A.rep=A.wk;logNote(`<b>${esc(tr('sales.desk'))}</b> ${esc(slWeekLine(A.rep,true))}`,A.rep.rev>0?'good':'',[],{a:'tab',v:'deals'});}A.wk={w,p,n:0,rev:0,x:0,y:0};}
const W=A.wk,used=new Map();W.p=p;let tries=0,dirty=false;
const tried=UI.slTried&&UI.slTried.s===S?UI.slTried.m:(UI.slTried={s:S,m:new Map()}).m;
const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;};
opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o);
if(A.min&&v<A.min){const b0=S.biz.length;ACT.decline({id:o.id});W.x++;if(S.biz.length>b0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;}
if(!A.on)continue;
if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cash<bizMo(o)))continue;ACT.accept({id:o.id});if(won(o))used.set(k,(used.get(k)||0)+o.bw);continue;}
if(!bCities(o).every(popUp))continue;
if(p==='shark'){if(S.cash<bizMo(o)||(T.event&&!(o.start>d)))continue;ACT.accept({id:o.id});won(o);continue;}
// Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week.
if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)continue;tries++;ACT.accept({id:o.id,auto:true});if(!won(o))tried.set(o.id,d);}});
if(dirty)compute();}
for(const o of S.offers.slice()){
// What this offer needs, muted: nothing, or a routing trial (b), which the day answers between the two quiet steps.
let b;const todo=opsQuiet(()=>{if(!S.offers.includes(o))return;const T=BIZ_T[o.type];if(!T||!(o.exp>d))return;const v=T.event?(o.fee||0):bizMo(o);
if(A.min&&v<A.min){const b0=S.biz.length;ACT.decline({id:o.id});W.x++;if(S.biz.length>b0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}return;}
if(!A.on)return;
if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cash<bizMo(o)))return;ACT.accept({id:o.id});if(won(o))used.set(k,(used.get(k)||0)+o.bw);return;}
if(!bCities(o).every(popUp))return;
if(p==='shark'){if(S.cash<bizMo(o)||(T.event&&!(o.start>d)))return;ACT.accept({id:o.id});won(o);return;}
// Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week.
if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;});
if(!todo)continue;
// o: the offer itself, for a trial the page has to run again on the game as it is by then (dayAgain()).
const got=b?yield {trial:b,hx:offerHealthy(b),o}:null;
// Signed or declined by hand while the trial routed: it is not the desk's.
if(!S.offers.includes(o))continue;
opsQuiet(()=>{OFFER_TRIED={o,b:got};try{ACT.accept({id:o.id,auto:true});}finally{OFFER_TRIED=null;}if(!won(o))tried.set(o.id,d);});}
if(dirty)yield;}

View file

@ -12,9 +12,11 @@ const SL_REN_WAIT=3;
const slRenOn=()=>!!(S&&S.slAuto&&S.slAuto.ren&&slP());
// The day the desk answers this haggle: a few days after it opened (30 days before the term ends), today at the earliest.
const slRenAt=b=>b.hag.until-30+SL_REN_WAIT;
function slRenDay(d){if(!slRenOn())return;const p=slP();let any=false;
// A step of the day (dayPost()): its yield is the routing after a price changed. slRenDay() is the same all at once.
function slRenDay(d){runNow(slRenRun(d));}
function* slRenRun(d){if(!slRenOn())return;const p=slP();let any=false;
for(const b of S.biz.slice())if(b.hag&&d>=slRenAt(b)&&d<b.hag.until){slRenOne(b,p);any=true;}
if(any)compute();}
if(any)yield;}
// One haggle: returns what happened (for the tests): 'tech', 'mid', 'cave', 'hold', 'walk', 'golf', 'yes', 'fight'.
function slRenOne(b,p){const ask=b.hag.rate,was=b.rate,mid=clMid(b),nerd=SALES_NERDS.includes(b.type),r=clR(b,'sl|'+p);
const v=x=>({name:esc(slCap()),cust:esc(b.name),...x}),bill=rate=>fmt$(clBill(b,rate));

View file

@ -1,12 +1,24 @@
/* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js).
It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};}
function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null).
let OFFER_TRIED=null;
function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;}
// The checks on the live game, and the customer the offer would be: null when there is nothing to trial.
function offerTrialOf(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
return b;}
const offerFuture=()=>S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
// Who is happy today (indices in S.biz), the one thing the trial reads from the live result: null when future events
// make the trial route without the offer first and judge on that.
const offerHealthy=b=>{if(offerFuture())return null;const h=[];S.biz.forEach((x,i)=>{if(!bizWhy(x).length)h.push(i);});return h;};
/* The trial: the game routed with the customer added, on a copy, S and R put back after. It reads nothing else of the
live result than hx (offerHealthy()), so the route worker can run it on the game it is sent (28-route-worker.js). */
function offerTrial(b,hx){const T=BIZ_T[b.type],start=b.start;
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
// Trial the added demand before signing; failed trials leave the live game untouched.
try{S={...S,biz:S.biz};
@ -19,6 +31,6 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra
if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null;
const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;}
compute();}
const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
const healthy=hx&&!future?hx.map(i=>S.biz[i]):S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
}finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}}
}finally{S=state;R=result;UI.hotMap=hot;b.start=start;if(T.cap)delete b.live;}}

View file

@ -139,17 +139,18 @@ function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day)
const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0];
// 'cheap' and 'have' (Already connected) name no network: quote the cheapest seller (#249).
const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);};
// The orders. Each takes the shift and does its jobs through the player's own actions.
// The orders. Each takes the shift and does its jobs through the player's own actions. Most are generators: a yield
// after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there.
const OPS_RUN={
repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');},
routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
*repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}},
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
// A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a
// step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there.
if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0;
if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue;
const cost=swapCost(c,m);if(!X.can('routers',cost))continue;
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m})))X.did('routers',c+' ⇧'+RG[m].pn);}
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}
for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue;
const ld=load(c);if(ld<at)continue;
const rt=p.routers||1,g=p.rgen||0,nx=mainRG(RG[g].cls+1);
@ -158,8 +159,8 @@ const OPS_RUN={
const swap=!fix&&nx>=0&&rgOpen(nx)&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt<RMAX;
const doSwap=how==='swap'?swap:how==='add'?false:swap&&(rt>=4||!add);if(!doSwap&&(how==='swap'||!add))continue;
const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue;
if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}},
transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x');
if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));yield;}},
*transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x');
for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue;
// Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak.
const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0)*opsAhead();if(!(peak>0))continue;
@ -177,11 +178,11 @@ const OPS_RUN={
else{const need=N*peak-cap,ok=PORT.map((P,i)=>i).filter(i=>portShown(i)&&portOk(c,i)),i=ok.find(i=>PORT[i].g>=need)??ok.at(-1);
if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}}
if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break;
X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}},
X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);yield;}}},
// PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a
// second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI
// augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for.
ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
*ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
// Router ports that pending PNI augments will take when they land are spoken for.
resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c);
// Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took.
@ -200,8 +201,8 @@ const OPS_RUN={
for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()<N*o.use;step++){
const lag=o.lag(),wantLag=o.n()<2&&o.rt>1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig();
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break;
X.did('ports',o.at+' '+job.w);}},
optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
X.did('ports',o.at+' '+job.w);yield;}},
*optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue;
let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead();
// New fiber gets its first channel; lit fiber gets more while it runs hot.
@ -213,20 +214,20 @@ const OPS_RUN={
o=fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break;
const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break;
X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break;
cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}},
optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}},
*optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a));
for(const l of ls){
// The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot.
const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]<SYS_RANK[goal]?goal:null;
if(want&&ups<OPTUP_MAX*(opsIs('kevin')?2:1)&&tries<OPTUP_TRY*(opsIs('kevin')?2:1)){const to=sysNext(l),cost=sysUpCost(l);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=opsDarkOk(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(ok){const s0=l.sys,top=goal==='next'?to:goal;
for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]<SYS_RANK[top];k++){const nx=sysNext(l);
if(!techOk('sys',nx,DF_SYS[nx].lvl)||!X.can('optup',sysUpCost(l))||!X.pay('optup',()=>{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;}
// The fiber is dark until tomorrow: its optics wait.
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);continue;}}}}
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}}
// Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and
// the old optics go on the shelf as spares.
if(!swap)continue;
@ -240,32 +241,35 @@ const OPS_RUN={
const was=dfCap(l);
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));}}},
caches(X){const g=opsP('caches','g');
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}},
*caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);}}},
for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);}
yield;}},
// Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192).
ix(X){if(S.day%7&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');}
for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}},
// Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181).
pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
*pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
// The traffic a PNI there would take over: what your users at that POP send to the network today over transit, an
// exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own
// cache boxes in that POP already serve most of it (#244).
const loc=q=>pniVal(q.net,q.city).want;
for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}},
// Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift
// let a frame through or waited for a routing, and the batch's quote would order it a second time.
for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}},
// Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102).
decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}
// Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go.
if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;}
for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue;
// Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a
// job changed the network and anything could go (opsDecomWaits()).
*decom(X){const keep=opsP('decom','keep');
for(const ls of opsPairs().values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue;
let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0);
const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)<capOf(big)&&!S.biz.some(b=>b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a));
// The spare is there for when the big link's trench is cut, so it has to live in another trench.
if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);}
for(const l of small.reverse()){if(cap-capOf(l)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}},
for(const l of small.reverse()){if(cap-capOf(l)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}},
};
// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once,
// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week
@ -275,23 +279,51 @@ const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,r
function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing
// is the yardstick (routed again first if this shift already changed the network); R is put back after.
function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){compute();X.dirty=false;}
const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{};
// is the yardstick (routed again first if this shift already changed the network). Both routings are steps the day
// answers (OPS_ROUTE, then {dark}: opsDarkTrial(), in play in the route worker).
const OPS_ROUTE={route:true};
function* opsDark(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;}
return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});}
// The test itself, on the game it is given: R is put back after.
function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0;
try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);}
finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}}
// The same test overtaken by an action: its checks, and today's routing as the yardstick, as the game is now.
function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l||S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;
return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first.
function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}}
// The links between each pair of cities, VXCs left out.
function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}return by;}
const opsDecomWaits=()=>[...opsPairs().values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'));
const OPS_ORDER=['repair','routers','transit','ports','optup','optics','caches','ix','pni','decom'];
// The shift: once per game day from dayTick, after outages and events have had their turn.
function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// One shift. Like a day (dayRun()), it is a generator: each yield is a compute() it needs, answered by the route worker
// in play, so the shift never routes on the page. opsDay() runs it in one go.
function opsDay(d){dayGo(opsRun(d),(g,v)=>g.next(v));}
function* opsRun(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// A new week: last week's tally becomes the shift report, and the one NOC notice of the week.
const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w<w){O.rep=O.wk;logNote(`<b>${esc(tr('ops.shift_report',{name:opsName()}))}</b> ${esc(opsWeekLine(O.rep))}`,'',[],{a:'ops'});}O.wk=opsWkNew(w);}
const X=opsShift();
// One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen.
opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}});
// Each order is a step of the day: a long shift lets the map draw between two (DAY_REST). The interface the orders
// click through (selection, tab, confirmation) goes on from where the last order left it, as in one go; the player's
// own is back in between.
let ui=null;
// One step of an order, muted (opsQuiet()): a plain order all at once, a generator up to its next yield. A bare yield
// is a rest; OPS_ROUTE or a {dark} test is a routing the day answers (v, passed back in).
const step=(k,st,v)=>opsQuiet(()=>{if(ui){UI.sel=ui.sel;UI.confirm=ui.cf;UI.tab=ui.tab;}st.ask=undefined;
try{if(!st.it){const r=OPS_RUN[k](X);if(r&&typeof r.next==='function')st.it=r;else st.done=true;}if(!st.done){const s=st.it.next(v);if(s.done)st.done=true;else st.ask=s.value;}}
catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);st.done=true;}
ui={sel:UI.sel,cf:UI.confirm,tab:UI.tab};});
const order=function*(k){const st={it:null,done:false};let v;for(;;){step(k,st,v);v=undefined;if(st.done)return;
if(st.ask===OPS_ROUTE)yield;else if(st.ask&&st.ask.dark)v=yield st.ask;else yield DAY_REST;}};
// Every order but the last, decommissioning, which reads today's loads: routed first when a job changed them.
for(const k of OPS_ORDER.slice(0,-1))if(O.on[k]){yield* order(k);yield DAY_REST;}
if(O.on.decom&&X.dirty&&opsDecomWaits()){yield;X.dirty=false;}
ui=null;if(O.on.decom)yield* order('decom');
const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]);
// Very rarely, and never under Change Freeze, the intern fat-fingers something harmless.
// Kevin rolls the same dice (so a seeded game plays the same whoever is hired) and catches it before pressing Enter.
@ -301,7 +333,7 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mo
e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);}}
if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo);
// Stopping at a budget changes nothing a route depends on: no recompute for that.
if(X.dirty)compute();
if(X.dirty)yield;
if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);}
// The day's detail stays in the Ops sheet; the NOC gets one notice a week (above).
const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);}

View file

@ -13,10 +13,16 @@ function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
return lead;}
// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots(p);return r;};
// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say).
// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them.
const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;};
function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0;
// Pending augments and earlier orders in this batch already own their future ports.
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p);
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
// Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G.
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;

View file

@ -1,13 +1,14 @@
/* 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.
Only the day uses it: the day is a generator (dayRun(), 10-day-tick.js) whose every yield is a routing it needs.
Each one goes to the worker with S, the day waits (no next day starts) and goes on 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}};
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}};
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';
@ -20,23 +21,52 @@ 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();};
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();};
}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;}
// 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;
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());}
// Runs the day's steps up to the next routing, posts it, and returns: rwDone() picks the day up when R is back. At a
// DAY_REST, a day that has run RW.budget ms already goes on after the next frame (RW.later), so a phone gets its frames
// between the steps of a big network's day. The day is still in flight meanwhile: no next day starts, nothing saves.
// v: what the step it resumes asked for (a sales trial's or the intern's fiber test's answer, dayAnswer()).
function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);}catch(e){tickErr(e);s={done:true};}v=undefined;
if(s.done){rwDayDone();return;}
if(s.value===DAY_REST){if(performance.now()-t0<RW.budget)continue;rwRest(g);return;}
// A routing, or a test (a sales trial, the intern's fiber test): the worker routes the game it is sent with the offer
// added or the fiber dark, and says yes or no.
const tr=dayAsk(s.value)?s.value:null,here=()=>{if(tr)v=dayAnswer(tr);else compute();};
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)});}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();}
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}}:{})});}
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
its own, and the browser draws the next frame between two tasks when it is due. Otherwise the day waits for that
frame. (Waiting for a frame every time made a day of many short steps take many frames: a slow phone fell behind.) */
const RW_CH=typeof MessageChannel==='function'&&!RW_IN?new MessageChannel():null,RW_TQ=[];
if(RW_CH)RW_CH.port1.onmessage=()=>{const f=RW_TQ.shift();if(f)f();};
function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75){RW_TQ.push(f);RW_CH.port2.postMessage(0);}
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);});}
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;}
let v;
// A sales trial: the customer it signed off, or null. Something routed here meanwhile (an action), or the worker
// 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();}
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();}
// 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();}}
/* 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
@ -52,5 +82,7 @@ const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[
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.
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);}
catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}}

View file

@ -19,7 +19,16 @@ const REQS={
skyfull:{only:true,bonus:0,l:()=>tr('requirements.promised_a_full_sky',{p:pct(PIE_PROMISE)}),ok:()=>pieHubs().some(id=>pieCov(id)>=PIE_PROMISE)},
puns:{l:tr('requirements.their_ceo_hates_puns_please_do'),bonus:.05,ok:()=>true},
};
function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
/* terrestrialPath() asked for many customers at once (the daily mood check, 10-day-tick.js): the islands the live land
links make, worked out the first time one asks (TERR.m: city -> island), and two cities with a land path are two
cities of one island. Walking the links is what costs (a dark fiber's capacity, every one of them), not the question.
TERR names the game and the routing count it was made for: an action between two steps of the day changes a link
only through after(), which routes, so the islands are worked out again; another game, and each question walks. */
let TERR=null;
function terrIslands(){const adj={};for(const l of S.links)if(!linkDown(l)&&!l.sub){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
const m=new Map();let n=0;for(const c in adj){if(m.has(c))continue;const q=[c];m.set(c,n);for(let h=0;h<q.length;h++)for(const v of adj[q[h]])if(!m.has(v)){m.set(v,n);q.push(v);}n++;}return m;}
function terrestrialPath(a,b){if(TERR&&TERR.S===S){if(TERR.gen!==RW.gen||!TERR.m){TERR.gen=RW.gen;TERR.m=terrIslands();}
if(a===b)return true;const A=TERR.m.get(a);return A!==undefined&&A===TERR.m.get(b);}const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b));
// Some requirements only make sense for some customers: nobody can reach another continent without getting wet.
const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b);

View file

@ -89,11 +89,13 @@ function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
return a;}
/* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and
teach each lesson once. */
function ddosNews(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
function ddosNews(){runNow(ddosNewsRun());}
// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug.
function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true;
toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}}
if(again)compute();
if(again)yield;
const T=S.stats.ddT||(S.stats.ddT={});
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97;

View file

@ -2,7 +2,12 @@
const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l);
// The wet season in the tropical north (November to April): floods close the tracks, so a cut on land takes twice as long to reach.
const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason();
function fireFailure(only){
/* failureRun() is a failure as a step of the day (10-day-tick.js): its yield is the routing that tells what it cost,
done by the route worker in play. fireFailure() is the same failure all at once, routed on the spot. */
function fireFailure(only){runNow(failureRun(only));}
// A step of the day played all at once: every routing it asks for, on the spot (tests, a failure outside a day).
function runNow(g){dayGo(g,(g,v)=>g.next(v));}
function* failureRun(only){
const opts=[];
const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);}
@ -111,13 +116,15 @@ function fireFailure(only){
}else if(type==='fabric'){
const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3);
addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0});
}else if(type==='ddos'){ddosAttack();return;
}else if(type==='ddos'){ddosAttack(false);yield;yield* ddosNewsRun();return;
}
compute();
// This failure's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const last=S.inc[S.inc.length-1];
yield;
if(!last)return;
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost&&S.inc.includes(last)?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
sfx('alert');
}
const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);

View file

@ -1,3 +1,8 @@
/* An event that cuts cables or power routes at once, as its last move (evRoute()). As a step of the day (eventRun())
that routing is the day's next yield instead: nothing reads R in between, so it is the same routing. */
let EV_DEFER=null;
const evRoute=()=>{if(EV_DEFER)EV_DEFER.n++;else compute();};
function* eventRun(){const k={n:0};EV_DEFER=k;try{fireEvent();}finally{EV_DEFER=null;}for(let i=0;i<k.n;i++)yield;}
function fireEvent(){
const opts=['viral','price','grant'];
if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
@ -36,16 +41,16 @@ function fireEvent(){
if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;}
if(e==='typhoon'){const c=pick(['mnl','ceb','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]);
if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;}
p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');compute();return;}
if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');compute();return;}
p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');evRoute();return;}
if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');evRoute();return;}
if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.baltic_cable_damaged_a_cargo_ship'),'goal');return;}
const dur=15+Math.floor(Math.random()*15),en=N_('events.a_cargo_ship_dragged_its_anchor');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;}
if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.cables_cut_in_the_red_sea'),'goal');return;}
const dur=20+Math.floor(Math.random()*15),en=N_('events.a_ship_drifting_without_power');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;}
if(e==='golden'){S.ev.golden=S.day+7;toast(tr('events.golden_week_demand_in_mainland_china'),'goal');return;}
if(e==='gfw'){S.ev.gfw=S.day+10;toast(tr('events.the_border_got_stricter_cross_border'),'bad');sfx('alert');return;}
if(e==='viral'){S.ev.viral=S.day+8;toast(tr('events.new_season_of_stranger_pings_just'),'goal');}

View file

@ -18,25 +18,29 @@ const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000
function mkWeak(l){const trc=l.trench||l.id,adj={};
for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;}
function mkTick(d){const M=S.monkey;if(!M)return;
function mkTick(d){runNow(mkTickRun(d));}
// The monkey's day as a step of the day: a snip's yield is the routing that tells what it cost.
function* mkTickRun(d){const M=S.monkey;if(!M)return;
if(!mkElig()){if(M.on)mkLeave('quiet');return;}
// The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was.
if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120;
if(!M.on){if(d<M.next)return;if(S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;}
if(d>=M.until){mkLeave();return;}
if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}}
if(d>=M.snip){yield* mkSnipRun();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}}
function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121);
S.stats.mkMet=(S.stats.mkMet||0)+1;
Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home});
toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive');
if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);}
function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return;
function mkSnip(){runNow(mkSnipRun());}
function* mkSnipRun(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return;
// Weak spots first: a sample keeps this cheap on big networks.
const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x]));
const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served;
hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a;
addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},'');
compute();const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp;
// The snip's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const i=S.inc[S.inc.length-1];yield;const imp=Math.max(0,before-R.served);if(i)i.impact=imp;
const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++;
toast(felt?`<b>🐒 ${incTitle('cut')}</b><br>${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert');
if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}}

View file

@ -1,13 +1,33 @@
/* ---------- daily tick ---------- */
/* 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. */
/* A day is a few steps around its routing: dayPre() (the world moves on), then dayPost() (bills, moods, offers, the
intern's shift). dayRun() is the whole day as a generator: each yield is a compute() it needs before going on, the
day's own routing first, then a recompute after a failure or after the intern's jobs. dayTick() (tests, the fallback)
answers each with compute() on the spot; in play the route worker answers them (28-route-worker.js), and the page
only runs the steps in between. Same steps, same random numbers either way: routing draws none. (A failure
routes as a step too, failureRun(); an event still routes on the spot: it reads R right away, every few weeks.) */
// UI.tick: what the day itself announces, which quiet notifications may keep to the NOC log.
function dayTick(){UI.tick=true;try{const d=dayPre();if(d===false)return;compute();dayPost(d);}finally{UI.tick=false;}}
function dayPre(){
// yield DAY_REST: no routing, only a place where the day may let a frame through when it has run long (rwGo()).
const DAY_REST=1;
function* dayRun(){const d=yield* dayPreRun();if(d===false)return;yield;yield* dayPost(d);}
// A step yields undefined (a routing), DAY_REST, or a sales trial ({trial}, 95-standing-orders.js) to answer with the
// customer it signs off or null (dayAnswer()): here at once, in play by the route worker.
const dayStep=(g,v)=>{UI.tick=true;try{return g.next(v);}finally{UI.tick=false;}};
// The intern's fiber test ({dark}, 95-standing-orders.js) is asked the same way, and answers true or false.
const dayAsk=y=>!!y&&(!!y.trial||!!y.dark);
const dayAnswer=y=>y.dark?opsDarkTrial(y):offerTrial(y.trial,y.hx);
// The same trial overtaken by an action (a customer gone shifts S.biz, so hx no longer points at the right ones):
// its checks, the customer and who is happy, made again on the game as it is now.
const dayAgain=y=>{if(y.dark)return opsDarkAgain(y);const o=y.o;if(!o||!S.offers.includes(o))return null;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;};
function dayGo(g,step=dayStep){let v;for(let s=step(g);!s.done;s=step(g,v)){v=undefined;const y=s.value;if(y===DAY_REST)continue;if(dayAsk(y))v=dayAnswer(y);else compute();}}
function dayTick(){dayGo(dayRun());}
// dayPre(): the world's morning all at once; dayPreRun() the same with a place or two to let a frame through.
function dayPre(){const g=dayPreRun();for(;;){const s=g.next();if(s.done)return s.value;}}
function* dayPreRun(){
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);
yield DAY_REST;
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
{const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;}
@ -27,13 +47,14 @@ function dayPre(){
// resolve incidents
for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i);
toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);}
yield DAY_REST;
// eyeball growth / churn uses last computed service
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));}
return d;}
function dayPost(d){
ddosNews();ddosTrack();
function* dayPost(d){
yield* ddosNewsRun();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)/monLen(d);
S.stats.peak=Math.max(S.stats.peak,R.served);
@ -48,7 +69,7 @@ function dayPost(d){
(a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1;
toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}}
// businesses mood
const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));for(const b of S.biz.slice()){if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b);
const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b);
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
else if(S.day-(b.since||0)<15){}
else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm;
@ -58,11 +79,13 @@ function dayPost(d){
else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause();
toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:'')+(paused?`<br><b>${tr('common.game_paused')}</b>`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');}
else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`<br><i>${esc(why)}</i>`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}}
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}}finally{TERR=null;}
yield DAY_REST;
// contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js)
clDay(d);
// the sales desk: meetings booked, golf played (38-sales-desk.js)
salesDay(d);slRenDay(d);
salesDay(d);yield* slRenRun(d);
yield DAY_REST;
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
@ -74,19 +97,21 @@ function dayPost(d){
S.offers=S.offers.filter(o=>o.exp>d);
brTick();
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);}
yield DAY_REST;
// failures & events
// Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never.
let dirty=false;const cm=chaosMul();
// A visiting chaos monkey does the breaking instead (its snips replace these while it is here).
mkTick(d);
if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);}
yield* mkTickRun(d);
if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;yield* failureRun();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);}
// Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year).
if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;fireFailure('cut');}}
if(cm&&d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);}
if(dirty)compute();
if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;yield* failureRun('cut');}}
if(cm&&d>=S.nextEvent){dirty=true;yield* eventRun();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);}
if(dirty)yield;
// the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them
slAutoDay(d);
opsDay(d);
yield* slAutoRun(d);
if(opsHired())yield DAY_REST;
yield* opsRun(d);
if(S.pie){pieDay(d);pieTier();}
// payday floaters
if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}

View file

@ -4,6 +4,9 @@ function frame(now){
// Schedule the next frame first: one bad lookup in a day tick must not freeze the whole game.
if(!window.__TUBES_TEST__)requestAnimationFrame(frame);
const dt=Math.min(250,now-last);last=now;
// A day's steps take half a frame at most before letting one through (rwGo()): 8 ms at 60 Hz, 3 ms on a 240 Hz screen,
// where 8 ms would be two frames lost. The frame time is followed slowly, a long frame counting as two at most.
if(dt>0){RW.fms=RW.fms?RW.fms*0.95+Math.min(dt,RW.fms*2)*0.05:dt;RW.budget=Math.min(8,Math.max(3,RW.fms/2));}
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
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.
@ -14,12 +17,16 @@ function frame(now){
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(DIAG.on)diagFrame(now);
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
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
function runClock(dt){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);}}}
// 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.
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);}}}
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