Merge #133: route new subsea cables around coastlines

This commit is contained in:
Frederic Jung 2026-10-26 21:52:59 +01:00
commit 656e904e05
No known key found for this signature in database
9 changed files with 289 additions and 34 deletions

View file

@ -9,6 +9,8 @@ All notable changes to this project are documented here. The project follows
- RouteScript has a new “Slop it with AI” button: an AI reads your live traffic, writes you a script and tells you how great it is. A new help page explains what every rule does and how real routers do the same, with seven ready-made scripts (Penny Pincher, Peering First, Shields Up and more) filled in from your own network and loaded with one tap. - RouteScript has a new “Slop it with AI” button: an AI reads your live traffic, writes you a script and tells you how great it is. A new help page explains what every rule does and how real routers do the same, with seven ready-made scripts (Penny Pincher, Peering First, Shields Up and more) filled in from your own network and loaded with one tap.
- Six Atlantic stops join the map: Halifax, Bermuda, the Azores, Tenerife, Cape Verde and St Helena (#120). The cables across the Atlantic now stop where they really land, and a POP on an island splits a crossing that is just too long for 1.6T into hops that each carry 1.6T or more: Miami to Madrid via Bermuda and the Azores, Atlanta to Lisbon via Bermuda, Lisbon and London to Lagos via Tenerife, and Fortaleza to Europe via Cape Verde. Halifax sits at the start of the shortest line to England. Three new cables, Sol Survivor, Atlantis-2: The Sequel and Canary in the Cable Mine, link the islands, and older ones gain island stops. Exchanges only where one runs today, in Praia and Halifax. New island networks from One Commotion to Pretty Sure South Atlantic, cables that go quiet in the Bermuda Triangle, and a new scenario, Mid-Atlantic Accent, asks you to cross at 1.6T hop by hop. Broadband in a very small town no longer starts above what the town can use. - Six Atlantic stops join the map: Halifax, Bermuda, the Azores, Tenerife, Cape Verde and St Helena (#120). The cables across the Atlantic now stop where they really land, and a POP on an island splits a crossing that is just too long for 1.6T into hops that each carry 1.6T or more: Miami to Madrid via Bermuda and the Azores, Atlanta to Lisbon via Bermuda, Lisbon and London to Lagos via Tenerife, and Fortaleza to Europe via Cape Verde. Halifax sits at the start of the shortest line to England. Three new cables, Sol Survivor, Atlantis-2: The Sequel and Canary in the Cable Mine, link the islands, and older ones gain island stops. Exchanges only where one runs today, in Praia and Halifax. New island networks from One Commotion to Pretty Sure South Atlantic, cables that go quiet in the Bermuda Triangle, and a new scenario, Mid-Atlantic Accent, asks you to cross at 1.6T hop by hop. Broadband in a very small town no longer starts above what the town can use.
- You can zoom in much further on the map, and a short link between two close cities can now be picked (#126). Dense regions like southern Brazil spread out properly when you zoom in, and tapping right on a link next to a city opens the link instead of the city. - You can zoom in much further on the map, and a short link between two close cities can now be picked (#126). Dense regions like southern Brazil spread out properly when you zoom in, and tapping right on a link next to a city opens the link instead of the city.
- New player-built subsea cables follow surveyed sea routes around land. Their map paths, prices, optical reach and latency use the same distance, and premium designs are consistently faster. Existing cables keep their saved characteristics.
## [1.31.0] — 2026-10-26 ## [1.31.0] — 2026-10-26
- Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen. - Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen.

View file

@ -10,7 +10,7 @@
"url": "git+https://github.com/fjaeckel/seriesoftubes.git" "url": "git+https://github.com/fjaeckel/seriesoftubes.git"
}, },
"scripts": { "scripts": {
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js tests/routing-reference.test.js tests/perf.test.js", "test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js tests/routing-reference.test.js tests/perf.test.js tests/sea-routing.test.js",
"build": "bash scripts/build.sh", "build": "bash scripts/build.sh",
"i18n:check": "node scripts/i18n-check.js", "i18n:check": "node scripts/i18n-check.js",
"serve": "npm run build && npx --yes serve@14.2.4 _site", "serve": "npm run build && npx --yes serve@14.2.4 _site",

View file

@ -2712,4 +2712,6 @@
"Loaded {name}. Check it, then deploy.":"{name} chargé. Vérifiez-le, puis déployez.", "Loaded {name}. Check it, then deploy.":"{name} chargé. Vérifiez-le, puis déployez.",
"<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit terminé. Trafic en baisse de {p}.</b><br>L’IA s’excuse pour la confusion, et reste absolument certaine que le script était juste. Corrigez-le depuis l’onglet NOC.", "<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit terminé. Trafic en baisse de {p}.</b><br>L’IA s’excuse pour la confusion, et reste absolument certaine que le script était juste. Corrigez-le depuis l’onglet NOC.",
"Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Des règles pour votre contrôleur Auto-TE : quelles sorties préférer, lesquelles éviter et quand déborder sur la suivante. L’aide de l’éditeur explique chaque règle et propose des scripts tout prêts.", "Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Des règles pour votre contrôleur Auto-TE : quelles sorties préférer, lesquelles éviter et quand déborder sur la suivante. L’aide de l’éditeur explique chaque règle et propose des scripts tout prêts.",
"No navigable sea route connects these landing stations.": "Aucun itinéraire maritime navigable ne relie ces stations d’atterrissement.",
"Surveying a sea route\u2026":"Recherche d’un itinéraire maritime…"
}; };

View file

@ -2712,4 +2712,6 @@
"Loaded {name}. Check it, then deploy.":"{name} caricato. Controllalo, poi fai il deploy.", "Loaded {name}. Check it, then deploy.":"{name} caricato. Controllalo, poi fai il deploy.",
"<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit completato. Traffico giù del {p}.</b><br>L’IA si scusa per la confusione, e resta sicurissima che lo script fosse giusto. Correggilo dalla scheda NOC.", "<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit completato. Traffico giù del {p}.</b><br>L’IA si scusa per la confusione, e resta sicurissima che lo script fosse giusto. Correggilo dalla scheda NOC.",
"Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Regole per il tuo controller Auto-TE: quali uscite preferire, quali evitare e quando passare alla successiva. L’aiuto dell’editor spiega ogni regola e ha script pronti.", "Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Regole per il tuo controller Auto-TE: quali uscite preferire, quali evitare e quando passare alla successiva. L’aiuto dell’editor spiega ogni regola e ha script pronti.",
"No navigable sea route connects these landing stations.": "Nessuna rotta marittima navigabile collega queste stazioni di approdo.",
"Surveying a sea route\u2026":"Ricerca di una rotta marittima…"
}; };

View file

@ -2712,4 +2712,6 @@
"Loaded {name}. Check it, then deploy.":"{name} carregado. Verifique e depois faça o deploy.", "Loaded {name}. Check it, then deploy.":"{name} carregado. Verifique e depois faça o deploy.",
"<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit concluído. Tráfego caiu {p}.</b><br>A IA pede desculpas pela confusão, e continua totalmente certa de que o script estava correto. Corrija pela aba NOC.", "<b>Commit complete. Traffic down {p}.</b><br>The AI apologises for the confusion, and remains completely sure the script was right. Fix it from the NOC tab.":"<b>Commit concluído. Tráfego caiu {p}.</b><br>A IA pede desculpas pela confusão, e continua totalmente certa de que o script estava correto. Corrija pela aba NOC.",
"Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Regras para o seu controlador Auto-TE: quais saídas preferir, quais evitar e quando passar para a próxima. A ajuda do editor explica cada regra e tem scripts prontos.", "Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.":"Regras para o seu controlador Auto-TE: quais saídas preferir, quais evitar e quando passar para a próxima. A ajuda do editor explica cada regra e tem scripts prontos.",
"No navigable sea route connects these landing stations.": "Nenhuma rota marítima navegável conecta estas estações de aterragem.",
"Surveying a sea route\u2026":"Pesquisando uma rota marítima…"
}; };

File diff suppressed because one or more lines are too long

View file

@ -590,8 +590,8 @@ test('buttons behind an open modal stay quiet, and a declined PNI clears its sta
test('#66 #68 subsea optics: engineered glass reaches further, and the same limit caps leased waves', () => { test('#66 #68 subsea optics: engineered glass reaches further, and the same limit caps leased waves', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
// your own Paris–Ashburn cable: 1.2T per channel instead of 400G // a legacy Paris–Ashburn cable: 1.2T per channel instead of 400G
ev("ACT.buildPop({city:'par'});ACT.buildPop({city:'ash'});S.pops.par.rgen=S.pops.ash.rgen=3;S.links.push({id:'oc',a:'par',b:'ash',kind:'df',own:true,sub:true,km:ownCabKm('par','ash'),sys:'roadm',ch:['tp16'],ready:0,mo:1,day:0,cut:0});compute()"); ev("ACT.buildPop({city:'par'});ACT.buildPop({city:'ash'});S.pops.par.rgen=S.pops.ash.rgen=3;S.links.push({id:'oc',a:'par',b:'ash',kind:'df',own:true,sub:true,km:Math.round(kmBetween('par','ash')*1.15),sys:'roadm',ch:['tp16'],ready:0,mo:1,day:0,cut:0});compute()");
assert.equal(ev("dfCap(S.links.find(l=>l.id==='oc'))"), 1200, `${ev("ownCabKm('par','ash')")} km of your own cable`); assert.equal(ev("dfCap(S.links.find(l=>l.id==='oc'))"), 1200, `${ev("ownCabKm('par','ash')")} km of your own cable`);
// counted as land glass it would be 400G, which is what #66 saw // counted as land glass it would be 400G, which is what #66 saw
ev("S.links.find(l=>l.id==='oc').sub=false;compute()"); ev("S.links.find(l=>l.id==='oc').sub=false;compute()");
@ -627,7 +627,7 @@ test('#67 a subsea cable can be laid between landing stations that also share a
assert.ok(ev("!!document.querySelector('#modalCard [data-act=ownCab]')"), 'the dark fiber window offers the cable'); assert.ok(ev("!!document.querySelector('#modalCard [data-act=ownCab]')"), 'the dark fiber window offers the cable');
ev("ACT.ownCab()"); ev("ACT.ownCab()");
assert.match(ev("document.getElementById('modalCard').textContent"), /km of seabed/); assert.match(ev("document.getElementById('modalCard').textContent"), /km of seabed/);
ev("ACT.orderCable()"); ev("UI.seaengineering=true;ACT.orderCable()");
assert.ok(ev("S.links.some(l=>l.own&&l.sub&&l.a==='mrs'&&l.b==='sin')"), 'Marseille–Singapore cable ordered'); assert.ok(ev("S.links.some(l=>l.own&&l.sub&&l.a==='mrs'&&l.b==='sin')"), 'Marseille–Singapore cable ordered');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
@ -699,8 +699,8 @@ test('NOC leased lines tab prices leased dark fiber, own fiber and cables agains
const sub = JSON.parse(ev("JSON.stringify(leaseSwaps().find(x=>x.sub))")); const sub = JSON.parse(ev("JSON.stringify(leaseSwaps().find(x=>x.sub))"));
assert.equal(sub.why, ''); assert.equal(sub.why, '');
assert.ok(sub.opts.find(o => o.k === 'cab').up > ev("ownCabCost(ownCabKm('lon','nyc'))")); assert.ok(sub.opts.find(o => o.k === 'cab').up > ev("ownCabCost(ownCabKm('lon','nyc'))"));
ev("for(const c of ['mrs','sin'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=2;UI.via=null;openLinkModal('mrs','sin');ACT.buildLink({tier:2});closeModal();compute()"); ev("for(const c of ['cai','pmo'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=2;UI.via=null;openLinkModal('cai','pmo');ACT.buildLink({tier:2});closeModal();compute()");
const ms = JSON.parse(ev("JSON.stringify(leaseSwaps().find(x=>x.a==='mrs'&&x.b==='sin'))")); const ms = JSON.parse(ev("JSON.stringify(leaseSwaps().find(x=>x.a==='cai'&&x.b==='pmo'))"));
assert.ok(ms && ms.opts.some(o => o.k === 'cab'), 'landing stations on one landmass can swap a wave for your own cable (#67)'); assert.ok(ms && ms.opts.some(o => o.k === 'cab'), 'landing stations on one landmass can swap a wave for your own cable (#67)');
ev("ACT.leaseSwap({a:'ams',b:'fra',src:'lease'})"); ev("ACT.leaseSwap({a:'ams',b:'fra',src:'lease'})");
assert.equal(ev("document.getElementById('dash').hidden"), true); assert.equal(ev("document.getElementById('dash').hidden"), true);
@ -1058,10 +1058,10 @@ test('#104 declining a loan offer clears the bank badge while paused', () => {
test('#88 no subsea cable longer than any optic can light, and a refund for calling one off', () => { test('#88 no subsea cable longer than any optic can light, and a refund for calling one off', () => {
const { ev, errors } = load(); const { ev, errors } = load();
ev("ACT.start({});S.cash=1e10;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0"); ev("ACT.start({});S.cash=1e10;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0");
// New York to Sydney is too long for plain optics; since #78 premium terminals light it, so the order screen asks // New York to Sydney is too long for plain optics; the marine route needs optical engineering, so the order screen asks
// for them instead of refusing. Only a length beyond even both upgrades is refused. // for them instead of refusing. Only a length beyond even both upgrades is refused.
assert.equal(ev("ownCabWhy('nyc','syd')"), ''); assert.equal(ev("ownCabWhy('nyc','syd')"), '');
assert.deepEqual(JSON.parse(ev("JSON.stringify(subNeed(ownCabKm('nyc','syd')))")), ['terminal']); assert.deepEqual(JSON.parse(ev("JSON.stringify(subNeed(ownCabKm('nyc','syd')))")), ['engineering']);
assert.equal(ev('subNeed(26000)'), null, 'nothing lights 26,000 km'); assert.equal(ev('subNeed(26000)'), null, 'nothing lights 26,000 km');
assert.equal(ev("ownCabWhy('lax','syd')"), '', 'Los Angeles to Sydney still works'); assert.equal(ev("ownCabWhy('lax','syd')"), '', 'Los Angeles to Sydney still works');
assert.ok(ev("subCarrier(ownCabKm('lax','syd'))") > 0); assert.ok(ev("subCarrier(ownCabKm('lax','syd'))") > 0);

View file

@ -706,9 +706,9 @@ test('subsea cable designs trade construction cost and time for previewed latenc
const quotes = JSON.parse(ev("JSON.stringify(['standard','optimized','express'].map(d=>seaQuote('lon','nyc',d)))")); const quotes = JSON.parse(ev("JSON.stringify(['standard','optimized','express'].map(d=>seaQuote('lon','nyc',d)))"));
assert.ok(quotes[0].ms > quotes[1].ms && quotes[1].ms > quotes[2].ms); assert.ok(quotes[0].ms > quotes[1].ms && quotes[1].ms > quotes[2].ms);
assert.ok(quotes[1].cost >= quotes[0].cost * 3 && quotes[2].cost >= quotes[0].cost * 7); assert.ok(quotes[1].cost >= quotes[0].cost * 3 && quotes[2].cost >= quotes[0].cost * 7);
assert.ok(quotes[1].days >= quotes[0].days * 1.3 && quotes[2].days >= quotes[0].days * 1.7); assert.ok(quotes[1].days >= Math.round(quotes[0].days * 1.3) && quotes[2].days >= Math.round(quotes[0].days * 1.7));
assert.ok(quotes[2].days < 3 * 365, 'a low-latency Atlantic cable takes years, not most of a decade'); assert.ok(quotes[2].days < 3 * 365, 'a low-latency Atlantic cable takes years, not most of a decade');
assert.equal(quotes[2].ms, ev("Math.min(...cablesFor('lon','nyc').map(c=>linkLat({kind:'wave',km:c.km,cable:c.cid})))"), 'express competes with Hibernia'); assert.equal(quotes[2].km, ev("seaLength(seaRoutes('lon','nyc')[2].pts)"), 'express length follows its surveyed marine path');
for (const q of quotes) assert.ok(dom.window.document.getElementById('modalCard').textContent.includes(q.ms.toFixed(1) + ' ms one-way'), 'every latency is visible before ordering'); for (const q of quotes) assert.ok(dom.window.document.getElementById('modalCard').textContent.includes(q.ms.toFixed(1) + ' ms one-way'), 'every latency is visible before ordering');
for (const [i, design] of ['standard', 'optimized', 'express'].entries()) { for (const [i, design] of ['standard', 'optimized', 'express'].entries()) {
ev("UI.lmode='df';UI.dfSrc='cable';openLinkModal('lon','nyc')"); ev("UI.lmode='df';UI.dfSrc='cable';openLinkModal('lon','nyc')");
@ -842,22 +842,22 @@ test('own subsea cables after #78: refunds of what was paid, upgrades a route ne
assert.equal(ev('UI.seaDesign'), 'standard', 'the next order starts from the standard design'); assert.equal(ev('UI.seaDesign'), 'standard', 'the next order starts from the standard design');
// its latency is worked out once per route, and stays the same // its latency is worked out once per route, and stays the same
const ms = ev('linkLat(S.links.at(-1))'); assert.equal(ev('linkLat(S.links.at(-1))'), ms); assert.ok(ev('SEA_XF.size') >= 1); const ms = ev('linkLat(S.links.at(-1))'); assert.equal(ev('linkLat(S.links.at(-1))'), ms); assert.ok(ev('SEA_XF.size') >= 1);
// New York to Sydney needs premium terminals: the screen says so and will not order without them // New York to Sydney needs optical engineering: the screen says so and will not order without them
open('nyc', 'syd'); open('nyc', 'syd');
assert.match(q('.why'), /Add Premium submarine terminals/); assert.match(q('.why'), /Add Optical engineering/);
assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /A leased .* wave on this route/, 'no leased wave reaches that far, so no comparison with one'); assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /A leased .* wave on this route/, 'no leased wave reaches that far, so no comparison with one');
assert.equal(ev("document.querySelector('#modalCard [data-act=orderCable]').disabled"), true); assert.equal(ev("document.querySelector('#modalCard [data-act=orderCable]').disabled"), true);
const n = ev('S.links.length'); ev('ACT.orderCable()'); assert.equal(ev('S.links.length'), n, 'the order itself checks too'); const n = ev('S.links.length'); ev('ACT.orderCable()'); assert.equal(ev('S.links.length'), n, 'the order itself checks too');
ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=terminal]').click()"); ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=engineering]').click()");
assert.equal(q('.why'), null); assert.match(q('[data-act=seaPackage][data-args*=terminal]'), /\+30 days/); assert.equal(q('.why'), null); assert.match(q('[data-act=seaPackage][data-args*=engineering]'), /\+180 days/);
// leaving and coming back to another route starts fresh // leaving and coming back to another route starts fresh
open('lon', 'nyc'); assert.equal(ev('!!UI.seaterminal'), false); open('lon', 'nyc'); assert.equal(ev('!!UI.seaengineering'), false);
open('nyc', 'syd'); ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=terminal]').click();ACT.orderCable()"); open('nyc', 'syd'); ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=engineering]').click();ACT.orderCable()");
const syd = JSON.parse(ev("JSON.stringify(S.links.at(-1))")); const syd = JSON.parse(ev("JSON.stringify(S.links.at(-1))"));
assert.equal(syd.b, 'syd'); assert.equal(syd.subterminal, syd.ready); assert.equal(syd.b, 'syd'); assert.equal(syd.subengineering, syd.ready);
ev('S.day=S.links.at(-1).ready'); assert.equal(ev("optG('tp16',S.links.at(-1))"), 400, 'lit across 18,387 km'); ev('S.day=S.links.at(-1).ready'); assert.equal(ev("optG('tp16',S.links.at(-1))"), 400, 'lit across the surveyed marine route');
// upgrades bought later count toward the price; sanitize keeps a sane price and drops junk // upgrades bought later count toward the price; sanitize keeps a sane price and drops junk
ev("S.links.at(-1).subengineering=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'engineering'})"); ev("S.links.at(-1).subterminal=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'terminal'})");
assert.ok(ev('S.links.at(-1).paid') > syd.paid); assert.ok(ev('S.links.at(-1).paid') > syd.paid);
ev("S.links.at(-1).paid='lots';S.links[0].paid=-5;S=sanitize(S)"); ev("S.links.at(-1).paid='lots';S.links[0].paid=-5;S=sanitize(S)");
assert.equal(ev('S.links.at(-1).paid'), undefined); assert.equal(ev('S.links[0].paid'), undefined); assert.equal(ev('S.links.at(-1).paid'), undefined); assert.equal(ev('S.links[0].paid'), undefined);

120
tests/sea-routing.test.js Normal file
View file

@ -0,0 +1,120 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Check the surveyed part independently against the original coastline segments.
// City markers may sit inland: their two short shore approaches are excluded.
function assertMarine(path, start, end, coast) {
const at = p => path.findIndex(q => Math.abs(p[0] - q[0]) < 1e-8 && Math.abs(p[1] - q[1]) < 1e-8);
const first = at(start), last = at(end);
assert.ok(first >= 0 && last >= first, 'both shore approaches appear in the saved path');
const edges = coast.flatMap(poly => poly.map((p, i) => [p, poly[(i + 1) % poly.length]]));
const turn = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
for (let i = first + 1; i <= last; i++) {
const a = path[i - 1], b = [...path[i]];
b[0] += 360 * Math.round((a[0] - b[0]) / 360);
for (const [p, q] of edges) {
const shift = 360 * Math.round((a[0] - p[0]) / 360), c = [p[0] + shift, p[1]], d = [q[0] + shift, q[1]];
assert.ok(!(turn(a, b, c) * turn(a, b, d) < -1e-12 && turn(c, d, a) * turn(c, d, b) < -1e-12),
`sea segment ${JSON.stringify([a, b])} crosses a coastline`);
}
}
}
test('surveyed designs avoid land, use real path lengths and improve latency', () => {
const { ev, dom, errors } = load();
try {
const coast = JSON.parse(ev('JSON.stringify(COAST_LL)'));
for (const [a, b] of [['lag', 'bde'], ['cbo', 'nyc'], ['lax', 'tok'], ['mrs', 'sin'], ['cai', 'pmo']]) {
const quotes = JSON.parse(ev(`JSON.stringify(Object.keys(SEA_DESIGNS).map(d=>seaQuote('${a}','${b}',d)))`));
for (let i = 0; i < quotes.length; i++) {
const q = quotes[i];
assert.ok(Number.isFinite(q.km) && q.pts.length > 2);
assertMarine(q.pts, ...q.shore, coast);
assert.equal(q.km, ev(`seaLength(${JSON.stringify(q.pts)})`));
if (i) {
assert.ok(q.km <= quotes[i - 1].km, 'premium surveys never lengthen the route');
assert.ok(q.ms < quotes[i - 1].ms, 'premium latency is strictly lower');
assert.ok(q.cost > quotes[i - 1].cost && q.days > quotes[i - 1].days);
}
}
const reverse = JSON.parse(ev(`JSON.stringify(seaQuote('${b}','${a}'))`));
assert.equal(reverse.km, quotes[0].km);
assert.deepEqual(reverse.pts, [...quotes[0].pts].reverse(), 'reverse direction uses the same survey');
}
assert.ok(ev("seaQuote('cai','pmo').km<3000"), 'Cairo approaches the Mediterranean rather than routing out of the Red Sea');
assert.equal(ev("cablesFor('cbo','nyc').length"), 0, 'route works without an existing cable');
assert.ok(ev("seaQuote('cbo','nyc').km > kmBetween('cbo','nyc')*1.3"), 'the route detours around Africa');
assert.ok(ev("seaQuote('mrs','sin').pts.some(p=>p[0]>-7&&p[0]<-4&&p[1]>35&&p[1]<37)"), 'the Mediterranean route passes Gibraltar');
assert.ok(ev("seaQuote('lax','tok').pts.some((p,i,a)=>i&&Math.abs(p[0]-a[i-1][0])>180)"), 'Pacific route wraps the date line');
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
test('grid edges and smoothing cannot jump across a thin island', () => {
const { ev, dom } = load();
try {
ev('COAST_LL.length=0;COAST_LL.push([[0.09,-0.1],[0.16,-0.1],[0.16,0.1],[0.09,0.1]])');
assert.equal(ev('seaLand(0,0)||seaLand(0.25,0)'), false, 'both grid endpoints are water');
assert.equal(ev('seaClear([0,0],[0.25,0])'), false, 'exact coastline check catches the island between them');
assert.equal(ev('seaStep(320*1440+720,1,0)'), false, 'the grid step also catches it');
assert.equal(ev('seaClear([0,-0.25],[0.25,-0.25])'), true, 'open water remains traversable');
} finally { dom.window.close(); }
});
test('orders, previews, saved paths and map geometry agree; legacy cables retain their values', () => {
const { ev, dom, errors } = load();
try {
ev("ACT.start({});S.cash=1e11;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0;for(const city of ['lag','bde'])ACT.buildPop({city});UI.lmode='df';UI.dfSrc='cable';openLinkModal('lag','bde')");
for (const design of ['standard', 'optimized', 'express']) {
const q = JSON.parse(ev(`JSON.stringify(seaQuote('lag','bde','${design}'))`));
assert.ok(dom.window.document.getElementById('modalCard').textContent.includes(q.ms.toFixed(1) + ' ms one-way'));
ev(`UI.pending={a:'lag',b:'bde'};UI.seaDesign='${design}';ACT.orderCable()`);
const l = JSON.parse(ev('JSON.stringify(S.links.at(-1))'));
assert.deepEqual(l.seaPath, q.pts);
assert.equal(l.km, q.km);
assert.equal(l.paid, q.cost);
assert.equal(l.ready - l.day, q.days);
assert.equal(ev('linkLat(S.links.at(-1))'), q.ms);
ev('S=migrate(JSON.parse(JSON.stringify(S)));GEO.clear()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.links.at(-1).seaPath)')), q.pts);
assert.deepEqual(JSON.parse(ev('JSON.stringify(linkGeom(S.links.at(-1)).pts)')),
JSON.parse(ev('JSON.stringify(seaMapPoints(S.links.at(-1).seaPath))')));
ev("UI.dfSrc='cable';openLinkModal('lag','bde')");
}
ev("S.links.push({id:'legacy',a:'lag',b:'bde',kind:'df',own:true,sub:true,seaDesign:'optimized',sys:'roadm',km:7515,ch:[],ready:0,mo:1,cut:0});S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.links.at(-1).seaPath'), undefined);
assert.equal(ev('S.links.at(-1).km'), 7515);
assert.equal(ev('linkLat(S.links.at(-1))'), 37.575);
ev('S.links.at(-1).seaPath=[[0,0],[NaN,1]];S=sanitize(S)');
assert.equal(ev('S.links.at(-1).seaPath'), undefined, 'invalid path data is discarded');
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
test('failed surveys refuse construction instead of falling back to a line through land', () => {
const { ev, dom } = load();
try {
ev("ACT.start({});S.cash=1e11;S.won=true;SEA_NAV.routes.set('bde|lag',[]);UI.pending={a:'lag',b:'bde'}");
assert.match(ev("ownCabWhy('lag','bde')"), /No navigable sea route/);
const count = ev('S.links.length'), cash = ev('S.cash');
ev('ACT.orderCable()');
assert.equal(ev('S.links.length'), count);
assert.equal(ev('S.cash'), cash);
} finally { dom.window.close(); }
});
test('background surveys deduplicate requests and do not replace a later dialog', () => {
const { ev, dom } = load();
try {
ev(`window.Worker=class{constructor(){window.surveyWorker=this;this.requests=[];}postMessage(m){this.requests.push(m);}terminate(){}};
URL.createObjectURL=()=> 'blob:test';URL.revokeObjectURL=()=>{};
ACT.start({});S.won=true;S.cash=1e11;UI.lmode='df';UI.dfSrc='cable';openLinkModal('lag','bde');`);
assert.match(dom.window.document.getElementById('modalCard').textContent, /Surveying a sea route/);
ev("ownCabWhy('bde','lag')");
assert.equal(ev('surveyWorker.requests.length'), 1, 'reverse-direction requests share a job');
ev("openModal('<p id=otherDialog>Another dialog</p>');surveyWorker.onmessage({data:{key:'bde|lag',routes:[]}})");
assert.ok(dom.window.document.getElementById('otherDialog'), 'a completed survey cannot reopen a stale build dialog');
assert.equal(ev('SEA_SURVEY.pending.size'), 0);
} finally { dom.window.close(); }
});