Split the game page into partials under src/, assembled into one index.html at build

site/index.html (900 KB of HTML, CSS and JS in one file) becomes src/: a shell
(src/index.html), styles/ and game/, concatenated in path order by
scripts/lib/page.js. The assembled page is byte-identical to the old file, so
load time and in-game performance are unchanged.

- scripts/build.js replaces build.sh (same env vars, same output)
- npm run dev: a zero-dependency dev server that assembles on every request
- tests assemble the page in memory; npm test runs every tests/*.test.js
- perf-bench takes --base-ref to build a git ref's page
- scripts/legacy/split-index-html.js is the splitter, kept for older branches
This commit is contained in:
Frederic Jung 2026-10-27 10:05:56 +01:00
parent 295e68cc46
commit 67a40942b4
No known key found for this signature in database
113 changed files with 5584 additions and 5195 deletions

View file

@ -0,0 +1,8 @@
/* ---------- toasts & modals ---------- */
function toast(html,kind='',actions=[],open=null){
if(S)logNote(html,kind,actions,open);
const el=document.createElement('div');el.className='toast '+kind;el.dataset.born=performance.now();
el.innerHTML=`<div class="tx">${html}</div>${actions.map(a=>btn(a.l,a.act,a.args,'sm')).join('')}`;
const box=$('toasts');box.prepend(el);const max=innerWidth<760?2:3;while(box.children.length>max)box.lastChild.remove();
setTimeout(()=>{el.style.transition='opacity .4s';el.style.opacity=0;setTimeout(()=>el.remove(),400);},actions.length?8000:4500);
}

View file

@ -0,0 +1,31 @@
/* ---------- notifications: the NOC keeps the last ten minutes, readable and openable ---------- */
const LOG_KEEP=60,LOG_MS=10*60*1000,LOG_KINDS=['','good','bad','goal'],LOG_OPEN=['city','link','cust','bank','tab','inbox'],LOG_TABS=['goals','deals','noc','nets'];
// What a notification is about, from the button it came with: the same place its own button would take you.
function openOf(actions){for(const a of actions||[]){const g=a.args||{};
if(a.act==='focusCity'&&isCity(g.city))return {a:'city',v:g.city};if(a.act==='selLink'&&g.id)return {a:'link',v:String(g.id)};
if(a.act==='custGo'&&g.id)return {a:'cust',v:String(g.id)};if(a.act==='bank')return {a:'bank'};if(a.act==='inbox')return {a:'inbox'};if(a.act==='leftTab'&&LOG_TABS.includes(g.t))return {a:'tab',v:g.t};}return null;}
// Otherwise from the text: a link between two of your cities it names, or the first of your cities it names.
function openFromText(t){const cs=Object.keys(S.pops).map(c=>[c,t.indexOf(CITY[c].name)]).filter(([,i])=>i>=0).sort((a,b)=>a[1]-b[1]).map(([c])=>c);
if(cs.length>=2){const l=S.links.find(l=>(l.a===cs[0]&&l.b===cs[1])||(l.a===cs[1]&&l.b===cs[0]));if(l)return {a:'link',v:l.id};}return cs.length?{a:'city',v:cs[0]}:null;}
// 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();
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.
if(last&&last.at&&now-last.at<60000&&last.k===kind&&(last.h||last.t).replace(/[\d.,]+/g,'#')===key&&JSON.stringify(last.o||null)===JSON.stringify(o)){last.n=(last.n||1)+1;last.t=t;last.h=b;last.at=now;last.d=S.day;return;}
S.log.unshift({id:uid(),d:S.day,t,h:b,k:kind,at:now,o,n:1});if(S.log.length>LOG_KEEP)S.log.length=LOG_KEEP;}
const logRecent=()=>{const now=Date.now();return (S.log||[]).filter(e=>e.at&&now-e.at<LOG_MS);};
const logUnread=()=>logRecent().filter(e=>e.at>(UI.logSeen||0)).length;
const agoStr=at=>{const m=Math.floor((Date.now()-at)/60000);return m<1?tr('just now'):trn('{n} min ago','{n} min ago',m);};
function logSection(){const L=logRecent(),MAX=5,all=UI.logAll,sh=all?L:L.slice(0,MAX);
let h=`<h3 style="font-size:15px;margin:10px 0 4px">${tr('Notifications')} <span class="meta">${tr('last 10 minutes')}</span></h3>`;
if(!L.length)return h+`<p class="empty">${tr('Nothing in the last 10 minutes.')}</p>`;
h+=sh.map(e=>{const body=e.h&&e.t.startsWith(e.h)?e.t.slice(e.h.length).trim():e.t;
return `<div class="row note ${e.k||'info'}"><span class="ndot" aria-hidden="true"></span><div class="grow">${e.h?`<div class="nm">${esc(e.h)}${e.n>1?` <span class="tag st">×${e.n}</span>`:''}</div>`:''}${body?`<div class="meta nbody">${esc(body)}${!e.h&&e.n>1?` <span class="tag st">×${e.n}</span>`:''}</div>`:''}<div class="meta">${agoStr(e.at)} · ${dateStr(e.d)}</div></div>${e.o?btn(tr('Open'),'logOpen',{id:e.id},'ghost sm'):''}</div>`;}).join('');
if(L.length>MAX)h+=`<div class="btns">${btn(all?tr('Show fewer'):tr('Show all {n}',{n:L.length}),'logAll',{},'ghost sm')}</div>`;
return h;}
const markLayer=()=>{UI.layerAt=performance.now();};
// Which layers are open: when that changes (a sheet, the dashboard, the bank, a selection), taps in flight are void.
function checkLayer(){const q=id=>{const e=$(id);return e?(e.hidden?0:1):0;},sig=[q('modal'),q('dash'),q('bankBox'),UI.leftOpen?1:0,UI.left||'',UI.sel?UI.sel.type+UI.sel.id:'',UI.tab||''].join('|');if(sig!==UI._layer){UI._layer=sig;markLayer();}}

View file

@ -0,0 +1,24 @@
// Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it.
function openModal(html){if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;}
const NETWORK_NAMES=[
'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom',
'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty',
'LAN Before Time','Bits Please','Hopless Networks','Route of All Evil',
'TTL You Later','Fiber McFiberface','RFC 1149 Avian Carriers','Spanning Tree Huggers',
'Dial-Up & Cry','404 Telecom','Loss Leaders','Last Mile Standing',
'Have You Tried Off & On','Bogon Voyage','Default Route 66','Anycast Away',
'Hot Potato Routing','Null Route Rangers','Looking Glass Half Full','Jumbo Frame Shop',
'Route Flap Jacks','Split Horizon & Co.','Path of Least Resistance',
];
function randomNetworkName(current){
// Naming must not advance a running scenario's seeded simulation.
const names=NETWORK_NAMES.filter(n=>n!==current);
return names[Math.floor(_rand()*names.length)];
}
const HTIW='https://tkjaer.github.io/how-the-internet-works/';
// The real thing: an interactive, zoomable guide to how packets actually travel. Go read it.
// Where players hang out: the community Signal group.
const SIGNAL='https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ';
const chatHtml=()=>`<a class="plug chat" href="${SIGNAL}" target="_blank" rel="noopener"><span class="pi" aria-hidden="true">💬</span><span><b>${tr('Join the NOC chat')}</b><span class="meta">${tr('Our Signal group: swap screenshots, report bugs and argue about peering policy with other players. Fewer backhoes than the real thing.')}</span></span><span class="go">${tr('Join →')}</span></a>`;
const plugHtml=(big)=>`<a class="plug" href="${HTIW}" target="_blank" rel="noopener"><span class="pi" aria-hidden="true">🌍</span><span><b>How the Internet Works</b><span class="meta">${big?tr('The real thing, by Thomas Kjær Aabo: a zoomable, interactive map of how your packets actually travel, from Wi-Fi to undersea fiber, today, in 2010 and in 1995. This game makes it up as it goes. That one gets it right.'):tr('The real thing: follow a packet from Wi-Fi to undersea fiber.')}</span></span><span class="go">${tr('Explore →')}</span></a>`;

