Merge upstream: Lambda Bazaar, traffic badges, moving customers and faster routing (3.3.0)
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
CHANGELOG.md: upstream's released sections as they are; main's 11 Unreleased bullets kept under Unreleased. scripts/lib/route-fuzz.js: upstream's skip of dashboard tabs the base lacks, plus main's trimming of args the base's buttons lack. src/game/10-catalog/40-ports.js: upstream's one-pass portsAt(); an express still takes ports per channel at its ends. src/game/10-catalog/60-reach-and-subsea.js: upstream's dfLit/dfCap0/dfOn (managed waves carved out); capOf() keeps xp and sat. src/game/60-features/80-new-game.js: upstream's vol and cm in a new game, with main's ip4, rgen, mp and saved-shape fields. src/game/60-features/95-standing-orders.js: upstream's portsAt, cachePlan and promiseCheck, inside main's build-standard routers order, optup marks, opsDarkPre and decom gone list; opsPairs still leaves satellites out. src/game/80-simulation/30-compute.js: upstream's routing core; main's satellite edges (SATN) pass into it, express risks and sat/ip4 money stay. src/game/80-simulation/29-route-core.js: main's satellite latency note moved into the core, where upstream moved the flow loop. src/game/80-simulation/40-billing.js: main's linkCut() and xp/sat in linkDown(), with upstream's dfOn(). src/game/80-simulation/50-sanitize.js: upstream's cmClean listings and cmFix/volFix; main keeps the xp/sat kinds, mpSanitize, ip4Fix and satSanitize. src/game/80-simulation/60-requirements.js: upstream's shared diversity graph; an express link carries the list of trenches it rides. src/game/91-save.js: upstream's saves in the worker, except a multiplayer session network, whose text is made on the page (mpSave) so the server gets the very save the slot holds; bootNotes() kept. src/game/91-slots.js: upstream's slot text and day, with main's mp badge on a slot. src/game/93-ui/70-link-panels.js: a fiber says both its managed waves and the expresses it carries. src/game/94-dashboard/60-dashboard.js: upstream's carried tile, main's themed demand line. src/game/95-modals/70-link-modal.js: main's Express tab, then upstream's hint for a coast no cable lands on (#321). After the merge: - Moving a circuit: a path over an express shares the trenches of the fibers it rides, so it is never called fully diverse from a path along them (test in express-fiber). - The capacity market and moving customers leave the slots expresses hold (test in express-fiber; no code change needed). - The NOC log keeps only the kinds a reload keeps: the market's info/warn news is a plain line, live as after a reload. - New acts classified for server-run play: market and path moves sent, marketOpen and pathOpen local; pathPin's path may be longer than 64 characters. - Server-play fixtures written again (new cm and vol fields); the dark-mode test reads mapStill()'s three states. - A big multiplayer network that moved on still pushes its save to the server (test in multiplayer). - The full suite ran on jsdom 31.0.0 and playwright-core 1.65.0, the versions the merged lockfile pins.
This commit is contained in:
commit
61e31c53d3
105 changed files with 3281 additions and 664 deletions
|
|
@ -9,20 +9,29 @@ const cachePerPort=(c,g)=>{const p=S.pops[c];return p?Math.max(1,Math.floor(port
|
|||
const cacheG=x=>x.g===CACHE_BIG?CACHE_BIG:CACHE_CAP,cacheMo=x=>x.g===CACHE_BIG?CACHE_BIG_MO:CACHE_MO,cachesMo=()=>S.caches.reduce((a,x)=>a+cacheMo(x),0);
|
||||
const cacheBox=c=>{const p=S.pops[c];return p&&portG(p.rgen||0)>=CACHE_BIG?{g:CACHE_BIG}:{};};
|
||||
function cachePorts(c,extra=[],g){const n={a:0,b:0};for(const x of S.caches)if(x.city===c)n[x.site==='b'?'b':'a']+=cacheG(x);for(const x of extra)n[x.site==='b'?'b':'a']+=cacheG(x);
|
||||
const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);}
|
||||
return cachePortsOf(c,n,g);}
|
||||
// n: the Gbps of boxes per site.
|
||||
function cachePortsOf(c,n,g){const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);}
|
||||
const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c);
|
||||
/* A dark fiber channel takes as many router ports at each end as the optic's speed needs (#256): a pluggable sits
|
||||
in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */
|
||||
const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;};
|
||||
function portsUsed(c,g){let u=0;
|
||||
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'&&l.kind!=='xp'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);}
|
||||
function portsUsed(c,g){return portsAt([c],g).get(c);}
|
||||
/* The router ports in use at each of the cities cs, in one pass over the network: the intern sizes every POP each day,
|
||||
and a pass per POP was a pass over every link, PNI and cache box for each. Each city's count adds the same things in
|
||||
the same order as on its own. g: another router model at those cities (what would fit). */
|
||||
function portsAt(cs,g){const u=new Map(),box=new Map();for(const c of cs){u.set(c,0);box.set(c,{a:0,b:0});}
|
||||
const add=(c,v)=>{const x=u.get(c);if(x!==undefined)u.set(c,x+v);};
|
||||
for(const l of S.links){if(l.kind==='vxc')continue;for(const c of l.a===l.b?[l.a]:[l.a,l.b]){if(!u.has(c))continue;
|
||||
if(l.kind!=='df'&&l.kind!=='xp'){add(c,1);continue;}for(const o of l.ch||[])add(c,chPorts(o,c,g));}}
|
||||
// A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours.
|
||||
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
|
||||
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
|
||||
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
|
||||
if(S.myIx[c])u+=1;
|
||||
for(const x of S.nni||[])if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
|
||||
u+=cachePorts(c,[],g);
|
||||
for(const t of S.transit)if(!t.pz)add(t.city,PORT_SLOT(t.tier)*(t.n||1));
|
||||
for(const x of S.pni)add(x.city,PORT_SLOT(x.tier)*(x.n||1));
|
||||
for(const c of u.keys()){for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])add(c,PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1));
|
||||
if(S.myIx[c])add(c,1);}
|
||||
for(const x of S.caches){const n=box.get(x.city);if(n)n[x.site==='b'?'b':'a']+=cacheG(x);}
|
||||
for(const x of S.nni||[])add(x.city,PORT_SLOT(x.tier)*(x.n||1));
|
||||
for(const c of u.keys())add(c,cachePortsOf(c,box.get(c),g));
|
||||
return u;}
|
||||
function portsMax(c,g,rt){const p=S.pops[c];if(!p)return 0;return RG[g===undefined?(p.rgen||0):g].ports*(rt||p.routers||1);}
|
||||
function portGate(c,add){if(!S.pops[c]||add<=0)return true;const u=portsUsed(c),m=portsMax(c);if(u+add<=m+1e-9)return true;
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ const subUpgradeReady=(l,k)=>l.kind==='df'&&l.sub&&l.own&&Number.isFinite(l['sub
|
|||
const subUpgradeCost=(l,k)=>SUB_UPGRADES[k].cost+(k==='engineering'?Math.round(l.km*1000):0);
|
||||
// Pending transmission work follows the construction schedule. Keep the actual
|
||||
// shift (the last crew purchase can save fewer than 30 days) and completed work.
|
||||
function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;
|
||||
function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;layHold(l,shift,day);
|
||||
if(l.kind==='df'&&l.own&&l.sub)for(const k of Object.keys(SUB_UPGRADES)){
|
||||
const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift);
|
||||
}l.ready=ready;
|
||||
|
|
@ -68,7 +68,14 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1)
|
|||
// all its channels. Nothing changes while a frame is drawn, so draw() keeps the answers in DFC for that frame.
|
||||
let DFC=null;
|
||||
const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;};
|
||||
const dfCap0=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
|
||||
// dfLit: everything the optics carry; dfCap0: what is left for your own traffic once managed waves sold on it (mwG(),
|
||||
// the capacity market) are carved out. A fiber's channels come in runs of one optic (a big one: a thousand of them):
|
||||
// optG() once per run, added up in order.
|
||||
const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0,o=null,x=0;for(const c of ch){if(c!==o){o=c;x=optG(c,l);}g+=x;}const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
|
||||
const dfCap0=l=>Math.max(0,dfLit(l)-mwG(l));
|
||||
// Whether a fiber carries anything for you (linkDown() asks of every fiber, often): dfCap(l)>0 without adding up every
|
||||
// channel. An optic out of service, or managed waves sold on it, take the sum.
|
||||
const dfOn=l=>{if(l.ready>S.day||l.eqDown>S.day)return false;if(l.chFail&&l.chFail.until>S.day||mwG(l)>0)return dfCap(l)>0;let o=null;for(const c of l.ch||[])if(c!==o){o=c;if(optG(c,l)>0)return true;}return false;};
|
||||
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):l.kind==='xp'?xpG(l):l.kind==='sat'?l.g:LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1);
|
||||
// A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears.
|
||||
const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ const BIZ_T={
|
|||
event:{l:tr('common.event_network'),opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['Carnaval Parade','Diwali Streaming Night','The Big Football Final','NANOG 99','APRICOT 2027','DENOG 18','UKNOF 56','RIPE 94','DKNOG 16','Burning Router Festival','Euro-Pop Song Contest','Formula Ping Grand Prix','The Big Game','Olympic Pings','A Pop Megastar Stadium Tour','LAN Party of the Century','The Keynote (One More Thing)','Gamer-Con Expo','Oktoberfest Livestream']},
|
||||
sdwan:{l:tr('businesses.sd_wan_for_a_chain'),opts:[1,2,5,10],rate:0,l2:true,sdwan:true,km:0,lv:2,names:['Kebab Kingdom','Pretzel Palace','Burger Router Inc.','Café Latte-ncy','Hardware Hut Stores','Pharma-See Pharmacies','Bank of Tiny Branches','Supermarket Superhighway','Fitness Pings Gyms','Hotel Hops Group','Doughnut Data Diners']},
|
||||
wwave:{l:tr('common.wholesale_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','G&T (Gin and Transit)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']},
|
||||
// A managed wave (the capacity market): carved out of capacity you lit; b.g is its size (100 or 400G), b.slots how many.
|
||||
mwave:{l:tr('market.managed_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Lambda Lambda Lambda','Coherent Thoughts Inc.','Photon Express','Transponder Tribe','Sea Change Networks','Spectrum Spectacle','Wavelength Wanderers','Muxed Signals Ltd.']},
|
||||
dfpair:{l:tr('businesses.dark_fiber_pair_lease'),opts:[1],rate:0,fiber:true,lv:3,names:['A Hyperscaler Who Shall Not Be Named','Goggle Fiber Division','Faceplant Infra','Amazin’ Backbone Team','A Very Secretive Trading Firm']},
|
||||
scrub:{l:tr('businesses.ddos_protection_dia'),opts:[1,5,10,20],rate:900},
|
||||
aiwan:{l:tr('businesses.ai_wan_between_two_ai_factories'),opts:[3200,6400,12800],rate:0,l2:true,div:true,mega:true,km:0.45,lv:4,names:['Fairweather AI WAN','Planet-Scale Superfactory Link','Two Brains One Model Inc.','Distributed Godlike Compute','The Gigawatt Handshake']},
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ const GOALS=[
|
|||
// (37-cable-broker.js). Ids of their own, so a save keeps the ladder it ran. Rewards are larger: glass costs more.
|
||||
const BROKER_GOALS=[
|
||||
{id:'bk_df',t:tr('goals.light_your_own_dark_fiber'),d:tr('broker.goal_df_d'),r:25000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)},
|
||||
{id:'bk_wave',t:tr('broker.goal_wave'),d:tr('broker.goal_wave_d'),r:40000,ok:()=>S.biz.some(b=>b.type==='wwave'||b.type==='capw'&&!capPend(b))},
|
||||
{id:'bk_wave',t:tr('broker.goal_wave'),d:tr('broker.goal_wave_d'),r:40000,ok:()=>S.biz.some(b=>b.type==='wwave'||b.type==='mwave'||b.type==='capw'&&!capPend(b))},
|
||||
{id:'bk_pair',t:tr('broker.goal_pair'),d:tr('broker.goal_pair_d'),r:50000,ok:()=>S.biz.some(b=>(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')&&!capPend(b))},
|
||||
{id:'bk_sea',t:tr('broker.goal_sea'),d:tr('broker.goal_sea_d'),r:150000,ok:()=>S.links.some(l=>ownGlassL(l)&&l.sub)},
|
||||
{id:'bk_deal',t:tr('broker.goal_deal'),d:tr('broker.goal_deal_d'),r:100000,ok:()=>(S.stats.capDone||0)>0},
|
||||
|
|
|
|||
|
|
@ -12,12 +12,12 @@ let BIGEYE=null;const bigEye=()=>BIGEYE||(BIGEYE=CITIES.slice().sort((x,y)=>y.P-
|
|||
let SPOTC=null;
|
||||
function spots(){const lv=lvl(),k=S.day+'|'+lv+'|'+S.links.length+'|'+Object.keys(S.pops).length+'|'+charter();if(SPOTC&&SPOTC.s===S&&SPOTC.k===k)return SPOTC.v;const v=spots0(lv);SPOTC={s:S,k,v};return v;}
|
||||
function spots0(lv){const out=[];if(gatesOpen()||S.scn)return out;const up=t=>BIZ_T[t].lv>lv,mine=Object.keys(S.pops).filter(bizCity);
|
||||
if(up('hft')){const f=FIN.filter(c=>S.pops[c]);for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],ms=bestLat(a,b);if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)});}}
|
||||
if(up('hft'))for(const [a,b,ms] of latPairs(FIN.filter(c=>S.pops[c])))if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)});
|
||||
const dci=['onramp','ai','hyper'].filter(up);
|
||||
if(dci.length)for(const l of S.links){if(l.kind!=='df'||l.sub||l.ready>S.day||linkDown(l))continue;const g=dfCap(l);
|
||||
for(const t of dci){const T=BIZ_T[t];if(g>=T.opts[0]*SPOT_DF&&(!T.div||reqCan('diverse',{city:l.a,city2:l.b})))out.push({t,a:l.a,b:l.b,k:'df',n:g});}}
|
||||
if(up('sov')){const by={};for(const c of mine)(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);
|
||||
for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(diversePaths(cs[i],cs[j]))out.push({t:'sov',a:cs[i],b:cs[j],k:'div',n:0});}
|
||||
const g=divGraph();for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(divOn(g,cs[i],cs[j]))out.push({t:'sov',a:cs[i],b:cs[j],k:'div',n:0});}
|
||||
if(up('cgame')&&R)for(const c of bigEye())if(S.pops[c]&&S.pops[c].bb&&sfOf(R,c)>=0.95)out.push({t:'cgame',a:c,b:null,k:'eye',n:0});
|
||||
return out;}
|
||||
// A spotted customer starts at the smallest size its type comes in; your level makes them bigger and more frequent.
|
||||
|
|
@ -79,10 +79,10 @@ const RG_GLASS=Math.max(...Object.values(OPT).map(o=>o.rg)),rgGlass=g=>broker()&
|
|||
const latPay=()=>charter()==='boutique'?LAT_PAY:1;
|
||||
// The fastest a leased wave or fiber gets between two cities: overland, or the quickest cable on the route.
|
||||
function leasedLat(a,b){let best=isSub(a,b)?Infinity:kmBetween(a,b)*1.25/200;for(const c of cablesFor(a,b))best=Math.min(best,c.km*Math.min(CAB[c.cid].lat||1,1.25)/200);return best;}
|
||||
const ownGlass=l=>l.kind==='df'&&l.own&&l.ready<=S.day&&dfCap(l)>0;
|
||||
const ownGlass=l=>l.kind==='df'&&l.own&&dfOn(l);
|
||||
let SOLC=null;
|
||||
function solRoutes(){const k=S.day+'|'+S.links.length+'|'+S.links.reduce((n,l)=>n+(l.ch||[]).length,0);if(SOLC&&SOLC.s===S&&SOLC.k===k)return SOLC.v;
|
||||
const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=bestLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}
|
||||
const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(const [a,b,o] of latPairs(f,ownGlass)){const l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}
|
||||
SOLC={s:S,k,v};return v;}
|
||||
const solCust=()=>S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].lat&&b.mood>=50&&reqOk(b)).length;
|
||||
// What each charter promises, as the picker and the agent's docs say it.
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ const glassKm=()=>S.links.reduce((a,l)=>a+(ownGlassL(l)?l.km:0),0);
|
|||
// The continents your own subsea cables land on.
|
||||
function cableConts(){const r=new Set();for(const l of S.links)if(ownGlassL(l)&&l.sub)for(const c of [l.a,l.b])r.add(CITY[c].reg);return r.size;}
|
||||
// Capacity other carriers buy from you: alien waves, fiber pairs and capacity deals (once delivered).
|
||||
const CAP_TYPES=['wwave','dfpair','pairs','capw','capsub','capfib'];
|
||||
const CAP_TYPES=['wwave','mwave','dfpair','pairs','capw','capsub','capfib'];
|
||||
const capSold=b=>CAP_TYPES.includes(b.type)&&!capPend(b);
|
||||
const capSalesMo=()=>S.biz.reduce((a,b)=>a+(capSold(b)?bizMo(b):0),0);
|
||||
// Lit capacity sold, in Gbps: waves (400G each) and subsea capacity. A dark pair is the buyer's to light.
|
||||
const capSoldG=()=>S.biz.reduce((a,b)=>a+(!capSold(b)?0:b.type==='wwave'?(b.slots||1)*400:b.type==='capw'||b.type==='capsub'?b.bw:0),0);
|
||||
const capSoldG=()=>S.biz.reduce((a,b)=>a+(!capSold(b)?0:b.type==='wwave'?(b.slots||1)*400:b.type==='mwave'?(b.slots||1)*(b.g||100):b.type==='capw'||b.type==='capsub'?b.bw:0),0);
|
||||
// Two hops of your own glass through one city, each lit to at least g.
|
||||
function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap(l)>=g)for(const [c,o] of [[l.a,l.b],[l.b,l.a]])(by[c]=by[c]||new Set()).add(o);
|
||||
return Object.values(by).some(s=>s.size>=2);}
|
||||
|
|
|
|||
75
src/game/60-features/37-customer-paths.js
Normal file
75
src/game/60-features/37-customer-paths.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
/* ---------- moving a customer to another path between the same two POPs ---------- */
|
||||
/* Fiber customers (an alien wave, leased pairs) sit on one fiber, b.link, so they move to a parallel one. Circuits have
|
||||
no link of their own: routing picks their path every day. Moving one pins it to a list of cities, b.pin. While a link
|
||||
on the pin is down it follows routing, as a protected wave would, and it comes back by itself. */
|
||||
const PATH_ALT=3,PATH_FAR=1000;
|
||||
const pathKind=b=>{const T=BIZ_T[b.type];if(pzOn()||!T||capPend(b)||!b.city2)return '';return T.fiber?(b.link?'fiber':''):T.l2&&!b.sites?'circuit':'';};
|
||||
const trenchOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
|
||||
const pathCity=c=>CITY[c].name,pathStr=p=>p.map(pathCity).join(' → ');
|
||||
const samePair=(l,a,b)=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a);
|
||||
const fibLab=l=>tr('customer_paths.fiber_label',{name:l.cname?esc(l.cname):capName(l),km:Math.round(l.km).toLocaleString()});
|
||||
// Why this fiber cannot take this customer, in the same terms as the market that sold it: waves only where the broker
|
||||
// could sell them, after the share kept back for your own traffic.
|
||||
function fiberNo(b,l){const n=b.slots||1,hold=S.cm.hold;
|
||||
if(b.type==='wwave'){const free=freeCh(l),spare=cmSpare(l,'spec');return spare>=n?'':free<n?tr('customer_paths.not_enough_free_channels',{free:Math.max(0,free),n}):tr('customer_paths.not_enough_spare_channels',{free:spare,n,hold});}
|
||||
// A managed wave rides one channel of your lit capacity, so it needs an optic that big and that many Gbps spare.
|
||||
if(b.type==='mwave'){const g=b.g||100,free=Math.max(0,cmFreeG(l));if(cmOptG(l)<g)return tr('customer_paths.needs_a_g_channel',{g:fmtCap(g)});
|
||||
return free>=n*g?'':tr('customer_paths.not_enough_spare_capacity',{free:fmtCap(free),g:fmtCap(n*g),hold});}
|
||||
if(!l.own)return tr('customer_paths.only_your_own_fiber_rents_pairs');
|
||||
if(b.type==='dfpair')return pairFree(l)?'':tr('customer_paths.its_spare_pairs_are_taken');
|
||||
return S.biz.some(x=>x!==b&&x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type))?tr('customer_paths.its_spare_pairs_are_taken'):'';}
|
||||
// The working fibers it could go to, those on another trench first.
|
||||
function fiberTargets(b){const cur=S.links.find(l=>l.id===b.link),t=cur?trenchOf(cur):'';
|
||||
return S.links.filter(l=>l.kind==='df'&&l.id!==b.link&&samePair(l,b.city,b.city2)&&l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day))
|
||||
.map(l=>({l,diverse:trenchOf(l)!==t,no:fiberNo(b,l)})).sort((x,y)=>(y.diverse-x.diverse)||(!!x.no-!!y.no)||x.l.km-y.l.km);}
|
||||
// The live backbone by city pair, as compute() sees it: every link of a pair is one edge.
|
||||
function pathEdges(){const E={},N={};for(const l of S.links){if(linkDown(l)||!popUp(l.a)||!popUp(l.b))continue;const k=edgeKey(l);let e=E[k];
|
||||
if(!e){e=E[k]={k,a:l.a,b:l.b,w:Infinity,km:Infinity,lat:Infinity,cap:0,load:0,ts:new Set()};(N[l.a]=N[l.a]||[]).push(e);(N[l.b]=N[l.b]||[]).push(e);}
|
||||
// An express (65-express.js) runs in the trench of every fiber it rides.
|
||||
e.w=Math.min(e.w,pairW(k,l.km));e.km=Math.min(e.km,l.km);e.lat=Math.min(e.lat,linkLat(l));e.cap+=capOf(l);e.load+=(R.load&&R.load[l.id])||0;if(l.kind==='xp')for(const t of xpRisk(l))e.ts.add(t);else e.ts.add(trenchOf(l));}
|
||||
return {E,N};}
|
||||
const hopKey=(a,b)=>a<b?a+'|'+b:b+'|'+a;
|
||||
// The cheapest path from a to b, as a list of cities.
|
||||
function pathWalk(G,a,b,cost){const dist={[a]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null||u===b)break;done.add(u);
|
||||
for(const e of G.N[u]||[]){const v=e.a===u?e.b:e.a,nd=ud+cost(e);if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=u;}}}
|
||||
if(dist[b]===undefined)return null;const p=[b];while(p[0]!==a)p.unshift(prev[p[0]]);return p;}
|
||||
const pathHops=(G,p)=>{const o=[];for(let i=1;i<p.length;i++){const e=G.E[hopKey(p[i-1],p[i])];if(!e)return null;o.push(e);}return o;};
|
||||
// The panels ask for every pinned customer: one graph per routing (a new R), not one per customer.
|
||||
let PIN_G=null;
|
||||
const pinG=()=>{const c=PIN_G;if(!c||c.R!==R||c.S!==S||c.d!==S.day||c.n!==S.links.length)PIN_G={R,S,d:S.day,n:S.links.length,G:pathEdges()};return PIN_G.G;};
|
||||
const pinUp=b=>!!pathHops(pinG(),b.pin);
|
||||
// Where the circuit runs today. Scenic circuits remember it; the others take the shortest path of their kind.
|
||||
function pathNow(b,G){if(b.pin&&pathHops(G,b.pin))return b.pin;
|
||||
const r=R.l2route&&R.l2route[b.id+'>'+b.city+'>'+b.city2];if(r&&r[0]){const p=r[0].ns.slice();if(p[0]!==b.city)p.reverse();if(pathHops(G,p))return p;}
|
||||
return pathWalk(G,b.city,b.city2,b.route==='fast'?e=>e.lat+0.05:e=>e.w);}
|
||||
// Paths that avoid what is in use: each one is priced as if every trench already used were nearly unusable, so the next
|
||||
// one is the most diverse there is, sharing a trench only if there is no way round it.
|
||||
function circuitTargets(b){const G=pathEdges(),now=pathNow(b,G);if(!now)return {now:null,alts:[]};
|
||||
const hops=pathHops(G,now)||[],used=new Set(),seen=new Set([now.join()]),own=new Set(hops.map(e=>e.k)),got=R.l2&&R.l2[b.id]||0,alts=[];
|
||||
const nowT=new Set();for(const e of hops)for(const t of e.ts){nowT.add(t);used.add(t);}
|
||||
for(let i=0;i<PATH_ALT+1&&alts.length<PATH_ALT;i++){const p=pathWalk(G,b.city,b.city2,e=>{for(const t of e.ts)if(used.has(t))return (e.w+1)*PATH_FAR;return e.w+1;});if(!p)break;
|
||||
const h=pathHops(G,p);for(const e of h)for(const t of e.ts)used.add(t);if(seen.has(p.join()))continue;seen.add(p.join());
|
||||
alts.push({p,shared:h.filter(e=>[...e.ts].some(t=>nowT.has(t))).length,km:h.reduce((a,e)=>a+e.km,0),lat:h.reduce((a,e)=>a+e.lat+0.05,0),
|
||||
room:Math.max(0,Math.min(...h.map(e=>e.cap-e.load+(own.has(e.k)?got:0))))});}
|
||||
alts.sort((x,y)=>x.shared-y.shared||x.lat-y.lat);return {now,alts};}
|
||||
// The pin as compute() walks it. Null while a link on it is down, and routing takes over.
|
||||
function pinRoute(p,edges){const path=[];for(let i=1;i<p.length;i++){const e=edges[hopKey(p[i-1],p[i])];if(!e)return null;path.push(e);}return {path,ni:p.map(x=>CIDX[x]),share:1};}
|
||||
// Under a customer in the panels.
|
||||
function pathCtl(b){if(!pathKind(b))return '';
|
||||
const pin=b.pin?`<div class="meta">${tr('customer_paths.pinned_to_path',{path:esc(pathStr(b.pin))})}${pinUp(b)?'':` · <b style="color:var(--bad)">${tr('customer_paths.that_path_is_down')}</b>`}</div>`:'';
|
||||
return `${pin}<div class="btns">${btn(tr('customer_paths.move_to_another_path'),'pathOpen',{id:b.id},'ghost sm')}</div>`;}
|
||||
function pathModal(b){const a=pathCity(b.city),z=pathCity(b.city2),k=pathKind(b);let h=`<div style="display:flex;align-items:center"><h2 style="font-size:24px">${tr('customer_paths.move_name',{name:esc(b.name)})}</h2><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>`;
|
||||
const row=(nm,meta,tag,button)=>`<div class="row"><div class="grow"><div class="nm">${nm}${tag?` <span class="tag st">${tag}</span>`:''}</div>${meta?`<div class="meta">${meta}</div>`:''}</div>${button}</div>`;
|
||||
if(k==='fiber'){const cur=S.links.find(l=>l.id===b.link),T=fiberTargets(b);
|
||||
h+=`<p class="lead" style="margin-top:6px">${tr('customer_paths.this_customer_rides_one_fiber',{a,b:z})}</p>`;
|
||||
if(cur)h+=`<div class="kv"><span>${tr('customer_paths.now_on')}</span><b>${fibLab(cur)}</b></div>`;
|
||||
if(!T.length)h+=`<p class="empty">${tr('customer_paths.no_other_working_fiber',{a,b:z})}</p>`;
|
||||
for(const t of T)h+=row(fibLab(t.l),t.no,t.diverse?tr('customer_paths.fully_diverse'):tr('customer_paths.same_trench'),btn(tr('customer_paths.move'),'pathMove',{id:b.id,link:t.l.id},'sm',!!t.no));}
|
||||
else{const {now,alts}=circuitTargets(b);
|
||||
h+=`<p class="lead" style="margin-top:6px">${tr('customer_paths.routing_chooses_this_circuit',{a,b:z})}</p>`;
|
||||
if(now)h+=`<div class="kv"><span>${tr('customer_paths.now_on')}</span><b>${esc(pathStr(now))}</b></div>`;
|
||||
if(b.pin)h+=`<div class="btns">${btn(tr('customer_paths.let_routing_choose_again'),'pathAuto',{id:b.id},'ghost sm')}</div>`;
|
||||
if(!alts.length)h+=`<p class="empty">${tr('customer_paths.no_other_path',{a,b:z})}</p>`;
|
||||
for(const t of alts){const warn=[t.room<b.bw?`<b style="color:var(--bad)">${tr('customer_paths.fits_only_g_of_bw',{g:fmtG(t.room),bw:fmtG(b.bw)})}</b>`:'',b.latMax&&t.lat>b.latMax?`<b style="color:var(--bad)">${tr('customer_paths.over_the_ms_budget',{ms:b.latMax})}</b>`:''].filter(Boolean).join(' · ');
|
||||
h+=row(esc(pathStr(t.p)),tr('customer_paths.path_facts',{km:Math.round(t.km).toLocaleString(),ms:t.lat.toFixed(1)})+(warn?' · '+warn:''),t.shared?trn('customer_paths.shares_n_spans',t.shared):tr('customer_paths.fully_diverse'),btn(tr('customer_paths.move'),'pathPin',{id:b.id,via:t.p.join()},'sm'));}}
|
||||
openModal(h);}
|
||||
|
|
@ -21,16 +21,5 @@ const brFree=l=>Math.max(0,brMarket(l.a,l.b)-brSold(l.a,l.b));
|
|||
const WW_SHARE=0.3,WW_FALL=0.6;
|
||||
function wwRate(l,n,cut=1){const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),s=brSold(l.a,l.b);let r=0;
|
||||
for(let i=0;i<n;i++)r+=F*WW_SHARE*(1-WW_FALL*Math.min(1,(s+i)/M));return Math.round(r*cut);}
|
||||
// Once a day, each listing may find a buyer: the more room the route has left, the sooner.
|
||||
function brTick(){for(const l of S.links){const L=l.list;if(!L||l.kind!=='df'||!fiberOk({link:l.id,type:'wwave'}))continue;
|
||||
const free=brFree(l);if(!free)continue;
|
||||
if(L.w>0&&freeCh(l)>=1&&Math.random()<Math.min(0.3,free/45)){const n=Math.max(1,Math.min(L.w,freeCh(l),free,1+Math.floor(Math.random()*4)));brSell(l,'wwave',n);L.w-=n;}
|
||||
else if(L.p>0&&pairFree(l)&&free>=BR_PAIR&&Math.random()<1/90){brSell(l,'dfpair',1);L.p--;}
|
||||
if(!(L.w>0)&&!(L.p>0))delete l.list;}}
|
||||
// A sale: a new carrier on this fiber, or more waves for one that already rents here.
|
||||
function brSell(l,t,n){const T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;};
|
||||
const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=wwRate(l,n,0.9);o.what=wwWhat(l,n);}
|
||||
const more=t==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===l.id&&b.name===o.name);
|
||||
if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(clSign(offerCustomer(o)));
|
||||
toast(tr('broker.sold',{name:esc(o.name),what:esc(t==='wwave'?wwWhat(l,n):o.what),price:fmt$(o.rate)}),'good');
|
||||
floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');}
|
||||
// The listings sell in the capacity market now (cmDay(), 37-fiber-market.js), with prices and demand that move.
|
||||
const brTick=()=>cmDay(S.day);
|
||||
|
|
|
|||
182
src/game/60-features/37-fiber-market.js
Normal file
182
src/game/60-features/37-fiber-market.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
/* ---------- the capacity market: what carriers want on each route, today and tomorrow ----------
|
||||
Every route you hold dark fiber on has buyers for spectrum (an alien wave, the buyer brings the optics), managed
|
||||
100G, 400G, 800G and 1.6T waves (carved out of capacity you lit yourself), and dark pairs on fiber you dug (an IRU: a
|
||||
big sum up front, then a little upkeep a month). How much each route wants moves all the time, as it does in real
|
||||
life: a slow cycle of its own, weeks of noise, and news (a cable cut next door, a hyperscaler breaking ground, a rival
|
||||
lighting new glass). Underneath, it grows: carriers want more every year, and bigger waves as the years go by (100G
|
||||
gives way to 400G, then 800G and 1.6T), and carriers already on your glass ask to move up a size. Hot routes pay more
|
||||
and fill faster; a short, straight route sells waves at a premium, and a long one costs more because its fiber does. The broker keeps 10% (3% for a Cable broker, who also sees where
|
||||
each route is heading). S.cm: hold (share kept for your own traffic), p (per product: auto on, min demand, price
|
||||
floor), off (routes left alone), sh (shocks), news, seen (incidents already turned into news). */
|
||||
const CM_P=['spec','w100','w400','w800','w1600','iru'],CM_W=['w100','w400','w800','w1600'];
|
||||
const CM_L={spec:'w',w100:'m1',w400:'m4',w800:'m8',w1600:'m16',iru:'p'},CM_G={w100:100,w400:400,w800:800,w1600:1600};
|
||||
const CM_HOLD=[0,10,25,50],CM_FLOOR=[60,80,100,120],CM_MIN={spec:[1,2,4,8],w100:[1,4,8,16],w400:[1,2,4,8],w800:[1,2,4,8],w1600:[1,2,4],iru:[1,2]};
|
||||
const CM_DEF={spec:{on:false,min:2,floor:80},w100:{on:false,min:4,floor:80},w400:{on:false,min:2,floor:80},w800:{on:false,min:1,floor:80},w1600:{on:false,min:1,floor:80},iru:{on:false,min:1,floor:100}};
|
||||
// A wave's price against a 100G one, on land and on subsea: 2.7x and 3.8x for 400G (real markets in 2025), and the
|
||||
// price of a bit keeps falling as waves grow.
|
||||
const CM_X={w100:[1,1],w400:[2.7,3.8],w800:[4.6,6.6],w1600:[7.8,11]};
|
||||
// Cities where trading firms sit: a short route between two of them pays the most for a fast wave.
|
||||
const CM_FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'];
|
||||
const CM_HMAX=2.5;
|
||||
const cmNew=()=>({hold:25,p:JSON.parse(JSON.stringify(CM_DEF)),off:{},sh:[],news:[],seen:[]});
|
||||
const cmCut=()=>broker()?0.97:0.9;
|
||||
/* A fiber's listing, l.list: {w: spectrum slots, p: pairs} as it always was, plus m1/m4/m8/m16 (managed 100G to 1.6T
|
||||
waves) when any are listed. cmClean() checks one (a save, or after a day of sales) and returns null when nothing is left. */
|
||||
const cmLs=l=>l.list||(l.list={w:0,p:0});
|
||||
function cmClean(L){if(!L||typeof L!=='object'||Array.isArray(L))return null;const x={w:int(L.w,0,256,0),p:int(L.p,0,2,0)};let any=x.w||x.p;
|
||||
for(const p of CM_W){const v=int(L[CM_L[p]],0,256,0);if(v){x[CM_L[p]]=v;any=1;}}return any?x:null;}
|
||||
// A stable number in [0,1) for a route and a question, different in every game.
|
||||
const cmU=(k,q)=>hstr(k+'|'+q+'|'+((S&&S.asn)||0))%100000/100000;
|
||||
/* How hot a route is (1 = its usual self). Its own slow cycle (two waves of 4 to 10 and 1.5 to 3 months) is what a
|
||||
forecast can see; the weeks of noise on top and news nobody has heard yet are not. */
|
||||
function cmCycle(k,d){const p1=120+180*cmU(k,'p1'),p2=40+50*cmU(k,'p2');return 1+0.25*Math.sin(2*Math.PI*(d/p1+cmU(k,'f1')))+0.15*Math.sin(2*Math.PI*(d/p2+cmU(k,'f2')));}
|
||||
function cmNoise(k,d){const i=Math.floor(d/15),t=(d-i*15)/15,u=t*t*(3-2*t),v=j=>0.85+0.3*cmU(k,'n'+j);return v(i)*(1-u)+v(i+1)*u;}
|
||||
// News: a shock ramps up over a week, holds, and fades over the last 40% of its time.
|
||||
const cmShockF=(x,d)=>d<x.from||d>=x.until?0:Math.max(0,Math.min(1,(d-x.from+1)/7,(x.until-d)/Math.max(1,(x.until-x.from)*0.4)));
|
||||
const cmHits=(x,r)=>x.k?x.k===r.k:x.c?x.c===r.a||x.c===r.b:!!x.sub&&r.sub;
|
||||
function cmShock(r,p,d){let m=1;for(const x of S.cm.sh)if(cmHits(x,r)&&(!x.p||x.p.includes(p))){const f=cmShockF(x,d);if(f)m*=1+(x.m-1)*f;}return m;}
|
||||
function cmHeat(r,p,d,fc){return clamp(cmCycle(r.k,d)*(fc?1:cmNoise(r.k,d))*cmShock(r,p,d),0.3,CM_HMAX);}
|
||||
// What a route is: its cities, its fiber (yours, if any), how far and how fast. Without fiber, as you could dig it
|
||||
// (straight, at your own fiber's 1.1 path factor).
|
||||
function cmRoute(a,b,ls=[]){const k=a<b?a+'|'+b:b+'|'+a,km=ls.length?Math.min(...ls.map(l=>l.km)):kmBetween(a,b),sub=ls.length?ls.some(l=>l.sub):isSub(a,b);
|
||||
const lat=ls.length?Math.min(...ls.map(linkLat)):kmBetween(a,b)*1.1/200,gc=kmBetween(a,b)/200,st=gc>0?lat/gc:2,fin=CM_FIN.includes(a)&&CM_FIN.includes(b);
|
||||
// Latency is dominated by the length of the route: a short, straight one sells fast waves at a premium (up to +50%,
|
||||
// +80% between two trading cities).
|
||||
const lp=1+0.5*clamp((1.5-st)/0.4,0,1)*(fin?1.6:1);
|
||||
return {k,a,b,ls,km,sub,lat,st,lp,fin,dc:MEGA.some(m=>m.c===a||m.c===b)};}
|
||||
// The routes you hold ready dark fiber on.
|
||||
function cmRoutes(){const by=new Map();for(const l of S.links)if(l.kind==='df'&&l.ready<=S.day){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}
|
||||
const rs=new Map();for(const [k,ls] of by){const [a,b]=k.split('|');rs.set(k,cmRoute(a,b,ls));}return rs;}
|
||||
/* Growth: carriers want about 15% more every year (non-AI traffic grows about that fast, AI traffic faster), up to 8
|
||||
times what they wanted at the start. */
|
||||
const cmGrowth=d=>Math.min(8,Math.pow(1.15,Math.max(0,d)/365));
|
||||
/* Which wave sizes buyers want: each size catches on along an S-curve over game years plus the network era, and takes
|
||||
over from the one before (100G, then 400G, 800G from about year 5, 1.6T from about year 9; a later network era
|
||||
brings each a little sooner). */
|
||||
const CM_ADOPT={w400:1.5,w800:5,w1600:9};
|
||||
const cmA=(p,d)=>1/(1+Math.exp(-(Math.max(0,d)/365+0.15*lvl()-CM_ADOPT[p])/1.3));
|
||||
function cmShare(p,d){const a4=cmA('w400',d),a8=cmA('w800',d),a16=cmA('w1600',d);return p==='w100'?1-a4:p==='w400'?a4-a8:p==='w800'?a8-a16:a16;}
|
||||
/* What a route wants of a product, in units: spectrum slots, waves of that size, dark pairs. The size comes from the
|
||||
eyeballs at both ends (brMarket(), as before) and growth; managed waves split by the sizes buyers want now, fast
|
||||
waves from latency, the big ones and dark pairs from data centers at either end; dark pairs are mostly bought for
|
||||
shorter hauls. */
|
||||
function cmDem(r,p,d,fc){const M=brMarket(r.a,r.b),H=cmHeat(r,p,d,fc),g=cmGrowth(d);
|
||||
if(p==='spec')return M*0.5*Math.pow(g,0.7)*H;
|
||||
if(p==='iru')return Math.min(2,M/12*(r.dc?2:1)*clamp(900/r.km,0.35,1.5))*Math.sqrt(g)*H;
|
||||
const dc=r.dc&&p!=='w100'?(p==='w400'?1.3:1.6):1;return M*160*Math.sqrt(r.lp)*g*cmShare(p,d)*dc*H/CM_G[p];}
|
||||
// What carriers already rent on a route, by product, in the same units.
|
||||
const cmWP=g=>CM_W.find(p=>CM_G[p]===g)||'w100';
|
||||
function cmSold(rs){const m=new Map(),ids=new Map();for(const r of rs.values()){m.set(r.k,Object.fromEntries(CM_P.map(p=>[p,0])));for(const l of r.ls)ids.set(l.id,r.k);}
|
||||
for(const b of S.biz){const k=b.link&&ids.get(b.link);if(!k)continue;const s=m.get(k);
|
||||
if(b.type==='wwave')s.spec+=b.slots||0;else if(b.type==='mwave')s[cmWP(b.g)]+=b.slots||0;else if(b.type==='dfpair')s.iru++;}
|
||||
return m;}
|
||||
/* List prices, before the market index (mkt()) and the broker's cut: spectrum is 30% of what the fiber costs a month
|
||||
(as before, #203); a managed 100G wave 30% of that times the latency premium, bigger ones by CM_X; a dark pair two
|
||||
years of its lease up front, then 15% of it a month. */
|
||||
const cmF=r=>dfLeaseMo(r.km)+ampCount(r.km)*AMP_MO;
|
||||
function cmList(r,p){return p==='spec'?cmF(r)*WW_SHARE:p==='iru'?dfLeaseMo(r.km)*0.15:cmF(r)*WW_SHARE*0.3*r.lp*CM_X[p][r.sub?1:0];}
|
||||
const cmUpList=r=>dfLeaseMo(r.km)*0.9*24;
|
||||
/* The price of the i-th unit from now, as a share of list: heat pushes it up or down (hot routes pay off), and each
|
||||
unit sold on the route makes the next one cheaper, down to 40% once its market is full. */
|
||||
function cmIdx(r,p,s,i,d,fc){const D=cmDem(r,p,d,fc),H=cmHeat(r,p,d,fc);return clamp(Math.pow(H,0.6),0.7,1.35)*(1-WW_FALL*Math.min(1,D>0?(s+i)/D:1));}
|
||||
// Managed waves sold on a fiber, in Gbps: they come off what your own traffic gets (dfCap0()).
|
||||
let CM_MW=null,CM_V=0;
|
||||
function mwG(l){if(!S||!S.biz)return 0;if(!CM_MW||CM_MW.b!==S.biz||CM_MW.n!==S.biz.length||CM_MW.v!==CM_V){const m=new Map();
|
||||
for(const b of S.biz)if(b.type==='mwave'&&b.link)m.set(b.link,(m.get(b.link)||0)+(b.slots||0)*(b.g||100));CM_MW={b:S.biz,n:S.biz.length,v:CM_V,m};}
|
||||
return CM_MW.m.get(l.id)||0;}
|
||||
// How much of a product a fiber has spare, after the share kept back for your own traffic (spectrum slots, or lit
|
||||
// capacity your traffic is not using). A wave rides one channel, so an 800G or 1.6T one needs an optic that big. A pair
|
||||
// is never kept back: it is glass you are not lighting.
|
||||
const cmFreeG=(l,hold=S.cm.hold)=>dfCap0(l)-(R.load[l.id]||0)*1.05-hold/100*dfLit(l);
|
||||
const cmOptG=l=>Math.max(0,...(l.ch||[]).map(c=>optG(c,l)));
|
||||
function cmSpare(l,p,hold=S.cm.hold){
|
||||
if(p==='spec')return Math.max(0,freeCh(l)-Math.ceil(hold/100*chMax(l)));
|
||||
if(p==='iru')return l.own&&pairFree(l)&&!(l.cut>S.day)?1:0;
|
||||
return cmOptG(l)<CM_G[p]?0:Math.max(0,Math.floor(cmFreeG(l,hold)/CM_G[p]));}
|
||||
const cmWhat=(l,p,n)=>p==='spec'?wwWhat(l,n):p==='iru'?tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}):trn('market.n_g_wave_on',n,{g:fmtCap(CM_G[p]),a:CITY[l.a].name,b:CITY[l.b].name});
|
||||
// A sale: a new carrier on this fiber, or more of the same product for one that already rents here.
|
||||
function cmSell(l,p,n,rate,up){const t=p==='spec'?'wwave':p==='iru'?'dfpair':'mwave',T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;};
|
||||
const g=CM_G[p],name=nm(),more=t!=='dfpair'&&S.biz.find(b=>b.type===t&&b.link===l.id&&b.name===name&&(t!=='mwave'||b.g===g));
|
||||
if(more){more.slots=(more.slots||0)+n;more.rate+=rate;more.what=cmWhat(l,p,more.slots);}
|
||||
else{const o={id:uid(),city:l.a,city2:l.b,link:l.id,slots:t==='dfpair'?0:n,what:cmWhat(l,p,n),name,type:t,bw:1,rate,reqs:[],exp:S.day+30};const b=clSign(offerCustomer(o));if(g)b.g=g;S.biz.push(b);}
|
||||
CM_V++;if(up)S.cash+=up;S.stats.cmSold=(S.stats.cmSold||0)+1;
|
||||
toast(up?tr('market.sold_pair',{name:esc(name),what:esc(cmWhat(l,p,n)),up:fmt$(up),price:fmt$(rate)}):tr('broker.sold',{name:esc(name),what:esc(cmWhat(l,p,n)),price:fmt$(rate)}),'good');
|
||||
floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');}
|
||||
// What one fiber can still sell of a product right now, whatever is listed: free spectrum, lit capacity your traffic
|
||||
// is not using, a free pair.
|
||||
function cmCan(l,p){if(!fiberOk({link:l.id,type:p==='iru'?'dfpair':'wwave'}))return 0;return p==='spec'?Math.max(0,freeCh(l)):p==='iru'?cmSpare(l,'iru'):cmSpare(l,p,0);}
|
||||
/* News: incidents that cut glass become news the next morning, and every so often something happens on its own.
|
||||
Each one is a shock on a route, around a city, or on every subsea route, for some products, for a while. */
|
||||
const CM_NEWS={
|
||||
cut:{m:1.6,days:45,p:null,t:N_('market.news_cut')},redsea:{m:1.8,days:90,p:null,t:N_('market.news_redsea')},
|
||||
dc:{m:2,days:150,p:['w400','w800','w1600','iru'],t:N_('market.news_dc_big')},ai:{m:2.5,days:70,p:['w400','w800','w1600'],t:N_('market.news_ai_big')},
|
||||
glut:{m:0.6,days:120,p:null,t:N_('market.news_glut')},exch:{m:1.7,days:60,p:CM_W,t:N_('market.news_exch')},
|
||||
merge:{m:0.75,days:90,p:null,t:N_('market.news_merge')},boom:{m:1.4,days:60,p:['spec','w100'],t:N_('market.news_boom')}};
|
||||
function cmNews(why,x,d){const N=CM_NEWS[why],s={why,from:d,until:d+N.days,m:N.m,...x};if(N.p)s.p=N.p.slice();S.cm.sh.push(s);
|
||||
S.cm.news.unshift({d,why,a:x.a||x.c||null,b:x.b||null});S.cm.news.length=Math.min(S.cm.news.length,8);
|
||||
const rs=cmRoutes();if([...rs.values()].some(r=>cmHits(s,r)))toast(cmNewsText(S.cm.news[0]),N.m>1?'info':'warn',[{l:tr('market.open'),act:'marketOpen',args:{}}]);}
|
||||
const cmNewsText=n=>tr(CM_NEWS[n.why].t,{a:n.a?CITY[n.a].name:'',b:n.b?CITY[n.b].name:''});
|
||||
function cmShocks(d){const C=S.cm;C.sh=C.sh.filter(x=>x.until>d);
|
||||
for(const i of S.inc)if(LINKCUT_TR.includes(i.type)&&!C.seen.includes(i.id)){C.seen.push(i.id);if(C.seen.length>40)C.seen.shift();
|
||||
if(i.type==='redsea'){cmNews('redsea',{sub:1},d);continue;}
|
||||
const l=S.links.find(x=>x.id===i.ref||x.trench===i.ref);if(l)cmNews('cut',{c:hstr(String(i.id))%2?l.a:l.b,a:l.a,b:l.b},d);}
|
||||
// Without dark fiber there is no market to move, and no random number is drawn (the rest of the day stays as it was).
|
||||
const rs=[...cmRoutes().values()],cs=[...new Set(rs.flatMap(r=>[r.a,r.b]))];if(!rs.length||Math.random()>=1/10)return;
|
||||
const why=pick(['dc','ai','glut','exch','merge','boom','boom','dc']),r=pick(rs),c=pick(cs);
|
||||
if(why==='dc'||why==='boom')cmNews(why,{c},d);
|
||||
else if(why==='exch'){const f=cs.filter(x=>CM_FIN.includes(x));if(f.length){const x=pick(f);cmNews(why,{c:x},d);}}
|
||||
else cmNews(why,{k:r.k,a:r.a,b:r.b},d);}
|
||||
/* Once a day: news, then on every route the broker lists what your thresholds allow (spare after the share kept back,
|
||||
while demand is at least your minimum and the price at least your floor) or takes it off, then each listing may
|
||||
find a buyer: the more room the route has left and the hotter it is, the sooner; the fastest fiber sells first. */
|
||||
function cmList1(r,p,s,d){const c=S.cm.p[p],lk=CM_L[p];if(!c.on||S.cm.off[r.k])return;const ok=cmDem(r,p,d)>=c.min&&cmIdx(r,p,s,0,d)*100>=c.floor;
|
||||
for(const l of r.ls){const n=ok?cmSpare(l,p):0;if(n>0)cmLs(l)[lk]=n;else if(l.list)l.list[lk]=0;}}
|
||||
// The listings as the thresholds want them right now (after you change a setting), without selling anything.
|
||||
function cmRelist(){const rs=cmRoutes(),sold=cmSold(rs);for(const r of rs.values())for(const p of CM_P)cmList1(r,p,sold.get(r.k)[p],S.day);cmTidy();}
|
||||
const cmTidy=()=>{for(const l of S.links)if(l.list){const L=cmClean(l.list);if(L)l.list=L;else delete l.list;}};
|
||||
function cmDay(d=S.day){const C=S.cm;cmShocks(d);const rs=cmRoutes(),sold=cmSold(rs);
|
||||
for(const r of rs.values()){const s=sold.get(r.k);
|
||||
for(const p of CM_P){const lk=CM_L[p];cmList1(r,p,s[p],d);
|
||||
// Room rounds to the nearest unit: a road to nowhere that wants about one wave sells one.
|
||||
const D=cmDem(r,p,d),room=Math.round(D-s[p]);if(room<1)continue;
|
||||
const ls=r.ls.filter(l=>l.list&&l.list[lk]>0&&cmCan(l,p)>0).sort((x,y)=>linkLat(x)-linkLat(y));if(!ls.length)continue;
|
||||
if(Math.random()>=Math.min(0.35,0.06+0.25*room/Math.max(1,D))*(p==='iru'?0.08:1)*(p==='spec'?1:Math.sqrt(r.lp)))continue;
|
||||
const l=ls[0];let n=p==='iru'?1:Math.max(1,Math.min(l.list[lk],cmCan(l,p),room,1+Math.floor(Math.random()*(p==='spec'||p==='w100'?4:2))));
|
||||
// Never below your floor: fewer units, or none.
|
||||
while(n>0&&cmIdx(r,p,s[p],n-1,d)*100<C.p[p].floor)n--;if(!n)continue;
|
||||
const cut=cmCut()*mkt(),L=cmList(r,p);let rate=0;for(let i=0;i<n;i++)rate+=L*cmIdx(r,p,s[p],i,d);
|
||||
const up=p==='iru'?Math.round(cmUpList(r)*cmIdx(r,p,s[p],0,d)*cut):0;
|
||||
cmSell(l,p,n,Math.round(rate*cut),up);s[p]+=n;l.list[lk]-=n;}}
|
||||
cmGrow(d);cmTidy();}
|
||||
/* What the next 30 and 90 days look like on a route, for a Cable broker: the route's own cycle and the news already
|
||||
out, but not the noise or news still to come. */
|
||||
const cmFc=(r,p,t)=>cmDem(r,p,S.day+t,true);
|
||||
/* Growth inside contracts: once the next size is common (15% of what buyers want), a carrier on a managed wave asks
|
||||
now and then to move all its waves up one size. With room on the fiber (after what you keep back) it moves at once
|
||||
and pays more (a bigger wave, at a lower price per bit); without, it tells you, at most twice a year. */
|
||||
function cmGrow(d){for(const b of S.biz){if(b.type!=='mwave')continue;const i=CM_W.indexOf(cmWP(b.g)),q=CM_W[i+1];if(!q||cmShare(q,d)<0.15||Math.random()>=1/300)continue;
|
||||
const l=S.links.find(x=>x.id===b.link);if(!l||!fiberOk(b))continue;const g1=CM_G[q],extra=(g1-b.g)*(b.slots||1),sub=l.sub?1:0,arg={name:esc(b.name),n:b.slots||1,g0:fmtCap(b.g),g1:fmtCap(g1),a:CITY[l.a].name,b:CITY[l.b].name};
|
||||
if(cmOptG(l)>=g1&&cmFreeG(l)>=extra){const p0=cmWP(b.g);b.rate=Math.round(b.rate*CM_X[q][sub]/CM_X[p0][sub]*0.85);b.g=g1;b.what=cmWhat(l,q,b.slots||1);CM_V++;
|
||||
toast(tr('market.upgraded',{...arg,price:fmt$(b.rate)}),'good');}
|
||||
else if(!(b.gw>d-180)){b.gw=d;toast(tr('market.wants_more',arg),'warn',[{l:tr('lease_swaps.open_your_fiber'),act:'dashLink',args:{id:l.id}}]);}}}
|
||||
// How many more spectrum slots a fiber's route wants today (the fiber panel's market line).
|
||||
function cmRoomSpec(l){const rs=cmRoutes(),r=rs.get(edgeKey(l));if(!r)return 0;return Math.max(0,Math.round(cmDem(r,'spec',S.day)-cmSold(rs).get(r.k).spec));}
|
||||
// Routes a Cable broker could build between two of its POPs, the most wanted first.
|
||||
function cmScout(n=6){const ps=Object.keys(S.pops),have=new Set(S.links.filter(l=>l.kind==='df').map(edgeKey)),out=[];
|
||||
for(let i=0;i<ps.length;i++)for(let j=i+1;j<ps.length;j++){const a=ps[i],b=ps[j],k=a<b?a+'|'+b:b+'|'+a;if(have.has(k))continue;
|
||||
const sub=isSub(a,b);if(sub?!seaCab(a,b):kmBetween(a,b)>1500||!dfAllowed(a,b))continue;const r=cmRoute(a,b);
|
||||
out.push({r,v:CM_P.reduce((s,p)=>s+cmDem(r,p,S.day)*cmList(r,p),0)});}
|
||||
return out.sort((x,y)=>y.v-x.v).slice(0,n).map(x=>x.r);}
|
||||
// Saves: everything checked, old saves get the defaults.
|
||||
function cmFix(s){const c=s.cm&&typeof s.cm==='object'&&!Array.isArray(s.cm)?s.cm:{},n=cmNew();
|
||||
n.hold=CM_HOLD.includes(+c.hold)?+c.hold:25;
|
||||
for(const p of CM_P){const x=c.p&&c.p[p]||{};n.p[p]={on:!!x.on,min:CM_MIN[p].includes(+x.min)?+x.min:CM_DEF[p].min,floor:CM_FLOOR.includes(+x.floor)?+x.floor:CM_DEF[p].floor};}
|
||||
if(c.off&&typeof c.off==='object')for(const k in c.off){const [a,b]=k.split('|');if(c.off[k]&&isCity(a)&&isCity(b)&&a<b)n.off[k]=1;}
|
||||
if(Array.isArray(c.sh))n.sh=c.sh.filter(x=>x&&own(CM_NEWS,x.why)&&(x.k?typeof x.k==='string'&&x.k.split('|').every(isCity):x.c?isCity(x.c):!!x.sub)).slice(-24).map(x=>{
|
||||
const y={why:x.why,from:int(x.from,-1e6,1e7,0),until:int(x.until,-1e6,1e7,0),m:clamp(num(x.m,1),0.3,3)};if(x.k)y.k=x.k;else if(x.c)y.c=x.c;else y.sub=1;
|
||||
if(isCity(x.a))y.a=x.a;if(isCity(x.b))y.b=x.b;if(Array.isArray(x.p)){const p=x.p.filter(q=>CM_P.includes(q));if(p.length)y.p=p;}return y;});
|
||||
if(Array.isArray(c.news))n.news=c.news.filter(x=>x&&own(CM_NEWS,x.why)).slice(0,8).map(x=>({d:int(x.d,-1e6,1e7,0),why:x.why,a:isCity(x.a)?x.a:null,b:isCity(x.b)?x.b:null}));
|
||||
if(Array.isArray(c.seen))n.seen=c.seen.filter(x=>typeof x==='string').slice(-40);
|
||||
s.cm=n;
|
||||
for(const l of s.links){if(l.kind!=='df'||!l.list)continue;const L=cmClean(l.list);if(L)l.list=L;else delete l.list;}
|
||||
for(const b of s.biz)if(b.type==='mwave'){b.g=CM_W.some(p=>CM_G[p]===b.g)?b.g:100;b.slots=Math.max(1,Math.round(b.slots||1));if(b.gw!==undefined)b.gw=int(b.gw,-1e6,1e7,0);}}
|
||||
|
|
@ -19,7 +19,7 @@ const SALES={
|
|||
const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30;
|
||||
// The ones the engineer never lands, and the nerds the shark never calls back.
|
||||
const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);};
|
||||
const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','dfpair'];
|
||||
const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','mwave','dfpair'];
|
||||
const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')];
|
||||
const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null;
|
||||
const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
function newGame(name,home){
|
||||
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
|
||||
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
|
||||
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null,
|
||||
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null,
|
||||
lvl:1,hist:[],ach:{},ixn:{},ixPref:{},ixSite:{},confReg:{},cl:{odd:-1e9,mo:[]},sales:{p:null,hired:0,vp:null,golf:null,say:null},baronWon:0};
|
||||
for(const o of OPS)S.ops.p[o.k]={};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -151,17 +151,19 @@ const OPS_RUN={
|
|||
// Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js).
|
||||
*std(X){yield* bstdShift(X);},
|
||||
*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'),G=bstd().g,fix=G!=='keep',
|
||||
load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
|
||||
// Ports in use are counted for every POP at once, after the model swaps: a router added or swapped here changes no other POP's count.
|
||||
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),G=bstd().g,fix=G!=='keep',cs=opsPops('routers'),
|
||||
load=(c,u)=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),u/Math.max(1,portsMax(c)));
|
||||
// The build standard's model: swap every POP still on a smaller one to the model the standard gives it (bstdModel():
|
||||
// the best unlocked one no bigger, never a step down, never one that does not fit or cannot run the core), the
|
||||
// busiest first, while the budget lasts, and only with a second router or no traffic there.
|
||||
if(fix)for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c];
|
||||
if(fix){const pu=portsAt(cs);for(const c of cs.slice().sort((a,b)=>load(b,pu.get(b))-load(a,pu.get(a)))){const p=S.pops[c];
|
||||
if(p.rupDay===S.day||!((p.routers||1)>1||popIdle(c)))continue;const m=bstdModel(G,c);if(m<0)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);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;
|
||||
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}}
|
||||
const pu=portsAt(cs);
|
||||
for(const c of cs){const p=S.pops[c];if(p.rupDay===S.day)continue;
|
||||
const ld=load(c,pu.get(c));if(ld<at)continue;
|
||||
const rt=p.routers||1,g=p.rgen||0,nx=mainRG(RG[g].cls+1);
|
||||
// A swap with one router is a maintenance window: the intern only swaps where a second router carries the traffic.
|
||||
// With a chosen model the swaps are the ones above; a busy POP only gets more routers.
|
||||
|
|
@ -193,7 +195,11 @@ const OPS_RUN={
|
|||
// 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=[],
|
||||
// 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);
|
||||
// Both, by city, are worked out once between two jobs (a job may change them; KV is dropped after each), in the order
|
||||
// the PNIs come, as the sum over them was: the same numbers.
|
||||
KV={rv:null,pu:new Map()},
|
||||
resv=c=>{if(!KV.rv){KV.rv=new Map();for(const p of S.pni)if(p.up)KV.rv.set(p.city,(KV.rv.get(p.city)||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)));}return KV.rv.get(c)||0;},
|
||||
used=c=>{let u=KV.pu.get(c);if(u===undefined)KV.pu.set(c,u=portsUsed(c));return u;},room=c=>portsMax(c)-used(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.
|
||||
for(const p of S.pni){const c=p.city,use=(R.usePni[p.id]||0)*opsAhead(),cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue;
|
||||
L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(),
|
||||
|
|
@ -209,8 +215,8 @@ const OPS_RUN={
|
|||
out.push({cost:ixPortMo(x,t)*n(),cap:cap()*lagCap(PORT[t].g,n())/lagCap(g(),n()),w:PORT[t0].n+'→'+PORT[t].n,go:()=>ACT.buyIx({city:x,tier:t})});}return out;}});}
|
||||
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);yield;}},
|
||||
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;})){KV.rv=null;KV.pu.clear();break;}
|
||||
KV.rv=null;KV.pu.clear();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();
|
||||
|
|
@ -255,20 +261,25 @@ const OPS_RUN={
|
|||
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.fib.set(l.id,'optup');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;
|
||||
// The boxes sorted by POP once: the boxes racked at one POP change no other POP's plan.
|
||||
*caches(X){const g=opsP('caches','g'),by=new Map();for(const x of S.caches){const a=by.get(x.city);if(a)a.push(x);else by.set(x.city,[x]);}
|
||||
for(const c of opsPops('caches')){const add=cachePlan(c,by.get(c)||[]);if(!add||!add.length)continue;
|
||||
const want=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);}
|
||||
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;
|
||||
// The batch a few networks at a time; if the player acted in between (an action routes), it is made again in one go.
|
||||
const g0=RW.gen,it=pniBatchRun(null,opsP('pni','tier'));let b;for(;;){const s=it.next();if(s.done){b=s.value;break;}yield;}
|
||||
if(RW.gen!==g0)b=pniBatch(null,opsP('pni','tier'));if(!b)return;yield;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;
|
||||
// pniVal()'s want, without the rest pniVal() prices (the transit it saves, the port): all the order asks (pniWant()).
|
||||
const lv=new Map(),loc=q=>{let v=lv.get(q);if(v===undefined)lv.set(q,v=pniWant(q.city,q.net));return v;};
|
||||
// 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))){
|
||||
|
|
@ -321,8 +332,15 @@ function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return fal
|
|||
return k!==null?k: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 (and gone) first.
|
||||
function opsDecomSafe(l,gone=[]){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&&!gone.includes(x));try{return was.every(chk);}finally{S.links=all;}}
|
||||
const was=bz.filter(promiseCheck()),all=S.links;S.links=all.filter(x=>x!==l&&!gone.includes(x));try{return was.every(promiseCheck());}finally{S.links=all;}}
|
||||
/* Those promises, asked for many customers on one network: each search is made once and shared (a diversity graph, the
|
||||
land islands, one latency search per city a customer starts from). Same answers as diversePaths(), terrestrialPath()
|
||||
and bestLat() asked one by one. */
|
||||
function promiseCheck(){let dg=null,ti=null,lg=null;const dv=new Map(),ld=new Map();
|
||||
const div=(a,b)=>{const k=a+'>'+b;let r=dv.get(k);if(r===undefined)dv.set(k,r=divOn(dg||(dg=divGraph()),a,b));return r;};
|
||||
const land=(a,b)=>{if(a===b)return true;ti=ti||terrIslands();const A=ti.get(a);return A!==undefined&&A===ti.get(b);};
|
||||
const lat=(a,b)=>{lg=lg||latGraph();if(!ld.has(a))ld.set(a,latRun(lg,a));return latAt(lg,ld.get(a),a,b);};
|
||||
return b=>(b.reqs||[]).every(k=>k==='diverse'?div(b.city,b.city2):k==='sharks'?land(b.city,b.city2):k==='lat'?lat(b.city,b.city2)<=b.latMax:true);}
|
||||
// The links between each pair of cities, VXCs and satellite circuits left out.
|
||||
function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){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'));
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
/* Single and bulk orders share the same checks, prices and provisioning. */
|
||||
function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)tier=0;
|
||||
// at: for a batch, where to look up the PNI there already is and the ports in use, which the batch itself never changes.
|
||||
function pniQuote(city,net,tier,reserved=0,at=null){tier=+tier;const g1=tier===-1;if(g1)tier=0;
|
||||
if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null;
|
||||
const ex=S.pni.find(p=>p.city===city&&p.net===net);
|
||||
const ex=at?at.ex(city,net):S.pni.find(p=>p.city===city&&p.net===net),used=at?at.used:portsUsed;
|
||||
if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null;
|
||||
const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier);
|
||||
let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n});
|
||||
else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)});
|
||||
else if(!g1&&tier<pniMin(net))why=tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n});
|
||||
else if(slots>0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});}
|
||||
else if(slots>0&&used(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(used(city)+reserved),m:portsMax(city)});}
|
||||
return {city,net,tier,g1,ex,cost,slots,why};}
|
||||
// A new PNI has every field sanitize() gives one, so live S is what a reload makes of it.
|
||||
function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
|
||||
|
|
@ -20,12 +21,18 @@ const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots
|
|||
// 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;
|
||||
function pniBatch(net,tier){const g=pniBatchRun(net,tier);for(;;){const s=g.next();if(s.done)return s.value;}}
|
||||
// The same batch with a place to let a frame through every few networks: the intern's weekly round (95-standing-orders.js).
|
||||
function* pniBatchRun(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;
|
||||
// Asked of every network at every shared POP: the PNIs by POP and network (the first one, as find() would), and the
|
||||
// ports in use, counted for every POP in one pass the first time a quote needs them.
|
||||
const exs=new Map();let use=null;for(const p of S.pni){const k=p.city+'|'+p.net;if(!exs.has(k))exs.set(k,p);}
|
||||
const at={ex:(c,n)=>exs.get(c+'|'+n),used:c=>(use||(use=portsAt(Object.keys(S.pops)))).get(c)};
|
||||
// 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)+pniUpSlots(p);
|
||||
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
|
||||
let nn=0;for(const n of all?NETS:[NET[net]]){if(++nn%16===0)yield;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;
|
||||
mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);}
|
||||
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0,at);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;
|
||||
mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);}}
|
||||
return {shared,orders,blocked,kept,cost,mo,raised};}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,18 @@ function pniIdx(){if(PNIX&&PNIX.R===R)return PNIX;
|
|||
const ix={},pn={};
|
||||
for(const c in S.ixp){const nm=ixName(c);for(const id of ixSessions(c)){const a=ix[id]||(ix[id]=[]);if(!a.includes(nm))a.push(nm);}}
|
||||
for(const p of S.pni)(pn[p.net]||(pn[p.net]=[])).push(p);
|
||||
return PNIX={R,fl:{},ix,pn};}
|
||||
return PNIX={R,fl:{},all:false,ix,pn};}
|
||||
// One POP's flows by network, added up the first time that POP is asked about.
|
||||
function pniFlows(c){const X=pniIdx();let m=X.fl[c];if(m)return m;m=X.fl[c]={};
|
||||
for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
|
||||
o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}
|
||||
return m;}
|
||||
// Every POP at once, in one pass over the flows: the intern's weekly PNI round asks about all of them, and one POP at a
|
||||
// time was a pass per POP. The flows are read straight from routing's columns (R.flc), not made into the objects of R.fl
|
||||
// (tens of thousands on a big network); each POP's sums still add up its flows in their order.
|
||||
function pniFlows(c){const X=pniIdx();if(!X.all){X.all=true;const F=X.fl,C=R.flc;
|
||||
const add=(c,n,rem,gt,gi,gp,gh,ti,ii)=>{const m=F[c]||(F[c]={});let o=m[n];if(!o)o=m[n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
|
||||
o.u+=rem;o.t+=gt;o.ix+=gi;o.p+=gp;o.h+=gh;if(gt)o.T[ti]=(o.T[ti]||0)+gt;if(gi)o.I[ii]=(o.I[ii]||0)+gi;};
|
||||
if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP,FGH,FTI,FII,E}=C;
|
||||
for(let i=0;i<NF;i++)add(CITIES[FCI[i]].id,NET_IDS[FNJ[i]],FREM[i],FGT[i],FGI[i],FGP[i],FGH[i],FTI[i]<0?null:E[FTI[i]].id,FII[i]<0?null:E[FII[i]].id);}
|
||||
else for(const f of R.fl||[])if(!f.junk)add(f.c,f.n,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii);}
|
||||
return X.fl[c]||(X.fl[c]={});}
|
||||
// One status, most direct first. c: the POP you are looking at (null: anywhere).
|
||||
function pniStat(id,c){const X=pniIdx(),ps=X.pn[id]||[],h=c?ps.find(p=>p.city===c):null;
|
||||
if(h)return {k:'here',p:h};
|
||||
|
|
@ -33,6 +39,16 @@ function pniChip(id,c){const s=pniStat(id,c);let t;
|
|||
/* What a new PNI with `id` at `c` would carry and save per month. It takes your users' traffic there that now
|
||||
leaves over transit, an exchange or a PNI elsewhere, or does not leave at all for want of room, up to its port; transit is billed on the 95th percentile,
|
||||
so the saving is the bill now minus the bill with that much less (commits included). */
|
||||
/* pniVal()'s want for network n at POP c (what the intern's weekly round sorts by), without the rest pniFlows() keeps
|
||||
for the PNI list: the same four sums of the same flows in the same order, in columns by (city, network). One pass,
|
||||
no objects; null when routing left no columns (an old R), then pniFlows() it is. */
|
||||
function pniWant(c,n){const X=pniIdx();if(X.w===undefined){const C=R.flc;X.w=null;
|
||||
if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP}=C;let K=1;for(let i=0;i<NF;i++)if(FNJ[i]>=K)K=FNJ[i]+1;
|
||||
const n4=CITIES.length*K,U=new Float64Array(n4),T=new Float64Array(n4),I=new Float64Array(n4),P=new Float64Array(n4);
|
||||
for(let i=0;i<NF;i++){const k=FCI[i]*K+FNJ[i];U[k]+=FREM[i];T[k]+=FGT[i];I[k]+=FGI[i];P[k]+=FGP[i];}
|
||||
X.w={K,U,T,I,P,ni:new Map(NET_IDS.map((id,j)=>[id,j]))};}}
|
||||
const W=X.w;if(!W){const o=pniFlows(c)[n];return o?o.t+o.ix+o.p+o.u:0;}
|
||||
const ci=CIDX[c],j=W.ni.get(n);if(ci===undefined||j===undefined||j>=W.K)return 0;const k=ci*W.K+j;return W.T[k]+W.I[k]+W.P[k]+W.U[k];}
|
||||
function pniVal(id,c){const o=pniFlows(c)[id]||{t:0,ix:0,p:0,h:0,u:0,T:{},I:{}},want=o.t+o.ix+o.p+o.u;
|
||||
const lo=pniMin(id);let tier=-1;for(let i=lo;i<PORT.length;i++)if(portShown(i)){tier=i;if(PORT[i].g*0.8>=want)break;}
|
||||
if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0;
|
||||
|
|
|
|||
|
|
@ -15,16 +15,26 @@ function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new
|
|||
// city cannot even reach, and too few for the ones it uses most.
|
||||
const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;
|
||||
const cityNetSh=(c,id)=>(cityShTab(c)[id]||0)*(id==='ggl'&&ruCity(c)?0.5:1);
|
||||
function cacheDem(c,id){const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;}
|
||||
// A city's total share only depends on its table and on the Russian throttle, and the tables never change after load:
|
||||
// summed once per kind of city, not once per network asked about (that was cities × networks² every shift).
|
||||
const CSH_SUM=new Map();
|
||||
function cityShSum(c){const T=cityShTab(c),k=ruCity(c)?1:0;let m=CSH_SUM.get(T);if(!m)CSH_SUM.set(T,m=[null,null]);
|
||||
if(m[k]===null){let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];}
|
||||
function cacheDem(c,id){const t=cityShSum(c);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;}
|
||||
// One box per site first, if the city sends the network anything at all; then more boxes while that demand outgrows them
|
||||
// (100G each, #248).
|
||||
function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={};
|
||||
for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;}
|
||||
for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&cacheDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0);
|
||||
// boxes: the city's own boxes in their order, when the caller has them sorted by city already (S.caches otherwise).
|
||||
function cachePlan(city,boxes=S.caches){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={};
|
||||
// One pass over the boxes: how many per network and site, and the capacity per network (summed in the same order).
|
||||
const capN={};for(const c of boxes)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;capN[c.net]=(capN[c.net]||0)+cacheG(c);}
|
||||
for(const n of NETS){if(!n.cache||!((R.demTo[n.id]||0)>=n.cache.min))continue;const dem=cacheDem(city,n.id);if(!(dem>1e-6))continue;const box=sites.map(st=>have[n.id+'@'+st]||0),a0=add.length;
|
||||
sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}});
|
||||
const dem=cacheDem(city,n.id),nb=cacheBox(city);
|
||||
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
|
||||
const nb=cacheBox(city);
|
||||
let cap=(capN[n.id]||0)+(add.length-a0)*cacheG(nb);
|
||||
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
|
||||
return add;}
|
||||
// The plan with its quote: the ports it takes and those free (counting ports walks the whole network), the monthly rent.
|
||||
function utilityCaches(city){const add=cachePlan(city);if(!add)return null;
|
||||
return {add,ports:cachePortsAdd(city,add),key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};}
|
||||
// A total a window showed still holds within 1% either way: hardware prices drift a little every day under the market
|
||||
// rule, and on a server-run network days go on while a window is open. A bigger change is a new plan, shown again.
|
||||
|
|
|
|||
|
|
@ -13,6 +13,21 @@ function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n)
|
|||
if(done[u]||d>D[u])continue;done[u]=1;if(u===stop)break;
|
||||
for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<D[v]){D[v]=nd;P[v]=e;put(nd,v);}}}
|
||||
return {D,P};}
|
||||
/* dijkstra() for one path thrown away at once (Auto-TE's detours, thousands in a big network's routing): the same search,
|
||||
heap and order, in arrays kept between calls instead of three new ones each time. A stamp per city says whether this
|
||||
call wrote its distance (DJ.S), so nothing is cleared. Returns the distance to `stop`; the path is in DJ.P. */
|
||||
const DJ={n:0,g:0,D:null,P:null,S:null,done:null,hd:new Float64Array(64),hu:new Int32Array(64)};
|
||||
function dijkstraTo(adj,src,wf,skip,stop){const n=adj.length;
|
||||
if(DJ.n!==n||DJ.g>2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;}
|
||||
const g=++DJ.g,D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length,m=0;
|
||||
const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;}
|
||||
let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}};
|
||||
D[src]=0;ST[src]=g;put(0,src);
|
||||
while(m){const d=hd[0],u=hu[0];m--;
|
||||
if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l<m&&hd[l]<hd[k])k=l;if(r<m&&hd[r]<hd[k])k=r;if(k===i)break;const td=hd[k],tu=hu[k];hd[k]=hd[i];hu[k]=hu[i];hd[i]=td;hu[i]=tu;i=k;}}
|
||||
if(DN[u]===g||d>(ST[u]===g?D[u]:Infinity))continue;DN[u]=g;if(u===stop)break;
|
||||
for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<(ST[v]===g?D[v]:Infinity)){D[v]=nd;ST[v]=g;P[v]=e;put(nd,v);}}}
|
||||
return ST[stop]===g?D[stop]:Infinity;}
|
||||
// The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices.
|
||||
function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};}
|
||||
// The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape.
|
||||
|
|
|
|||
|
|
@ -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)});}}
|
||||
|
|
|
|||
|
|
@ -39,14 +39,27 @@ function exIdx(L){L.hi=L.some(e=>e.hp===0);L.mx=L.some(e=>e.dt>0)&&L.some(e=>e.d
|
|||
function rcReachTake(R2){return {reachable:{...R2.reachable},nt:{...R2.nt},cone:{...R2.cone},reach:R2.reach,reachNT:R2.reachNT};}
|
||||
function rcReachPut(X,R2){const r=X.reach;Object.assign(R2.reachable,r.reachable);Object.assign(R2.nt,r.nt);Object.assign(R2.cone,r.cone);R2.reach=r.reach;R2.reachNT=r.reachNT;}
|
||||
// Keep what was built (on a miss): okBy, the exit lists (each shared list once), each network's lists by rank, DSEL, RSET.
|
||||
function rcExitKeep(key,E,okBy,reach,LIST,BRJ,DSEL,RSET){const ok=[];for(let j=0;j<NET_IDS.length;j++)ok[j]=rcIx(okBy[NET_IDS[j]],E);
|
||||
/* A list's orders (by source city) follow from its exits in list order, each exit's city and preference, and the graph's
|
||||
distances. When the exits change (a PNI comes up, a network leaves an exchange), most lists do not: one with the same
|
||||
exits, cities and preferences on the same graph keeps the orders it had, and uses them today already. Only the lists
|
||||
that changed start again (scanned today, sorted from tomorrow). */
|
||||
function rcExitKeep(key,E,okBy,reach,LIST,BRJ,DSEL,RSET,bk=''){const ok=[];for(let j=0;j<NET_IDS.length;j++)ok[j]=rcIx(okBy[NET_IDS[j]],E);
|
||||
// An exit's kind counts too: an exchange exit sorts behind a PNI at the same distance (dt).
|
||||
const sig=new Int32Array(E.length);for(let i=0;i<E.length;i++)sig[i]=E[i].ci*8+E[i].hp*2+(E[i].dt>0?1:0);
|
||||
const P=RC.x&&RC.x.gk===RC.gk&&RC.x.bk===bk&&RC.x.sig?RC.x:null,old=new Map();
|
||||
if(P)for(const d of P.lists){if(d.cs){for(let k=0;k<d.cs.length;k++)if(d.cs[k])old.set(k+'/'+d.cs[k].join(','),d.ord[k]);}else old.set(d.a.join(','),d.ord);}
|
||||
const same=a=>{for(let i=0;i<a.length;i++){const x=a[i];if(x>=P.sig.length||P.sig[x]!==sig[x])return false;}return true;};
|
||||
const kept=(k,a)=>{if(!P)return null;const o=old.get(k);return o&&same(a)?o:null;};
|
||||
const id=new Map(),lists=[];for(const V of LIST.values()){id.set(V,lists.length);
|
||||
if(V.cs){const cs=[];for(let k=0;k<V.cs.length;k++)if(V.cs[k])cs[k]=rcIx(V.cs[k],E);lists.push({cs,a:null});}else lists.push({cs:null,a:rcIx(V,E)});}
|
||||
if(V.cs){const cs=[],ord=[];for(let k=0;k<V.cs.length;k++)if(V.cs[k]){cs[k]=rcIx(V.cs[k],E);const o=kept(k+'/'+cs[k].join(','),cs[k]);ord[k]=o||[];if(o)V.cs[k].ord=o;}lists.push({cs,a:null,ord});}
|
||||
else{const a=rcIx(V,E),o=kept(a.join(','),a);lists.push({cs:null,a,ord:o||[]});if(o)V.ord=o;}}
|
||||
const brj=BRJ.map(m=>{const o=[];for(const r in m)o.push(r,id.get(m[r]));return o;});
|
||||
RC.xk=key;RC.x={ok,reach,lists,brj,DSEL,RSET:[...RSET]};}
|
||||
RC.xk=key;RC.x={ok,reach,lists,brj,DSEL,RSET:[...RSET],gk:RC.gk,bk,sig};}
|
||||
// Fresh lists for today's exits from a kept build.
|
||||
function rcExitLists(X,E,BRJ,DSEL,RSET){const V=X.lists.map(d=>{if(d.cs){const cs={cs:[]};for(let k=0;k<d.cs.length;k++)if(d.cs[k]){const s=rcEx(d.cs[k],E);exIdx(s);cs.cs[k]=s;}return cs;}
|
||||
const L=rcEx(d.a,E);exIdx(L);return L;});
|
||||
// Each list also gets the orders kept with it (ord: by source city, the list in the order routing tries it, see xOrder()
|
||||
// in 30-compute.js), filled in as routing asks for them.
|
||||
function rcExitLists(X,E,BRJ,DSEL,RSET){const V=X.lists.map(d=>{if(d.cs){const cs={cs:[]};for(let k=0;k<d.cs.length;k++)if(d.cs[k]){const s=rcEx(d.cs[k],E);exIdx(s);s.ord=d.ord[k];cs.cs[k]=s;}return cs;}
|
||||
const L=rcEx(d.a,E);exIdx(L);L.ord=d.ord;return L;});
|
||||
for(let j=0;j<X.brj.length;j++){const o=X.brj[j],m={};for(let k=0;k<o.length;k+=2)m[o[k]]=V[o[k+1]];BRJ[j]=m;}
|
||||
for(const [r,a] of X.DSEL)DSEL.set(r,a);for(const r of X.RSET)RSET.add(r);}
|
||||
function rcOkBy(X,E){const okBy={};for(let j=0;j<NET_IDS.length;j++)okBy[NET_IDS[j]]=rcEx(X.ok[j],E);return okBy;}
|
||||
|
|
|
|||
227
src/game/80-simulation/29-route-core.js
Normal file
227
src/game/80-simulation/29-route-core.js
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
/* The routing core: the loops that place every flow on an exit (compute() in 30-compute.js does everything around them).
|
||||
They are made once, here, and not inside compute() as they used to be: V8 compiles a function for the objects it
|
||||
meets, and every compute() made new copies of these, so each routing threw the optimised code away (a new function
|
||||
where it had inlined the old one) and ran a good part of its loops unoptimised until it was compiled again. Made once,
|
||||
they stay compiled from one day to the next. compute() hands them the day's state: nodes() what floods and circuits
|
||||
carry before routing (nodeTake(), carry()), run() the rest, then run() routes every pass. The code is the same
|
||||
code; only where it lives changed (tests/routing-reference.test.js, tests/speed.test.js, scripts/route-fuzz.js). */
|
||||
function routeCore(){
|
||||
// The day's state, set by nodes() and run(). (TR, base and eff, the ranks, are for the reference loop of the tests.)
|
||||
let NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD,
|
||||
E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP,
|
||||
TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff,SATN,
|
||||
NX=0,USED=null,CAPX=null,CIX=null,HPX=null,DTX=null,VISX=null,TEF=null,EP=0;
|
||||
// The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index.
|
||||
// F: its index; fci, fnj: its city and network index. BRX: BRJ with each list as a list object of one shape (lx()).
|
||||
let F=0,fci=0,fnj=0,Dv=null,Pv=null,PP=null,vis=0,GN=0,walked=[],BRX=[];const G=[],REST=[];
|
||||
const wW=e=>e.w;
|
||||
// Each network's list at one rank, in an array by network index: BRX[j] are objects of as many shapes as networks have
|
||||
// sets of ranks, and reading one per flow made the loop's code give up on them.
|
||||
const byRank=rank=>{const B=new Array(BRX.length);for(let j=0;j<BRX.length;j++){const l=BRX[j][rank];B[j]=l===undefined?null:l;}return B;};
|
||||
const nodeTake=(i,a)=>{const o=NRES[i];NRES[i]=o-a;if(o>1e-3&&NRES[i]<=1e-3)EP++;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;};
|
||||
// t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum).
|
||||
const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a;
|
||||
let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;};
|
||||
// TEF[src*NC+dst]: 1 once no detour exists for that pair (capacity only shrinks, so there never will be one again).
|
||||
// Most calls are those: a byte read, not a Map lookup. The kept path is still valid while every edge and node on it has room.
|
||||
const altPath=(src,dst,base)=>{const key=src*NC+dst;if(TEF[key]===1)return null;const c0=teCache.get(key);
|
||||
if(c0){let ok=true;const p=c0.path,ni=c0.ni;for(let k=0;k<p.length;k++)if(!(p[k].res>1e-3)){ok=false;break;}
|
||||
if(ok)for(let k=0;k<ni.length;k++){const i=ni[k];if(HAS[i]&&!(NRES[i]>1e-3)){ok=false;break;}}
|
||||
if(ok)return c0;}
|
||||
const d=teSearch(src,dst);
|
||||
if(d===Infinity||d>REACH*base+60){teCache.set(key,false);TEF[key]=1;return null;}
|
||||
const Q=walkP(DJ.P,src,dst);teCache.set(key,Q);return Q;};
|
||||
/* Auto-TE's detour search (the one 10-dijkstra.js does to a stop), step for step: neighbours in the same order, the same heap, written into the
|
||||
same DJ (walkP() reads its paths, the reuse above its marks). Only on the graph as flat arrays (TEO offsets by city,
|
||||
TEN neighbours, TEE edges, made once per routing in run()) and with the test of an edge written out: no pairs to
|
||||
unpack and no call for each edge. On a big network with Auto-TE these searches were most of the routing. */
|
||||
/* A search from one POP picks up where the last one from there stopped (LR*), as a search of its own would run: every
|
||||
city closer than the last exit is settled and the heap holds the rest, so the next exit has its answer already or
|
||||
the search goes on from there, the last exit's neighbours first (it stops before them). One that found nothing has
|
||||
walked all src reaches and answers the next ones at once. Only on the same graph: EP counts the edges and routers
|
||||
that run out of room (capacity only shrinks while routing, so none comes back), and another search in DJ moves its
|
||||
mark. An exit out of the core is let into a graph of its own (OUT[dst]): that search neither resumes nor is resumed.
|
||||
On a big network nearly all detours of a flow are found from one search (extreme: 3.6 M heap steps a routing → 0.17 M). */
|
||||
let TEO=null,TEN=null,TEE=null,LRs=-1,LRe=-1,LRg=-1,LRD=null,LRu=-1,LRm=0;
|
||||
const teSearch=(src,dst)=>{const n=TEO.length-1,core=CORE,cut=!!(core&&OUT[dst]),go=LRs===src&&LRe===EP&&LRg===DJ.g&&LRD===DJ.D&&!cut;
|
||||
let g,m=0,u=-1;
|
||||
if(go){g=LRg;if(DJ.done[dst]===g)return DJ.D[dst];m=LRm;u=LRu;}
|
||||
else{if(DJ.n!==n||DJ.g>2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;}g=++DJ.g;}
|
||||
const D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length;
|
||||
if(!go){D[src]=0;ST[src]=g;
|
||||
if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;}
|
||||
let i=m++;hd[i]=0;hu[i]=src;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}
|
||||
for(;;){
|
||||
if(u>=0){const d=D[u];for(let k=TEO[u],K=TEO[u+1];k<K;k++){const v=TEN[k],e=TEE[k];if(e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3)||(core&&OUT[v]&&v!==dst))continue;
|
||||
const nd=d+e.w;if(nd<(ST[v]===g?D[v]:Infinity)){D[v]=nd;ST[v]=g;P[v]=e;
|
||||
if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;}
|
||||
let i=m++;hd[i]=nd;hu[i]=v;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}}}
|
||||
if(!m){u=-1;break;}
|
||||
const d=hd[0];u=hu[0];m--;
|
||||
if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l<m&&hd[l]<hd[k])k=l;if(r<m&&hd[r]<hd[k])k=r;if(k===i)break;const td=hd[k],tu=hu[k];hd[k]=hd[i];hu[k]=hu[i];hd[i]=td;hu[i]=tu;i=k;}}
|
||||
if(DN[u]===g||d>(ST[u]===g?D[u]:Infinity)){u=-1;continue;}DN[u]=g;if(u===dst)break;}
|
||||
// An exit out of the core that was found sits in the heap of its own graph; one never found was never let in.
|
||||
if(cut&&u>=0)LRs=-1;else{LRs=src;LRe=EP;LRg=g;LRD=D;LRu=u;LRm=m;}
|
||||
return ST[dst]===g?D[dst]:Infinity;};
|
||||
/* The routing loops work on exits by number (xi, their index in E): what they read for every exit they look at sits in
|
||||
columns, USED, CAPX, CIX, HPX, DTX and VISX, and the lists they scan hold numbers (lst.x, lst.xat). Scanning objects of
|
||||
thirty fields each read one cache line per exit; the columns keep a list's exits side by side. The objects are only
|
||||
read for an exit that takes traffic (push()), and e.used is written back once routing is done (run()). */
|
||||
// An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path.
|
||||
const usable=x=>VISX[x]!==vis&&USED[x]<CAPX[x]&&Dv[CIX[x]]<Infinity&&!gone(x),byDist=(a,b)=>HPX[a]-HPX[b]||Dv[CIX[a]]-Dv[CIX[b]]+(DTX[a]-DTX[b]);
|
||||
// Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a
|
||||
// path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing
|
||||
// (most tries are into paths that filled up earlier).
|
||||
const push=(x,P,want,keep=0)=>{if(P.dead)return 0;const e=E[x];const path=P.path,ni=P.ni;let amt=want;
|
||||
const PN=path.length;for(let k=0;k<PN;k++){const l=path[k],r=l.res;if(r<=1e-6){P.dead=1;return 0;}amt=Math.min(amt,r-l.cap*keep);}
|
||||
const last=ni.length-1;
|
||||
for(let k=0;k<=last;k++){const i=ni[k];if(!HAS[i])continue;const r=NRES[i];if(r<=1e-6){P.dead=1;return 0;}const w=k&&k<last?PASS[i]:1;amt=Math.min(amt,r/w);}
|
||||
if(amt<=1e-6)return 0;
|
||||
for(let k=0;k<=last;k++){const i=ni[k];if(HAS[i])nodeTake(i,k&&k<last?amt*PASS[i]:amt);}
|
||||
const ek=e.ek,nr=fnj,ci=fci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc||(e.desc={lab:e.lab,city:e.city,k:e.k});e.told=true;}
|
||||
for(let k=0;k<PN;k++){const l=path[k],o=l.res;l.res=o-amt;if(o>1e-3&&l.res<=1e-3)EP++;l.ld+=amt;carry(l,ek,nr,ci,amt);}
|
||||
USED[x]+=amt;FREM[F]-=amt;
|
||||
{let ok=amt;const cf=CNB[ci],ce=e.cn,cn=NCN[nr],bz=FBZ[F]===1;
|
||||
if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
|
||||
SRV[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;}
|
||||
// Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then
|
||||
// it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays,
|
||||
// Korean users notice any exit far away, transit or not, and much sooner.
|
||||
// Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose
|
||||
// on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt).
|
||||
if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){if(P.ms<0){let ms=0,mt=0,se=null;for(let k=0;k<PN;k++){const x=path[k];ms+=x.lat;if(!x.sx)mt+=x.lat;if(x.sv)(se||(se=[])).push(x);}P.ms=ms;P.mt=mt;P.se=se;}const rtt=2*P.mt,kl=snd&&CITIES[ci].kr;
|
||||
const tl=(e.k==='t'||kl)&&rtt>(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0;
|
||||
if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok;
|
||||
// Where each flow left (the PNI list asks what a PNI here would take over, #175).
|
||||
if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);}
|
||||
if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}}
|
||||
return amt;
|
||||
};
|
||||
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
|
||||
// with free capacity, as long as they are no more than twice as long.
|
||||
const send=(x,want)=>{
|
||||
let room=Math.min(want,FREM[F],CAPX[x]-USED[x]);if(room<=1e-6)return;const ci=CIX[x];
|
||||
const P=PP[ci]||(PP[ci]=walkP(Pv,fci,ci));if(!P.dead)room-=push(x,P,room,TE&&SPILL<1?1-SPILL:0);
|
||||
if(TE&&room>1e-6&&FREM[F]>1e-6&&USED[x]<CAPX[x]&&ci!==fci)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(fci,ci,Dv[ci]);if(!P)break;const m=push(x,P,Math.min(room,CAPX[x]-USED[x]));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
|
||||
};
|
||||
// Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over
|
||||
// them by free capacity (like several transits in one city), then top up in order if one fills.
|
||||
// The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order).
|
||||
// Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes).
|
||||
const gone=x=>{if(TE)return false;const P=PP[CIX[x]];return !!P&&P.dead===1;};
|
||||
// Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group.
|
||||
const allRoom=c=>{for(let k=0;k<c.length;k++){const x=c[k];if(!(USED[x]<CAPX[x])||gone(x))return false;}return true;},NOG=[];
|
||||
/* dud(x): send() to x would do nothing, its path from here is full and, with Auto-TE, no detour exists (TEF) or the
|
||||
exit is here. Both last for the rest of the routing. Most exits a flow tries once its first group is full are such
|
||||
(seven in eight sends on a big network): they keep their share of a group's room, but are not called. */
|
||||
const dud=x=>{const ci=CIX[x],P=PP[ci];return P!==undefined&&P.dead===1&&(!TE||ci===fci||TEF[fci*NC+ci]===1);};
|
||||
const ROOM=[],sendGroup=(g,i0=0,i1=g.length)=>{let live=false;for(let k=i0;k<i1;k++){const x=g[k];VISX[x]=vis;if(!live&&!dud(x))live=true;}
|
||||
if(!live)return;
|
||||
if(i1-i0>1){let tot=0;for(let k=i0;k<i1;k++){const x=g[k],r=Math.max(0,CAPX[x]-USED[x]);ROOM[k-i0]=r;tot+=r;}const want=FREM[F];if(tot>1e-6)for(let k=i0;k<i1;k++)if(!dud(g[k]))send(g[k],want*ROOM[k-i0]/tot);}
|
||||
for(let k=i0;k<i1;k++){if(FREM[F]<=1e-6)break;if(!dud(g[k]))send(g[k],FREM[F]);}};
|
||||
// Stable, in place: short lists by insertion (no garbage), long ones by the built-in sort. Both are stable with the
|
||||
// same comparison, so the order is the same either way.
|
||||
// n: sort only a[0..n) (the group G holds GN exits).
|
||||
const sortD=(a,n=a.length)=>{if(n>24){if(n===a.length)a.sort(byDist);else{const t=a.slice(0,n).sort(byDist);for(let i=0;i<n;i++)a[i]=t[i];}return;}for(let i=1;i<n;i++){const x=a[i];let j=i-1;while(j>=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}};
|
||||
// The direct ranks (25-direct-egress.js) have short lists, one carrier's ports, so they take the plain way: the usable exits
|
||||
// nearest first, tried in groups of equal distance, as the reference loop in the tests does. A direct rank only concerns the
|
||||
// networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes
|
||||
// its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape.
|
||||
const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1],BR=byRank(rank);
|
||||
for(F=0;F<NF;F++){fnj=FNJ[F];fci=FCI[F];
|
||||
if(FREM[F]<=1e-6||DS[fnj]===0||PREFC[fci]===1||(pass!==0&&FBZ[F]!==(pass===1?1:0)))continue;
|
||||
let lst=BR[fnj];if(!lst)continue;if(lst.cs){lst=lst.cs[COMP[fci]];if(!lst)continue;}
|
||||
Dv=SDi[fci];Pv=SPi[fci];PP=walked[fci]||(walked[fci]=[]);vis++;
|
||||
REST.length=0;
|
||||
if(LOC){const here=lst.xat.get(fci);if(!here)continue;for(let h=0;h<here.length;h++)if(usable(here[h]))REST.push(here[h]);}
|
||||
else{const L=lst.x;for(let li=0;li<L.length;li++)if(usable(L[li]))REST.push(L[li]);}
|
||||
sortD(REST);
|
||||
for(let i=0;i<REST.length&&FREM[F]>1e-6;){let j=i+1;while(j<REST.length&&HPX[REST[j]]===HPX[REST[i]]&&Math.abs(Dv[CIX[REST[j]]]-Dv[CIX[REST[i]]]+(DTX[REST[j]]-DTX[REST[i]]))<1e-6)j++;sendGroup(REST,i,j);i=j;}}};
|
||||
/* One rank of one pass over every flow. Each hot loop of compute() sits in a function of its own: V8 optimises a small
|
||||
function quickly and keeps it, while compute() as a whole is too big to optimise cheaply (it would run unoptimised,
|
||||
boxing every number, and be compiled again and again in the background). The tables of a flow's city (distances,
|
||||
paths) are set up only once it has an exit list at this rank. */
|
||||
const rankPass=(rank,pass)=>{const BR=byRank(rank);
|
||||
for(F=0;F<NF;F++){
|
||||
if(FREM[F]<=1e-6||(rank===0&&FCA[F]===0)||(pass!==0&&FBZ[F]!==(pass===1?1:0)))continue;
|
||||
fnj=FNJ[F];let lst=BR[fnj];if(!lst)continue;fci=FCI[F];if(lst.cs){lst=lst.cs[COMP[fci]];if(!lst)continue;}
|
||||
Dv=SDi[fci];Pv=SPi[fci];PP=walked[fci]||(walked[fci]=[]);vis++;
|
||||
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
|
||||
exits gives. Exits only fill up once tried, so the usable ones stay the same until then. Nearly every flow
|
||||
fits in its first group: find that one with a scan (nothing is visited yet), and sort only what is left
|
||||
when it does not fit. Most often the group is the POP's own exits: with no preferred exit on the list
|
||||
and no other city at distance 0, the usable ones here are exactly the first group, already in order.
|
||||
The group is G[0..GN): emptying an array (length=0) gives back its storage, and the next push allocates it again. */
|
||||
GN=0;
|
||||
if(!lst.hi&&!lst.mx&&ALONE[fci]){const here=lst.xat.get(fci);if(here)for(let h=0;h<here.length;h++){const x=here[h];if(USED[x]<CAPX[x]&&!gone(x))G[GN++]=x;}}
|
||||
if(!GN){
|
||||
// One scan: the best (preference, distance) so far and, in list order, the exits within 1e-6 of it. The best
|
||||
// distance only goes down, so dropping the ones it leaves behind gives exactly the exits a second scan would.
|
||||
// Exits that are full stay full for this pass: when a quarter of a list is, it is rewritten without them.
|
||||
/* gc[ci]: the first group this list gave a flow from city ci. Exits only fill up during routing, so while all of
|
||||
them still have room no other exit can have become better, and the scan would find the same group (an
|
||||
empty one, no usable exit, stays empty). */
|
||||
const gc=lst.gc,c=gc[fci];
|
||||
if(c!==undefined&&allRoom(c)){if(!c.length)continue;for(let k=0;k<c.length;k++)G[GN++]=c[k];}else{
|
||||
if(lst.ord){
|
||||
/* The list in this city's order, kept by the route cache (xOrder()): the first group is where it starts, past
|
||||
the exits that are full or on a full path. Those stay so for the rest of the routing, so the start (cur) only
|
||||
moves on. The group is the next exits of the same preference within 1e-6 of the first one's distance, in the
|
||||
order the sort gave them: what the scan below finds. */
|
||||
const A=xOrder(lst,fci),N=A.length,cur=lst.cur;let k=cur[fci]|0;while(k<N&&(USED[A[k]]>=CAPX[A[k]]||gone(A[k])))k++;cur[fci]=k;
|
||||
if(k===N){gc[fci]=NOG;continue;}
|
||||
const bh=HPX[A[k]],bd=Dv[CIX[A[k]]]+DTX[A[k]];
|
||||
for(let i=k;i<N;i++){const x=A[i];if(HPX[x]!==bh||Dv[CIX[x]]+DTX[x]-bd>=1e-6)break;if(USED[x]<CAPX[x]&&!gone(x))G[GN++]=x;}
|
||||
gc[fci]=G.slice(0,GN);}else{
|
||||
let bh=2,bd=Infinity,full=0;const L=lst.x;
|
||||
for(let li=0,LN=L.length;li<LN;li++){const e=L[li];if(USED[e]>=CAPX[e]||gone(e)){full++;continue;}const d=Dv[CIX[e]]+DTX[e];if(d===Infinity)continue;const h=HPX[e];
|
||||
if(h<bh){bh=h;bd=d;GN=0;G[GN++]=e;}
|
||||
else if(h===bh){if(d<bd){bd=d;let k=0;for(let gi=0;gi<GN;gi++){const x=G[gi];if(Dv[CIX[x]]+DTX[x]-d<1e-6)G[k++]=x;}GN=k;G[GN++]=e;}else if(d-bd<1e-6)G[GN++]=e;}}
|
||||
if(full*4>=L.length&&full){let k=0;for(let li=0;li<L.length;li++){const e=L[li];if(USED[e]<CAPX[e])L[k++]=e;}L.length=k;}
|
||||
if(bh>1){gc[fci]=NOG;continue;}
|
||||
if(GN>1)sortD(G,GN);gc[fci]=G.slice(0,GN);}}}
|
||||
sendGroup(G,0,GN);
|
||||
if(FREM[F]<=1e-6)continue;
|
||||
// What is left, nearest first: with a kept order, the usable exits in it (the order sorting them gives).
|
||||
REST.length=0;if(lst.ord){const A=xOrder(lst,fci);for(let i=lst.cur[fci]|0;i<A.length;i++)if(usable(A[i]))REST.push(A[i]);}
|
||||
else{const L=lst.x;for(let li=0;li<L.length;li++)if(usable(L[li]))REST.push(L[li]);sortD(REST);}
|
||||
for(let i=0;i<REST.length&&FREM[F]>1e-6;){
|
||||
let j=i+1;while(j<REST.length&&HPX[REST[j]]===HPX[REST[i]]&&Math.abs(Dv[CIX[REST[j]]]-Dv[CIX[REST[i]]]+(DTX[REST[j]]-DTX[REST[i]]))<1e-6)j++;
|
||||
sendGroup(REST,i,j);i=j;
|
||||
}
|
||||
}};
|
||||
/* xOrder(lst, ci): the list's exits that city ci reaches, in a stable sort by preference and distance from ci (byDist,
|
||||
the comparison the scans sort their finds with). It only follows from the network's shape (distances, the exits and
|
||||
how they are preferred), so the route cache keeps it with the list (lst.ord, 29-route-cache.js): made the first time
|
||||
a flow from ci uses the list on a day the cache is used, then read every day until the shape changes. A list made
|
||||
fresh (the shape just changed) has no lst.ord and is scanned instead: one scan costs less than a sort. */
|
||||
const xOrder=(lst,ci)=>{let a=lst.ord[ci];if(a===undefined){const b=[],L=lst.x;
|
||||
for(let i=0;i<L.length;i++){const x=L[i];if(Dv[CIX[x]]<Infinity)b.push(x);}b.sort(byDist);a=lst.ord[ci]=Int32Array.from(b);}return a;};
|
||||
/* Each exit list once as a list object, all of one shape: x the exits by number in list order, xat by city, hi whether
|
||||
one is preferred, gc the first group each city found, ord the orders the route cache keeps (null on a fresh build),
|
||||
cur where each city's usable exits start in its order, cs the lists by island. */
|
||||
const lx=(A,W)=>{let w=W.get(A);if(w)return w;
|
||||
if(A.cs)w={x:null,xat:null,hi:false,mx:false,gc:null,ord:null,cur:null,cs:A.cs.map(s=>s&&lx(s,W))};
|
||||
else{const xat=new Map();for(const [c,h] of A.at)xat.set(c,h.map(e=>e.xi));w={x:A.map(e=>e.xi),xat,hi:!!A.hi,mx:!!A.mx,gc:[],ord:A.ord||null,cur:[],cs:null};}
|
||||
W.set(A,w);return w;};
|
||||
return {nodeTake,carry,
|
||||
nodes(o){({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD}=o);},
|
||||
run(o,PASSES,RANKS,RSET){({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP,
|
||||
TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff,SATN}=o);
|
||||
NX=E.length;USED=new Float64Array(NX);CAPX=new Float64Array(NX);CIX=new Int32Array(NX);HPX=new Uint8Array(NX);DTX=new Float64Array(NX);VISX=new Int32Array(NX);
|
||||
for(let x=0;x<NX;x++){const e=E[x];USED[x]=e.used;CAPX[x]=e.cap;CIX[x]=e.ci;HPX[x]=e.hp;DTX[x]=e.dt;}
|
||||
F=0;fci=0;fnj=0;Dv=null;Pv=null;PP=null;vis=0;GN=0;walked=[];EP=0;LRs=-1;LRD=null;
|
||||
if(TE){const n=adj.length;TEO=new Int32Array(n+1);let k=0;for(let u=0;u<n;u++){TEO[u]=k;const a=adj[u];if(a)k+=a.length;}TEO[n]=k;
|
||||
TEN=new Int32Array(k);TEE=new Array(k);k=0;for(let u=0;u<n;u++){const a=adj[u];if(a)for(let j=0;j<a.length;j++){TEN[k]=a[j][0];TEE[k]=a[j][1];k++;}}}TEF=TE?new Uint8Array(NC*NC):null;
|
||||
const W=new Map();BRX=new Array(BRJ.length);for(let j=0;j<BRJ.length;j++){const m=BRJ[j],b={};for(const r in m)b[r]=lx(m[r],W);BRX[j]=b;}
|
||||
for(const pass of PASSES)for(const rank of RANKS){
|
||||
if(!RSET.has(rank))continue;
|
||||
if(DSEL.has(rank)){directPass(rank,pass);continue;}
|
||||
rankPass(rank,pass);
|
||||
}
|
||||
for(let x=0;x<NX;x++)E[x].used=USED[x];
|
||||
// Nothing of this day is kept: the next run() sets its own.
|
||||
E=R2=BRJ=BRX=SDi=SPi=teCache=TEF=TEE=null;walked=[];}};
|
||||
}
|
||||
// The core in use (a test can put the plain one in its place: tests/speed.test.js).
|
||||
let ROUTE=routeCore();
|
||||
|
|
@ -22,7 +22,7 @@ function flDefine(R2,c){const {NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E
|
|||
/* Every exit has the same fields in the same order, whatever its kind, so the routing loop reads them from one object shape
|
||||
(exits of six shapes made each property read there a slow lookup). */
|
||||
function mkEx(k,id,city,cap,rank,pref,lab,ok,nets,net){return {k,net,id,city,lab,cap,used:0,rank,pref,ok,nets,dir:null,clean:false,prem:false,carry:false,prep:false,sac:false,pnc:false,
|
||||
ek:'',J:0,byC:null,desc:null,dup:false,told:false,hp:1,dt:0,ci:0,cn:false,vis:0,ts:-1,xi:0,kx:EXK.indexOf(k),fac:undefined};}
|
||||
ek:'',J:0,byC:null,desc:null,dup:false,told:false,hp:1,dt:0,ci:0,cn:false,ts:-1,xi:0,kx:EXK.indexOf(k),fac:undefined};}
|
||||
// The exit kinds by number (mkEx's kx), for what routing adds up per kind in typed arrays.
|
||||
const EXK=['t','ix','p','c'];
|
||||
function compute(){RW.gen++;
|
||||
|
|
@ -69,7 +69,9 @@ function compute(){RW.gen++;
|
|||
return E;})();
|
||||
const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);}
|
||||
// Who reaches whom and each network's exit lists, kept while the exits are the same (XC, 29-route-cache.js).
|
||||
const XK=RCON?rcExitKey(GK,E,(depeer?1:0)+'|'+leak+'|'+(snd?1:0)+'|'+(rp?ev.rpki.nets.join(','):'')+'|'+(TRX?S.te.script:'')+'|'+(PX&&PX.bh.length?PX.bh.map(e=>e.bh.city+'>'+e.bh.land).join(','):'')):null,XC=XK!==null&&RC.xk===XK?RC.x:null;
|
||||
// A backhaul through a dish changes a cut-off POP's distances: lists kept in order (29-route-cache.js) only for the same one.
|
||||
const BHK=PX&&PX.bh.length?PX.bh.map(e=>e.bh.city+'>'+e.bh.land).join(','):'';
|
||||
const XK=RCON?rcExitKey(GK,E,(depeer?1:0)+'|'+leak+'|'+(snd?1:0)+'|'+(rp?ev.rpki.nets.join(','):'')+'|'+(TRX?S.te.script:'')+'|'+BHK):null,XC=XK!==null&&RC.xk===XK?RC.x:null;
|
||||
// coneOf: does exit e reach network n only through a peer's customer cone (#85)?
|
||||
const coneOf=(e,n)=>e.k==='p'?e.net!==n:!!e.dir&&!e.dir.has(n);
|
||||
// ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank.
|
||||
|
|
@ -79,7 +81,7 @@ function compute(){RW.gen++;
|
|||
// TSL: a slot per transit port id, for what it carries to each network (R.tNet, added up in TNA).
|
||||
const ekN={},TSL=new Map();(()=>{for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;}
|
||||
// dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last.
|
||||
for(let i=0;i<E.length;i++){const e=E[i];e.xi=i;e.J=0;e.byC=null;e.desc=null;e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.dt=e.k==='ix'?PNI_TIE:0;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;}
|
||||
for(let i=0;i<E.length;i++){const e=E[i];e.xi=i;e.J=0;e.byC=null;e.desc=null;e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.dt=e.k==='ix'?PNI_TIE:0;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;}
|
||||
if(XC)continue;
|
||||
// Index loops or forEach (same order): for…of here made an iterator result per exit and network.
|
||||
const ns=e.nets||NET_IDS;if(Array.isArray(ns)){for(let q=0;q<ns.length;q++)okAdd(e,ns[q]);}else ns.forEach(n=>okAdd(e,n));}
|
||||
|
|
@ -127,12 +129,10 @@ function compute(){RW.gen++;
|
|||
for(const k in edges)edges[k].res=edges[k].cap;for(const c of pops){const i=CIDX[c];NRES[i]=nodeCap(c);HAS[i]=1;R2.nodeCap[c]=NRES[i];}
|
||||
// The core (backbone technology): what passing-through traffic costs each router, and which POPs TE must avoid.
|
||||
const CORE=coreOn()&&S.core.run>=1;if(CORE)for(const c of pops){const i=CIDX[c];PASS[i]=corePass(c);OUT[i]=inCore(c)?0:1;}
|
||||
const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;};
|
||||
const TNA=new Float64Array(TSL.size*NN),TNS=new Uint8Array(TSL.size*NN),TNK=[],TORD=[];
|
||||
const NKN=NN+3,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[];
|
||||
// t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum).
|
||||
const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a;
|
||||
let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;};
|
||||
// The routing core (29-route-core.js) adds up what floods and circuits carry too.
|
||||
ROUTE.nodes({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD});const nodeTake=ROUTE.nodeTake,carry=ROUTE.carry;
|
||||
R2.l2route={};R2.l2split={};
|
||||
/* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate
|
||||
hysteresis, so they do not flap). A second call can still move one; the third gives the same answer as the second. */
|
||||
|
|
@ -149,7 +149,7 @@ function compute(){RW.gen++;
|
|||
if(!seen[b])return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=CIDX[l.a]===v?CIDX[l.b]:CIDX[l.a];}return path;};
|
||||
const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.flatMap(l=>l.kind==='xp'?xpRisk(l):[srlg(l)])));};
|
||||
for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;}
|
||||
const l2Routes=(A,B,b)=>{const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B];
|
||||
const l2Routes=(A,B,b)=>{if(b.pin){const r=pinRoute(b.pin,edges);if(r)return [r];}const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B];
|
||||
if(PX&&m==='fast')return pieFast(PX,fastSP,A,B,b,wLat);
|
||||
if(m!=='scenic')return [{...walkI(m==='fast'?(fastSP[A]||(fastSP[A]=dijkstra(adj,Ai,wLat))).P:SPP[A],Ai,Bi),share:1}];
|
||||
const ek='l2:'+b.id,own=e=>(R.efg&&R.efg[e.id]&&R.efg[e.id].get(ek))||0;
|
||||
|
|
@ -190,11 +190,6 @@ function compute(){RW.gen++;
|
|||
for(const i of ni)if(HAS[i])nodeTake(i,amt);for(const l of path){l.res-=amt;l.ld+=amt;if(!clean){l.jk=(l.jk||0)+amt;JK=1;}carry(l,ek,clean?NN+2:NN,Bi,amt);}return amt;};
|
||||
const DD=ddosLoad({E,okBy,R2,autoBh:!!(TRX&&TRX.blackhole),haul,ms:msOf});
|
||||
const TE=!!(S.te&&S.te.on)&&coreTE(),TR=TE?teRules():null,REACH=coreTeReach();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1;
|
||||
const altPath=(src,dst,base)=>{const key=src*NC+dst,c0=teCache.get(key);
|
||||
if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0;
|
||||
const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3)||(CORE&&OUT[v]&&v!==dst),dst);
|
||||
if(D[dst]===Infinity||D[dst]>REACH*base+60){teCache.set(key,false);return null;}
|
||||
const Q=walkP(P,src,dst);teCache.set(key,Q);return Q;};
|
||||
/* A network in a peer's customer cone, reached through that peer (#85): after every network you peer with directly
|
||||
(its AS path is one hop longer) and before transit. */
|
||||
const base=(e,n)=>e.pref==='low'?4:e.rank>0&&e.rank<3&&coneOf(e,n)?CONE_RANK:e.rank;
|
||||
|
|
@ -218,126 +213,13 @@ function compute(){RW.gen++;
|
|||
if(dm&&r===3&&e.k==='t'){const t=dm.get(e.net);if(t){const d=DIRECT_RANK[t][e.carry?0:1];let ds=DSEL.get(d);if(!ds)DSEL.set(d,ds=new Uint8Array(NET_IDS.length));ds[j]=1;RSET.add(d);(m[d]||(m[d]=[])).push(e);}}}
|
||||
for(const r in m){const L=m[r],key=L.map(e=>e.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;}
|
||||
let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}}
|
||||
if(RCH)rcExitKeep(XK,E,okBy,RCH,LIST,BRJ,DSEL,RSET);})();
|
||||
// The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index.
|
||||
// F: its index; fci, fnj: its city and network index.
|
||||
let F=0,fci=0,fnj=0,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[];let GN=0;
|
||||
if(RCH)rcExitKeep(XK,E,okBy,RCH,LIST,BRJ,DSEL,RSET,BHK);})();
|
||||
/* What each kind of exit served, in all (EGT) and per network (NEA, by network index and kind): numbers in typed arrays,
|
||||
where a sum by key would box every new value. EGO and NEO keep the order each first got traffic, which is the order
|
||||
R.egT and R.netEg list them in; both are written back after routing. */
|
||||
const EGT=new Float64Array(4),EGO=[],NEA=new Float64Array(NN*4),NEO=[];
|
||||
// An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path.
|
||||
// byDist: (Da-Db)+(dta-dtb), so exits of one kind at one distance compare as exactly equal and keep their order.
|
||||
const usable=e=>e.vis!==vis&&e.used<e.cap&&Dv[e.ci]<Infinity&&!gone(e),byDist=(a,b)=>a.hp-b.hp||Dv[a.ci]-Dv[b.ci]+(a.dt-b.dt);
|
||||
// Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a
|
||||
// path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing
|
||||
// (most tries are into paths that filled up earlier).
|
||||
const push=(e,P,want,keep=0)=>{if(P.dead)return 0;const path=P.path,ni=P.ni;let amt=want;
|
||||
const PN=path.length;for(let k=0;k<PN;k++){const l=path[k],r=l.res;if(r<=1e-6){P.dead=1;return 0;}amt=Math.min(amt,r-l.cap*keep);}
|
||||
const last=ni.length-1;
|
||||
for(let k=0;k<=last;k++){const i=ni[k];if(!HAS[i])continue;const r=NRES[i];if(r<=1e-6){P.dead=1;return 0;}const w=k&&k<last?PASS[i]:1;amt=Math.min(amt,r/w);}
|
||||
if(amt<=1e-6)return 0;
|
||||
for(let k=0;k<=last;k++){const i=ni[k];if(HAS[i])nodeTake(i,k&&k<last?amt*PASS[i]:amt);}
|
||||
const ek=e.ek,nr=fnj,ci=fci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc||(e.desc={lab:e.lab,city:e.city,k:e.k});e.told=true;}
|
||||
for(let k=0;k<PN;k++){const l=path[k];l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);}
|
||||
e.used+=amt;FREM[F]-=amt;
|
||||
{let ok=amt;const cf=CNB[ci],ce=e.cn,cn=NCN[nr],bz=FBZ[F]===1;
|
||||
if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
|
||||
SRV[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;}
|
||||
// Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then
|
||||
// it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays,
|
||||
// Korean users notice any exit far away, transit or not, and much sooner.
|
||||
// Over a satellite users notice too, whatever the exit: the path's edges with one (se) keep what this flow would lose
|
||||
// on each orbit, and satAfter() charges the share the satellite really carried. The haul to transit counts on the ground (mt).
|
||||
if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr||SATN)){if(P.ms<0){let ms=0,mt=0,se=null;for(let k=0;k<PN;k++){const x=path[k];ms+=x.lat;if(!x.sx)mt+=x.lat;if(x.sv)(se||(se=[])).push(x);}P.ms=ms;P.mt=mt;P.se=se;}const rtt=2*P.mt,kl=snd&&CITIES[ci].kr;
|
||||
const tl=(e.k==='t'||kl)&&rtt>(kl?KR_LAT_OK:LAT_OK)?(kl?krLatLoss(rtt):latLoss(rtt)):0;
|
||||
if(tl>0){LATP[ci]+=ok*tl;if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}if(P.se)satNote(P.se,ci,ok,tl);}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok;
|
||||
// Where each flow left (the PNI list asks what a PNI here would take over, #175).
|
||||
if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);}
|
||||
if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}}
|
||||
return amt;
|
||||
};
|
||||
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
|
||||
// with free capacity, as long as they are no more than twice as long.
|
||||
const send=(e,want)=>{
|
||||
let room=Math.min(want,FREM[F],e.cap-e.used);if(room<=1e-6)return;
|
||||
const P=PP[e.ci]||(PP[e.ci]=walkP(Pv,fci,e.ci));if(!P.dead)room-=push(e,P,room,TE&&SPILL<1?1-SPILL:0);
|
||||
if(TE&&room>1e-6&&FREM[F]>1e-6&&e.used<e.cap&&e.ci!==fci)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(fci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
|
||||
};
|
||||
// Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over
|
||||
// them by free capacity (like several transits in one city), then top up in order if one fills.
|
||||
// The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order).
|
||||
// Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes).
|
||||
const gone=e=>{if(TE)return false;const P=PP[e.ci];return !!P&&P.dead===1;};
|
||||
// Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group.
|
||||
const allRoom=c=>{for(let k=0;k<c.length;k++){const e=c[k];if(!(e.used<e.cap)||gone(e))return false;}return true;},NOG=[];
|
||||
const ROOM=[],sendGroup=(g,i0=0,i1=g.length)=>{for(let k=i0;k<i1;k++)g[k].vis=vis;
|
||||
if(i1-i0>1){let tot=0;for(let k=i0;k<i1;k++){const e=g[k],r=Math.max(0,e.cap-e.used);ROOM[k-i0]=r;tot+=r;}const want=FREM[F];if(tot>1e-6)for(let k=i0;k<i1;k++)if(!gone(g[k]))send(g[k],want*ROOM[k-i0]/tot);}
|
||||
for(let k=i0;k<i1;k++){if(FREM[F]<=1e-6)break;if(!gone(g[k]))send(g[k],FREM[F]);}};
|
||||
// Stable, in place: short lists by insertion (no garbage), long ones by the built-in sort. Both are stable with the
|
||||
// same comparison, so the order is the same either way.
|
||||
// n: sort only a[0..n) (the group G holds GN exits).
|
||||
const sortD=(a,n=a.length)=>{if(n>24){if(n===a.length)a.sort(byDist);else{const t=a.slice(0,n).sort(byDist);for(let i=0;i<n;i++)a[i]=t[i];}return;}for(let i=1;i<n;i++){const x=a[i];let j=i-1;while(j>=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}};
|
||||
// The direct ranks (25-direct-egress.js) have short lists, one carrier's ports, so they take the plain way: the usable exits
|
||||
// nearest first, tried in groups of equal distance, as the reference loop in the tests does. A direct rank only concerns the
|
||||
// networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes
|
||||
// its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape.
|
||||
const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1];
|
||||
for(F=0;F<NF;F++){fnj=FNJ[F];fci=FCI[F];
|
||||
if(FREM[F]<=1e-6||DS[fnj]===0||PREFC[fci]===1||(pass!==0&&FBZ[F]!==(pass===1?1:0)))continue;
|
||||
let lst=BRJ[fnj][rank];if(!lst)continue;if(lst.cs){lst=lst.cs[COMP[fci]];if(!lst)continue;}
|
||||
Dv=SDi[fci];Pv=SPi[fci];PP=walked[fci]||(walked[fci]=[]);vis++;
|
||||
REST.length=0;
|
||||
if(LOC){const here=lst.at.get(fci);if(!here)continue;for(let h=0;h<here.length;h++)if(usable(here[h]))REST.push(here[h]);}
|
||||
else for(let li=0;li<lst.length;li++)if(usable(lst[li]))REST.push(lst[li]);
|
||||
sortD(REST);
|
||||
for(let i=0;i<REST.length&&FREM[F]>1e-6;){let j=i+1;while(j<REST.length&&REST[j].hp===REST[i].hp&&Math.abs(Dv[REST[j].ci]-Dv[REST[i].ci]+(REST[j].dt-REST[i].dt))<1e-6)j++;sendGroup(REST,i,j);i=j;}}};
|
||||
/* One rank of one pass over every flow. Each hot loop of compute() sits in a function of its own: V8 optimises a small
|
||||
function quickly and keeps it, while compute() as a whole is too big to optimise cheaply (it would run unoptimised,
|
||||
boxing every number, and be compiled again and again in the background). The tables of a flow's city (distances,
|
||||
paths) are set up only once it has an exit list at this rank. */
|
||||
const rankPass=(rank,pass)=>{
|
||||
for(F=0;F<NF;F++){
|
||||
if(FREM[F]<=1e-6||(rank===0&&FCA[F]===0)||(pass!==0&&FBZ[F]!==(pass===1?1:0)))continue;
|
||||
fnj=FNJ[F];let lst=BRJ[fnj][rank];if(!lst)continue;fci=FCI[F];if(lst.cs){lst=lst.cs[COMP[fci]];if(!lst)continue;}
|
||||
Dv=SDi[fci];Pv=SPi[fci];PP=walked[fci]||(walked[fci]=[]);vis++;
|
||||
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
|
||||
exits gives. Exits only fill up once tried, so the usable ones stay the same until then. Nearly every flow
|
||||
fits in its first group: find that one with a scan (nothing is visited yet), and sort only what is left
|
||||
when it does not fit. Most often the group is the POP's own exits: with no preferred exit on the list
|
||||
and no other city at distance 0, the usable ones here are exactly the first group, already in order.
|
||||
The group is G[0..GN): emptying an array (length=0) gives back its storage, and the next push allocates it again. */
|
||||
GN=0;
|
||||
if(!lst.hi&&!lst.mx&&ALONE[fci]){const here=lst.at.get(fci);if(here)for(let h=0;h<here.length;h++){const e=here[h];if(e.used<e.cap&&!gone(e))G[GN++]=e;}}
|
||||
if(!GN){
|
||||
// One scan: the best (preference, distance) so far and, in list order, the exits within 1e-6 of it. The best
|
||||
// distance only goes down, so dropping the ones it leaves behind gives exactly the exits a second scan would.
|
||||
// Exits that are full stay full for this pass: when a quarter of a list is, it is rewritten without them.
|
||||
/* gc[ci]: the first group this list gave a flow from city ci. Exits only fill up during routing, so while all of
|
||||
them still have room no other exit can have become better, and the scan would find the same group (an
|
||||
empty one, no usable exit, stays empty). */
|
||||
const gc=lst.gc||(lst.gc=[]),c=gc[fci];
|
||||
if(c!==undefined&&allRoom(c)){if(!c.length)continue;for(let k=0;k<c.length;k++)G[GN++]=c[k];}else{
|
||||
let bh=2,bd=Infinity,full=0;
|
||||
for(let li=0,LN=lst.length;li<LN;li++){const e=lst[li];if(e.used>=e.cap||gone(e)){full++;continue;}const d=Dv[e.ci]+e.dt;if(d===Infinity)continue;const h=e.hp;
|
||||
if(h<bh){bh=h;bd=d;GN=0;G[GN++]=e;}
|
||||
else if(h===bh){if(d<bd){bd=d;let k=0;for(let gi=0;gi<GN;gi++){const x=G[gi];if(Dv[x.ci]+x.dt-d<1e-6)G[k++]=x;}GN=k;G[GN++]=e;}else if(d-bd<1e-6)G[GN++]=e;}}
|
||||
if(full*4>=lst.length&&full){let k=0;for(let li=0;li<lst.length;li++){const e=lst[li];if(e.used<e.cap)lst[k++]=e;}lst.length=k;}
|
||||
if(bh>1){gc[fci]=NOG;continue;}
|
||||
if(GN>1)sortD(G,GN);gc[fci]=G.slice(0,GN);}}
|
||||
sendGroup(G,0,GN);
|
||||
if(FREM[F]<=1e-6)continue;
|
||||
REST.length=0;for(let li=0;li<lst.length;li++)if(usable(lst[li]))REST.push(lst[li]);sortD(REST);
|
||||
for(let i=0;i<REST.length&&FREM[F]>1e-6;){
|
||||
let j=i+1;while(j<REST.length&&REST[j].hp===REST[i].hp&&Math.abs(Dv[REST[j].ci]-Dv[REST[i].ci]+(REST[j].dt-REST[i].dt))<1e-6)j++;
|
||||
sendGroup(REST,i,j);i=j;
|
||||
}
|
||||
}};
|
||||
for(const pass of PASSES)for(const rank of RANKS){
|
||||
if(!RSET.has(rank))continue;
|
||||
if(DSEL.has(rank)){directPass(rank,pass);continue;}
|
||||
rankPass(rank,pass);
|
||||
}
|
||||
R.egT and R.netEg list them in; both are written back after routing. NEG: each network's R.netEg record. */
|
||||
const EGT=new Float64Array(4),EGO=[],NEA=new Float64Array(NN*4),NEO=[],NEG=[];
|
||||
ROUTE.run({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP,
|
||||
TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff,SATN},PASSES,RANKS,RSET);
|
||||
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
|
||||
for(const k of EGO)R2.egT[EXK[k]]=EGT[k];for(const j of NEO){const ne=NEG[j];for(let k=0;k<4;k++)ne[EXK[k]]=NEA[j*4+k];}
|
||||
(()=>{
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}
|
|||
function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];}
|
||||
// Cut, or cut off by an event between its two countries, whatever runs on it (an express asks this of each fiber it rides).
|
||||
function linkCut(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))));}
|
||||
function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0)||(l.kind==='xp'&&xpDown(l))||(l.kind==='sat'&&l.ready>S.day);}
|
||||
function linkDown(l){return linkCut(l)||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l))||(l.kind==='xp'&&xpDown(l))||(l.kind==='sat'&&l.ready>S.day);}
|
||||
function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);}
|
||||
function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);}
|
||||
// Monthly price of one connection; compute() sums these, the connections overview lists them.
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ function sanitize(s){
|
|||
if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra';
|
||||
opsSanitize(s);
|
||||
const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40);
|
||||
s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;});
|
||||
s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);if(l.list!==undefined){const L=l.kind==='df'?cmClean(l.list):null;if(L)l.list=L;else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&(!own(CAB,l.cable)||!cablePair(l.cable,l.a,l.b)))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;});
|
||||
for(const l of s.links)repairSubUpgradeDates(l,s.day);
|
||||
xpSanitize(s);
|
||||
/* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its
|
||||
|
|
@ -55,7 +55,7 @@ function sanitize(s){
|
|||
for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];}
|
||||
for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);}
|
||||
const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity));
|
||||
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;};
|
||||
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;if(b.pin!==undefined){const p=b.pin;if(!Array.isArray(p)||p.length<2||p.length>64||!p.every(isCity)||new Set(p).size!==p.length||!BIZ_T[b.type].l2||b.sites||p[0]!==b.city||p[p.length-1]!==b.city2)delete b.pin;}return b;};
|
||||
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz);
|
||||
// Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally.
|
||||
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s);
|
||||
|
|
@ -77,7 +77,10 @@ function sanitize(s){
|
|||
for(const i of s.inc){if(i.type!=='cut'||i.st==null){for(const k of ['ship','seaq','st','sw','sp','sl'])delete i[k];continue;}
|
||||
i.st=clamp(num(i.st,0.5),0.03,0.97);i.sw=int(i.sw,1,30,4);i.sp=int(i.sp,0,60,0);i.sl=typeof i.sl==='string'?i.sl.slice(0,40):'';i.rushed=!!i.rushed||undefined;
|
||||
if(i.ship!=null&&!(own(SHIP,i.ship)&&o[i.ship]&&o[i.ship].inc===i.id))i.ship=null;if(i.ship==null){i.ship=null;i.seaq=1;}else delete i.seaq;}
|
||||
for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2;}
|
||||
for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2;
|
||||
// A lay ship held by a delay (#322): only on your own subsea cable still being laid.
|
||||
for(const l of s.links){const v=l.lay;if(v===undefined)continue;if(!(v&&typeof v==='object'&&!Array.isArray(v)&&l.kind==='df'&&l.own&&l.sub&&l.ready>s.day)){delete l.lay;continue;}
|
||||
const t=Math.round(clamp(num(v.t,s.day),0,l.ready));l.lay={s:Math.round(clamp(num(v.s,s.day),0,Math.min(s.day,t))),q:clamp(num(v.q,0),0,1),t};}}
|
||||
s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank));
|
||||
s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&e.o.a==='inbox'?{a:'tab',v:'nets'}:e&&e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='ops'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null;
|
||||
return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};});
|
||||
|
|
@ -113,7 +116,8 @@ function sanitize(s){
|
|||
{const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{};
|
||||
const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);}
|
||||
specSanitize(s);mpSanitize(s);
|
||||
pieSanitize(s);pieIncFix(s);
|
||||
cmFix(s);
|
||||
pieSanitize(s);pieIncFix(s);volFix(s);
|
||||
ip4Fix(s);
|
||||
satSanitize(s);
|
||||
if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}}
|
||||
|
|
|
|||
|
|
@ -25,54 +25,69 @@ const REQS={
|
|||
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);}
|
||||
function terrIslands(){const adj={};for(const l of S.links)if(!l.sub&&!linkDown(l)){(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;}
|
||||
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=>!l.sub&&!linkDown(l));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);
|
||||
function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(lab)}</div>`;}).join('');}
|
||||
function diversePaths(a,b){
|
||||
const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);
|
||||
return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));}
|
||||
function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?['fab:'+l.prov]:l.kind==='xp'?xpRisk(l):[l.trench||l.id];
|
||||
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
|
||||
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
|
||||
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
|
||||
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.flatMap(srlg));return !!bfs(live.filter(l=>!srlg(l).some(r=>used.has(r))));}
|
||||
/* diversePaths(): a shortest path by hops over the live links (and VXCs to remote cities), then another one that shares
|
||||
none of its risks. divGraph() numbers the cities and the risks and lists each city's links once, in list order, as
|
||||
disjointOn() reads them; divOn() asks it, so many pairs on one network (spots0(), opsDecomSafe()) share one graph. The
|
||||
second search skips the first path's risks rather than rebuilding the graph without them: the same lists in the same
|
||||
order, so the same answer. An express runs in the trenches of every fiber it rides (xpRisk()): one backhoe in any of
|
||||
them takes it out, so its link carries the list of those risks. */
|
||||
const srlgOf=l=>l.kind==='vxc'?'fab:'+l.prov:l.kind==='xp'?xpRisk(l):(l.trench||l.id);
|
||||
function divGraph(live){if(!live){const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));}
|
||||
const ix=new Map(),rk=new Map(),adj=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=adj.length);adj.push([]);}return i;},
|
||||
rid=s=>{let r=rk.get(s);if(r===undefined)rk.set(s,r=rk.size);return r;};
|
||||
for(const l of live){const s=srlgOf(l),r=Array.isArray(s)?(s.length===1?rid(s[0]):s.map(rid)):rid(s);const u=id(l.a),v=id(l.b);adj[u].push(v,r);adj[v].push(u,r);}return {ix,adj};}
|
||||
function divOn(g,a,b){if(a===b)return true;const i=g.ix.get(a),j=g.ix.get(b);return i!==undefined&&j!==undefined&&disjointOn(g.adj,i,j);}
|
||||
function diversePaths(a,b){return divOn(divGraph(),a,b);}
|
||||
function disjointRoutes(a,b,live){return divOn(divGraph(live),a,b);}
|
||||
// Check buildable geography, not today's POPs, capacity or outages. Parallel land
|
||||
// routes can use separate trenches; all segments of one cable share its risk.
|
||||
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);}}}
|
||||
if(prev[b]<0)return null;const used=new Set();for(let v=b;v!==a;v=prev[v])used.add(pl[v]);return used;};
|
||||
// A link's risk is a number, or a list of them for an express (divGraph()); pk: where each city's arriving link sits in adj.
|
||||
function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pk=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)continue;const r=L[k+1];
|
||||
if(skip&&(typeof r==='number'?skip.has(r):r.some(x=>skip.has(x))))continue;prev[v]=u;pk[v]=k+1;q.push(v);}}
|
||||
if(prev[b]<0)return null;const used=new Set();for(let v=b;v!==a;v=prev[v]){const r=adj[prev[v]][pk[v]];if(typeof r==='number')used.add(r);else for(const x of r)used.add(x);}return used;};
|
||||
const p1=bfs(null);return !!p1&&!!bfs(p1);}
|
||||
// Big networks have thousands of links and customers: callers that ask about all of them (compute(), the daily mood
|
||||
// check, new offers) look links up and add up what is sold in one pass (linkIds(), fiberUse()), not once per item.
|
||||
|
|
@ -80,7 +95,7 @@ const linkIds=()=>{const m=new Map();for(const l of S.links)if(!m.has(l.id))m.se
|
|||
function fiberUse(){const sold=new Map(),dfp=new Map(),pairs=new Set();
|
||||
for(const b of S.biz){if(b.type==='wwave')sold.set(b.link,(sold.get(b.link)||0)+(b.slots||0));else if(b.type==='dfpair')dfp.set(b.link,(dfp.get(b.link)||0)+1);else if(b.type==='pairs'||b.type==='capfib')pairs.add(b.link);}
|
||||
return {sold,dfp,pairs};}
|
||||
function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day);}
|
||||
function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day)&&(b.type!=='mwave'||dfLit(l)>=mwG(l));}
|
||||
function soldSlots(l,u){return u?u.sold.get(l.id)||0:S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);}
|
||||
// Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build
|
||||
// a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices.
|
||||
|
|
|
|||
|
|
@ -53,16 +53,40 @@ function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let
|
|||
function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`<p class="note">${landWhy(a,b)}</p>`:'';const wr=waveRoute(a,b,1,false);
|
||||
const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} <small>${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}</small>`})));
|
||||
return `<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}</p>`:''}`;}
|
||||
function bestLat(a,b,f){const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}
|
||||
/* bestLat(a,b,f): the lowest one-way latency over the live links (f: only those), +0.05 ms a hop. latGraph() numbers the
|
||||
cities with a live link (ix) and lists each one's links once, in S.links order, with their latency (off/nb/w). latRun() is
|
||||
the search itself: the next city is the closest found so far, the first found among equals, and the sums are the same
|
||||
(d + latency + 0.05), so the same answers. Stopped at b, or run whole (no b): distances by city number, which is what
|
||||
asking from a for several cities takes (latAt(): solRoutes(), spots0(), opsDecomSafe()). */
|
||||
function latGraph(f){const ix=new Map(),deg=[],E=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=deg.length);deg.push(0);}return i;};
|
||||
for(const l of S.links){if(linkDown(l)||f&&!f(l))continue;const u=id(l.a),v=id(l.b);E.push(u,v,linkLat(l));deg[u]++;if(v!==u)deg[v]++;}
|
||||
const n=deg.length,off=new Int32Array(n+1);for(let i=0;i<n;i++)off[i+1]=off[i]+deg[i];const at=off.slice(0,n),nb=new Int32Array(off[n]),w=new Float64Array(off[n]);
|
||||
for(let k=0;k<E.length;k+=3){const u=E[k],v=E[k+1];nb[at[u]]=v;w[at[u]++]=E[k+2];if(v!==u){nb[at[v]]=u;w[at[v]++]=E[k+2];}}return {ix,n,off,nb,w};}
|
||||
function latRun(g,a,b){const s=g.ix.get(a),all=b===undefined;if(s===undefined)return all?null:a===b?0:Infinity;const t=all?-1:g.ix.get(b);if(t===undefined)return Infinity;
|
||||
const {n,off,nb,w}=g,d=new Float64Array(n).fill(Infinity),seen=new Int32Array(n),done=new Uint8Array(n);let m=1;seen[0]=s;d[s]=0;
|
||||
for(;;){let u=-1,ud=Infinity;for(let i=0;i<m;i++){const k=seen[i];if(!done[k]&&d[k]<ud){u=k;ud=d[k];}}if(u<0)break;if(u===t)return ud;done[u]=1;
|
||||
for(let e=off[u];e<off[u+1];e++){const v=nb[e],nd=ud+w[e]+0.05;if(nd<d[v]){if(d[v]===Infinity)seen[m++]=v;d[v]=nd;}}}return all?d:Infinity;}
|
||||
// From a whole run d out of a: the latency to b.
|
||||
const latAt=(g,d,a,b)=>{if(a===b)return 0;const k=g.ix.get(b);return d&&k!==undefined?d[k]:Infinity;};
|
||||
function bestLat(a,b,f){return latRun(latGraph(f),a,b);}
|
||||
// From each of these cities to the ones after it in the list: [[a,b,ms]…], one search per city.
|
||||
function latPairs(f,g){const G=latGraph(g),o=[];for(let i=0;i<f.length-1;i++){const d=latRun(G,f[i]);for(let j=i+1;j<f.length;j++)o.push([f[i],f[j],latAt(G,d,f[i],f[j])]);}return o;}
|
||||
// The lowest one-way latency anything you could build gets between two cities (#273), the way bestLat() adds it up:
|
||||
// your own fiber over land (×1.1, wherever isSub() allows it), or the route of a cable that lands at both ends (your own cable in the low-latency
|
||||
// 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;}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,11 @@ function shipStatus(i){if(!shipSea(i))return '';const l=shipLink(i);if(!l)return
|
|||
/* Laying your own subsea cable: the last part of the build is a lay ship at sea, about 150 km a day. A second ship,
|
||||
booked before laying starts, works from the other end and halves that part; nothing at sea speeds up the survey,
|
||||
the permits or the cable factory. */
|
||||
const layDays=l=>Math.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.ready-layLen(l);
|
||||
const layDays=l=>Math.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.lay?l.lay.s:l.ready-layLen(l);
|
||||
/* A delay once the ship is at sea (#322) holds it where it is: l.lay = {s: the day laying began, q: the share laid,
|
||||
t: the day it lays on}. Without it, laying is simply the last layLen() days before ready. */
|
||||
function layHold(l,shift,day){if(!layOwn(l)||!(shift>0)||l.ready<=day||day<layStart(l))return;
|
||||
l.lay={s:layStart(l),q:+layDone(l,day).toFixed(4),t:Math.max(day,l.lay?l.lay.t:day)+shift};}
|
||||
const layOwn=l=>l.kind==='df'&&l.own&&l.sub;
|
||||
const layName=(l,k=0)=>{let h=0;for(const ch of String(l.id))h=(h*31+ch.charCodeAt(0))>>>0;return LAY_SHIPS[(h+k)%LAY_SHIPS.length];};
|
||||
function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+1)return null;const save=Math.floor(layDays(l)/2);if(save<1)return null;return {save,cost:SHIP_MOB+save*LAY_DAY};}
|
||||
|
|
@ -83,4 +87,4 @@ function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+
|
|||
const PREP_STEP=30,prepMin=l=>leadDays(Math.round(60+(l.km||0)*0.012)),prepCost=l=>Math.round((500000+(l.km||0)*60)*hwMul('build')),
|
||||
prepFloor=l=>Math.max(S.day+1,(l.day||0)+prepMin(l))+layLen(l),
|
||||
prepSteps=l=>layOwn(l)&&l.ready>S.day&&S.day<layStart(l)?Math.max(0,Math.ceil((l.ready-prepFloor(l))/PREP_STEP)):0;
|
||||
const layDone=(l,T)=>clamp((T-layStart(l))/layLen(l),0,1);
|
||||
const layDone=(l,T)=>l.lay?l.lay.q+(1-l.lay.q)*clamp((T-l.lay.t)/Math.max(1,l.ready-l.lay.t),0,1):clamp((T-layStart(l))/layLen(l),0,1);
|
||||
|
|
|
|||
|
|
@ -60,11 +60,11 @@ 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);
|
||||
S.stats.peak=Math.max(S.stats.peak,R.served);volDay();
|
||||
S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift();
|
||||
{const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`<br><i>${esc(LEVELS[lv-1].q)}</i>`,'goal');}S.lvl=top;sfx('coin');}}
|
||||
for(const l of S.links){if(l.kind!=='df')continue;
|
||||
if(l.ready===d){toast(`<b>${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}</b><br>${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);sfx('coin');}
|
||||
if(l.ready===d){delete l.lay;toast(`<b>${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}</b><br>${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);sfx('coin');}
|
||||
if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+leadDays(extra));toast(tr('day_tick.construction_delay_n_days_why_a',{n:leadDays(extra),why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}}
|
||||
// DDoS protection SLA: a protected customer under attack who goes down, or is blackholed, is paid out (once per attack).
|
||||
for(const a of ddosAll()){
|
||||
|
|
@ -98,7 +98,7 @@ function* dayPost(d){
|
|||
if(rule('money')==='infinite'&&S.cash<1e8)S.cash=1e9;
|
||||
// offers
|
||||
S.offers=S.offers.filter(o=>o.exp>d);
|
||||
brTick();
|
||||
cmDay(d);
|
||||
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
|
||||
|
|
|
|||
15
src/game/88-days/15-day-pace.js
Normal file
15
src/game/88-days/15-day-pace.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
/* ---------- the pace of days, as measured ----------
|
||||
How fast days really come with the route worker, for Settings › Diagnostic info: the speed asked, the speed held
|
||||
(from the starts of the last 12 days), how long a day takes from its start to its end, and the slowest of them.
|
||||
Measured only: a clock that started days on a steady beat was tried, and on big networks it cost a sixth of the
|
||||
speed without making the days any more regular (their spread comes from the long days themselves, a second routing
|
||||
for the intern's jobs or a failure, which no beat can hide). */
|
||||
const PACE={s:null,sp:0,st:[],d:[],t0:0};
|
||||
// A day starts (runClock(), 99-loop.js) / has ended (rwDayDone(), 28-route-worker.js). A new speed or another game:
|
||||
// the measure starts again.
|
||||
function paceStart(now){const P=PACE;if(P.s!==S||P.sp!==UI.speed){P.s=S;P.sp=UI.speed;P.st.length=0;P.d.length=0;}
|
||||
P.st.push(now);if(P.st.length>13)P.st.shift();P.t0=now;}
|
||||
function paceEnd(now){const P=PACE;if(!P.t0)return;P.d.push(now-P.t0);if(P.d.length>12)P.d.shift();P.t0=0;}
|
||||
function diagPace(){const P=PACE;if(!S||!UI.speed)return 'days: paused';if(P.s!==S||P.sp!==UI.speed||P.st.length<3)return `days: x${UI.speed} asked · measuring`;
|
||||
const gap=(P.st[P.st.length-1]-P.st[0])/(P.st.length-1),d=P.d.length?P.d.reduce((a,x)=>a+x,0)/P.d.length:0;
|
||||
return `days: x${UI.speed} asked · x${(DAY_MS/gap).toFixed(1)} held (one every ${Math.round(gap)} ms)`+(d?` · a day takes ${Math.round(d)} ms, slowest ${Math.round(Math.max(...P.d))}`:'');}
|
||||
12
src/game/88-days/15-traffic-volume.js
Normal file
12
src/game/88-days/15-traffic-volume.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/* ---------- Traffic carried: the network's odometer ----------
|
||||
S.vol counts the petabytes the network has carried in this game: every day adds a day of what it served. R.served
|
||||
is in Gbps, so a day of 1 Gbps is 86,400 gigabits, 10.8 terabytes, 0.0108 PB. Badges ride on it (20-badges.js),
|
||||
from the first petabyte to a zettabyte, the whole internet's traffic in a year around 2016. */
|
||||
const PB_DAY=86400/8/1e6;
|
||||
function volDay(){S.vol=(S.vol||0)+(R.served>0?R.served*PB_DAY:0);}
|
||||
// A volume of traffic, from the petabytes it is stored in: TB, PB, EB, ZB.
|
||||
const fmtVol=pb=>pb>=1e6?(pb/1e6).toFixed(pb>=1e7?1:2)+' ZB':pb>=1000?(pb/1000).toFixed(pb>=1e4?1:2)+' EB':pb>=1?pb.toFixed(pb>=10?0:1)+' PB':(pb*1000).toFixed(pb>=0.01?0:1)+' TB';
|
||||
// Saves: a number of petabytes. A save from before the odometer starts from the days its history still holds (the
|
||||
// last 180), so an old network gets most of the credit it earned.
|
||||
function volFix(s){if(typeof s.vol==='number'&&Number.isFinite(s.vol)&&s.vol>=0)return;
|
||||
s.vol=(Array.isArray(s.hist)?s.hist:[]).reduce((a,h)=>a+(h&&typeof h.srv==='number'&&h.srv>0&&Number.isFinite(h.srv)?h.srv:0),0)*PB_DAY;}
|
||||
|
|
@ -54,8 +54,15 @@ const BADGES=[
|
|||
{id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13},
|
||||
{id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))},
|
||||
{id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&S.day<=730},
|
||||
{id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'l',ok:()=>R.served>=100000},
|
||||
{id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'c',ok:()=>R.served>=1000},
|
||||
{id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'r',ok:()=>R.served>=10000},
|
||||
{id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'e',ok:()=>R.served>=100000},
|
||||
{id:'petabit',i:'🪐',t:tr('badges.a_petabit_a_second'),d:tr('badges.serve_1_pbps_a_thousand_terabits'),r:'l',ok:()=>R.served>=1e6},
|
||||
// Traffic carried in total (15-traffic-volume.js): the odometer, in petabytes.
|
||||
{id:'vol_pb',i:'💾',t:tr('badges.vol_pb'),d:tr('badges.vol_pb_d'),r:'c',ok:()=>(S.vol||0)>=1},
|
||||
{id:'vol_100pb',i:'🗄️',t:tr('badges.vol_100pb'),d:tr('badges.vol_100pb_d'),r:'r',ok:()=>(S.vol||0)>=100},
|
||||
{id:'vol_eb',i:'🚂',t:tr('badges.vol_eb'),d:tr('badges.vol_eb_d'),r:'e',ok:()=>(S.vol||0)>=1000},
|
||||
{id:'vol_zb',i:'🌠',t:tr('badges.vol_zb'),d:tr('badges.vol_zb_d'),r:'l',ok:()=>(S.vol||0)>=1e6},
|
||||
{id:'llama',i:'🦙',t:tr('common.llama_drama'),d:tr('badges.lose_fiber_to_a_llama_herd'),r:'l',secret:true,ok:()=>!!(st().f||{}).llama},
|
||||
{id:'hallway',i:'🎤',t:tr('common.hallway_track'),d:tr('badges.attend_a_conference'),r:'r',ok:()=>(st().confs||0)>=1},
|
||||
{id:'beer',i:'🍺',t:tr('badges.peering_over_beer'),d:tr('badges.set_up_a_pni_while_the'),r:'e',ok:()=>!!st().beerPni},
|
||||
|
|
|
|||
15
src/game/90-actions/53-customer-paths.js
Normal file
15
src/game/90-actions/53-customer-paths.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
Object.assign(ACT,{
|
||||
pathOpen:({id})=>{const b=S.biz.find(x=>x.id===id);if(b&&pathKind(b))pathModal(b);},
|
||||
pathMove:({id,link})=>{const b=S.biz.find(x=>x.id===id),l=b&&pathKind(b)==='fiber'&&fiberTargets(b).find(t=>t.l.id===link&&!t.no);if(!l)return;
|
||||
// A carrier already renting waves of that kind (and size) on that fiber: one contract, as when it orders more there.
|
||||
const wv=b.type==='wwave'||b.type==='mwave',what=(x,n)=>b.type==='wwave'?wwWhat(l.l,n):cmWhat(l.l,cmWP(x.g),n);
|
||||
const more=wv&&S.biz.find(x=>x!==b&&x.type===b.type&&x.link===link&&x.name===b.name&&x.g===b.g);
|
||||
if(more){more.slots=(more.slots||0)+(b.slots||0);more.rate+=b.rate;more.since=Math.min(more.since??0,b.since??0);more.mood=Math.min(more.mood??100,b.mood??100);more.what=what(more,more.slots);S.biz=S.biz.filter(x=>x!==b);}
|
||||
else{b.link=link;if(wv)b.what=what(b,b.slots||1);}
|
||||
CM_V++; // managed waves come off their fiber's capacity (mwG()), which caches by fiber
|
||||
closeModal();toast(tr('customer_paths.name_moved_to_fiber',{name:esc(b.name),fiber:fibLab(l.l)}),'good');sfx('build');after();},
|
||||
pathPin:({id,via})=>{const b=S.biz.find(x=>x.id===id);if(!b||pathKind(b)!=='circuit'||typeof via!=='string')return;const p=via.split(',');
|
||||
if(p.length<2||p[0]!==b.city||p[p.length-1]!==b.city2||new Set(p).size!==p.length||!pathHops(pathEdges(),p))return;
|
||||
b.pin=p;closeModal();toast(tr('customer_paths.name_now_rides_path',{name:esc(b.name),path:esc(pathStr(p))}),'good');sfx('build');after();},
|
||||
pathAuto:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b||!b.pin)return;delete b.pin;closeModal();toast(tr('customer_paths.name_follows_routing_again',{name:esc(b.name)}),'good');sfx('click');after();},
|
||||
});
|
||||
14
src/game/90-actions/53-market.js
Normal file
14
src/game/90-actions/53-market.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
// The capacity market (37-fiber-market.js): its tab, and the settings the broker sells by.
|
||||
Object.assign(ACT,{
|
||||
marketOpen:()=>{if(!S||pzOn())return;UI.dtab='market';$('dash').hidden=false;renderDash();},
|
||||
mktHold:({v})=>{if(!CM_HOLD.includes(v))return;S.cm.hold=v;cmRelist();sfx('click');after();},
|
||||
// Switching a product off takes what the broker listed of it off the market; what it already sold stays sold.
|
||||
mktCfg:({p,k,v})=>{const c=CM_P.includes(p)&&S.cm.p[p];if(!c)return;
|
||||
if(k==='on'){c.on=!!v;if(!c.on)for(const l of S.links)if(l.list&&l.list[CM_L[p]])l.list[CM_L[p]]=0;}
|
||||
else if(k==='min'&&CM_MIN[p].includes(v))c.min=v;else if(k==='floor'&&CM_FLOOR.includes(v))c.floor=v;else return;
|
||||
cmRelist();sfx('click');after();},
|
||||
// A route the broker leaves alone keeps nothing listed by the thresholds.
|
||||
mktRoute:({k})=>{const r=typeof k==='string'&&cmRoutes().get(k);if(!r)return;if(S.cm.off[k]){delete S.cm.off[k];}else{S.cm.off[k]=1;
|
||||
for(const l of r.ls)if(l.list)for(const p of CM_P)if(S.cm.p[p].on)l.list[CM_L[p]]=0;}
|
||||
cmRelist();sfx('click');after();},
|
||||
});
|
||||
|
|
@ -9,7 +9,7 @@ Object.assign(ACT,{
|
|||
routingOpen:()=>{if(S&&!pzOn())routingModal();},
|
||||
coreSet:({v})=>{if(!S.core)return;v=+v;if(!(v>=0&&v<=S.core.lv)||(v===S.core.run&&!S.core.legacy))return;S.core.run=v;delete S.core.legacy;sfx('click');after();},
|
||||
via:({v})=>{UI.via=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
|
||||
setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}},
|
||||
setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;delete b.pin;sfx('click');after();}},
|
||||
route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);},
|
||||
addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);},
|
||||
// This POP's build becomes the standard's POP part: its model, routers, second building and generator.
|
||||
|
|
|
|||
|
|
@ -14,29 +14,41 @@ 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. Not a network in a
|
||||
multiplayer session: its text is made here (mpSave()), so the server gets the very save this slot holds. */
|
||||
if(!force&&!failed&&st===S&&!(MP_API&&S.mp)&&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;}}
|
||||
// A network in a multiplayer session: the server keeps a copy too (60-features/89-multiplayer.js).
|
||||
const txt=MP_API&&st===S&&S.mp?mpSave(st):JSON.stringify(packSave(st));
|
||||
// The very text the slot already holds (a paused game, nothing changed): writing a big network to storage costs more
|
||||
// than turning it into text, every 5 seconds, for nothing. Unless a write is still on its way, or the page is closing.
|
||||
if(!force&&!failed&&SLOT.txt[id]===txt&&(SLOT.top[id]||0)===(SLOT.sq[id]||0))return;
|
||||
let tier=null;if(st===S)try{tier=tierLabel();}catch(e){}
|
||||
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)};
|
||||
if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));}
|
||||
const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,day:st.day,meta:slotMeta(st,tier)};
|
||||
if(gzOk()&&(txt.length>=GZ_MIN||!force&&txt.length>=GZ_BG&&rwOn()))gzSave(j);else slotPut(j,slotStamp(txt,seq));}
|
||||
function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)};
|
||||
// Say so once per game (#176): a save that silently fails loses everything since the last one that worked.
|
||||
if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);}
|
||||
/* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage.
|
||||
Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save
|
||||
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */
|
||||
const GZ='gz:',GZ_MIN=1e6,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
|
||||
of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before.
|
||||
From GZ_BG up, the autosave is compressed too when the route worker does it: writing that much plain text held the
|
||||
page longer than everything else in a save (a save as the page closes stays plain below GZ_MIN: at once). */
|
||||
const GZ='gz:',GZ_MIN=1e6,GZ_BG=2e5,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function';
|
||||
async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below
|
||||
const r=stream.readable.getReader(),parts=[];let n=0;
|
||||
for(;;){const {done,value}=await r.read();if(done)break;parts.push(value);n+=value.length;}
|
||||
const out=new Uint8Array(n);let o=0;for(const p of parts){out.set(p,o);o+=p.length;}return out;}
|
||||
const b64=u=>{let s='';for(let i=0;i<u.length;i+=0x8000)s+=String.fromCharCode.apply(null,u.subarray(i,i+0x8000));return btoa(s);};
|
||||
const unb64=t=>{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u;};
|
||||
const gzip=async txt=>GZ+b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
|
||||
const gzB64=async txt=>b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip')));
|
||||
const gzip=async txt=>GZ+await (rwGzip(txt)||gzB64(txt));
|
||||
const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip')));
|
||||
// Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then.
|
||||
function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true;
|
||||
gzip(slotStamp(j.txt,j.seq)).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
|
||||
(j.p?j.p.then(r=>{j.txt=r.txt;return r.data;}):gzip(slotStamp(j.txt,j.seq))).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);})
|
||||
.catch(e=>{console.error('[tubes] compressing the save failed',e);})
|
||||
.finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});}
|
||||
/* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it.
|
||||
Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:<id>. */
|
||||
const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main';
|
||||
const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
|
||||
// txt: the text of each slot's last save that landed, before its stamp.
|
||||
const SLOT={sq:{},top:{},txt:{},day:{},big:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''};
|
||||
function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}}
|
||||
const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back
|
||||
const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}};
|
||||
|
|
@ -90,12 +91,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);const c=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});if(!c.mp)delete e.mp;Object.assign(e,c);
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ function cityPanel(c){
|
|||
h+=`</section><section><h3>${tr('common.business_customers')}</h3>`;
|
||||
const bz=S.biz.filter(b=>bCities(b).includes(c));
|
||||
if(!bz.length)h+=`<p class="empty">${tr('city_panel.no_businesses_yet_offers_pop_up')}</p>`;
|
||||
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">'+tr('city_panel.fiber_is_down')+'</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}</b>`:''}${b.type==='scrub'&&!hasScrub()?' · <b style="color:var(--bad)">'+tr('common.needs_a_scrubbing_center')+'</b>':''}${S.day-(b.since||0)<15?` · <b>${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}</b>`:''}</div>${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}</div></div>${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}</div>`;
|
||||
for(const b of bz)h+=`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · <b style="color:var(--bad)">'+tr('city_panel.fiber_is_down')+'</b>':''}${BIZ_T[b.type].event&&eventLive(b)?` · <b>${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}</b>`:''}${b.type==='scrub'&&!hasScrub()?' · <b style="color:var(--bad)">'+tr('common.needs_a_scrubbing_center')+'</b>':''}${S.day-(b.since||0)<15?` · <b>${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}</b>`:''}</div>${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}${pathCtl(b)}<div class="bar ${b.mood<30?'bad':b.mood<65?'warn':''}"><i style="width:${b.mood}%"></i></div><div class="meta">${tr('common.happiness_p',{p:Math.round(b.mood)})}</div></div>${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}</div>`;
|
||||
h+=`</section>`+offersHere(c);
|
||||
}else if(UI.tab==='up'){
|
||||
h+=portNote(c)+latNote(c);
|
||||
|
|
|
|||
|
|
@ -117,12 +117,12 @@ function dfPanel(l){
|
|||
if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
|
||||
h+=`<section><h3>${l.own?tr('common.under_construction'):tr('common.being_spliced')}</h3><div class="kv"><span>${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}</span><b>${tr('common.n_days_left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own&&l.sub?layPanel(l):l.own?`<div class="btns">${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash<crewCost(l))}${btn(trn('link_panels.all_crews_done_in_n_days_price',Math.max(1,crewFloor(l)-S.day),{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash<crewSteps(l)*crewCost(l))}</div>${!crewSteps(l)&&l.ready>S.day+1?`<p class="note">${tr('link_panels.crews_can_halve_a_build_at_most')}</p>`:''}`:''}<p class="note">${tr('link_panels.you_can_pre_install_optics_now')}</p></section>`;}
|
||||
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">${tr('common.dark_6bf5')}</h3><p class="lead">${esc(inc.msg)}</p>${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
|
||||
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${xpSlots(l)?` · ${trn('express.n_carry_expresses',xpSlots(l))}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
|
||||
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${mwG(l)?` · ${tr('market.g_sold_as_managed',{g:fmtCap(mwG(l))})}`:''}${xpSlots(l)?` · ${trn('express.n_carry_expresses',xpSlots(l))}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
|
||||
${seatPanel(l)}${l.own&&l.sub?`<div class="kv"><span>${tr('common.cable_design')}</span><b>${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}</b></div>`:''}
|
||||
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}</b></div><div class="kv"><span>${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}</span><b>${tr('common.price_mo',{price:fmt$(l.mo)})}</b></div><div class="kv"><span>${tr('link_panels.n_amp_huts',{n:amps})}</span><b>${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">${tr('link_panels.this_fiber_is_dark_add_optics')}</p>`:''}</section>`;
|
||||
if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l);
|
||||
if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='mwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l);
|
||||
h+=`<section><h3>${tr('link_panels.selling_spare_capacity')}</h3><p class="lead">${tr('link_panels.other_carriers_rent_what_you_do')}</p>
|
||||
<div class="kv"><span>${tr('common.free_channels')}</span><b>${fc} / ${chMax(l)}</b></div>${sold.map(b=>`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}</div></div></div>`).join('')}
|
||||
<div class="kv"><span>${tr('common.free_channels')}</span><b>${fc} / ${chMax(l)}</b></div>${sold.map(b=>`<div class="row"><div class="grow"><div class="nm">${esc(b.name)}</div><div class="meta">${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}</div>${pathCtl(b)}</div></div>`).join('')}
|
||||
${off?`<div class="row"><div class="grow"><div class="nm">${esc(off.name)}</div><div class="meta">${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}</div></div>${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}</div>`:brListHtml(l,fc)}</section>`;}
|
||||
h+=`<section><h3>${tr('common.optics')}</h3><p class="lead">${tr('link_panels.each_channel_is_a_pair_of')}</p>`;
|
||||
if(l.own&&l.sub&&!l.seat)h+=subUpgradePanel(l);
|
||||
|
|
@ -191,10 +191,10 @@ function offTransitHint(id,city){const n=NET[id];if(n.type==='t1'&&n.pol==='rest
|
|||
if(pniC.length)return tr('link_panels.pni_in_city_why',{city:CITY[pniC[0]].name,why:pOk.why});{const x=nearestSpot(id);return x?tr('link_panels.not_in_your_cities_yet_nearest',{city:CITY[x.c].name}):tr('link_panels.not_present_in_any_of_your');}}
|
||||
function transitTop(ids,k=5){const m={};for(const id of ids)for(const [n,v] of Object.entries(R.tNet[id]||{}))m[n]=(m[n]||0)+v;return Object.entries(m).filter(([,v])=>v>0.01).sort((a,b)=>b[1]-a[1]).slice(0,k);}
|
||||
// The broker: what is listed and how the route's market looks, or the buttons to list some (#203).
|
||||
function brListHtml(l,fc){const L=l.list,free=brFree(l),pf=l.own&&pairFree(l)&&!(L&&L.p);
|
||||
function brListHtml(l,fc){const L=l.list,free=cmRoomSpec(l),pf=l.own&&pairFree(l)&&!(L&&L.p),cut=Math.round((1-cmCut())*100),go=`<div class="btns">${btn(tr('market.open'),'marketOpen',{},'ghost sm')}</div>`;
|
||||
const mk=`<div class="kv"><span>${tr('broker.market',{a:CITY[l.a].name,b:CITY[l.b].name})}</span><b>${trn('broker.n_waves',free)}</b></div>`;
|
||||
if(L)return mk+`<div class="row"><div class="grow"><div class="nm">${tr('broker.listed_title')}</div><div class="meta">${[L.w?trn('broker.n_waves_left',L.w):'',L.p?trn('broker.n_pairs_left',L.p):''].filter(Boolean).join(' · ')} · ${tr('broker.how')}</div></div>${btn(tr('broker.unlist'),'unlistFiber',{id:l.id},'ghost sm')}</div>`+
|
||||
(fc-L.w>=1?`<div class="btns">${btn(tr('broker.list_more',{n:Math.min(4,fc-L.w)}),'listFiber',{id:l.id,w:Math.min(4,fc-L.w)},'ghost sm')}</div>`:'');
|
||||
if(fc<1&&!pf)return mk+`<p class="note">${tr('link_panels.nothing_spare_to_sell_on_this')}</p>`;
|
||||
if(L)return mk+`<div class="row"><div class="grow"><div class="nm">${tr('broker.listed_title')}</div><div class="meta">${[L.w?trn('broker.n_waves_left',L.w):'',...CM_W.map(p=>L[CM_L[p]]?trn('market.n_g_left',L[CM_L[p]],{g:fmtCap(CM_G[p])}):''),L.p?trn('broker.n_pairs_left',L.p):''].filter(Boolean).join(' · ')} · ${tr('market.how',{n:cut})}</div></div>${btn(tr('broker.unlist'),'unlistFiber',{id:l.id},'ghost sm')}</div>`+
|
||||
(fc-L.w>=1?`<div class="btns">${btn(tr('broker.list_more',{n:Math.min(4,fc-L.w)}),'listFiber',{id:l.id,w:Math.min(4,fc-L.w)},'ghost sm')}${btn(tr('market.open'),'marketOpen',{},'ghost sm')}</div>`:go);
|
||||
if(fc<1&&!pf)return mk+`<p class="note">${tr('link_panels.nothing_spare_to_sell_on_this')}</p>`+go;
|
||||
const ns=[...new Set([1,4,Math.min(16,fc),fc])].filter(n=>n>=1&&n<=fc);
|
||||
return mk+`<p class="meta">${tr('broker.lead')}</p><div class="btns">${ns.map(n=>btn(n===fc&&n>1?tr('broker.list_all',{n}):trn('broker.list_n',n),'listFiber',{id:l.id,w:n},'sm')).join('')}${pf?btn(tr('broker.list_pair'),'listFiber',{id:l.id,p:1},'sm'):''}</div>`+(free<1?`<p class="why">${tr('broker.no_market')}</p>`:'');}
|
||||
return mk+`<p class="meta">${tr('market.lead_fiber',{n:cut})}</p><div class="btns">${ns.map(n=>btn(n===fc&&n>1?tr('broker.list_all',{n}):trn('broker.list_n',n),'listFiber',{id:l.id,w:n},'sm')).join('')}${pf?btn(tr('broker.list_pair'),'listFiber',{id:l.id,p:1},'sm'):''}</div>`+(free<1?`<p class="why">${tr('broker.no_market')}</p>`:'')+go;}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ const popOrder=()=>S&&S.pops?Object.keys(S.pops).filter(isCity).sort((a,b)=>CITY
|
|||
const offerOrder=()=>S&&S.offers?S.offers.filter(o=>isCity(o.city)).sort((a,b)=>a.exp-b.exp):[];
|
||||
// n opens the NOC dashboard, and a letter within KEY_LEAD ms of it picks a tab (n c: Connections). n never closes the
|
||||
// dashboard, so n c switches tabs without it flashing shut; Escape closes it.
|
||||
const DASH_KEYS={o:'overview',u:'cust',c:'conn',t:'traffic',r:'infra',l:'lease'},KEY_LEAD=1000;let keyLead=0;
|
||||
const DASH_KEYS={o:'overview',u:'cust',c:'conn',t:'traffic',r:'infra',l:'lease',m:'market'},KEY_LEAD=1000;let keyLead=0;
|
||||
// Arrow keys and WASD move the map while held, at a steady speed on screen. Their own frame loop runs only while one is
|
||||
// down, so the game loop does no extra work; letting go, a window opening or leaving the browser window stops it.
|
||||
const PAN_KEYS={ArrowUp:[0,-1],w:[0,-1],ArrowDown:[0,1],s:[0,1],ArrowLeft:[-1,0],a:[-1,0],ArrowRight:[1,0],d:[1,0]},PAN_SPEED=700;
|
||||
|
|
@ -15,7 +15,7 @@ function panFrame(t){if(!panHeld.size||!$('modal').hidden||!$('dash').hidden){pa
|
|||
// A slow frame (a busy day, a background tab) moves at most 50 ms worth, not a jump across the map.
|
||||
const dt=panAt==null?0:Math.min(0.05,(t-panAt)/1000);panAt=t;let dx=0,dy=0;for(const k of panHeld){dx+=PAN_KEYS[k][0];dy+=PAN_KEYS[k][1];}
|
||||
cam.x+=dx*PAN_SPEED*dt/cam.z;cam.y+=dy*PAN_SPEED*dt/cam.z;wrapCam();requestAnimationFrame(panFrame);}
|
||||
function showKeys(){const k=s=>`<span class="kbd">${s}</span>`,TN={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines')};
|
||||
function showKeys(){const k=s=>`<span class="kbd">${s}</span>`,TN={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines'),market:tr('market.tab')};
|
||||
const tabs=Object.entries(DASH_KEYS).map(([l,t])=>`<span class="keytab">${k(l)} ${TN[t]}</span>`).join(' ');
|
||||
const rows=[[[...'←↑↓→'].map(k).join(' ')+'<br>'+[...'wasd'].map(k).join(' '),tr('keys.move_around_the_map')],[k(tr('keys.space')),tr('keys.pause_or_play')],[k('0')+' – '+k('4'),tr('keys.game_speed')],[k('/'),tr('find.find_a_city')],[k('[')+' '+k(']'),tr('keys.previous_or_next_of_your')],[k('$'),tr('keys.next_open_offer_soonest_to')],[k('-')+' '+k('='),tr('keys.zoom_the_map_out_or')],[k('n'),`${tr('keys.noc_dashboard_a_letter_right')}<br>${tabs}`],[k(tr('keys.esc')),tr('keys.close_a_window_or_deselect')],[k('?'),tr('keys.show_this_list')]];
|
||||
openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:28px">⌨️ ${tr('keys.keyboard_shortcuts')}</h2><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
|
||||
|
|
|
|||
|
|
@ -66,4 +66,4 @@ function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||(
|
|||
function netWhere(n,where){const ch=(where||netWhereIdx())(n.id);
|
||||
if(!ch.length)return '';const MAX=6;
|
||||
return `<div class="btns">${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} <small>${esc(CITY[c].name)}</small>`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('dashboard.n_more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}</div>`;}
|
||||
const DTABS=['overview','cust','conn','traffic','infra','pops','lease'];
|
||||
const DTABS=['overview','cust','conn','traffic','infra','pops','lease','market'];
|
||||
|
|
|
|||
38
src/game/94-dashboard/55-market.js
Normal file
38
src/game/94-dashboard/55-market.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
/* ---------- the capacity market tab (37-fiber-market.js) ----------
|
||||
Your settings (what the broker may sell, from what demand and price, and how much it keeps back), the news, and
|
||||
every route you hold dark fiber on: per product what is wanted, sold and listed, as a bar with your threshold on
|
||||
it, and today's price against your floor. A Cable broker also sees where each route is heading, and routes it could
|
||||
build. Markup is deterministic (the NOC window copies it). */
|
||||
const CM_NAME={spec:N_('market.p_spec'),w100:N_('market.p_w100'),w400:N_('market.p_w400'),w800:N_('market.p_w800'),w1600:N_('market.p_w1600'),iru:N_('market.p_iru')};
|
||||
const CM_DESC={spec:N_('market.p_spec_d'),w100:N_('market.p_w100_d'),w400:N_('market.p_w400_d'),w800:N_('market.p_w800_d'),w1600:N_('market.p_w1600_d'),iru:N_('market.p_iru_d')};
|
||||
const cmN=v=>v>=10?String(Math.round(v)):v.toFixed(1).replace(/\.0$/,'');
|
||||
// Why nothing is listed although the route wants it and the price is right: no optic that big, or no room left on
|
||||
// the fiber after what you keep back. Growing means lighting more.
|
||||
// A bar: sold (green) of what the route wants (the dark line), and your minimum (the pink tick) when the broker lists.
|
||||
function cmBar(D,sold,min){const top=Math.max(D,sold,min||0,1)*1.15,w=v=>(100*Math.min(1,v/top)).toFixed(1)+'%';
|
||||
return `<div class="cmbar"><i style="width:${w(sold)}"></i><b style="left:${w(D)}"></b>${min?`<u style="left:${w(min)}"></u>`:''}</div>`;}
|
||||
const cmSeg=(vals,cur,act,args,f)=>`<div class="seg">${vals.map(v=>btn(f(v),act,{...args,v},v===cur?'pink sm':'ghost sm')).join('')}</div>`;
|
||||
function cmHeatTag(r){const H=cmHeat(r,'spec',S.day);return H>=1.15?`<span class="tag cmhot">${tr('market.hot',{x:H.toFixed(1)})}</span>`:H<=0.85?`<span class="tag cmcool">${tr('market.cool',{x:H.toFixed(1)})}</span>`:`<span class="tag st">${tr('market.steady')}</span>`;}
|
||||
function cmProdLine(r,p,s,L,fc){const C=S.cm.p[p],D=cmDem(r,p,S.day),i=cmIdx(r,p,s,0,S.day),pc=Math.round(i*100),m=mkt()*cmCut();
|
||||
const price=p==='iru'?tr('market.price_pair',{up:fmt$(Math.round(cmUpList(r)*i*m)),price:fmt$(Math.round(cmList(r,p)*m)),pct:pc}):tr('market.price',{price:fmt$(Math.round(cmList(r,p)*i*m)),pct:pc});
|
||||
return `<div class="cmp"><div class="meta"><b>${tr(CM_NAME[p])}</b> · ${tr('market.row',{want:cmN(D),sold:s,listed:L})} · ${price}${C.on&&pc<C.floor?` <b style="color:var(--bad)">${tr('market.below_floor')}</b>`:C.on&&!L&&D>=C.min&&p!=='iru'&&!S.cm.off[r.k]?` <b style="color:var(--warn)">${CM_G[p]&&!r.ls.some(l=>cmOptG(l)>=CM_G[p])?tr('market.needs_optic',{g:fmtCap(CM_G[p])}):tr('market.no_room')}</b>`:''}</div>
|
||||
${cmBar(D,s,C.on?C.min:0)}${fc?`<div class="meta">${tr('market.forecast',{a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}</div>`:''}</div>`;}
|
||||
function marketTab(){const C=S.cm,rs=[...cmRoutes().values()].sort((x,y)=>brMarket(y.a,y.b)-brMarket(x.a,x.b)),sold=cmSold(new Map(rs.map(r=>[r.k,r]))),bk=broker();
|
||||
const mo=S.biz.reduce((a,b)=>a+(['wwave','mwave','dfpair'].includes(b.type)?bizMo(b):0),0),ago=n=>S.day-n.d<1?tr('market.today'):trn('market.days_ago',S.day-n.d);
|
||||
let h=`<div class="panel2" style="margin-top:12px"><h3>${tr('market.title')}</h3><p class="note" style="margin-top:0">${tr('market.lead')}</p>
|
||||
<div class="kv"><span>${tr('market.sales')}</span><b>${tr('common.price_mo',{price:fmt$(mo)})}</b></div>
|
||||
<div class="kv"><span>${tr('market.fee')}</span><b>${Math.round((1-cmCut())*100)}%${bk?` · ${tr('market.fee_broker')}`:''}</b></div>
|
||||
<div class="cmset"><div class="nm">${tr('market.hold')}</div><div class="meta">${tr('market.hold_d')}</div>${cmSeg(CM_HOLD,C.hold,'mktHold',{},v=>v+'%')}</div>
|
||||
${CM_P.map(p=>{const c=C.p[p];return `<div class="cmset"><div class="nm">${tr(CM_NAME[p])} ${btn(c.on?tr('market.selling'):tr('market.not_selling'),'mktCfg',{p,k:'on',v:c.on?0:1},c.on?'pink sm':'ghost sm')}</div><div class="meta">${tr(CM_DESC[p])}</div>
|
||||
${c.on?`<div class="meta">${tr('market.min')}</div>${cmSeg(CM_MIN[p],c.min,'mktCfg',{p,k:'min'},v=>'≥ '+v)}<div class="meta">${tr('market.floor')}</div>${cmSeg(CM_FLOOR,c.floor,'mktCfg',{p,k:'floor'},v=>v+'%')}`:''}</div>`;}).join('')}
|
||||
<h3 style="margin-top:10px">${tr('market.news')}</h3>${C.news.length?C.news.slice(0,5).map(n=>`<div class="meta">${ago(n)} · ${cmNewsText(n)}</div>`).join(''):`<p class="empty">${tr('market.no_news')}</p>`}</div>`;
|
||||
h+=`<div class="panel2" style="margin-top:12px"><h3>${tr('market.routes')}</h3>${rs.length?`<p class="meta" style="margin-top:0">${tr('market.legend')}${bk?'':' '+tr('market.forecast_lock')}</p>`+rs.map(r=>{const s=sold.get(r.k),off=!!C.off[r.k],L=p=>r.ls.reduce((a,l)=>a+((l.list&&l.list[CM_L[p]])||0),0);
|
||||
return `<div class="row cmroute"><div class="grow"><div class="nm">${CITY[r.a].name} ⇄ ${CITY[r.b].name} <span class="tag st">${r.sub?tr('common.subsea'):tr('common.land')}</span> ${cmHeatTag(r)}</div>
|
||||
<div class="meta">${tr('market.route_meta',{km:Math.round(r.km).toLocaleString(),ms:r.lat.toFixed(1),n:Math.round((r.lp-1)*100)})}</div>
|
||||
${(()=>{const shown=CM_P.filter(p=>s[p]>0||L(p)>0||cmDem(r,p,S.day)>=0.3||bk&&cmFc(r,p,90)>=0.3),rest=CM_P.filter(p=>!shown.includes(p));
|
||||
return shown.map(p=>cmProdLine(r,p,s[p],L(p),bk)).join('')+(rest.length?`<div class="meta">${tr('market.not_yet',{list:rest.map(p=>tr(CM_NAME[p])).join(', ')})}</div>`:'');})()}
|
||||
<div class="btns">${btn(off?tr('market.route_off'):tr('market.route_on'),'mktRoute',{k:r.k},off?'ghost sm':'pink sm')}${btn(tr('lease_swaps.open_your_fiber'),'dashLink',{id:r.ls[0].id},'ghost sm')}</div></div></div>`;}).join(''):`<p class="empty">${tr('market.no_routes')}</p>`}</div>`;
|
||||
if(bk){const sc=cmScout();h+=`<div class="panel2" style="margin-top:12px"><h3>${tr('market.scout')}</h3><p class="meta" style="margin-top:0">${tr('market.scout_d')}</p>${sc.length?sc.map(r=>{const v=CM_P.reduce((a,p)=>a+cmDem(r,p,S.day)*cmList(r,p),0)*mkt()*cmCut();
|
||||
return `<div class="row"><div class="grow"><div class="nm">${CITY[r.a].name} ⇄ ${CITY[r.b].name} <span class="tag st">${r.sub?tr('common.subsea'):tr('common.land')}</span> ${cmHeatTag(r)}</div>
|
||||
<div class="meta">${tr('market.scout_spend',{km:Math.round(r.km).toLocaleString(),v:fmt$(Math.round(v))})}</div>${CM_P.filter(p=>cmDem(r,p,S.day)>=0.3||cmFc(r,p,90)>=0.3).map(p=>`<div class="meta"><b>${tr(CM_NAME[p])}</b> · ${tr('market.forecast_now',{n:cmN(cmDem(r,p,S.day)),a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}</div>`).join('')}</div></div>`;}).join(''):`<p class="empty">${tr('market.scout_none')}</p>`}</div>`;}
|
||||
return h;}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines')};
|
||||
function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines'),market:tr('market.tab')};
|
||||
return `<nav class="dtabs">${DTABS.map(k=>`<button class="${cur===k?'on':''}" data-act="dashTab" data-args='{"k":"${k}"}'>${L[k]}${k==='cust'&&u?`<span class="cnt red">${u}</span>`:''}</button>`).join('')}</nav>`;}
|
||||
function renderDash(){checkLayer();
|
||||
const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30);
|
||||
|
|
@ -6,7 +6,7 @@ function renderDash(){checkLayer();
|
|||
const net=R.revMo-R.costMo,tot=Object.values(R.egT).reduce((a,b)=>a+b,0)||1;
|
||||
const tile=(l,v,sub)=>`<div class="tile"><div class="lbl">${l}</div><div class="val">${v}</div>${sub?`<div class="sub">${sub}</div>`:''}</div>`;
|
||||
let h=`<div style="display:flex;align-items:center;gap:10px"><div><div class="eyebrow">AS${S.asn} · ${esc(S.name)} · ${tierLabel()}</div><h2 style="font-size:28px">${tr('common.noc_dashboard')}</h2></div><button class="x" data-act="dashClose" aria-label="${tr('common.close')}">×</button></div>`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
|
||||
<div class="dgrid">${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}</div>
|
||||
<div class="dgrid">${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.carried'),fmtVol(S.vol||0),tr('dashboard.carried_sub'))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`<span style="color:${net>=0?'var(--eye)':'var(--bad)'}">${net>=0?'+':''}${fmt$(net)}</span>`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}</div>
|
||||
<div class="dcols"><div class="panel2"><h3>${tr('dashboard.traffic_by_way_out')}</h3>${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'var(--text)',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}</div>
|
||||
<div class="panel2"><h3>${tr('dashboard.money_per_month')}</h3>${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}
|
||||
<h3 style="margin-top:8px">${tr('dashboard.where_the_money_goes')}</h3>${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`<div class="kv"><span>${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row'),ip4:tr('ip4.leases_cgnat_nat64'),sat:tr('satellites.costs_row')}[k]||k}</span><b>${tr('common.price_mo',{price:fmt$(v)})}</b></div>`).join('')}</div></div>`;
|
||||
|
|
@ -31,5 +31,6 @@ function renderDash(){checkLayer();
|
|||
<h3 style="margin-top:10px">${tr('common.your_as')}</h3><div class="kv"><span>${tr('common.as_number')}</span><b>AS${S.asn}</b></div><div class="kv"><span>${tr('common.prefixes')}</span><b>${(ip4On()&&ip4Pfx())||Math.max(1,Math.ceil(Object.keys(S.pops).length/3))+' × /22'} IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>${tr('common.bgp_sessions')}</span><b>${R.sessions}</b></div><div class="kv"><span>${tr('common.upstreams')}</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>${tr('common.reach')}</span><b>${pct(R.reach)}</b></div><div class="kv"><span>${tr('common.customers')}</span><b>${tr('dashboard.n_businesses',{n:S.biz.length})}</b></div></div></div>`;
|
||||
if(DT==='pops')h+=popsSection();
|
||||
if(DT==='lease')h+=leaseTab();
|
||||
if(DT==='market')h+=marketTab();
|
||||
if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000;
|
||||
// What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list.
|
||||
const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore','popsReg','popsSort'];
|
||||
const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','netFocus','opsOpen','pni','pniAllOpen','popGo'];
|
||||
const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','mktCfg','mktHold','mktRoute','netFocus','opsOpen','pni','pniAllOpen','popGo'];
|
||||
const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false};
|
||||
{const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}}
|
||||
if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@ function openFromText(t){const cs=Object.keys(S.pops).map(c=>[c,t.indexOf(CITY[c
|
|||
// An incident points at a link, a trench, a city, or a port in a city.
|
||||
function incOpen(i){const r=i&&i.ref;if(typeof r!=='string')return null;const l=S.links.find(l=>l.id===r||l.trench===r);if(l)return {a:'link',v:l.id};
|
||||
if(isCity(r))return {a:'city',v:r};const x=S.transit.find(t=>t.id===r)||S.pni.find(t=>t.id===r);if(x)return {a:'city',v:x.city};if(isIx(r)&&isCity(ixCity(r)))return {a:'city',v:ixCity(r)};return null;}
|
||||
function logNote(html,kind,actions,open){S.log=S.log||[];const tmp=document.createElement('div');tmp.innerHTML=html.replace(/<br>/g,' ');const t=tmp.textContent.trim();
|
||||
// A kind the log does not keep (the capacity market's 'info' and 'warn') is a plain line, as a reload makes it (sanitize()).
|
||||
function logNote(html,kind,actions,open){S.log=S.log||[];if(!LOG_KINDS.includes(kind))kind='';const tmp=document.createElement('div');tmp.innerHTML=html.replace(/<br>/g,' ');const t=tmp.textContent.trim();
|
||||
const b=tmp.firstElementChild&&tmp.firstElementChild.tagName==='B'&&html.startsWith('<b>')?tmp.firstElementChild.textContent.trim():'';
|
||||
const o=open||openOf(actions)||openFromText(t),now=Date.now(),key=(b||t).replace(/[\d.,]+/g,'#'),last=S.log[0];
|
||||
// The same notice again within a minute folds into the last one, with a count: twenty "new sessions" read as one line.
|
||||
|
|
|
|||
|
|
@ -12,7 +12,10 @@ function openLinkModal(a,b){
|
|||
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km</div><h2 style="font-size:26px">${CITY[a].name} → ${CITY[b].name}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>${tabs}`;
|
||||
if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;}
|
||||
if(mode==='xp'){openModal(head+xpModalBody(a,b,xr));return;}
|
||||
if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));openModal(head+`<p class="lead" style="margin-top:10px">${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}</p>${cabOpen()&&!ownCabWhy(a,b)?ownCabTeaser(a,b):''}`);return;}
|
||||
if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));
|
||||
// a beach with no cable yet (#321): hopping cannot help, only a road in or a cable of your own
|
||||
const bare=!dry&&[a,b].find(c=>!CABLE_PAIRS.some(p=>p.a===c||p.b===c)),road=bare&&CITIES.some(x=>x.id!==bare&&!isSub(bare,x.id));
|
||||
openModal(head+`<p class="lead" style="margin-top:10px">${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):bare?(road?tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY[bare].name}):tr('link_modal.no_subsea_cable_lands_in_city_own',{city:CITY[bare].name})):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}</p>${(cabOpen()?!ownCabWhy(a,b):bare)?ownCabTeaser(a,b):''}`);return;}
|
||||
if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`<p class="lead" style="margin-top:10px">${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}</p>`);return;}
|
||||
if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`<p class="note" style="margin-top:8px">${landWhy(a,b)}</p>`;
|
||||
route+=`<p class="note" style="margin-top:6px">📈 ${esc(marketNote(a,b,sub))}</p>`;
|
||||
|
|
|
|||
|
|
@ -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();}
|
||||
|
|
|
|||
|
|
@ -18,8 +18,11 @@ function frame(now){
|
|||
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()&&!srvOn())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
|
||||
|
|
@ -27,9 +30,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
|
||||
|
|
@ -38,12 +41,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){
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue