Karte: Linien und Verbandssymbole schließen am Hafen-/Nestzeichen an (Routen-Anker)

Seit Karte 2 stehen Hafen- und Nestzeichen am Ufer, Handelshäfen an der echten Lage; Routen,
Schiffe, Konvois usw. endeten weiter in der Feldmitte. Neues map/anchor.ts (anchorXY,
routePointsOnMap, pointOnMap) setzt nur die Darstellung um; angewendet in movers, naval,
world-events, fields, intel, selection, Seewege-Vorschau. Prüfhilfen data-mission-ends und
__tfMapProbe, Unit- und E2E-Test.
This commit is contained in:
db9979 committed 2026-11-29 08:38:43 +01:00
1 parent b9421d5411
commit 22c8b4e1f2
13 files changed
+442 -62

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
// Karte 2: Linien und Verbandssymbole schließen an die Hafen- und Nestzeichen an (apps/web/src/map/anchor.ts). Seit
// Karte 2 stehen die Zeichen auf Küstenfeldern am Ufer statt in der Feldmitte; Routen rechnen weiter mit Feldmitten.
// Geprüft über die Prüfhilfen der Karte: data-mission-ends (erster/letzter gezeichneter Punkt je Mission) und
// window.__tfMapProbe (Lage der Zeichen und Verbandssymbole). Mit TF_ROUTEN_SHOTS=<vorher|nachher> entstehen
// Bildschirmfotos (390 px, hell/dunkel nach TF_ROUTEN_THEME) einer Insel- und einer Küstenbasis unter /tmp/tf-routen/.
import { mkdirSync } from "node:fs";
import type { Page } from "@playwright/test";
import type postgres from "postgres";
import { COLS, ROWS, hexCenter, hexCenterXY, hexDistanceKm, isTradePortHex, seaRoute, terrainAt } from "@tidefront/world";
import { markerXY } from "../src/map/anchor.ts";
import { awayFromEdge, expect, test } from "./fixtures.ts";
type Sql = ReturnType<typeof postgres>;
type Hex = { col: number; row: number };
type XY = { x: number; y: number };
const H = 3600_000;
const PREFIX = process.env.TF_ROUTEN_SHOTS ?? null;
const THEME = process.env.TF_ROUTEN_THEME === "dark" ? "dark" : "light";
async function taken(sql: Sql): Promise<Set<string>> {
const rows = await sql`select col, row from nest union all select col, row from base union all select col, row from resource_field
union all select target_col as col, target_row as row from mission where status in ('outbound', 'holding')`;
return new Set(rows.map((r) => `${r.col},${r.row}`));
}
/** Ziel 150–600 km entfernt mit Seeweg über mindestens drei Felder; bevorzugt ein Küstenfeld mit verschobenem Zeichen. */
function targetNear(home: Hex, busy: Set<string>): Hex | null {
let fallback: Hex | null = null;
for (let dr = -7; dr <= 7; dr++) for (let dc = -7; dc <= 7; dc++) {
const h = { col: home.col + dc, row: home.row + dr };
const t = terrainAt(h.col, h.row);
if (!awayFromEdge(h) || (t !== "sea" && t !== "coast") || busy.has(`${h.col},${h.row}`) || isTradePortHex(h.col, h.row)) continue;
const d = hexDistanceKm(home, h);
if (d < 150 || d > 600 || seaRoute(home, h).hexes.length < 3 || seaRoute(home, h).partial) continue;
const c = hexCenterXY(h.col, h.row), m = markerXY(h.col, h.row);
if (t === "coast" && Math.hypot(c.x - m.x, c.y - m.y) > 8) return h;
fallback ??= h;
}
return fallback;
}
/** Laufende Mission direkt in der Datenbank (Seeweg im Plan wie beim Auslaufen); `departInMs` < 0: schon unterwegs. */
async function insertMission(sql: Sql, player: { id: number; baseId: number }, home: Hex, target: Hex, departInMs: number): Promise<number> {
const r = seaRoute(home, target);
const now = Date.now();
const travel = 4 * H;
const plan = { units: { korvette: 2 }, departAtMs: now + departInMs, travelSeconds: travel / 1000, route: { hexes: r.hexes.map(([c, w]) => [c, w]), km: r.km } };
const [m] = await sql`insert into mission (player_id, base_id, type, target_kind, target_col, target_row, plan, status, arrive_at, return_at)
values (${player.id}, ${player.baseId}, 'aufklaerung', 'hex', ${target.col}, ${target.row}, ${JSON.stringify(plan)}::jsonb, 'outbound',
${new Date(now + departInMs + travel).toISOString()}::timestamptz, ${new Date(now + departInMs + 2 * travel).toISOString()}::timestamptz) returning id`;
return m.id as number;
}
type Probe = { markers: (XY & Hex)[]; ships: { key: number; x: number; y: number }[] };
async function probe(page: Page): Promise<Probe> {
await page.waitForFunction(() => typeof (window as unknown as { __tfMapProbe?: unknown }).__tfMapProbe === "object");
return page.evaluate(() => {
const p = (window as unknown as { __tfMapProbe: { markers: () => unknown; ships: () => unknown } }).__tfMapProbe;
return { markers: p.markers(), ships: p.ships() } as Probe;
});
}
/** data-mission-ends: „id:x,y;x,y“ je Mission. */
async function missionEnds(page: Page, id: number): Promise<[XY, XY]> {
let out: [XY, XY] | null = null;
await expect.poll(async () => {
const raw = (await page.locator("main [data-mission-ends]").first().getAttribute("data-mission-ends")) ?? "";
const hit = raw.split(" ").find((s) => s.startsWith(`${id}:`));
if (!hit) return false;
const [a, b] = hit.slice(String(id).length + 1).split(";").map((s) => { const [x, y] = s.split(",").map(Number); return { x, y }; });
out = [a, b];
return true;
}, { timeout: 15_000 }).toBe(true);
return out!;
}
const near = (a: XY, b: XY, tol = 0.05) => Math.hypot(a.x - b.x, a.y - b.y) <= tol;
test("Linien und Schiffssymbole schließen am Hafen- und Nestzeichen an (nicht an der Feldmitte)", async ({ page, player, seed }) => {
test.slow();
const home = { col: player.col, row: player.row };
const target = targetNear(home, await taken(seed.sql));
test.skip(!target, "kein Ziel mit Seeweg neben diesem Hafen");
const [n] = await seed.sql`insert into nest (col, row, level) values (${target!.col}, ${target!.row}, 1) returning id`;
const running = await insertMission(seed.sql, player, home, target!, -20 * 60_000);
const waiting = await insertMission(seed.sql, player, home, target!, 2 * H); // Sammelangriff: liegt noch im Hafen
try {
await page.goto("/?tab=karte");
const [first, last] = await missionEnds(page, running);
const pr = await probe(page);
const own = pr.markers.find((m) => m.col === home.col && m.row === home.row);
const nest = pr.markers.find((m) => m.col === target!.col && m.row === target!.row);
expect(own, "Hafenzeichen auf der Karte").toBeTruthy();
expect(nest, "Nestzeichen auf der Karte").toBeTruthy();
// Erster Punkt = Hafenzeichen, letzter = Nestzeichen (bei Küstenfeldern also nicht die Feldmitte).
expect(near(first, own!), `Anfang ${JSON.stringify(first)} am Hafenzeichen ${JSON.stringify(own)}`).toBe(true);
expect(near(last, nest!), `Ende ${JSON.stringify(last)} am Nestzeichen ${JSON.stringify(nest)}`).toBe(true);
// Der wartende Verband liegt sichtbar am Hafenzeichen.
const ship = pr.ships.find((s) => s.key === waiting * 2);
expect(ship, "Symbol des wartenden Verbands").toBeTruthy();
expect(near(ship!, own!), `Schiff ${JSON.stringify(ship)} am Hafenzeichen`).toBe(true);
} finally {
await seed.sql`delete from mission where player_id = ${player.id}`;
await seed.sql`delete from nest where id = ${n.id}`;
}
});
/** Freies Küstenfeld, dessen Zeichen deutlich neben der Feldmitte steht (nahe `around`). */
function shiftedCoast(around: Hex, busy: Set<string>, minKm: number): Hex | null {
let best: { h: Hex; d: number } | null = null;
for (let row = 8; row < ROWS - 8; row++) for (let col = 8; col < COLS - 8; col++) {
if (terrainAt(col, row) !== "coast" || busy.has(`${col},${row}`) || isTradePortHex(col, row)) continue;
const c = hexCenterXY(col, row), m = markerXY(col, row);
if (Math.hypot(c.x - m.x, c.y - m.y) < minKm) continue;
const d = hexDistanceKm(around, { col, row });
if (!best || d < best.d) best = { h: { col, row }, d };
}
return best?.h ?? null;
}
test.describe("Bildschirmfotos 390 px", () => {
test.use({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2 });
test("Insel- und Küstenbasis mit laufender Fahrt", async ({ page, player, seed }) => {
test.skip(!PREFIX, "nur mit TF_ROUTEN_SHOTS");
test.setTimeout(240_000);
mkdirSync("/tmp/tf-routen", { recursive: true });
await page.addInitScript((t) => { if (t === "dark") localStorage.setItem("tf-theme", "dark"); }, THEME);
// Insel: Bornholm (Zeichen ~28 km neben der Feldmitte); Küste: freies Festlandufer mit verschobenem Zeichen.
const busy = await taken(seed.sql);
const spots: [string, Hex | null][] = [["insel", busy.has("70,21") ? null : { col: 70, row: 21 }], ["kueste", shiftedCoast({ col: player.col, row: player.row }, busy, 15)]];
for (const [name, spot] of spots) {
if (!spot) continue;
await seed.sql`delete from mission where player_id = ${player.id}`;
await seed.sql`update base set col = ${spot.col}, row = ${spot.row} where id = ${player.baseId}`;
const target = targetNear(spot, await taken(seed.sql));
if (!target) continue;
await insertMission(seed.sql, player, spot, target, -25 * 60_000);
await page.goto("/?tab=karte");
await page.waitForFunction(() => typeof (window as unknown as { __tfMapView?: unknown }).__tfMapView === "function");
const c = hexCenter(spot.col, spot.row);
for (const scale of [1.2, 2.4]) {
await page.evaluate(([lo, la, s]) => (window as unknown as { __tfMapView: (a: number, b: number, c: number) => unknown }).__tfMapView(lo, la, s), [c.lon, c.lat, scale] as const);
await page.waitForTimeout(900);
await page.screenshot({ path: `/tmp/tf-routen/${PREFIX}-${THEME === "dark" ? "dunkel" : "hell"}-${name}-${scale}.png` });
}
}
await seed.sql`delete from mission where player_id = ${player.id}`;
});
});
+104
View File
@@ -0,0 +1,104 @@
// Karte 2: Zeichenposition eines Felds („Anker“) und Linien/bewegte Symbole, die dort anschließen. Seit Karte 2 stehen
// Hafen- und Nestzeichen auf Küstenfeldern am Ufer (markerXY) und Handelshäfen an ihrer echten Lage – Routen und
// Verbände rechnen aber (wie der Server) mit den Feldmitten. Diese Hilfen setzen nur die Darstellung um: Anfangs- und
// Endpunkt einer Linie, die auf einer Feldmitte beginnt oder endet, rücken auf das Zeichen; ein Symbol auf dem ersten
// bzw. letzten Abschnitt wandert mit (gleicher Anteil des Abschnitts). Entfernungen und Fahrzeiten bleiben unverändert.
// Ohne Pixi (Unit-Tests: packages/game-core/test/karte-anker.test.ts).
import { HEX_SIZE_KM, hexAtXY, hexCenterXY, inGrid, terrainAt, tradePortHexes } from "@tidefront/world";
import { nearestShore, xyOf, type XY } from "./coastline.ts";
type Hex = { col: number; row: number };
/**
* Lage eines Zeichens auf einem Feld: Küstenfelder (Häfen, Nester) auf dem nächsten Punkt der gezeichneten Küste
* innerhalb des Felds, sonst die Feldmitte. So steht ein Hafen am Ufer statt bis zu 50 km im Binnenland.
*/
export function markerXY(col: number, row: number): XY {
const c = hexCenterXY(col, row);
if (terrainAt(col, row) !== "coast") return c;
const s = nearestShore(c, HEX_SIZE_KM * 0.8);
if (!s) return c;
// ein Stück landeinwärts (2 km), damit das Zeichen nicht halb im Wasser steht
const d = Math.hypot(c.x - s.x, c.y - s.y) || 1;
const k = Math.min(1, 2 / d);
return { x: s.x + (c.x - s.x) * k, y: s.y + (c.y - s.y) * k };
}
const anchors = new Map<string, XY>();
/**
* Zeichenposition eines Felds: Handelshafen an seiner echten Lage (wie das Ankerzeichen in HexMap), sonst markerXY.
* Zwischengespeichert (Küstensuche).
*/
export function anchorXY(col: number, row: number): XY {
const key = `${col},${row}`;
let p = anchors.get(key);
if (p) return p;
// Feld eines Handelshafens: Ankerzeichen an der echten Lage (tradePortHexes: Feld = nächstes Küstenfeld dazu).
const port = tradePortHexes().find((t) => t.col === col && t.row === row);
p = port ? xyOf(port.lon, port.lat) : markerXY(col, row);
anchors.set(key, p);
return p;
}
/** Zeichenposition, wenn p (Projektions-km) auf einer Feldmitte liegt, sonst null (Wendepunkt, freie Position). */
function anchorAt(p: XY): XY | null {
const h = hexAtXY(p.x, p.y);
if (!inGrid(h.col, h.row)) return null;
const c = hexCenterXY(h.col, h.row);
return Math.hypot(c.x - p.x, c.y - p.y) <= 0.5 ? anchorXY(h.col, h.row) : null;
}
/**
* Gezeichneter Linienzug: erster und letzter Punkt rücken von der Feldmitte auf die Zeichenposition (Hafen am Ufer,
* Handelshafen, Nest). Punkte, die nicht auf einer Feldmitte liegen (Wendepunkt der Aufklärung), bleiben; ebenso alle
* Zwischenpunkte – die Fahrt führt so vom Zeichen am Ufer direkt zum ersten Wegpunkt auf See.
*/
export function routePointsOnMap(pts: readonly XY[]): XY[] {
const out = pts.map((p) => ({ x: p.x, y: p.y }));
if (out.length === 0) return out;
const a = anchorAt(out[0]);
if (a) out[0] = { ...a };
if (out.length > 1) {
const b = anchorAt(out[out.length - 1]);
if (b) out[out.length - 1] = { ...b };
}
return out;
}
/** Linienzug über die Mitten der Felder einer Route (Seewege), Enden auf den Zeichen. */
export function routeHexesOnMap(hexes: readonly (readonly [number, number])[]): XY[] {
return routePointsOnMap(hexes.map(([c, r]) => hexCenterXY(c, r)));
}
/** Gerade Linie zwischen zwei Feldern (ohne Route), Enden auf den Zeichen. */
export function lineOnMap(from: Hex, to: Hex): XY[] {
return [anchorXY(from.col, from.row), anchorXY(to.col, to.row)];
}
/** Anteil t (0–1) von p auf dem Abschnitt a→b, wenn p (bis auf Rundung) darauf liegt, sonst null. */
function along(p: XY, a: XY, b: XY): number | null {
const vx = b.x - a.x, vy = b.y - a.y;
const l2 = vx * vx + vy * vy;
if (l2 <= 1e-9) return Math.hypot(p.x - a.x, p.y - a.y) <= 0.5 ? 0 : null;
const t = ((p.x - a.x) * vx + (p.y - a.y) * vy) / l2;
if (t < -1e-6 || t > 1 + 1e-6) return null;
const qx = a.x + vx * t, qy = a.y + vy * t;
return Math.hypot(p.x - qx, p.y - qy) <= 0.5 ? Math.max(0, Math.min(1, t)) : null;
}
/**
* Position eines bewegten Symbols auf der gezeichneten Linie: `p` rechnet (wie der Server) auf dem Linienzug über die
* Feldmitten (`centers`); liegt p auf dem ersten oder letzten Abschnitt, steht das Symbol auf demselben Anteil des
* gezeichneten Abschnitts (`drawn` = routePointsOnMap(centers)). Sonst unverändert (dort sind beide Linien gleich).
*/
export function pointOnMap(p: XY, centers: readonly XY[], drawn: readonly XY[]): XY {
const n = centers.length;
if (n < 2 || drawn.length !== n) return n === 1 && drawn.length === 1 && Math.hypot(p.x - centers[0].x, p.y - centers[0].y) <= 0.5 ? { ...drawn[0] } : p;
const lerp = (a: XY, b: XY, t: number) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });
const t0 = along(p, centers[0], centers[1]);
if (t0 !== null) return lerp(drawn[0], drawn[1], t0);
const t1 = along(p, centers[n - 2], centers[n - 1]);
if (t1 !== null) return lerp(drawn[n - 2], drawn[n - 1], t1);
return p;
}
+5 -4
View File
@@ -2,7 +2,8 @@
// Ring in der Besitzerfarbe (eigene/Allianz/Pakt/Krieg/neutral wie die Häfen, Kartell rot gestrichelt, frei grau).
// Allianz-Einflusszonen: Verbindungslinien und Hof um die Felder. Zeichen in Bildschirmgröße (HexMap skaliert gegen).
import { Container, Graphics } from "pixi.js";
import { hexCenterXY, hexDistanceKm } from "@tidefront/world";
import { hexDistanceKm } from "@tidefront/world";
import { anchorXY } from "./anchor.ts"; // Zeichenposition (Küstenfelder am Ufer)
import { ALLY, INK, PAKT, PAPER, SEE, SIEGEL } from "./symbols.ts";
export interface MapField {
@@ -72,12 +73,12 @@ export function buildFieldLayer(fields: MapField[], linkKm: number): { root: Con
const color = FIELD_COLOR[list[0].relation] ?? SEE;
const bonus = list[0].zone!.bonus;
for (const f of list) {
const p = hexCenterXY(f.col, f.row);
const p = anchorXY(f.col, f.row);
if (bonus) zones.circle(p.x, p.y, 70).fill({ color, alpha: 0.07 });
}
for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) {
if (hexDistanceKm(list[i], list[j]) > linkKm) continue;
const a = hexCenterXY(list[i].col, list[i].row), b = hexCenterXY(list[j].col, list[j].row);
const a = anchorXY(list[i].col, list[i].row), b = anchorXY(list[j].col, list[j].row); // von Zeichen zu Zeichen
const len = Math.hypot(b.x - a.x, b.y - a.y), k = Math.max(1, Math.floor(len / 16));
for (let s = 0; s < k; s++) {
const t0 = s / k, t1 = (s + 0.55) / k;
@@ -87,7 +88,7 @@ export function buildFieldLayer(fields: MapField[], linkKm: number): { root: Con
zones.stroke({ color, width: 1.4, pixelLine: true, alpha: bonus ? 0.9 : 0.5 });
}
for (const f of fields) {
const p = hexCenterXY(f.col, f.row);
const p = anchorXY(f.col, f.row);
const s = fieldSymbol(f);
s.position.set(p.x, p.y);
root.addChild(s);
+5 -4
View File
@@ -10,6 +10,7 @@ import { TEXT_RESOLUTION } from "./density.ts"; // Karte 2: Schrift in Gerätepi
import { COLS, ROWS, HEX_SIZE_KM, hexAtXY, hexCenterXY } from "@tidefront/world";
import { liveLevelAt, type SensorCircle, type SensorKind } from "@tidefront/game-core";
import { hexPoints } from "./terrain.ts";
import { anchorXY } from "./anchor.ts"; // Sensorringe, Verbände und Posten an den Zeichen (Ufer)
import { ALLY, INK, PAPER, RELATION_COLOR, SEE, SIEGEL, type Relation } from "./symbols.ts";
import { sensorRing } from "./sensor-ring.ts";
import { fmtAt } from "../lib/time.ts";
@@ -160,7 +161,7 @@ export function buildIntelLayer(intel: MapIntel, clip: () => Graphics, showSenso
rings.clear();
for (const s of own) {
// Eigene Verbände auf See zeichnet movers.ts mit wanderndem Kreis; hier nur Häfen, Posten und Fremde der Allianz.
const c = hexCenterXY(s.col, s.row);
const c = anchorXY(s.col, s.row); // Hafen am Ufer: Ring um das Hafenzeichen (Nebel rechnet weiter mit der Feldmitte)
const radar = s.kind === "radar" || s.kind === "posten";
const color = radar ? SEE : s.kind === "sonar" ? ALLY : INK;
const faint = s.kind === "sonar" || s.kind === "flug" ? 0.7 : 1;
@@ -203,7 +204,7 @@ export function buildFleetLayer(fleets: MapFleetIn[]): { root: Container; pinned
const root = new Container();
const pinned: { obj: Container; min?: number }[] = [];
for (const f of fleets) {
const p = hexCenterXY(f.col, f.row);
const p = anchorXY(f.col, f.row); // im Hafen: am Hafenzeichen
const s = fleetArrow(f);
s.position.set(p.x, p.y);
root.addChild(s);
@@ -238,7 +239,7 @@ export function buildPostLayer(posts: MapPostIn[]): { root: Container; pinned: {
const root = new Container();
const pinned: { obj: Container; min?: number }[] = [];
for (const p of posts) {
const xy = hexCenterXY(p.col, p.row);
const xy = anchorXY(p.col, p.row);
const s = postSymbol(p);
s.position.set(xy.x, xy.y);
root.addChild(s);
@@ -255,7 +256,7 @@ export function buildMarkLayer(marks: { col: number; row: number }[], loop: bool
const root = new Container();
const g = new Graphics();
root.addChild(g);
const pts = marks.map((m) => hexCenterXY(m.col, m.row));
const pts = marks.map((m) => anchorXY(m.col, m.row)); // Ziele (Häfen, Nester) am Zeichen
if (pts.length > 1) {
g.moveTo(pts[0].x, pts[0].y);
for (const p of pts.slice(1)) g.lineTo(p.x, p.y);
+25 -13
View File
@@ -3,6 +3,7 @@
// Route, Rückruf, Patrouillenrunde, Kampagne). Läuft gedrosselt im Ticker der Hexkarte (HexMap.tsx).
import { Container, Graphics } from "pixi.js";
import { hexCenterXY, routePointsXY, routePrefixXY } from "@tidefront/world";
import { anchorXY, pointOnMap, routeHexesOnMap, routePointsOnMap } from "./anchor.ts"; // Enden auf den Zeichen
import { fleetPosition, patrolPoints, type MissionRoute, type PatrolPlan, type RoutedPlan, type SightTurn } from "@tidefront/game-core";
import { serverNow } from "../lib/time.ts";
import { HALO, INK, SIEGEL, alertRing, planeSymbol, shipSymbol } from "./symbols.ts";
@@ -73,8 +74,9 @@ function planOf(m: MapMission): RoutedPlan {
}
/**
* Gezeichneter Weg: Route (Seewege) oder gerade Linie; Kampagne nach dem ersten Ziel ab dem letzten Ziel bzw.
* Wendepunkt. Aufklärung auf Sicht: nur bis zum Wendepunkt (Route: Teilstück).
* Weg über die Feldmitten (wie der Server rechnet): Route (Seewege) oder gerade Linie; Kampagne nach dem ersten Ziel ab dem letzten Ziel bzw.
* Wendepunkt. Aufklärung auf Sicht: nur bis zum Wendepunkt (Route: Teilstück). Gezeichnet wird er mit den Enden auf
* den Zeichen (anchor.ts routePointsOnMap), das Schiff auf derselben Linie (pointOnMap).
*/
function pathOf(m: MapMission, plan: RoutedPlan, home: XY, tgt: XY): XY[] {
const c = m.campaign;
@@ -106,17 +108,23 @@ function polyline(g: Graphics, pts: XY[]): void {
for (const p of pts.slice(1)) g.lineTo(p.x, p.y);
}
/** Prüfhilfe: Missions-ID mit erstem und letztem gezeichneten Punkt („7:x,y;x,y“, km auf zwei Stellen). */
const endsOf = (id: number, path: XY[]) => `${id}:${[path[0], path[path.length - 1]].map((p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(";")}`;
/**
* Routen, Schiffe und Warnring; läuft gedrosselt im Ticker. Liefert die eigenen bewegten Sichtkreise (Nebel) und die
* Zahl der gezeichneten Wegpunkte laufender Fahrten (Prüfhilfe der Oberflächentests, data-mission-route).
* Routen, Schiffe und Warnring; läuft gedrosselt im Ticker. Liefert die eigenen bewegten Sichtkreise (Nebel), die
* Zahl der gezeichneten Wegpunkte laufender Fahrten und deren Enden (Prüfhilfen der Oberflächentests,
* data-mission-route und data-mission-ends).
*/
export function drawMovers(s: Scene, live: { home?: { col: number; row: number } | null; missions?: MapMission[]; alert?: boolean; focus?: number | null }): { sights: MovingSight[]; routePoints: number } {
export function drawMovers(s: Scene, live: { home?: { col: number; row: number } | null; missions?: MapMission[]; alert?: boolean; focus?: number | null }): { sights: MovingSight[]; routePoints: number; ends: string } {
const sc = s.world.scale.x;
s.routes.clear();
const seen = new Set<number>();
const sights: MovingSight[] = [];
let routePoints = 0;
const ends: string[] = [];
const home = live.home ? hexCenterXY(live.home.col, live.home.row) : null;
const homeAt = live.home ? anchorXY(live.home.col, live.home.row) : null; // Hafenzeichen (Ufer)
if (home) {
const now = serverNow();
for (const m of live.missions ?? []) {
@@ -138,26 +146,30 @@ export function drawMovers(s: Scene, live: { home?: { col: number; row: number }
}
if (m.status !== "outbound" && m.status !== "returning") continue;
const tgt = hexCenterXY(m.target.col, m.target.row);
const tgtAt = anchorXY(m.target.col, m.target.row);
const outbound = m.status === "outbound";
const row = { status: m.status, arriveAt: new Date(m.arriveAtMs), returnAt: outbound ? null : new Date(m.returnAtMs), plan };
// Vor der Abfahrt (Sammelangriff) liegt der Verband im Hafen.
const fp = fleetPosition(row, home, tgt, now) ?? { at: outbound ? home : tgt, from: home, to: tgt };
const pos = fp.at;
// Gezeichnet: Enden auf Hafen- bzw. Zielzeichen; das Schiff auf demselben Anteil des Abschnitts.
const centers = pathOf(m, plan, home, tgt);
const path = routePointsOnMap(centers);
const pos = pointOnMap(fp.at, centers, path);
if (m.sightKm) { sensorRing(s.routes, pos.x, pos.y, m.sightKm, sc, SIGHT); sights.push({ ...pos, km: m.sightKm }); } // Bordsicht
const color = outbound ? SIEGEL : INK;
const path = pathOf(m, plan, home, tgt);
routePoints += path.length;
ends.push(endsOf(m.id, path));
polyline(s.routes, path);
s.routes.stroke({ color: HALO, width: 5 / sc, alpha: 0.8, cap: "round", join: "round" });
for (let i = 1; i < path.length; i++) dashed(s.routes, path[i - 1], path[i], 6 / sc);
s.routes.stroke({ color, width: 1.8 / sc, alpha: 0.95 });
s.routes.moveTo(tgt.x - 8 / sc, tgt.y).lineTo(tgt.x + 8 / sc, tgt.y).moveTo(tgt.x, tgt.y - 8 / sc).lineTo(tgt.x, tgt.y + 8 / sc);
s.routes.moveTo(tgtAt.x - 8 / sc, tgtAt.y).lineTo(tgtAt.x + 8 / sc, tgtAt.y).moveTo(tgtAt.x, tgtAt.y - 8 / sc).lineTo(tgtAt.x, tgtAt.y + 8 / sc);
s.routes.stroke({ color, width: 1.2 / sc });
if (m.sightTurn) {
// Aufklärung auf Sicht: Wendepunkt (Ring) und Sichtlinie zum Ziel (fein gepunktet).
const t = m.sightTurn;
s.routes.circle(t.x, t.y, 5 / sc).stroke({ color, width: 1.6 / sc, alpha: 0.95 });
dashed(s.routes, t, tgt, 2 / sc);
dashed(s.routes, t, tgtAt, 2 / sc);
s.routes.stroke({ color, width: 0.9 / sc, alpha: 0.6 });
}
const key = m.id * 2 + (outbound ? 0 : 1);
@@ -185,19 +197,19 @@ export function drawMovers(s: Scene, live: { home?: { col: number; row: number }
s.ships.delete(id);
}
}
if (live.alert && home) {
if (live.alert && homeAt) {
if (!s.alert) {
s.alert = alertRing();
s.world.addChild(s.alert);
}
s.alert.position.set(home.x, home.y);
s.alert.position.set(homeAt.x, homeAt.y);
const pulse = 1 + 0.15 * Math.sin(performance.now() / 180);
s.alert.scale.set(pinScale(sc) * pulse);
} else if (s.alert) {
s.alert.destroy();
s.alert = null;
}
return { sights, routePoints };
return { sights, routePoints, ends: ends.join(" ") };
}
/**
@@ -208,7 +220,7 @@ export function buildRouteLayer(hexes: readonly (readonly [number, number])[], c
const root = new Container();
const g = new Graphics();
root.addChild(g);
const pts = routePointsXY({ hexes });
const pts = routeHexesOnMap(hexes); // Enden auf Hafen- und Zielzeichen
if (pts.length >= 2) {
polyline(g, pts);
g.stroke({ color: HALO, width: 9, alpha: 0.8, cap: "round", join: "round" });
+14 -8
View File
@@ -6,10 +6,13 @@
import { Container, Graphics, Text } from "pixi.js";
import { TEXT_RESOLUTION } from "./density.ts"; // Karte 2: Schrift in Gerätepixeldichte
import { hexCenterXY, routePointsXY } from "@tidefront/world";
import { anchorXY, pointOnMap, routePointsOnMap } from "./anchor.ts"; // Linien und Symbole an den Hafenzeichen
import { convoyXY, type MapConvoy } from "../lib/convoy.ts";
import { fmtDuration, serverNow } from "../lib/time.ts";
import { ALLY, INK, PAPER, SIEGEL, SEE } from "./symbols.ts";
type XY = { x: number; y: number };
export interface MapNaval {
minefields: { id: number; col: number; row: number; strength: number; own: boolean; allied: boolean }[];
blockades: { id: number; col: number; row: number; endsAtMs: number; role: string }[];
@@ -99,28 +102,31 @@ export function buildNavalLayer(n: MapNaval, now: number): { root: Container; pi
};
const radius = n.rules?.mines?.fieldRadiusKm ?? 35;
for (const f of n.minefields) {
const p = hexCenterXY(f.col, f.row);
const p = anchorXY(f.col, f.row); // vor einem Hafen: am Hafenzeichen
const color = f.own ? INK : f.allied ? ALLY : SIEGEL;
for (let i = 0; i < 20; i++) lines.arc(p.x, p.y, radius, (i * Math.PI) / 10, (i * Math.PI) / 10 + 0.18).moveTo(p.x, p.y);
lines.stroke({ color, width: 1, pixelLine: true, alpha: 0.85 });
pin(mineSymbol(f.own || f.allied ? PAPER : SIEGEL), p.x, p.y, 0.08);
}
for (const b of n.blockades) {
const p = hexCenterXY(b.col, b.row);
const p = anchorXY(b.col, b.row); // Kettenring um das Hafenzeichen
const color = b.role === "own" ? INK : SIEGEL;
pin(blockadeRing(color), p.x, p.y);
pin(tag(`Blockade · ${hours(b.endsAtMs - now)}`, color, 30), p.x, p.y, 0.12);
}
const ships: { c: MapConvoy; obj: Container }[] = [];
const ships: { c: MapConvoy; obj: Container; centers: XY[]; drawn: XY[] }[] = [];
for (const c of n.convoys) {
const color = c.enemy ? SIEGEL : c.own ? SEE : INK;
if (c.route && c.route.length >= 2) dashedLine(lines, routePointsXY({ hexes: c.route }), 7);
else if (c.from && c.to) dashedLine(lines, [hexCenterXY(c.from.col, c.from.row), hexCenterXY(c.to.col, c.to.row)], 7);
// Linie über die Feldmitten (wie der Server), gezeichnet mit den Enden auf Handelshafen bzw. Hafenzeichen.
const centers = c.route && c.route.length >= 2 ? routePointsXY({ hexes: c.route })
: c.from && c.to ? [hexCenterXY(c.from.col, c.from.row), hexCenterXY(c.to.col, c.to.row)] : [];
const drawn = routePointsOnMap(centers);
if (drawn.length >= 2) dashedLine(lines, drawn, 7);
lines.stroke({ color, width: 1, pixelLine: true, alpha: 0.8 });
const at = convoyXY(c, now);
const at = pointOnMap(convoyXY(c, now), centers, drawn);
const ship = convoySymbol(c.escorted ? INK : c.own || c.enemy ? color : PAPER);
pin(ship, at.x, at.y, 0.08);
ships.push({ c, obj: ship });
ships.push({ c, obj: ship, centers, drawn });
if (!c.own && !c.enemy) pin(tag(`Konvoi · ${c.size === "gross" ? "groß" : c.size}`, INK, 10), at.x, at.y, 0.12);
}
// Fahrt entlang der Route: alle 2 s neu setzen (gleiche Rechnung wie der Server); endet mit der Ebene.
@@ -128,7 +134,7 @@ export function buildNavalLayer(n: MapNaval, now: number): { root: Container; pi
if (moving.length > 0) {
const timer = setInterval(() => {
const t = serverNow();
for (const s of moving) { const p = convoyXY(s.c, t); s.obj.position.set(p.x, p.y); }
for (const s of moving) { const p = pointOnMap(convoyXY(s.c, t), s.centers, s.drawn); s.obj.position.set(p.x, p.y); }
}, 2000);
root.once("destroyed", () => clearInterval(timer));
}
+5 -3
View File
@@ -3,6 +3,7 @@
import type { Graphics } from "pixi.js";
import { HEX_SIZE_KM, hexCenter, hexCenterXY } from "@tidefront/world";
import { hexPoints, xyOf } from "./terrain.ts";
import { anchorXY } from "./anchor.ts"; // Zeichenposition (Hafen am Ufer)
import { BRASS as MESSING, INK, SIEGEL } from "./symbols.ts";
export interface HarborOverlay {
@@ -34,7 +35,7 @@ function rangeRing(lat: number, lon: number, km: number, steps = 96): number[] {
function drawHarbors(g: Graphics, sc: number, o: HarborOverlay): void {
if (!o.active) return;
const { x, y } = hexCenterXY(o.active.col, o.active.row);
const { x, y } = anchorXY(o.active.col, o.active.row); // Doppelring um das Hafenzeichen
if (o.rangeKm) {
const c = hexCenter(o.active.col, o.active.row);
const pts = rangeRing(c.lat, c.lon, o.rangeKm);
@@ -57,11 +58,12 @@ export function drawSelection(g: Graphics, sc: number, selected: { col: number;
g.clear();
if (harbors) drawHarbors(g, sc, harbors);
if (!selected) return;
const { x, y } = hexCenterXY(selected.col, selected.row);
const c = hexCenterXY(selected.col, selected.row); // Feldumriss in der Feldmitte
const { x, y } = anchorXY(selected.col, selected.row); // Zielwinkel und Punkt am Zeichen (Hafen am Ufer)
// Zielmarke: Eckwinkel um das Feld, mindestens 22 px Halbmesser am Bildschirm
const h = Math.max(HEX_SIZE_KM * 1.05, 22 / sc);
const l = h * 0.42;
g.poly(hexPoints(x, y, HEX_SIZE_KM)).fill({ color: SIEGEL, alpha: 0.06 }).stroke({ color: SIEGEL, width: 1 / sc, alpha: 0.6 });
g.poly(hexPoints(c.x, c.y, HEX_SIZE_KM)).fill({ color: SIEGEL, alpha: 0.06 }).stroke({ color: SIEGEL, width: 1 / sc, alpha: 0.6 });
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
g.moveTo(x + sx * h, y + sy * (h - l)).lineTo(x + sx * h, y + sy * h).lineTo(x + sx * (h - l), y + sy * h);
}
+4 -17
View File
@@ -4,12 +4,14 @@
// Vektor-Landfläche maskiert – scharfe Küste bei jedem Zoom und jeder Pixeldichte.
import { CanvasSource, Container, Graphics, Matrix, Rectangle, Sprite, Texture, type FillInput } from "pixi.js";
import { MAP_BOUNDS } from "./gestures.ts";
import { COLS, HEX_SIZE_KM, ROWS, hexCenterXY, terrainAt } from "@tidefront/world";
import { coastGeometry, nearestShore, xyOf, type XY } from "./coastline.ts";
import { COLS, HEX_SIZE_KM, ROWS, hexCenterXY } from "@tidefront/world";
import { coastGeometry, xyOf } from "./coastline.ts";
import { ScreenLines, clipPaths, clipPolygon } from "./linework.ts";
import { COLORS, H, KM_PX, W, X0, Y0, terrainRaster } from "./terrain-raster.ts";
export { xyOf };
/** Zeichenposition auf Küstenfeldern (map/anchor.ts, ohne Pixi). */
export { markerXY } from "./anchor.ts";
export function hexPoints(cx: number, cy: number, size: number): number[] {
const pts: number[] = [];
@@ -20,21 +22,6 @@ export function hexPoints(cx: number, cy: number, size: number): number[] {
return pts;
}
/**
* Lage eines Zeichens auf einem Feld: Küstenfelder (Häfen, Nester) auf dem nächsten Punkt der gezeichneten Küste
* innerhalb des Felds, sonst die Feldmitte. So steht ein Hafen am Ufer statt bis zu 50 km im Binnenland.
*/
export function markerXY(col: number, row: number): XY {
const c = hexCenterXY(col, row);
if (terrainAt(col, row) !== "coast") return c;
const s = nearestShore(c, HEX_SIZE_KM * 0.8);
if (!s) return c;
// ein Stück landeinwärts (2 km), damit das Zeichen nicht halb im Wasser steht
const d = Math.hypot(c.x - s.x, c.y - s.y) || 1;
const k = Math.min(1, 2 / d);
return { x: s.x + (c.x - s.x) * k, y: s.y + (c.y - s.y) * k };
}
export interface TerrainLayers {
root: Container;
/** Zartes Hexraster; Deckkraft je Zoom setzt der Aufrufer. */
+10 -3
View File
@@ -6,10 +6,17 @@ import { xyOf } from "./terrain.ts";
type ViewFn = (lon: number, lat: number, scale: number) => { scale: number; resolution: number };
export function installViewHook(app: Application, world: Container): () => void {
/** Prüfhilfe (E2E): Lage der Kartenzeichen und der Verbandssymbole in Weltkoordinaten (km). */
export interface MapProbe {
markers: () => { x: number; y: number; col: number; row: number }[];
ships: () => { key: number; x: number; y: number }[];
}
export function installViewHook(app: Application, world: Container, probe?: MapProbe): () => void {
if (!import.meta.env.DEV) return () => {};
const w = window as unknown as { __tfMapView?: ViewFn; __tfMapApp?: Application };
const w = window as unknown as { __tfMapView?: ViewFn; __tfMapApp?: Application; __tfMapProbe?: MapProbe };
w.__tfMapApp = app; // Leistungsmessung (E2E)
if (probe) w.__tfMapProbe = probe; // Linien und Symbole an den Zeichen (E2E 34-routen-anker)
w.__tfMapView = (lon, lat, scale) => {
const { width, height } = app.screen;
const p = xyOf(lon, lat);
@@ -19,5 +26,5 @@ export function installViewHook(app: Application, world: Container): () => void
clampView(world, width, height);
return { scale: world.scale.x, resolution: app.renderer.resolution };
};
return () => { delete w.__tfMapView; delete w.__tfMapApp; };
return () => { delete w.__tfMapView; delete w.__tfMapApp; delete w.__tfMapProbe; };
}
+9 -7
View File
@@ -5,6 +5,7 @@
import { Container, Graphics, Text } from "pixi.js";
import { TEXT_RESOLUTION } from "./density.ts"; // Karte 2: Schrift in Gerätepixeldichte
import { hexCenterXY } from "@tidefront/world";
import { anchorXY, pointOnMap, routePointsOnMap } from "./anchor.ts"; // Linien und Zeichen an den Hafen-/Nestzeichen
import { routePosition } from "@tidefront/game-core";
import { BRASS, INK, MUTED, PAPER, SIEGEL } from "./symbols.ts";
import { xyOf } from "./terrain.ts";
@@ -160,20 +161,21 @@ export function buildWorldEventLayer(events: MapWorldEvent[], now: number): { ro
for (const e of events) {
const ended = e.status === "ended";
if (e.kind === "schatzschiff") {
const pts = (e.path ?? []).map((h) => hexCenterXY(h.col, h.row));
const centers = (e.path ?? []).map((h) => hexCenterXY(h.col, h.row));
const pts = routePointsOnMap(centers); // Enden auf Handelshafen/Hafenzeichen
if (!ended && pts.length > 1) {
dashedPath(lines, pts, 9);
lines.stroke({ color: SIEGEL, width: 1, pixelLine: true, alpha: 0.9 });
}
const here = !ended && e.route && e.route.length > 0 ? (() => { const p = routePosition(e.route!, now); return xyOf(p.lon, p.lat); })() : hexCenterXY(e.col, e.row);
const here = !ended && e.route && e.route.length > 0 ? (() => { const p = routePosition(e.route!, now); return pointOnMap(xyOf(p.lon, p.lat), centers, pts); })() : anchorXY(e.col, e.row);
pin(treasureSymbol(ended), here.x, here.y);
pin(label(ended ? (e.outcome === "defeated" ? "aufgebracht" : "entkommen") : `Schatzschiff · ${hours(e.endsAtMs - now)}`, ended ? INK : SIEGEL, 18), here.x, here.y, 0.12);
} else if (e.kind === "grossflotte") {
const at = hexCenterXY(e.col, e.row);
const at = anchorXY(e.col, e.row);
if (!ended && e.region) {
const c = hexCenterXY(e.region.col, e.region.row);
lines.circle(c.x, c.y, e.region.radiusKm).stroke({ color: SIEGEL, width: 1, pixelLine: true, alpha: 0.5 });
const pending = e.targets.filter((t) => t.status === "pending").map((t) => hexCenterXY(t.col, t.row));
const pending = e.targets.filter((t) => t.status === "pending").map((t) => anchorXY(t.col, t.row)); // Häfen: am Hafenzeichen
if (pending.length > 0) {
dashedPath(lines, [at, ...pending], 5);
lines.stroke({ color: SIEGEL, width: 1, pixelLine: true, alpha: 0.75 });
@@ -184,11 +186,11 @@ export function buildWorldEventLayer(events: MapWorldEvent[], now: number): { ro
: e.status === "announced" ? `Großflotte läuft aus in ${hours(e.activeAtMs - now)}` : "Großflotte greift an";
pin(label(text, ended ? INK : SIEGEL, 19), at.x, at.y, 0.1);
} else if (e.kind === "finale") {
const at = hexCenterXY(e.col, e.row);
const at = anchorXY(e.col, e.row);
if (!ended) {
for (const v of e.finale?.vanguards ?? []) {
if (e.status === "active" && (e.finale?.boats ?? 0) <= 0) continue; // Vorhuten aufgelöst
const p = hexCenterXY(v.col, v.row);
const p = anchorXY(v.col, v.row);
dashedPath(lines, [p, at], 7);
lines.stroke({ color: SIEGEL, width: 1, pixelLine: true, alpha: 0.6 });
pin(armadaSymbol(), p.x, p.y);
@@ -201,7 +203,7 @@ export function buildWorldEventLayer(events: MapWorldEvent[], now: number): { ro
: e.status === "announced" ? `Saisonfinale · erscheint in ${hours(e.activeAtMs - now)}` : `Kartell-Armada · ${hours(e.endsAtMs - now)}`;
pin(label(text, ended ? INK : SIEGEL, e.status === "active" && !ended ? 34 : 23), at.x, at.y, 0.08);
} else if (e.kind === "belagerung") {
const at = hexCenterXY(e.col, e.row);
const at = anchorXY(e.col, e.row); // Ring um das Hafenzeichen
if (!ended) {
pin(siegeRing(), at.x, at.y);
pin(label(`Belagerung · ${hours(e.endsAtMs - now)}`, SIEGEL, -44), at.x, at.y, 0.12);
+8 -3
View File
@@ -13,7 +13,8 @@ import type { MapData } from "../lib/trpc.ts";
import { MapToolbar } from "../map/MapControls.tsx";
import { serverNow, useNow } from "../lib/time.ts";
import { registerSnapshotSurface } from "../lib/screenshot.ts";
import { buildTerrain, hexPoints, markerXY, xyOf } from "../map/terrain.ts";
import { buildTerrain, hexPoints, xyOf } from "../map/terrain.ts";
import { anchorXY } from "../map/anchor.ts"; // Zeichenposition (Ufer, Handelshafen); Linien schließen dort an
import { Graticule } from "../map/graticule.ts";
import { installViewHook } from "../map/view-hook.ts";
import { chartFrame, mapClip, tappedHex } from "../map/frame.ts"; // Kartenrahmen, Maske, Tippen auf Zeichen
@@ -266,6 +267,7 @@ export function HexMap(props: HexMapProps) {
intelLayer.current?.moving?.(mv.sights); // Nebel um die aktuellen Positionen der eigenen Verbände
const hostEl = host.current;
if (hostEl && hostEl.dataset.missionRoute !== String(mv.routePoints)) hostEl.dataset.missionRoute = String(mv.routePoints);
if (hostEl && hostEl.dataset.missionEnds !== mv.ends) hostEl.dataset.missionEnds = mv.ends; // Prüfhilfe: Enden der Linien
const wl = weatherLayer.current;
if (wl) wl.update(serverNow(), sc);
}
@@ -293,7 +295,10 @@ export function HexMap(props: HexMapProps) {
const h = tappedHex(s, x, y, radius);
if (inGrid(h.col, h.row)) onSelectRef.current(h);
}));
cleanups.push(installViewHook(app, world)); // nur Entwicklung/E2E: Karte per Skript ausrichten
cleanups.push(installViewHook(app, world, {
markers: () => s.markerHexes.map((m) => ({ ...m })),
ships: () => [...s.ships].map(([key, c]) => ({ key, x: c.x, y: c.y })),
})); // nur Entwicklung/E2E: Karte per Skript ausrichten, Zeichen und Verbände abfragen
setReady(true);
});
return () => {
@@ -344,7 +349,7 @@ export function HexMap(props: HexMapProps) {
s.pinnedMarkers = [];
s.markerHexes = [];
const add = (c: Container, col: number, row: number, pin: Omit<Pinned, "obj"> = {}) => {
const p = markerXY(col, row); // Karte 2: Küstenfelder am Ufer statt in der Feldmitte
const p = anchorXY(col, row); // Karte 2: Küstenfelder am Ufer statt in der Feldmitte
s.markerHexes.push({ x: p.x, y: p.y, col, row });
c.position.set(p.x, p.y);
s.markerLayer.addChild(c);
+25
View File
@@ -0,0 +1,25 @@
# Entscheidungen 9
## Kartenlinien am Hafenzeichen (Routen-Anker)
Befund: Seit Karte 2 (0.52.0) stehen Hafen- und Nestzeichen auf Küstenfeldern am Ufer (`markerXY`), Handelshäfen an
ihrer echten Lage; Missionslinien, Schiffs-/Flugzeugsymbole, Konvois usw. endeten weiter in der Feldmitte – oft im
Wasser neben dem Hafen.
- **Nur Darstellung:** Server, Entfernungen, Fahrzeiten, Nebel und Sichtprüfung rechnen unverändert mit den
Feldmitten. Neues Modul `apps/web/src/map/anchor.ts` (ohne Pixi): `anchorXY` (Zeichenposition: Handelshafen an der
echten Lage, sonst `markerXY`, das von `terrain.ts` dorthin umgezogen ist), `routePointsOnMap` (erster/letzter Punkt,
der auf einer Feldmitte liegt, rückt auf das Zeichen; Zwischenpunkte und Wendepunkte bleiben), `pointOnMap`
(bewegtes Symbol auf dem ersten/letzten Abschnitt steht auf demselben Anteil des gezeichneten Abschnitts – im Hafen
also auf dem Hafenzeichen, unterwegs immer auf der Linie).
- **Angewendet:** Hafen-/Nestzeichen selbst (`HexMap`), eigene Missionen inkl. Kampagne, Aufklärung auf Sicht,
Rückfahrt, Heimweg der Patrouille, Zielkreuz, Warnring (`movers.ts`), Seewege-Vorschau der Planung, Konvois mit
Frachtschiff, Blockade-Ring, Minenfeld (`naval.ts`), Schatzschiff, Großflotte, Vorhuten, Belagerung
(`world-events.ts`), Felder und Zonenlinien (`fields.ts`), Sensorringe der Häfen/Posten, fremde Verbände, Radarposten,
Wegpunkte der Planung (`intel.ts`), Zielwinkel der Auswahl und Ring des aktiven Hafens (`selection.ts`).
- **Bewusst Feldmitte:** Feldumriss der Auswahl (das Feld selbst), Nebelfelder und deren Aussparung (Spiellogik wie der
Server), Reichweitenkreis der Gründung (Regelreichweite), Zielregion der Großflotte, Kartenzentrierung (Oberflächentests
rechnen damit). Tippen: Zeichen werden über `markerHexes` (jetzt `anchorXY`) getroffen, Verbände über die
gezeichnete Symbolposition – beides passt.
- **Prüfhilfen:** `data-mission-ends` am Kartenhost (je Mission erster/letzter gezeichneter Punkt) und in der Entwicklung
`window.__tfMapProbe` (Lage der Zeichen und Verbandssymbole); E2E `34-routen-anker.spec.ts`.
@@ -0,0 +1,79 @@
// Karte 2: Linien und bewegte Symbole schließen an die Zeichenposition an (apps/web/src/map/anchor.ts). Hafen- und
// Nestzeichen stehen auf Küstenfeldern am Ufer, Handelshäfen an ihrer echten Lage; Routen rechnen mit Feldmitten.
import { test } from "node:test";
import assert from "node:assert/strict";
import { COLS, ROWS, hexCenterXY, pointAlongRoute, routePointsXY, seaRoute, terrainAt, tradePortHexes } from "@tidefront/world";
import { anchorXY, lineOnMap, markerXY, pointOnMap, routeHexesOnMap, routePointsOnMap } from "../../../apps/web/src/map/anchor.ts";
import { xyOf } from "../../../apps/web/src/map/coastline.ts";
type Hex = { col: number; row: number };
const dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);
/** Küstenfeld, dessen Zeichen deutlich (> 10 km) neben der Feldmitte steht, und ein Seeziel mit Route dorthin. */
function shiftedCoast(): { home: Hex; target: Hex } {
const ports = new Set(tradePortHexes().map((p) => `${p.col},${p.row}`));
for (let row = 20; row < ROWS - 20; row++) for (let col = 20; col < COLS - 20; col++) {
if (terrainAt(col, row) !== "coast" || ports.has(`${col},${row}`)) continue;
if (dist(markerXY(col, row), hexCenterXY(col, row)) < 10) continue;
for (let dc = -4; dc <= 4; dc++) {
const t = { col: col + dc, row: row + 4 };
if (terrainAt(t.col, t.row) !== "sea") continue;
if (seaRoute({ col, row }, t).hexes.length >= 3) return { home: { col, row }, target: t };
}
}
throw new Error("kein verschobenes Küstenfeld gefunden");
}
test("Zeichenposition: Küstenfeld am Ufer, Seefeld in der Mitte, Handelshafen an der echten Lage", () => {
const { home, target } = shiftedCoast();
assert.deepEqual(anchorXY(home.col, home.row), markerXY(home.col, home.row));
assert.ok(dist(anchorXY(home.col, home.row), hexCenterXY(home.col, home.row)) > 10);
assert.deepEqual(anchorXY(target.col, target.row), hexCenterXY(target.col, target.row));
const port = tradePortHexes()[0];
const real = xyOf(port.lon, port.lat);
assert.ok(dist(anchorXY(port.col, port.row), real) < 1e-9, "Handelshafen: Anker an der echten Lage");
});
test("routePointsOnMap: erster und letzter Punkt auf den Zeichen, Zwischenpunkte unverändert", () => {
const { home, target } = shiftedCoast();
const r = seaRoute(home, target);
const centers = routePointsXY(r);
const drawn = routeHexesOnMap(r.hexes);
assert.equal(drawn.length, centers.length);
assert.deepEqual(drawn[0], anchorXY(home.col, home.row));
assert.deepEqual(drawn[drawn.length - 1], anchorXY(target.col, target.row));
for (let i = 1; i < drawn.length - 1; i++) assert.deepEqual(drawn[i], centers[i]);
// Rückfahrt: umgekehrt ebenso
const back = routePointsOnMap([...centers].reverse());
assert.deepEqual(back[back.length - 1], anchorXY(home.col, home.row));
// Punkt neben jeder Feldmitte (Wendepunkt der Aufklärung auf Sicht) bleibt stehen
const turn = { x: centers[1].x + 7, y: centers[1].y + 3 };
assert.deepEqual(routePointsOnMap([centers[0], turn]).at(-1), turn);
// Gerade Linie zwischen zwei Feldern
assert.deepEqual(lineOnMap(home, target), [anchorXY(home.col, home.row), anchorXY(target.col, target.row)]);
});
test("pointOnMap: Symbol an den Enden auf dem Zeichen, unterwegs auf der gezeichneten Linie", () => {
const { home, target } = shiftedCoast();
const r = seaRoute(home, target);
const centers = routePointsXY(r);
const drawn = routePointsOnMap(centers);
// Im Hafen (Fahrt noch nicht begonnen) und am Ziel
assert.ok(dist(pointOnMap(pointAlongRoute(r, 0), centers, drawn), drawn[0]) < 1e-6);
assert.ok(dist(pointOnMap(pointAlongRoute(r, r.km), centers, drawn), drawn[drawn.length - 1]) < 1e-6);
// Auf dem ersten Abschnitt: gleicher Anteil der gezeichneten Linie (liegt auf ihr)
const seg = dist(centers[0], centers[1]);
const p = pointOnMap({ x: centers[0].x + (centers[1].x - centers[0].x) * 0.4, y: centers[0].y + (centers[1].y - centers[0].y) * 0.4 }, centers, drawn);
const want = { x: drawn[0].x + (drawn[1].x - drawn[0].x) * 0.4, y: drawn[0].y + (drawn[1].y - drawn[0].y) * 0.4 };
assert.ok(seg > 0 && dist(p, want) < 1e-6);
// Zwischenabschnitte (falls vorhanden) unverändert
if (centers.length >= 4) {
const mid = { x: (centers[1].x + centers[2].x) / 2, y: (centers[1].y + centers[2].y) / 2 };
assert.deepEqual(pointOnMap(mid, centers, drawn), mid);
}
// Gerade Linie ohne Route: auf halbem Weg zwischen den Zeichen
const line = [hexCenterXY(home.col, home.row), hexCenterXY(target.col, target.row)];
const half = pointOnMap({ x: (line[0].x + line[1].x) / 2, y: (line[0].y + line[1].y) / 2 }, line, routePointsOnMap(line));
const a = anchorXY(home.col, home.row), b = anchorXY(target.col, target.row);
assert.ok(dist(half, { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }) < 1e-6);
});