View file

@ -0,0 +1,26 @@
function showTitle(){
const sv=loadSave();
if(UI.nm==null)UI.nm=randomNetworkName();
const starts=[['fra',tr('Crossroads of Europe. DE-KICKS IX, cheap transit.')],['nyc',tr('Huge eyeball market. Pricey neighbours.')],['sin',tr('Asia hub. Great peering, far from home.')],['sao',tr('Big hungry market, few providers.')],['syd',tr('Hard mode. Everything overseas costs a fortune, locals pay top dollar, mostly to the Nearly Broadband Network, and everything else is trying to kill you.')]];
openModal(`<div class="title-art"><svg width="74" height="74" viewBox="0 0 74 74" aria-hidden="true"><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#1E2640" stroke-width="16" stroke-linecap="round"/><path d="M10 60V40c0-14 10-24 24-24h18" fill="none" stroke="#FFD23F" stroke-width="9" stroke-linecap="round"/><circle cx="58" cy="16" r="11" fill="#FF4F9A" stroke="#1E2640" stroke-width="4"/><circle cx="21" cy="44" r="3" fill="#fff"/><circle cx="30" cy="27" r="3" fill="#fff"/></svg>
<h1>Series<br>of <span>Tubes</span></h1></div>
<p class="tagline">${tr('Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.')}</p>${plugHtml(false)}${isPhone()?installRow():''}
${sv?`<div class="btns" style="margin-bottom:6px">${btn(tr('Continue {name} · {date}',{name:esc(sv.name),date:dateStr(sv.day)}),'cont',{},'pink big')}</div>`:''}
<label class="f" for="nmIn">${tr('Name your network')}</label><div class="network-name"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off">${btn(tr('Another one'),'randomName',{},'ghost sm')}</div>
<label class="f">${tr('Pick your home city')}</label><div class="starts">${starts.map(([c,d])=>`<button class="start ${UI.startCity===c?'on':''}" data-city="${c}" data-act="pickStart" data-args='{"city":"${c}"}'><b>${CITY[c].name}</b><span>${d}</span></button>`).join('')}</div>
<label class="f">${tr('Mode')}</label><div class="btns">${[['normal',tr('Normal')],['sandbox',tr('Sandbox')]].map(([m,l])=>`<button class="b sm modeb ${(UI.mode||'normal')===m?'pink':'ghost'}" data-m="${m}" data-act="modeSet" data-args='{"m":"${m}"}'>${l}</button>`).join('')}${btn(tr('Scenarios &amp; weekly challenge →'),'scenarios',{},'sm')}</div>
<label class="f">${tr('Language')}</label><div class="btns">${segBtns('langSet',LANG,Object.entries(LANGS))}</div>
<div class="btns cta" style="margin-top:16px;justify-content:space-between;align-items:center">${btn(sv?tr('Start a new network'):tr('Start building'),'start',{},'big')}${btn(tr('How to play'),'help',{},'ghost')}${btn(tr('Import a save'),'importPick',{},'ghost sm')}${btn(tr('Settings'),'settings',{},'ghost sm')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('Source on GitHub')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('Chat on Signal')}</a> · ${tr('Cookieless stats, no tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
if(sv){S=migrate(sv);compute();}
}
// "What's new": shown once to returning players after an update, or on demand.
function whatsNew(returning,force){
if(IS_DEV||!RELEASE_NOTES.length)return false;let seen=null;
try{seen=localStorage.getItem('sot-seen-version');localStorage.setItem('sot-seen-version',APP_VERSION);}catch(e){}
if(!force&&(!returning||seen===APP_VERSION))return false;
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Release notes')}</div><h2 style="font-size:28px">${tr('New in Series of Tubes {v}',{v:esc(APP_VERSION)})}</h2></div><button class="x" data-act="${UI.started?'closeModal':'helpClose'}" aria-label="${tr('Close')}">×</button></div>
${notesHtml(RELEASE_NOTES,APP_VERSION)}
${returning&&S?`<p class="note">${tr('Your network {name} was saved and is waiting for you.',{name:esc(S.name)})}</p>`:''}
<div class="btns" style="margin-top:12px">${btn(UI.started?tr('Back to my network'):tr('Got it'),UI.started?'closeModal':'helpClose',{},'pink big')}${notesLong(RELEASE_NOTES)?'':`<a class="b ghost" href="https://github.com/fjaeckel/seriesoftubes/blob/main/CHANGELOG.md" target="_blank" rel="noopener">${tr('Full changelog')}</a>`}</div>`);
return true;}

View file

@ -0,0 +1,17 @@
/* In-app notes stay short: at most NOTE_MAX changes, each cut to its first sentence. When anything was cut, a
link leads to the full notes of this version on GitHub. The CHANGELOG and the GitHub release keep every word. */
const NOTE_MAX=5,NOTE_CH=140;
function slimNote(n){const m=String(n).match(/^(.+?[.!?])(\s|$)/);let t=m?m[1]:String(n);if(t.length>NOTE_CH)t=t.slice(0,NOTE_CH-1).replace(/\s+\S*$/,'')+'…';return t;}
const notesLong=ns=>ns.length>NOTE_MAX||ns.some(n=>slimNote(n)!==n);
function notesHtml(ns,ver){const more=Math.max(0,ns.length-NOTE_MAX);
return `<ul class="notes">${ns.slice(0,NOTE_MAX).map(n=>`<li>${esc(slimNote(n))}</li>`).join('')}${more?`<li class="meta">${trn('…and {n} more change','…and {n} more changes',more)}</li>`:''}</ul>`+
(notesLong(ns)?`<p style="margin:6px 0 0"><a class="b pink sm" href="https://github.com/fjaeckel/seriesoftubes/releases/tag/v${esc(ver)}" target="_blank" rel="noopener">${tr('Read the full notes on GitHub')}</a></p>`:'');}
function newerVer(a,b){const x=String(a).split('.').map(Number),y=String(b).split('.').map(Number);for(let i=0;i<3;i++){if((x[i]||0)>(y[i]||0))return true;if((x[i]||0)<(y[i]||0))return false;}return false;}
// While the game is open, look for a newer release now and then and offer a reload.
function checkUpdate(){
if(IS_DEV||location.protocol==='file:'||!window.fetch)return;const now=Date.now();if(now-(UI.updChecked||0)<60000)return;UI.updChecked=now;
fetch('/version.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(j=>{
if(!j||!j.version||!newerVer(j.version,APP_VERSION))return;if(UI.updLater&&now-UI.updLater<6*3600*1000)return;
const top=(j.notes||[])[0]||'';$('update').innerHTML=`<div class="tx"><b>${tr('Series of Tubes {v} is out!',{v:esc(j.version)})}</b>${top?`<br>${esc(top.length>120?top.slice(0,117)+'…':top)}`:''}<br><span class="meta">${tr('Your game is saved automatically.')}</span></div>${btn(tr('Reload now'),'updateNow',{},'pink sm')}${btn(tr('Later'),'updateLater',{},'ghost sm')}`;$('update').hidden=false;
}).catch(()=>{});
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,21 @@
function openLinkModal(a,b){
if([a,b].includes('kyv')&&[a,b].includes('mos')){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">${tr('Not happening')}</h2><button class="x" data-act="closeModal" aria-label="${tr('Close')}">×</button></div><p class="lead" style="margin-top:8px">${tr('Nobody sells capacity between Kyiv and Moscow, and nobody is going to. Route through Warsaw, Bucharest or Helsinki instead.')}</p>`);return;}
if((cnCity(a)||cnCity(b))&&!cnOk()){openModal(`<div style="display:flex;align-items:center"><h2 style="font-size:24px">${tr('Not without a license')}</h2><button class="x" data-act="closeModal" aria-label="${tr('Close')}">×</button></div><p class="lead" style="margin-top:8px">${tr('Building into mainland China needs a joint venture and an operating license. Open {city} to apply.',{city:CITY[cnCity(a)?a:b].name})}</p>`);return;}
let route='';UI.pending={a,b};const km=kmBetween(a,b),sub=isSub(a,b),pop=S.pops[b]?0:popCost(b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc');
if(!sib.length)UI.route='diverse';const border=cnCity(a)!==cnCity(b),jn=sib.length?routeJoin(a,b):null,ts=landTrenches(a,b),mult=(sib.length&&!(jn&&jn.k===(ts[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);
if(border)route+=`<p class="lead" style="margin-top:8px">${tr('Cross-border circuits into mainland China are sold only by licensed carriers, at 3× the price. Regular ones lose about 20% of traffic at the border.')}</p>${a==='hkg'||b==='hkg'?`<div class="seg">${btn(tr('Regular crossing'),'cnPrem',{v:0},!UI.cnPrem?'pink':'ghost')}${btn(tr('Premium crossing <small>+60% · ~3% loss</small>'),'cnPrem',{v:1},UI.cnPrem?'pink':'ghost')}</div>`:`<p class="note">${tr('Premium crossings are only sold in Hong Kong.')}</p>`}`;
if(sib.length&&!(isSub(a,b)&&cablesFor(a,b).length)&&!(UI.via&&UI.via!=='land'&&cablesFor(a,b).some(c=>c.cid===UI.via))){route+=`<p class="lead" style="margin-top:8px">${trn('You already have {n} link here ({list}). Parallel links add capacity. How should this one be routed?','You already have {n} links here ({list}). Parallel links add capacity. How should this one be routed?',sib.length,{list:sib.map(l=>capName(l)).join(', ')})}</p>
<div class="seg">${ts.length>1?ts.map((t,i)=>btn(`${i?tr('Diverse route {n}',{n:i}):tr('Main route')} <small>${esc(t.caps.join(', '))}${i?' · +40%':''}</small>`,'route',{r:'t:'+t.k},jn&&jn.k===t.k?'pink':'ghost')).join('')+btn(tr('New diverse route <small>+40% · survives cuts alone</small>'),'route',{r:'diverse'},!jn?'pink':'ghost'):btn(tr('Diverse route <small>+40% · survives cuts alone</small>'),'route',{r:'diverse'},!jn?'pink':'ghost')+btn(tr('Same trench <small>cheaper · one backhoe cuts all</small>'),'route',{r:'same'},jn?'pink':'ghost')}</div>${ts.length>1?`<p class="note">${tr('Waves on the same route share its fate: one backhoe cuts them all.')}</p>`:''}`;}
const mode=UI.lmode==='df'?'df':'wave',tabs=`<div class="seg" style="margin-top:8px">${btn(tr('Lease a wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('Dark fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}</div>`;
const head=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${sub?tr('Subsea'):tr('Terrestrial')} · ${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('Close')}">×</button></div>${tabs}`;
if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));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('No subsea cable lands in {city}. The nearest landing station is {near}: run fiber there first, then take a cable from it.',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('No subsea cable lands in both {a} and {b}. Cables from {a} reach {list}. Hop through one of those.',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}</p>${S.won&&!ownCabWhy(a,b)?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('The landing permit dispute in {city} blocks new subsea links for {n} more days.',{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>`;
const wr=waveRoute(a,b,mult,border);
openModal(`${head}
<p class="lead" style="margin-top:8px">${tr('Waves are leased at a flat monthly rate. Bigger and longer costs more, and subsea is 1.8×. First month is due now.')}</p>
${pop?`<p class="lead" style="margin-top:8px">${tr('Includes a new POP in {city} ({price}{extra}).',{city:CITY[b].name,price:fmt$(popCost(b)),extra:ruCity(b)?', '+tr('government box included'):CITY[b].uae?', '+tr('free-zone license included'):CITY[b].saudi?', '+tr('local telecom licence included'):''})}</p>`:''}${route}${viaSeg(a,b)}
<div class="tiers">${LT.map((T,i)=>{const lc=Math.round(waveMo(wr.km,wr.sub,i)*wr.wm),c=lc+pop,sw=subWaveWhy(i,wr.km,wr.sub),so=!sw&&soldOut(a,b,i,wr.cab),ok=waveOk(a,b,i)&&!sw&&!so;return !waveShown(i)?'':`<button class="tierbtn" data-act="buildLink" data-args='{"tier":${i}}'${S.cash<c||!ok?' disabled':''}><span class="sz">${T.n}</span><span class="grow meta">${sw?tr('too far for this cable'):so?tr('sold out for {n} days',{n:Math.max(1,so.until-S.day)}):!ok?tr('needs {what} at both ends',{what:esc(waveNeed(i))}):pop?tr('due now {price}',{price:fmt$(c)}):tr('flat rate')}</span><span class="pr num">${tr('{price}/mo',{price:fmt$(lc)})}</span></button>`;}).join('')}</div>`);
}

View file

@ -0,0 +1,215 @@
/* Your own subsea cable (#22). Tier 1 networks lay their own: very expensive, slow to build, and it pays for
itself after a few years if it replaces enough leased waves. Both ends need a cable landing station. You own
up to eight fiber pairs; the first comes lit with a ROADMaster, the repeaters are powered from shore. */
const SEA_DELAYS=[N_('A whale has parked on the route and will not move.'),N_('The cable ship’s coffee machine broke. Nobody works without coffee.'),N_('A fishing fleet is trawling exactly where you need to lay.'),N_('The seabed survey found an old sea mine. A small, very careful detour.'),N_('Storm season. The ship is sheltering in port, playing cards.'),N_('The crew fished out somebody else’s cable by mistake and has to put it back.')];
const OWNCAB_LAND=3000000,OWNCAB_KM=6000,OWNCAB_OM=25;
const OWNCAB_NAMES=['Big Wet Tube','Davy Jones’ Backhaul','Kraken-1','Mariana Trench Coat','The Wet Ethernet','Sea-ya Later','Deep Pockets Express','Salty Sausage','Poseidon’s Patch Cable','Neptune Neutrality','Moby Disk','Fibre Nemo','The Long Wet Thing','Bermuda Triangle Routing','Seabed & Breakfast','Atlantis Backhaul'];
const OWNCAB_SHIPS=['MV Cable Guy','Spool of Thought','Wet Willy','Reel Deal','Splice Girl','Knot Today','Seas the Day','HMS Unplugged'];
const landing=c=>CABLE_PAIRS.some(p=>p.a===c||p.b===c);
const nearLanding=c=>CITIES.filter(x=>x.id!==c&&landing(x.id)).sort((x,y)=>kmBetween(c,x.id)-kmBetween(c,y.id))[0].id;
const ownCabKm=(a,b)=>seaRoutes(a,b)[0]?.km||Infinity;
const ownCabCost=km=>Math.round((2*OWNCAB_LAND+km*OWNCAB_KM+DF_SYS.roadm.cost)*hwMul('build'));
const ownCabMo=km=>Math.round(km*OWNCAB_OM)+ampCount(km)*AMP_MO;
const ownCabDays=km=>Math.round(300+km*0.05);
// Marine routing uses the same coastline as the map, in geographic coordinates.
// A quarter-degree grid keeps narrow passages open; edges are checked against
// coastline segments as well as water cells, so diagonal steps cannot cut land.
// Nothing is built until an order is quoted; topology and finished routes are reused.
const SEA_NAV={step:0.25,nx:1440,ny:641,rows:new Map(),edges:null,tiles:new Map(),fine:new Set(),routes:new Map(),ports:new Map(),pass:null,closed:new Set()};
// Real Europe–Asia cables land at Port Said and cross Egypt beside the canal to Suez; PAN AM crosses Panama by land.
// Each is an overland edge between two sea cells, priced as the distance it covers.
const SEA_PASS=[{id:'suez',a:[32.30,31.30],b:[32.58,29.85]},{id:'panama',a:[-79.90,9.40],b:[-79.50,8.85]}];
function seaSnap(p){const cx=Math.round((seaLon(p[0])+180)/SEA_NAV.step)%SEA_NAV.nx,cy=Math.round((p[1]+80)/SEA_NAV.step);let best=null;
for(let r=0;r<=16&&!best;r++)for(let dy=-r;dy<=r;dy++)for(let dx=-r;dx<=r;dx++){if(Math.max(Math.abs(dx),Math.abs(dy))!==r)continue;const x=(cx+dx+SEA_NAV.nx)%SEA_NAV.nx,y=cy+dy;if(!seaWater(x,y)||!seaNode(x,y))continue;const id=y*SEA_NAV.nx+x;if(!seaOpen(id))continue;const d=hav(...p,...seaPoint(id));if(!best||d<best.d)best={id,d};}
return best&&best.id;}
function seaPasses(){if(!SEA_NAV.pass){SEA_NAV.pass=new Map();for(const P of SEA_PASS){const a=seaSnap(P.a),b=seaSnap(P.b);if(a==null||b==null||a===b)continue;const km=hav(...seaPoint(a),...seaPoint(b));
for(const [u,v] of [[a,b],[b,a]]){let L=SEA_NAV.pass.get(u);if(!L)SEA_NAV.pass.set(u,L=[]);L.push({to:v,km,id:P.id});}}}return SEA_NAV.pass;}
// Which passages are shut: the Red Sea Crisis closes Suez. The main page sets this; the survey worker is told.
function seaSync(){if(typeof S==='undefined')return;SEA_NAV.closed=new Set(S&&S.scn&&S.scn.id==='redsea'?['suez']:[]);}
const seaKey=(a,b)=>(a<b?a+'|'+b:b+'|'+a)+(SEA_NAV.closed.size?'|x'+[...SEA_NAV.closed].sort().join(','):'');
const seaLon=x=>((x+180)%360+360)%360-180;
function seaInit(){if(SEA_NAV.edges)return;
SEA_NAV.edges=Array.from({length:181},()=>[]);
for(const poly of COAST_LL)for(let i=0,j=poly.length-1;i<poly.length;j=i++){
const a=poly[j],b=poly[i],e=[a[0],a[1],b[0],b[1]];
for(let y=Math.floor(Math.min(a[1],b[1]))-1;y<=Math.floor(Math.max(a[1],b[1]))+1;y++)for(let x=Math.floor(Math.min(a[0],b[0]))-1;x<=Math.floor(Math.max(a[0],b[0]))+1;x++)SEA_NAV.fine.add(seaLon(x)+','+y);
for(let y=Math.max(0,Math.floor(Math.min(a[1],b[1]))+90);y<=Math.min(180,Math.floor(Math.max(a[1],b[1]))+90);y++)SEA_NAV.edges[y].push(e);
for(let y=Math.floor(Math.min(a[1],b[1])/2);y<=Math.floor(Math.max(a[1],b[1])/2);y++)for(let x=Math.floor(Math.min(a[0],b[0])/2);x<=Math.floor(Math.max(a[0],b[0])/2);x++){
const k=(((x+90)%180+180)%180)+','+y;let t=SEA_NAV.tiles.get(k);if(!t)SEA_NAV.tiles.set(k,t=[]);t.push(e);
}
}
}
function seaLand(lon,lat){seaInit();lon=seaLon(lon);
const ray=x=>{let inside=false;for(const e of SEA_NAV.edges[clamp(Math.floor(lat)+90,0,180)])if((e[1]>lat)!==(e[3]>lat)&&x<(e[2]-e[0])*(lat-e[1])/(e[3]-e[1])+e[0])inside=!inside;return inside;};
return ray(lon)||(lon<-170&&ray(lon+360));
}
function seaWater(x,y){if(y<0||y>=SEA_NAV.ny)return false;x=(x+SEA_NAV.nx)%SEA_NAV.nx;
let row=SEA_NAV.rows.get(y);if(!row){row=new Uint8Array(SEA_NAV.nx);const lat=-80+y*SEA_NAV.step;for(let i=0;i<row.length;i++)row[i]=seaLand(-180+i*SEA_NAV.step,lat)?0:1;SEA_NAV.rows.set(y,row);}return !!row[x];
}
function seaCross(a,b,e){let x=e[0]+360*Math.round((a[0]-e[0])/360),u=e[2]+x-e[0];
const dx=b[0]-a[0],dy=b[1]-a[1],ex=u-x,ey=e[3]-e[1],den=dx*ey-dy*ex;
if(Math.abs(den)<1e-12)return false;
const t=((x-a[0])*ey-(e[1]-a[1])*ex)/den,v=((x-a[0])*dy-(e[1]-a[1])*dx)/den;
return t>=0&&t<=1&&v>=0&&v<=1;
}
function seaClear(A,B,margin=0){const a=[A[0],A[1]],b=[a[0]+seaLon(B[0]-a[0]),B[1]],n=Math.max(1,Math.ceil(Math.max(Math.abs(b[0]-a[0]),Math.abs(b[1]-a[1]))/0.25));
const checked=new Set();
for(let i=0;i<=n;i++){const t=i/n,x=a[0]+(b[0]-a[0])*t,y=a[1]+(b[1]-a[1])*t;
if(seaLand(x,y))return false;
if(margin&&[[margin,0],[-margin,0],[0,margin],[0,-margin]].some(([dx,dy])=>seaLand(x+dx,y+dy)))return false;
const tx=Math.floor(x/2),ty=Math.floor(y/2);
// Include adjacent tiles so segments touching a tile boundary are checked too.
for(let v=ty-1;v<=ty+1;v++)for(let u=tx-1;u<=tx+1;u++){const k=(((u+90)%180+180)%180)+','+v;if(checked.has(k))continue;checked.add(k);
for(const e of SEA_NAV.tiles.get(k)||[])if(seaCross(a,b,e))return false;}
}return true;
}
const seaPoint=id=>[-180+(id%SEA_NAV.nx)*SEA_NAV.step,-80+Math.floor(id/SEA_NAV.nx)*SEA_NAV.step];
const seaNode=(x,y)=>x%4===0&&y%4===0||SEA_NAV.fine.has(Math.floor(-180+x*SEA_NAV.step)+','+Math.floor(-80+y*SEA_NAV.step));
// A coarse city marker must not snap into a tiny disconnected estuary or lake.
function seaOpen(id){if(!SEA_NAV.connected)SEA_NAV.connected=new Map();if(SEA_NAV.connected.has(id))return SEA_NAV.connected.get(id);
const seen=new Set([id]),queue=[id];let open=false;
for(let i=0;i<queue.length;i++){const v=queue[i];if(SEA_NAV.connected.has(v)){open=SEA_NAV.connected.get(v);if(open)break;}
if(queue.length>256){open=true;break;}const x=v%SEA_NAV.nx,y=Math.floor(v/SEA_NAV.nx);
for(const stride of (x%4===0&&y%4===0?[4,1]:[1]))for(let sy=-1;sy<=1;sy++)for(let sx=-1;sx<=1;sx++){if(!sx&&!sy)continue;const dx=sx*stride,dy=sy*stride,xx=(x+dx+SEA_NAV.nx)%SEA_NAV.nx,yy=y+dy,n=yy*SEA_NAV.nx+xx;
if(seen.has(n)||!seaNode(xx,yy)||!seaWater(xx,yy)||!seaStep(v,dx,dy))continue;seen.add(n);queue.push(n);}
}for(const v of seen)SEA_NAV.connected.set(v,open);return open;
}
function seaPorts(city){if(SEA_NAV.ports.has(city))return SEA_NAV.ports.get(city);
const c=CITY[city],p=[c.lon,c.lat],cx=Math.round((seaLon(c.lon)+180)/SEA_NAV.step)%SEA_NAV.nx,cy=Math.round((c.lat+80)/SEA_NAV.step),wet=!seaLand(...p),bins=new Map();
// Inland city markers may reach more than one sea (Cairo, for example).
// Keep shore approaches in different directions; routing chooses the right sea.
for(let r=0;r<=16;r++)for(let dy=-r;dy<=r;dy++)for(let dx=-r;dx<=r;dx++){
if(Math.max(Math.abs(dx),Math.abs(dy))!==r)continue;const x=(cx+dx+SEA_NAV.nx)%SEA_NAV.nx,y=cy+dy;if(!seaWater(x,y)||!seaNode(x,y))continue;
const id=y*SEA_NAV.nx+x,q=seaPoint(id),d=hav(...p,...q),angle=Math.atan2(q[1]-p[1],seaLon(q[0]-p[0])*Math.cos(c.lat*Math.PI/180)),bin=Math.floor((angle+Math.PI)*8/Math.PI)%16+'|'+Math.floor(d/100);
if(d>350||bins.has(bin)&&d>=bins.get(bin).d)continue;
if(wet&&!seaClear(p,q))continue;
if(!wet){const n=Math.max(2,Math.ceil(d/2));let water=false,ok=true;for(let i=0;i<=n;i++){const t=i/n,pt=[p[0]+seaLon(q[0]-p[0])*t,p[1]+(q[1]-p[1])*t];if(!seaLand(...pt)){water=true;if(!seaClear(pt,q)){ok=false;break;}}else if(water){ok=false;break;}}if(!ok)continue;}
if(seaOpen(id))bins.set(bin,{id,d,bin});
}
// Nearby approaches are the default. A low-latency survey may also land further off and backhaul overland, like real
// transatlantic systems that land in the west of England and run to London on land.
const sorted=[...bins.values()].sort((a,b)=>a.d-b.d),limit=sorted.length?(sorted[0].d<30?sorted[0].d+15:sorted[0].d*1.75):0,dir=new Set(),ports=sorted.map(p=>{const k=p.bin.split('|')[0]>>1;const first=!dir.has(k);dir.add(k);return {id:p.id,d:p.d,near:first&&p.d<=limit};});SEA_NAV.ports.set(city,ports);return ports;
}
const seaPort=city=>seaPorts(city)[0]?.id??null,seaNear=ps=>ps.filter(p=>p.near);
// The grid topology is shared by all designs. Test each edge only once.
function seaStep(id,dx,dy){if(!SEA_NAV.known){const n=SEA_NAV.nx*SEA_NAV.ny;SEA_NAV.known=new Uint8Array(n);SEA_NAV.open=new Uint8Array(n);SEA_NAV.knownWide=new Uint8Array(n);SEA_NAV.openWide=new Uint8Array(n);}
const wide=Math.abs(dx)>1||Math.abs(dy)>1,sx=Math.sign(dx),sy=Math.sign(dy),bit=1<<((sy+1)*3+sx+1-(sy>0||sy===0&&sx>0?1:0)),known=wide?SEA_NAV.knownWide:SEA_NAV.known,open=wide?SEA_NAV.openWide:SEA_NAV.open;
if(known[id]&bit)return !!(open[id]&bit);known[id]|=bit;
const a=seaPoint(id),b=[a[0]+dx*SEA_NAV.step,a[1]+dy*SEA_NAV.step];
for(let y=Math.floor(Math.min(a[1],b[1])/2);y<=Math.floor(Math.max(a[1],b[1])/2);y++)for(let x=Math.floor(Math.min(a[0],b[0])/2);x<=Math.floor(Math.max(a[0],b[0])/2);x++)
for(const e of SEA_NAV.tiles.get((((x+90)%180+180)%180)+','+y)||[])if(seaCross(a,b,e))return false;
open[id]|=bit;return true;
}
function seaSearch(starts,ends,target,clearance){const PASS=seaPasses();
const dist=new Map(),prev=new Map(),done=new Set(),heap=[],goals=new Map(ends.map(p=>[p.id,p.d]));let goal=Infinity,goalEnd=null;
const put=(id,g)=>{const v={id,g,f:g+(id===-1?0:hav(...seaPoint(id),...target))};let i=heap.length;heap.push(v);while(i){const p=(i-1)>>1;if(heap[p].f<=v.f)break;heap[i]=heap[p];i=p;}heap[i]=v;};
const take=()=>{const out=heap[0],v=heap.pop();if(heap.length){let i=0;while(i*2+1<heap.length){let j=i*2+1;if(j+1<heap.length&&heap[j+1].f<heap[j].f)j++;if(heap[j].f>=v.f)break;heap[i]=heap[j];i=j;}heap[i]=v;}return out;};
for(const p of starts){dist.set(p.id,p.d);put(p.id,p.d);}
while(heap.length){const {id,g}=take();if(id===-1){const path=[];for(let v=goalEnd;v!==undefined;v=prev.get(v))path.push(seaPoint(v));return path.reverse();}if(done.has(id))continue;done.add(id);if(goals.has(id)&&g+goals.get(id)<goal){goal=g+goals.get(id);goalEnd=id;put(-1,goal);}
const x=id%SEA_NAV.nx,y=Math.floor(id/SEA_NAV.nx),a=seaPoint(id);
for(const P of PASS.get(id)||[]){if(SEA_NAV.closed.has(P.id)||done.has(P.to))continue;const ng=g+P.km;if(ng<(dist.get(P.to)??Infinity)){dist.set(P.to,ng);prev.set(P.to,id);put(P.to,ng);}}
for(const stride of (x%4===0&&y%4===0?[4,1]:[1]))for(let sy=-1;sy<=1;sy++)for(let sx=-1;sx<=1;sx++){if(!sx&&!sy)continue;const dx=sx*stride,dy=sy*stride,xx=(x+dx+SEA_NAV.nx)%SEA_NAV.nx,yy=y+dy,v=yy*SEA_NAV.nx+xx;if(done.has(v)||!seaNode(xx,yy)||!seaWater(xx,yy))continue;
const b=seaPoint(v);if(!seaStep(id,dx,dy))continue;
const near=clearance&&(!seaWater(xx-2,yy)||!seaWater(xx+2,yy)||!seaWater(xx,yy-2)||!seaWater(xx,yy+2)),ng=g+hav(...a,...b)*(near?1+clearance:1);
if(ng<(dist.get(v)??Infinity)){dist.set(v,ng);prev.set(v,id);put(v,ng);}
}
}return null;
}
function seaSimplify(path,margin){const out=[path[0]];for(let i=0;i<path.length-1;){let j=Math.min(path.length-1,i+64);while(j>i+1&&!seaClear(path[i],path[j],margin))j--;out.push(path[j]);i=j;}return out;}
function seaDensify(path){const out=[path[0].slice()];for(let i=1;i<path.length;i++){const a=path[i-1],b=path[i],dx=seaLon(b[0]-a[0]),n=Math.max(1,Math.ceil(Math.max(Math.abs(dx),Math.abs(b[1]-a[1]))));for(let j=1;j<=n;j++)out.push([seaLon(a[0]+dx*j/n),a[1]+(b[1]-a[1])*j/n]);}return out;}
// Points along the great circle from a to b, about every half degree.
function seaGC(a,b){const r=Math.PI/180,v=([lo,la])=>[Math.cos(la*r)*Math.cos(lo*r),Math.cos(la*r)*Math.sin(lo*r),Math.sin(la*r)],A=v(a),B=v(b),w=Math.acos(Math.min(1,A[0]*B[0]+A[1]*B[1]+A[2]*B[2]));
const n=Math.max(1,Math.ceil(w/r/0.5)),out=[];if(w<1e-9)return [b.slice()];for(let i=1;i<=n;i++){const t=i/n,f=Math.sin((1-t)*w)/Math.sin(w),g=Math.sin(t*w)/Math.sin(w),x=f*A[0]+g*B[0],y=f*A[1]+g*B[1],z=f*A[2]+g*B[2];out.push([seaLon(Math.atan2(y,x)/r),Math.atan2(z,Math.hypot(x,y))/r]);}return out;}
// A straight line on the map is not the shortest way across an ocean. Long legs follow the great circle where it stays at sea.
function seaGreat(path,margin){const out=[path[0]];for(let i=1;i<path.length;i++){const a=path[i-1],b=path[i];
if(hav(...a,...b)>300){const gc=seaGC(a,b);let ok=true,q=a;for(const p of gc){if(!seaClear(q,p,margin)){ok=false;break;}q=p;}if(ok){out.push(...gc);continue;}}out.push(b);}return out;}
const seaLength=pts=>Math.round(pts.slice(1).reduce((s,p,i)=>s+hav(...pts[i],...p),0));
function seaRoutes(a,b){seaSync();const reverse=a>b,key=seaKey(a,b);let routes=SEA_NAV.routes.get(key);
if(!routes){const A=reverse?b:a,B=reverse?a:b,PA=seaPorts(A),PB=seaPorts(B);routes=[];
if(seaNear(PA).length&&seaNear(PB).length)for(const [penalty,margin,all] of [[1,0.5,false],[0.3,0.25,false],[0,0,true]]){
const raw=seaSearch(all?PA:seaNear(PA),all?PB:seaNear(PB),[CITY[B].lon,CITY[B].lat],penalty);if(!raw)break;
const pts=seaDensify(seaGreat([[CITY[A].lon,CITY[A].lat],...seaSimplify(raw,margin),[CITY[B].lon,CITY[B].lat]],margin)),r={pts,km:seaLength(pts),shore:[raw[0],raw[raw.length-1]]};
// A survey can reuse the previous feasible route if its new candidate is longer.
routes.push(routes.length&&r.km>routes[routes.length-1].km?routes[routes.length-1]:r);
}SEA_NAV.routes.set(key,routes);
}
return reverse?routes.map(r=>({km:r.km,pts:r.pts.slice().reverse(),shore:r.shore.slice().reverse()})):routes;
}
// Surveys run off the UI thread in browsers. Tests and browsers without workers
// use the same deterministic router synchronously. Switching designs uses the cache.
const SEA_SURVEY={worker:null,pending:new Set(),failed:false};
function seaReady(a,b){seaSync();const key=seaKey(a,b);
if(SEA_NAV.routes.has(key)||typeof Worker==='undefined'||SEA_SURVEY.failed)return true;
if(SEA_SURVEY.pending.has(key))return false;
try{
if(!SEA_SURVEY.worker){
const helpers=[seaSnap,seaPasses,seaGC,seaGreat,seaNear,seaKey,seaSync,seaLon,seaInit,seaLand,seaWater,seaCross,seaClear,seaPoint,seaNode,seaOpen,seaPorts,seaPort,seaStep,seaSearch,seaSimplify,seaDensify,seaLength,seaRoutes,hav,clamp];
const code='const SEA_PASS='+JSON.stringify(SEA_PASS)+';const COAST_LL='+JSON.stringify(COAST_LL)+';const CITY='+JSON.stringify(Object.fromEntries(CITIES.map(c=>[c.id,{lon:c.lon,lat:c.lat}])))+';const SEA_NAV={step:0.25,nx:1440,ny:641,rows:new Map(),edges:null,tiles:new Map(),fine:new Set(),routes:new Map(),ports:new Map(),pass:null,closed:new Set()};'+
helpers.map(f=>'const '+f.name+'='+f.toString()+';').join('')+'onmessage=({data:{a,b,key,closed}})=>{try{SEA_NAV.closed=new Set(closed||[]);postMessage({key,routes:seaRoutes(a,b)});}catch(e){postMessage({key,error:String(e)});}};';
const url=URL.createObjectURL(new Blob([code],{type:'text/javascript'}));
try{SEA_SURVEY.worker=new Worker(url);}finally{URL.revokeObjectURL(url);}
const refresh=key=>{if(!S)return;const survey=$('modalCard').querySelector('[data-sea-survey]');if(UI.pending&&!$('modal').hidden&&survey&&(!key||survey.dataset.seaSurvey===key))openLinkModal(UI.pending.a,UI.pending.b);renderPanel();renderLeft();if(!$('dash').hidden)renderDash();};
SEA_SURVEY.worker.onmessage=({data})=>{SEA_SURVEY.pending.delete(data.key);if(data.error){SEA_SURVEY.failed=true;SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();}else SEA_NAV.routes.set(data.key,data.routes);refresh(data.error?undefined:data.key);};
SEA_SURVEY.worker.onerror=()=>{SEA_SURVEY.failed=true;SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();refresh();};
}
SEA_SURVEY.pending.add(key);const [from,to]=key.split('|');SEA_SURVEY.worker.postMessage({a:from,b:to,key,closed:[...SEA_NAV.closed]});return false;
}catch(e){SEA_SURVEY.failed=true;if(SEA_SURVEY.worker)SEA_SURVEY.worker.terminate();SEA_SURVEY.worker=null;SEA_SURVEY.pending.clear();return true;}
}
const seaSurveyAttr=(a,b)=>{seaSync();const k=seaKey(a,b);return SEA_SURVEY.pending.has(k)?`data-sea-survey="${k}"`:'';};
function seaMapPoints(pts){const out=[];for(const p of pts){const q=proj(...p);if(out.length)q[0]+=W*Math.round((out[out.length-1][0]-q[0])/W);out.push(q);}return out;}
// Designs pay for progressively tighter surveys; all use a feasible marine path.
const SEA_DESIGNS={standard:{n:N_('Standard'),cost:1,time:1},optimized:{n:N_('Optimized'),cost:3,time:1.3},express:{n:N_('Low latency'),cost:7,time:1.7}};
function seaReference(a,b,express){
const cs=cablesFor(a,b).filter(c=>express||(CAB[c.cid].lat||1)>=1);
return cs.sort((x,y)=>x.km*(express?(CAB[x.cid].lat||1):1)-y.km*(express?(CAB[y.cid].lat||1):1))[0];
}
// Routing asks for link latency often; the cables on a route never change, so the express factor is worked out once.
const SEA_XF=new Map();
function seaLatencyFactor(l){if(l.seaDesign==='optimized')return 1;if(l.seaDesign!=='express')return 1.1;
const k=CIDX[l.a]*4096+CIDX[l.b];let f=SEA_XF.get(k);if(f===undefined){const c=seaReference(l.a,l.b,true);SEA_XF.set(k,f=Math.min(0.9,c?(CAB[c.cid].lat||1):0.9));}return f;}
// The low-latency survey may also follow the corridor of the fastest cable already on this route, where that is shorter
// (only a cable that is in service: one cut by a crisis proves nothing):
// that cable proves the path, and it keeps the fastest design as fast as the fastest cable on the map.
function seaCorridor(a,b){const c=cablesOk(a,b).sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];if(!c)return null;const P=CAB[c.cid].pairs.find(([x,y])=>x===c.a&&y===c.b);if(!P)return null;
let ll=[[CITY[c.a].lon,CITY[c.a].lat],...P[2],[CITY[c.b].lon,CITY[c.b].lat]].map(q=>[seaLon(q[0]),q[1]]);if(c.a!==a)ll=ll.reverse();
const pts=[ll[0]];for(let i=1;i<ll.length;i++)pts.push(...seaGC(ll[i-1],ll[i]));return {km:seaLength(pts),pts,shore:[pts[1],pts[pts.length-2]]};}
function seaQuote(a,b,design='standard',upgrades={}){
const D=SEA_DESIGNS[design],routes=seaRoutes(a,b),cor=design==='express'&&routes.length?seaCorridor(a,b):null;let route=routes[Object.keys(SEA_DESIGNS).indexOf(design)];if(cor&&route&&cor.km<route.km)route=cor;
const base=routes[0]?.km||Infinity,km=route?.km||Infinity;
// Higher survey and permitting costs dominate any savings from shorter glass.
let cost=Math.round(ownCabCost(Math.max(base,km))*D.cost),days=Math.round(ownCabDays(Math.max(base,km))*D.time);
for(const k of Object.keys(SUB_UPGRADES))if(upgrades[k]){cost+=subUpgradeCost({km},k);days+=SUB_UPGRADES[k].days;}
const ms=linkLat({a,b,kind:'df',own:true,sub:true,km,seaDesign:design});
return {km,cost,days,ms,pts:route?.pts,shore:route?.shore,cor:!!cor&&route===cor};
}
// Some pairs share a landmass and still have cables between them (Marseille–Singapore, Cairo–Palermo) (#67).
const seaCab=(a,b)=>isSub(a,b)||(landing(a)&&landing(b)&&cablesFor(a,b).length>0);
// What you get back for giving up your own subsea cable (#88): what you paid for it (design and upgrades included)
// if no optic can light it even with both upgrades,
// one still being laid returns most of the part not laid yet, a working one is yours for good.
const cabBack=l=>{if(!l||l.kind!=='df'||!l.own||!l.sub)return 0;const c=l.paid>0?l.paid:ownCabCost(l.km);if(!subNeed(l.km))return c;
if(l.ready>S.day){const tot=Math.max(1,l.ready-(l.day||0));return Math.round(c*0.75*Math.min(1,(l.ready-S.day)/tot));}return 0;};
function ownCabWhy(a,b){if(!seaCab(a,b))return tr('This route is on land. Build your own fiber instead.');
if(!S.won)return tr('Laying your own subsea cable is a Tier 1 thing. Go transit-free first.');
for(const c of [a,b])if(!landing(c))return tr('{city} has no cable landing station.',{city:CITY[c].name});
if(cnCity(a)||cnCity(b))return tr('Nobody gives a foreign network a landing licence in mainland China.');
if(!seaReady(a,b))return tr('Surveying a sea route…');
const routes=seaRoutes(a,b);if(!routes.length)return tr('No navigable sea route connects these landing stations.');
const km=Math.min(...routes.map(r=>r.km));if(!subNeed(km))return tr('{km} km is more than any optic can light, even on the best subsea gear ({max} km at most). Real cables stop at an island or a landing station on the way: lay two shorter ones.',{km:km.toLocaleString(),max:Math.round(SUB_MAXKM()).toLocaleString()});
return '';}
function ownCabTeaser(a,b){const why=ownCabWhy(a,b);return `<div class="btns" style="margin-top:8px">${btn(S.won?tr('Lay your own subsea cable…'):tr('Your own subsea cable <small>Tier 1 only</small>'),'ownCab',{},S.won&&!why?'pink':'ghost',!!why)}</div>${why&&S.won?`<p class="note" ${seaSurveyAttr(a,b)}>${esc(why)}</p>`:''}`;}
function ownCabBody(a,b,pop){const why=ownCabWhy(a,b);if(why)return `<p class="lead" style="margin-top:10px" ${seaSurveyAttr(a,b)}>${esc(why)}</p>${btn(tr('Back'),'dfSrc',{v:'lease'},'ghost sm')}`;
const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',upgrades={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering},q=seaQuote(a,b,design,upgrades),{km,cost,days}=q,lack=seaLack(km,upgrades),mo=ownCabMo(km),wt=subMaxTier(km),w=Math.round(waveMo(km,true,wt)*waveMarket(a,b,true).m),save=10*w*LT[4].g/LT[wt].g-mo,pay=save>0?Math.ceil(cost/save):0;
return `<p class="lead" style="margin-top:8px">${tr('Your very own subsea cable. A ship lays it across the seabed, you own every fiber pair in it, and nobody else’s waves share your glass. It costs a frankly rude amount of money and takes a long time.')}</p>
<h4 class="sub4">${tr('Cable design')}</h4><div class="starts one">${Object.entries(SEA_DESIGNS).map(([v,D])=>{const o=seaQuote(a,b,v,upgrades);return `<button class="start ${design===v?'on':''}" data-act="seaDesign" data-args='{"v":"${v}"}'><b>${tr(D.n)}</b><span>${tr('{ms} ms one-way',{ms:o.ms.toFixed(1)})} · ${fmt$(o.cost+pop)} · ${tr('about {n} days',{n:o.days})}</span></button>`;}).join('')}</div>
<h4 class="sub4">${tr('Submarine transmission')}</h4>${Object.entries(SUB_UPGRADES).map(([k,U])=>btn(`${tr(U.n)} <small>${upgrades[k]?'✓ · ':''}${fmt$(subUpgradeCost({km},k))} · ${tr('+{n} days',{n:U.days})}</small>`,'seaPackage',{k},upgrades[k]?'green sm':'ghost sm')).join('')}
${lack.length?`<p class="why">${lack[0]==='design'?tr('This design’s route is {km} km: too long for any optics, even with both upgrades. A shorter design can make it.',{km:km.toLocaleString()}):tr('{km} km is too far for your optics on their own. Add {what} to light this cable.',{km:km.toLocaleString(),what:lack.length>1?tr('{a} and {b}',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)})}</p>`:`<p class="note">${tr('Up to {g} per channel',{g:fmtG(submarineRate({a,b,km,kind:'df',own:true,sub:true,subterminal:upgrades.terminal?S.day:undefined,subengineering:upgrades.engineering?S.day:undefined}))})} · ${tr('Better terminals and optical tuning extend long-haul reach. Repeaters are already included; these upgrades do not change latency.')}</p>`}
<div class="kv"><span>${tr('Estimated latency')}</span><b>${tr('{ms} ms one-way',{ms:q.ms.toFixed(1)})}</b></div>
<div class="kv"><span>${tr('Route')}</span><b>${tr('{km} km of seabed',{km:km.toLocaleString()})}</b></div>
<div class="kv"><span>${tr('Fiber pairs')}</span><b>${tr('{n} in the cable, the first one lit',{n:SUB_PAIRS_MAX})}</b></div>
<div class="kv"><span>${tr('Landing stations')}</span><b>${tr('{a} and {b}',{a:CITY[a].name,b:CITY[b].name})}</b></div>
<div class="kv"><span>${tr('Build time')}</span><b>${tr('about {n} days',{n:days})}</b></div>
<div class="kv" style="margin-top:10px"><span>${tr('Due now')}</span><b>${fmt$(cost+pop)}</b></div><div class="kv"><span>${tr('Monthly')}</span><b>${tr('{price}/mo',{price:fmt$(mo)})}</b></div>
<p class="note">${subCarrier(km)?`${tr('A leased {wave} wave on this route costs {price}/mo.',{wave:LT[wt].n,price:fmt$(w)})} ${pay?tr('Replace 16 Tbps of them and the cable pays for itself in about {n} months.',{n:pay}):''} `:''}${tr('Cuts still happen, anchors and sharks included, but the repair ship is yours to call.')}</p>
<div class="btns" style="margin-top:10px">${btn(tr('Lay the cable <small>{price}</small>',{price:fmt$(cost+pop)}),'orderCable',{},'pink big',S.cash<cost+pop||lack.length>0)}${btn(tr('Back'),'dfSrc',{v:'lease'},'ghost')}</div>`;}

View file

@ -0,0 +1,35 @@
function dfModalBody(a,b,km,pop){
if(seaCab(a,b)&&UI.dfSrc==='cable')return ownCabBody(a,b,pop);
const sea=!isSub(a,b)&&seaCab(a,b)?ownCabTeaser(a,b):'';
if(isSub(a,b)&&!subDfCable(a,b))return `<p class="lead" style="margin-top:10px">${tr('Nobody sells dark fiber on a subsea cable here. Subsea capacity comes as leased waves.')}</p>`+ownCabTeaser(a,b);
const sc=isSub(a,b)?subDfCable(a,b):null;if(sc)km=sc.km;
if(uaePair(a,b))return `<p class="lead" style="margin-top:10px">${tr('No dark fiber inside the UAE. Only the two licensed operators may run fiber here, and they only sell waves.')}</p>`+sea;
if(landX(a,b)&&cnCity(a)===cnCity(b))return `<p class="lead" style="margin-top:10px">${tr('Nobody sells one fiber pair across a dozen borders. Between continents, overland capacity only comes as leased waves.')}</p>`+sea;
if(!dfAllowed(a,b))return `<p class="lead" style="margin-top:10px">${tr('Dark fiber across the Chinese border is not for sale. Buy a cross-border wave instead.')}</p>`+sea;
if(lvl()<2)return `<p class="lead" style="margin-top:10px">${tr('Dark fiber unlocks at customer level 2. You need the scale to justify buying your own optical gear.')}</p>`+sea;
const src=UI.dfSrc==='build'&&lvl()>=3&&!sc?'build':'lease',sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite',amps=ampCount(km);
const up=(src==='build'?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO;
const w=Math.round(waveMo(km,false,4));
return `<p class="lead" style="margin-top:8px">${tr('A fiber pair of your own. The glass is cheap, the gear is not: you buy a line system with an amplifier every {km} km, then optics for each channel. Your gear can fail, and you fix it.',{km:AMP_EVERY})}</p>
<h4 class="sub4">${tr('The glass')}</h4><div class="seg">${btn(tr('Lease an IRU <small>{price}/mo · ready in 30 days</small>',{price:fmt$(dfLeaseMo(km))}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(S.won?tr('Lay your own subsea cable…'):tr('Your own subsea cable <small>Tier 1 only</small>'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(lvl()>=3?tr('Build your own <small>{price} · ~{n} days</small>',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('Build your own <small>level 3</small>'),'dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}${sea?btn(S.won?tr('Lay your own subsea cable…'):tr('Your own subsea cable <small>Tier 1 only</small>'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}</div>${sc?`<p class="note">${tr("A fiber pair on {cable}, {km} km. It shares the cable with everyone else's waves, anchors included.",{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}</p>`:''}
${src==='build'?`<p class="note">${tr('Your own trench: almost no rent, but permits and digging take forever, and delays happen.')}</p>`:''}
<h4 class="sub4">${tr('Line system')}</h4><div class="seg">${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} <small>${DF_SYS[k].lvl>lvl()?tr('level {n}',{n:DF_SYS[k].lvl}):fmt$(DF_SYS[k].cost)}</small>`,'dfSys',{v:k},sys===k?'pink':'ghost',DF_SYS[k].lvl>lvl())).join('')}</div>
<p class="note">${esc(DF_SYS[sys].blurb)} ${trn('Plus {n} in-line amplifier ({price} each, {mo}/mo for hut rent and power).','Plus {n} in-line amplifiers ({price} each, {mo}/mo for hut rent and power).',amps,{price:fmt$(AMP_COST),mo:fmt$(AMP_MO)})}</p>${km>reachOn(OPT.tp16.reach,!!sc)?`<p class="note">${tr('<b>{km} km is longer than any optic reaches at full speed.</b> Transponders will run in long-haul mode (1.2T, 800G or 400G per channel), or add regen sites along the way to get full speed back.',{km:km.toLocaleString()})}</p>`:''}
<div class="kv" style="margin-top:10px"><span>${tr('Due now')}</span><b>${fmt$(up)}</b></div><div class="kv"><span>${tr('Monthly')}</span><b>${tr('{price}/mo',{price:fmt$(mo)})}</b></div>
<p class="note">${tr('For comparison, a leased 1.6T wave on this route is {price}/mo. Optics come next, from the link panel.',{price:fmt$(w)})}</p>
<div class="btns" style="margin-top:10px">${btn(`${src==='build'?tr('Start construction'):tr('Sign the IRU')} <small>${fmt$(up)}</small>`,'orderDf',{},'pink big',S.cash<up)}</div>`;
}
function openVxcModal({from,to,prov}){
let rows='';const row=(f,a,b)=>{const km=kmBetween(a,b),sub=isSub(a,b),pb=S.pops[b]?nniPort(b,f.id):null,remote=!S.pops[b];
const label=remote?tr('Remote peering at {ix} · discouraged',{ix:esc(CITY[b].ix)}):pb?tr('Your POP'):tr('Your POP · needs a fabric port there');
const freeA=nniPort(a,f.id)?NNI[nniPort(a,f.id).tier].g-nniUsed(a,f.id):0,freeB=remote?1e9:pb?NNI[pb.tier].g-nniUsed(b,f.id):0;
return `<div class="row"><span class="logo" style="--c:${f.col}">${initials(f)}</span><div class="grow"><div class="nm">${CITY[a].name} → ${CITY[b].name}</div><div class="meta">${label} · ${km.toLocaleString()} km${sub?' '+tr('subsea'):''}</div>
<div class="btns">${VXC.map((V,t)=>btn(`${V.n} <small>${tr('{price}/mo',{price:fmt$(vxcMo(km,sub,t))})}</small>`,'buyVxc',{a,b,prov:f.id,t},'sm',(!remote&&!pb)||V.g>freeA||V.g>freeB||S.cash<vxcMo(km,sub,t))).join('')}</div></div></div>`;};
for(const f of FABS){if(prov&&f.id!==prov)continue;
if(from){if(!nniPort(from,f.id))continue;for(const b of f.cities){if(b===from)continue;if(!S.pops[b]&&!CITY[b].ix)continue;rows+=row(f,from,b);}}
else if(to&&f.cities.includes(to)){for(const a of Object.keys(S.pops))if(a!==to&&nniPort(a,f.id))rows+=row(f,a,to);}}
if(!rows){const fs=FABS.filter(f=>!to||f.cities.includes(to));rows=`<p class="empty">${tr("You need a fabric port at one of your POPs first. Open a POP's Infra tab and buy a port on {list}.",{list:fs.map(f=>`<b>${esc(f.name)}</b> (${f.cities.filter(c=>S.pops[c]).map(c=>CITY[c].name).join(', ')||tr('no POP of yours on it yet')})`).join(', ')})}</p>`;}
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Virtual circuit over an NNI fabric')}</div><h2 style="font-size:26px">${from?tr('From {city}',{city:CITY[from].name}):tr('To {city}',{city:CITY[to].name})}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('Close')}">×</button></div>
<p class="lead" style="margin-top:8px">${tr("No install fee, live in minutes, billed monthly. Cheaper than a wave for small capacity, but it rides someone else's fabric, and that fabric can fail.")}</p>${rows}`);
}