Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff432da97e | ||
|
|
37bdf902cc | ||
|
|
b683c4e546 | ||
|
|
82e4c64206 | ||
|
|
db5ad639fb | ||
|
|
7f28666f2e | ||
|
|
5093fba82e | ||
|
|
cde4334946 | ||
|
|
127d8f97f0 | ||
|
|
479c5448f7 |
@@ -1,5 +1,22 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v1.12.0 — 2026-09-28 06:59
|
||||||
|
- **Takeoff & landing phases on the marker.** Every leg now has a 10-minute takeoff phase at the origin and a 10-minute landing phase at the destination, on top of the pure cruise time (`lib/sim/movement.ts`): new `BASE_PHASE_MS`, `phaseFactor(weather)` ∈ [1, 2] (monotone over Clear < Cloudy < Rain < Fog — clear stays at 1×, Fog is exactly 2×), and `legPhases(distanceKm, speedKmh, originIcao, destIcao) → {takeoffMs, cruiseMs, landingMs, totalMs}` as the single composition. Takeoff scales on ORIGIN weather, landing on DESTINATION weather — both deterministic via `weatherFor(icao)`, so no stored state. The engine's arrival gate (`lib/sim/engine.ts`), the client's live position/fuel recompute (`lib/game/state.ts`) and the job expiry floor (`lib/game/seed.ts`) all route through it; `progressAt` is now piecewise — 0 while holding at the origin during takeoff, linear over cruise, 1 while holding at the destination during landing — so markers park at each gate instead of crawling along the whole route. The phases burn no fuel (pure time); the weighted-burn model is untouched.
|
||||||
|
- **Marker phase label.** `lib/mapData.ts` derives a phase label client-side from `departureSimTime + clockMs + legPhases` (all already in the snapshot) and the plane popup shows it next to the status — "flying · taking off" / "flying · cruising" / "flying · landing" (`components/Map.tsx`, new `data-testid="plane-phase"` sibling; `plane-status` keeps the raw status so existing assertions stay exact).
|
||||||
|
- **Tests.** Unit: `lib/sim/movement.test.ts` — pinned cruise duration unchanged, new suites for `phaseFactor` bounds/monotonicity (with `MAX_PHASE_FACTOR` pinned to the factor function like `MAX_WIND_BURN_FACTOR`), origin-vs-dest weather composition on a non-vacuous Rain/Cloudy pair, and piecewise `progressAt` holds; `lib/sim/engine.test.ts` — deleted the local `travelMs` mirror, all ~18 "exactly at arrival" fixture clocks now use the real `arrivalTimeFor(...)` composition (the wear-clamp second leg chains off leg 1's exact phase-inclusive arrival); `lib/game/seed.test.ts` expiry-floor mirrors updated to the phase-inclusive floor. E2E: new `e2e/phases.spec.ts` — dispatches the starter on EDDF→LEMD and, using the same `legPhases` boundaries as the engine, asserts the popup shows "taking off" while the plane holds at the origin gate, "landing" while it holds at the destination gate (scale dropped to 30× so each 600–1200 game-s window is observable), then "available" at Madrid; relocates home and restores the world rate.
|
||||||
|
|
||||||
|
## v1.11.0 — 2026-09-27 22:55
|
||||||
|
- **Do not show jobs for planes that are in air (ISS-159).** The right pane's open-package list now hides a row while no GROUNDED plane sits at the package's origin (`components/RightPane.tsx`): new exported `visibleOpenPackages(state)` replaces the bare `status === 'open'` filter — a job whose only claimant is still en route disappears from the list and reappears on landing. Payload-blocked rows (a grounded plane at the origin with no room) stay visible with their disabled Load button, exactly as before. Display-only: `poolAirports` and the spawner are untouched, so world state — jobs waiting at a flying plane's destination — is unchanged; this only stops rendering rows the player cannot dispatch yet. Known pre-existing gap (NOT fixed here): `loadEligiblePlanes` ignores plane ownership per the v1.4.0 shared-market design, so another player's grounded plane at an origin can make Load enabled for you → 403 on click.
|
||||||
|
- **Tests.** Unit: new `visibleOpenPackages` suite in `components/right-pane.test.ts` — grounded plane at origin → visible; only a flying plane there → hidden; grounded elsewhere + one flying to the origin → hidden; payload-blocked grounded plane at origin → still visible with Load disabled. E2E: new test in `e2e/right-pane.spec.ts` dispatches the only plane toward an airport, creates a job AT that destination (in the pool while airborne, so it reaches `/api/state`), and asserts no row renders until landing — pinning the client-side filter rather than the v0.65.0 server-side pool visibility.
|
||||||
|
|
||||||
|
## v1.10.0 — 2026-09-27 22:31
|
||||||
|
- **Top-bar Log out (ISS-157).** New `Log out` button as the last child of the top bar (`components/Map.tsx`) — flex row puts it top-right, no CSS. Same three steps as the admin panel's in-modal button: best-effort `POST /api/logout` with the session header, clear the stored session id, drop back to the sign-in screen via the existing `onLogout`. The two in-modal Log out buttons are kept (zero e2e churn).
|
||||||
|
- **Admin button only for admins (ISS-158).** The top-bar `Admin` button now renders only when `/api/me` reports `admin: true` — hidden entirely, not disabled. No server change: the endpoint already returns `{username, admin}`; `app/page.tsx` now parses that body on its mount probe and passes `isAdmin` down AppShell → Map. The probe also re-runs after a form sign-in (bumped `probeKey`) so `isAdmin` tracks the user who just signed in, not whoever was probed before — an admin logging out followed by a non-admin signing in no longer sees the Admin button.
|
||||||
|
- **E2E.** New test in `e2e/map.spec.ts`: top-bar Log out → sign-in form visible and app header gone (mirrors the existing admin-panel logout assertion).
|
||||||
|
|
||||||
|
## v1.9.0 — 2026-09-27 20:57
|
||||||
|
- **E2E speedup follow-up (test-only, no game code changed).** `e2e/relocation.spec.ts`'s self-heal helper `flyHomeViaApi` now fast-forwards its cleanup legs at the v1.8.0 `FAST = 10_000` rate instead of a blanket `SCALE = 1000` — every scale-dependent wait in that file is a pure arrival wait (status `'available'` / `locationIcao === HUB`) with no mid-leg observation, so the higher rate is safe and the now-unused `SCALE` constant was dropped. Expected CI wall time for the file drops from ~40 s to ~25 s (~2–3 s off test 1, ~10–11 s each off tests 2 and 3). Test 3's deliberate `setScale(page, 1)` guard is untouched; `map.spec.ts` wheel-zoom (real-time-bound) and `multiplayer.spec.ts`'s N-player clock (measures sim-vs-real elapsed time) stay as-is.
|
||||||
|
|
||||||
## v1.8.0 — 2026-09-27 20:13
|
## v1.8.0 — 2026-09-27 20:13
|
||||||
- **E2E speedup (test-only, no game code changed).** Every Playwright spec that fast-forwards legs now uses the fastest rate its assertions allow instead of a blanket `SCALE = 1000`: pure arrival waits (no mid-leg observation) run at `FAST` — a lagged tick can only land a plane sooner, never skip an observed state. Expected CI wall time for the affected tests drops ~5–6× overall (e.g. the antimeridian test's relocation chains go from ~3 min to ~15 s per direction; two-planes' parallel-flight test loses its ~24 s afterEach heal leg).
|
- **E2E speedup (test-only, no game code changed).** Every Playwright spec that fast-forwards legs now uses the fastest rate its assertions allow instead of a blanket `SCALE = 1000`: pure arrival waits (no mid-leg observation) run at `FAST` — a lagged tick can only land a plane sooner, never skip an observed state. Expected CI wall time for the affected tests drops ~5–6× overall (e.g. the antimeridian test's relocation chains go from ~3 min to ~15 s per direction; two-planes' parallel-flight test loses its ~24 s afterEach heal leg).
|
||||||
- **Per-test rates.** `actions.spec.ts` + `hover.spec.ts` + `two-planes.spec.ts`: new local `FAST = 10_000` for expiry fast-forwards, landing waits and fly-home cleanups. `queue.spec.ts`: same `FAST`, plus `CHAIN = 4_000` for the auto-chain observation (max per-tick advance 2 s × S stays below the LEMD-length leg's ~1e7 sim-ms duration so one lagged tick can't complete it before a poll sees the chained state); its refuel-before-chained-leg test moves to an explicit `2_000` with the fuel lower bound relaxed from `> 1.3×required` to `> required` (at 2_000× the snapshot can land ~0.4×required into leg 2's burn under dind load; a wrong top-up level still lands far below the bound, and the exact level stays pinned by the unchanged cash assertion). `map-interactions.spec.ts`: `FAST = 50_000` for chain hops (≤3400 km each) and arrival waits.
|
- **Per-test rates.** `actions.spec.ts` + `hover.spec.ts` + `two-planes.spec.ts`: new local `FAST = 10_000` for expiry fast-forwards, landing waits and fly-home cleanups. `queue.spec.ts`: same `FAST`, plus `CHAIN = 4_000` for the auto-chain observation (max per-tick advance 2 s × S stays below the LEMD-length leg's ~1e7 sim-ms duration so one lagged tick can't complete it before a poll sees the chained state); its refuel-before-chained-leg test moves to an explicit `2_000` with the fuel lower bound relaxed from `> 1.3×required` to `> required` (at 2_000× the snapshot can land ~0.4×required into leg 2's burn under dind load; a wrong top-up level still lands far below the bound, and the exact level stays pinned by the unchanged cash assertion). `map-interactions.spec.ts`: `FAST = 50_000` for chain hops (≤3400 km each) and arrival waits.
|
||||||
|
|||||||
+14
-6
@@ -19,6 +19,11 @@ export default function Home() {
|
|||||||
// the sign-in screen or the game shell. The shell only mounts once authenticated, so its state
|
// the sign-in screen or the game shell. The shell only mounts once authenticated, so its state
|
||||||
// feed never polls an unauthenticated /api/state.
|
// feed never polls an unauthenticated /api/state.
|
||||||
const [authed, setAuthed] = useState<boolean | null>(null);
|
const [authed, setAuthed] = useState<boolean | null>(null);
|
||||||
|
// v1.10.0 (ISS-158): /api/me's `admin` flag — gates the top-bar Admin button in Map.
|
||||||
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
|
// Bumped after a form sign-in so the probe below re-runs for the NEW session — isAdmin must
|
||||||
|
// track whoever just signed in, not the user probed on mount (or before the last logout).
|
||||||
|
const [probeKey, setProbeKey] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sid = storedSession();
|
const sid = storedSession();
|
||||||
@@ -28,9 +33,10 @@ export default function Home() {
|
|||||||
}
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
fetch('/api/me', { headers: sessionHeaders(sid), cache: 'no-store' })
|
fetch('/api/me', { headers: sessionHeaders(sid), cache: 'no-store' })
|
||||||
.then((res) => {
|
.then(async (res) => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (!res.ok) clearStoredSession(); // stale/expired id — drop it and show sign-in
|
if (!res.ok) clearStoredSession(); // stale/expired id — drop it and show sign-in
|
||||||
|
else setIsAdmin(Boolean(((await res.json()) as { admin?: boolean }).admin)); // v1.10.0 (ISS-158)
|
||||||
setAuthed(res.ok);
|
setAuthed(res.ok);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
@@ -39,7 +45,7 @@ export default function Home() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, []);
|
}, [probeKey]);
|
||||||
|
|
||||||
if (authed === null) {
|
if (authed === null) {
|
||||||
return (
|
return (
|
||||||
@@ -51,14 +57,16 @@ export default function Home() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (!authed) {
|
if (!authed) {
|
||||||
return <SignInScreen onAuthed={() => setAuthed(true)} />;
|
// v1.10.0 (ISS-158): re-probe /api/me for the new session instead of blindly flipping authed —
|
||||||
|
// isAdmin has to come from the user who just signed in.
|
||||||
|
return <SignInScreen onAuthed={() => setProbeKey((k) => k + 1)} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The admin panel's Log out cleared the session — drop back to sign-in (ISS-107).
|
// The admin panel's Log out cleared the session — drop back to sign-in (ISS-107).
|
||||||
return <AppShell onLogout={() => setAuthed(false)} />;
|
return <AppShell onLogout={() => setAuthed(false)} isAdmin={isAdmin} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function AppShell({ onLogout }: { onLogout: () => void }) {
|
function AppShell({ onLogout, isAdmin }: { onLogout: () => void; isAdmin: boolean }) {
|
||||||
// Single polling source for the whole shell (v0.9.0): one /api/state loop, snapshot passed
|
// Single polling source for the whole shell (v0.9.0): one /api/state loop, snapshot passed
|
||||||
// down as props so later panes can share it without extra poll loops. applySnapshot (v0.10.0)
|
// down as props so later panes can share it without extra poll loops. applySnapshot (v0.10.0)
|
||||||
// lets a pane push an action endpoint's full response snapshot in immediately.
|
// lets a pane push an action endpoint's full response snapshot in immediately.
|
||||||
@@ -95,7 +103,7 @@ function AppShell({ onLogout }: { onLogout: () => void }) {
|
|||||||
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines;
|
||||||
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
ISS-010 (v0.18.0) — applySnapshot lets the airport popup's Relocate row push its
|
||||||
action response into the shared state, exactly like RightPane does */}
|
action response into the shared state, exactly like RightPane does */}
|
||||||
<Map state={state} hovered={hovered} applySnapshot={applySnapshot} onLogout={onLogout} />
|
<Map state={state} hovered={hovered} applySnapshot={applySnapshot} onLogout={onLogout} isAdmin={isAdmin} />
|
||||||
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} onError={onError} />
|
||||||
<ToastStack toasts={toasts} onDismiss={dismiss} />
|
<ToastStack toasts={toasts} onDismiss={dismiss} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+24
-4
@@ -14,7 +14,7 @@ import { approxLocalTime } from '../lib/localTime';
|
|||||||
import Modal from './Modal';
|
import Modal from './Modal';
|
||||||
import AdminPanel from './AdminPanel';
|
import AdminPanel from './AdminPanel';
|
||||||
import Leaderboard from './Leaderboard';
|
import Leaderboard from './Leaderboard';
|
||||||
import { sessionHeaders } from '../lib/authClient';
|
import { clearStoredSession, sessionHeaders } from '../lib/authClient';
|
||||||
|
|
||||||
// v0.70.0 default view: null island [0,0] at zoom 2 — the world is 2048 px wide there and the
|
// v0.70.0 default view: null island [0,0] at zoom 2 — the world is 2048 px wide there and the
|
||||||
// Africa+Europe bounding box (lat −35..+71, lon −18..+52) spans ~800 px vertically in Web Mercator,
|
// Africa+Europe bounding box (lat −35..+71, lon −18..+52) spans ~800 px vertically in Web Mercator,
|
||||||
@@ -74,11 +74,13 @@ interface MapProps {
|
|||||||
// v1.1.0 (ISS-107): the admin panel's Log out cleared the session — tell the shell to drop back
|
// v1.1.0 (ISS-107): the admin panel's Log out cleared the session — tell the shell to drop back
|
||||||
// to the sign-in screen instead of leaving a signed-out user staring at a live dashboard.
|
// to the sign-in screen instead of leaving a signed-out user staring at a live dashboard.
|
||||||
onLogout?: () => void;
|
onLogout?: () => void;
|
||||||
|
// v1.10.0 (ISS-158): /api/me says this session is an admin → show the top-bar Admin button.
|
||||||
|
isAdmin?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
// Named FlightMap (not Map): a component called `Map` would shadow the global
|
||||||
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
// Map constructor inside its own body, breaking `new Map(...)` for the airport index.
|
||||||
export default function FlightMap({ state, hovered, applySnapshot, onLogout }: MapProps) {
|
export default function FlightMap({ state, hovered, applySnapshot, onLogout, isAdmin = false }: MapProps) {
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||||
// /api/airports is fetched at most once per page life: every styledata event
|
// /api/airports is fetched at most once per page life: every styledata event
|
||||||
@@ -324,12 +326,15 @@ export default function FlightMap({ state, hovered, applySnapshot, onLogout }: M
|
|||||||
if (!f) return;
|
if (!f) return;
|
||||||
const p = f.properties as PlaneFeatureProps;
|
const p = f.properties as PlaneFeatureProps;
|
||||||
const routeLine = p.routeText ? `<br/><span data-testid="plane-route">${escapeHtml(p.routeText)}</span>` : '';
|
const routeLine = p.routeText ? `<br/><span data-testid="plane-route">${escapeHtml(p.routeText)}</span>` : '';
|
||||||
|
// v1.12.0: phase label next to the status — "flying · taking off" etc. plane-status keeps
|
||||||
|
// the raw status so existing assertions on it stay exact.
|
||||||
|
const phaseLine = p.phaseLabel ? `<span data-testid="plane-phase"> · ${p.phaseLabel}</span>` : '';
|
||||||
new maplibregl.Popup({ offset: 12 })
|
new maplibregl.Popup({ offset: 12 })
|
||||||
.setLngLat(f.geometry.coordinates as [number, number])
|
.setLngLat(f.geometry.coordinates as [number, number])
|
||||||
.setHTML(
|
.setHTML(
|
||||||
`<div data-testid="plane-popup">` +
|
`<div data-testid="plane-popup">` +
|
||||||
`<strong>${escapeHtml(p.modelLabel)}</strong><br/>` +
|
`<strong>${escapeHtml(p.modelLabel)}</strong><br/>` +
|
||||||
`<span data-testid="plane-status">${p.status}</span><br/>` +
|
`<span data-testid="plane-status">${p.status}</span>${phaseLine}<br/>` +
|
||||||
`fuel <span data-testid="plane-fuel">${p.fuelText}</span>` +
|
`fuel <span data-testid="plane-fuel">${p.fuelText}</span>` +
|
||||||
routeLine +
|
routeLine +
|
||||||
`</div>`,
|
`</div>`,
|
||||||
@@ -569,6 +574,14 @@ export default function FlightMap({ state, hovered, applySnapshot, onLogout }: M
|
|||||||
void localAssetsAvailable().then((available) => mapRef.current?.setStyle(styleUrlFor(id, available)));
|
void localAssetsAvailable().then((available) => mapRef.current?.setStyle(styleUrlFor(id, available)));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// v1.10.0 (ISS-157): top-bar Log out — same three steps as the admin panel's button: best-effort
|
||||||
|
// server-side session kill, drop the stored id, tell the shell to show sign-in again.
|
||||||
|
const onTopBarLogout = async () => {
|
||||||
|
await fetch('/api/logout', { method: 'POST', headers: sessionHeaders() }).catch(() => undefined);
|
||||||
|
clearStoredSession();
|
||||||
|
onLogout?.();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="map-wrap">
|
<div className="map-wrap">
|
||||||
<header data-testid="app-header" className="app-header">
|
<header data-testid="app-header" className="app-header">
|
||||||
@@ -596,10 +609,17 @@ export default function FlightMap({ state, hovered, applySnapshot, onLogout }: M
|
|||||||
<button type="button" data-testid="leaderboard-btn" className="pane-btn" onClick={() => setLeaderboardOpen(true)}>
|
<button type="button" data-testid="leaderboard-btn" className="pane-btn" onClick={() => setLeaderboardOpen(true)}>
|
||||||
Leaderboard
|
Leaderboard
|
||||||
</button>
|
</button>
|
||||||
{/* v0.71.0: admin panel entry point — right side of the top bar, opens a modal (no URL). */}
|
{/* v0.71.0: admin panel entry point — right side of the top bar, opens a modal (no URL).
|
||||||
|
v1.10.0 (ISS-158): only for admins (/api/me `admin` flag) — hidden entirely otherwise. */}
|
||||||
|
{isAdmin && (
|
||||||
<button type="button" data-testid="admin-btn" className="pane-btn" onClick={() => setAdminOpen(true)}>
|
<button type="button" data-testid="admin-btn" className="pane-btn" onClick={() => setAdminOpen(true)}>
|
||||||
Admin
|
Admin
|
||||||
</button>
|
</button>
|
||||||
|
)}
|
||||||
|
{/* v1.10.0 (ISS-157): Log out — last child, so the flex row puts it top-right of the bar. */}
|
||||||
|
<button type="button" data-testid="logout-btn" className="pane-btn" onClick={() => void onTopBarLogout()}>
|
||||||
|
Log out
|
||||||
|
</button>
|
||||||
</header>
|
</header>
|
||||||
<div ref={containerRef} data-testid="map" className="map-container" />
|
<div ref={containerRef} data-testid="map" className="map-container" />
|
||||||
<Modal open={adminOpen} onClose={() => setAdminOpen(false)} title="Admin">
|
<Modal open={adminOpen} onClose={() => setAdminOpen(false)} title="Admin">
|
||||||
|
|||||||
@@ -46,6 +46,15 @@ export function loadEligiblePlanes(state: StateSnapshot, pkg: PackageState): Pla
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v1.11.0 (ISS-159): the open packages the market list shows — hidden while no GROUNDED plane sits at
|
||||||
|
// their origin ("jobs for planes that are in air" disappear until landing). Payload-blocked rows stay:
|
||||||
|
// a grounded plane at the origin keeps the row visible with its disabled Load button.
|
||||||
|
export function visibleOpenPackages(state: StateSnapshot): PackageState[] {
|
||||||
|
return state.packages.filter(
|
||||||
|
(p) => p.status === 'open' && state.planes.some((pl) => pl.status === 'available' && pl.locationIcao === p.originIcao),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Load controls for one open package: a single Load button when exactly one plane
|
// Load controls for one open package: a single Load button when exactly one plane
|
||||||
// is eligible (it acts on that plane directly), a small plane picker + Load when
|
// is eligible (it acts on that plane directly), a small plane picker + Load when
|
||||||
// several are, and a disabled button with the reason otherwise. Each row owns its
|
// several are, and a disabled button with the reason otherwise. Each row owns its
|
||||||
@@ -141,7 +150,7 @@ export default function RightPane({ state, loading, applySnapshot, onHover, onEr
|
|||||||
if (!state) return null;
|
if (!state) return null;
|
||||||
|
|
||||||
const clockMs = state.simState.clockMs;
|
const clockMs = state.simState.clockMs;
|
||||||
const open = state.packages.filter((p) => p.status === 'open');
|
const open = visibleOpenPackages(state);
|
||||||
|
|
||||||
const catalog = state.catalog;
|
const catalog = state.catalog;
|
||||||
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
const buyEntry = catalog.find((e) => e.model === buyModelId) ?? catalog[0] ?? null;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { cargoWeightFor, loadEligiblePlanes } from './RightPane';
|
import { cargoWeightFor, loadEligiblePlanes, visibleOpenPackages } from './RightPane';
|
||||||
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||||
|
|
||||||
// v0.12.0 (weight model v0.27.0) — the package-model picker rules: a plane can LOAD a
|
// v0.12.0 (weight model v0.27.0) — the package-model picker rules: a plane can LOAD a
|
||||||
@@ -134,3 +134,39 @@ describe('loadEligiblePlanes (Load button eligibility)', () => {
|
|||||||
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
expect(loadEligiblePlanes(s, pkg({ id: 'x' }))).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('visibleOpenPackages (market list row filter, ISS-159)', () => {
|
||||||
|
it('shows an open package when a grounded plane sits at its origin', () => {
|
||||||
|
const s = snap(
|
||||||
|
[plane({ id: 'at-origin' })],
|
||||||
|
[pkg({ id: 'x' }), pkg({ id: 'onboard', status: 'loaded', planeId: 'at-origin' })], // non-open statuses never listed
|
||||||
|
);
|
||||||
|
expect(visibleOpenPackages(s).map((p) => p.id)).toEqual(['x']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides an open package when only a flying plane is at its origin (in air, not grounded)', () => {
|
||||||
|
const s = snap([plane({ id: 'en-route', status: 'flying', destIcao: 'LEMD' })], [pkg({ id: 'x' })]);
|
||||||
|
expect(visibleOpenPackages(s)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides an open package when the grounded plane is elsewhere and another flies to its origin', () => {
|
||||||
|
const s = snap(
|
||||||
|
[
|
||||||
|
plane({ id: 'grounded-elsewhere', locationIcao: 'LEMD' }),
|
||||||
|
plane({ id: 'en-route', status: 'flying', destIcao: 'EDDF' }), // flying TO the package's origin — not grounded there yet
|
||||||
|
],
|
||||||
|
[pkg({ id: 'x' })],
|
||||||
|
);
|
||||||
|
expect(visibleOpenPackages(s)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a payload-blocked row visible when a grounded plane at the origin has no room (disabled Load path preserved)', () => {
|
||||||
|
const packages = [
|
||||||
|
...Array.from({ length: 4 }, (_, i) => pkg({ id: `fill-${i}`, status: 'loaded', planeId: 'full', weightKg: 1_200 })), // 4 × 1200 = 4800 — full
|
||||||
|
pkg({ id: 'x' }),
|
||||||
|
];
|
||||||
|
const s = snap([plane({ id: 'full' })], packages);
|
||||||
|
expect(visibleOpenPackages(s).map((p) => p.id)).toEqual(['x']); // row stays…
|
||||||
|
expect(loadEligiblePlanes(s, s.packages.find((p) => p.id === 'x')!)).toEqual([]); // …with Load disabled
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -78,6 +78,17 @@ test('header shows the app version sourced from package.json', async ({ page })
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// v1.10.0 (ISS-157): top-bar Log out — same drop-to-sign-in as the admin panel's button
|
||||||
|
// (mirrors e2e/admin.spec.ts' logout assertion).
|
||||||
|
test('top bar Log out drops back to the sign-in screen', async ({ page }) => {
|
||||||
|
await page.goto(APP_URL);
|
||||||
|
const header = page.getByTestId('app-header');
|
||||||
|
await expect(header).toBeVisible({ timeout: 30_000 });
|
||||||
|
await page.getByTestId('logout-btn').click();
|
||||||
|
await expect(page.getByTestId('sign-in-form')).toBeVisible({ timeout: 10_000 });
|
||||||
|
await expect(header).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
test('clicking an airport marker opens a popup with name and ICAO', async ({ page }) => {
|
test('clicking an airport marker opens a popup with name and ICAO', async ({ page }) => {
|
||||||
await page.goto(APP_URL);
|
await page.goto(APP_URL);
|
||||||
await waitForAirportCount(page);
|
await waitForAirportCount(page);
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { test, expect, type Page } from '@playwright/test';
|
||||||
|
|
||||||
|
import { authenticate } from './auth';
|
||||||
|
import { haversineKm } from '../lib/geo';
|
||||||
|
import { legPhases } from '../lib/sim/movement';
|
||||||
|
import { PLANE_TYPES, STARTER_MODEL } from '../lib/game/catalog';
|
||||||
|
|
||||||
|
// v1.12.0 — takeoff & landing phases on the marker: dispatch the starter plane on a known leg and
|
||||||
|
// assert the popup shows 'taking off' shortly after departure (the plane holds at the origin gate)
|
||||||
|
// and 'landing' near arrival (holding at the destination gate), then 'available' once landed. The
|
||||||
|
// phase boundaries come from the SAME legPhases composition the engine uses, so no timing guesswork:
|
||||||
|
// each observation happens inside a window computed from departureSimTime + clockMs.
|
||||||
|
|
||||||
|
test.beforeEach(async ({ page }) => { await authenticate(page); });
|
||||||
|
|
||||||
|
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
|
||||||
|
const DEST = 'LEMD'; // ~1420 km — the same leg map-interactions.spec.ts uses
|
||||||
|
const STARTER = 'plane-starter';
|
||||||
|
// Observation rate: a phase window (600–1200 game-s) lasts 20–40 real seconds at this scale — long
|
||||||
|
// enough for the fit + click + popup pipeline, short enough to keep the test fast.
|
||||||
|
const OBS = 30;
|
||||||
|
// Fast-forward through the cruise between the two observations (pure arrival wait).
|
||||||
|
const MID = 1_000;
|
||||||
|
// Self-heal and final arrival waits — no mid-leg observation at this rate.
|
||||||
|
const FAST = 50_000;
|
||||||
|
const WORLD = 24; // the fixed world rate (ISS-117) — must match lib/worldClock.ts
|
||||||
|
|
||||||
|
interface StateBody {
|
||||||
|
simState: { clockMs: number };
|
||||||
|
planes: Array<{ id: string; status: string; locationIcao: string; departureSimTime: number | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getState(page: Page): Promise<StateBody> {
|
||||||
|
// ISS-127: /api/state intermittently 500s under dind load — retry briefly instead of failing.
|
||||||
|
for (let attempt = 1; ; attempt++) {
|
||||||
|
const res = await page.request.get('/api/state');
|
||||||
|
if (res.status() === 200) return (await res.json()) as StateBody;
|
||||||
|
if (attempt >= 3) throw new Error(`/api/state returned ${res.status()} after 3 attempts`);
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setScale(page: Page, scale: number): Promise<void> {
|
||||||
|
const res = await page.request.post('/api/test/set-timescale', { data: { timeScale: scale } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const body = (await res.json()) as { timeScale: number };
|
||||||
|
expect(body.timeScale, `timeScale should be ${scale} after POST /api/test/set-timescale`).toBe(scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leave the live instance in a sane state for the other specs (the fixed world rate).
|
||||||
|
test.afterEach(async ({ page }) => {
|
||||||
|
await setScale(page, WORLD);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function waitForAirportCount(page: Page): Promise<void> {
|
||||||
|
const countEl = page.getByTestId('airport-count');
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const text = (await countEl.textContent()) ?? '';
|
||||||
|
const m = text.match(/(\d+)/);
|
||||||
|
return m ? parseInt(m[1], 10) : -1;
|
||||||
|
}).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-heal: wait until the starter is grounded at HUB, flying it back first if another spec left
|
||||||
|
// it elsewhere. Runs at FAST — a cross-Europe hop lands in well under a second.
|
||||||
|
async function ensureGroundedAt(page: Page, icao: string): Promise<void> {
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === STARTER)!;
|
||||||
|
if (p.status === 'available' && p.locationIcao === icao) return 'ok';
|
||||||
|
if (p.status === 'available') {
|
||||||
|
await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: icao } });
|
||||||
|
return `flying home from ${p.locationIcao}`;
|
||||||
|
}
|
||||||
|
return p.status; // flying or repairing — keep waiting (FAST makes both finish quickly)
|
||||||
|
}, { timeout: 120_000, message: 'waiting for the starter plane to be grounded at ' + icao }).toBe('ok');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Frame both endpoints so the marker is rendered wherever it holds on the leg.
|
||||||
|
async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const points = icaos.map((icao) => {
|
||||||
|
const f = fc.features.find((x) => x.properties.icao === icao);
|
||||||
|
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
|
||||||
|
return [f.properties.lon, f.properties.lat] as [number, number];
|
||||||
|
});
|
||||||
|
await page.evaluate((pts: [number, number][]) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) throw new Error('map not ready');
|
||||||
|
const lons = pts.map((p) => p[0]);
|
||||||
|
const lats = pts.map((p) => p[1]);
|
||||||
|
// duration 0 → instant camera jump, no animation to wait out.
|
||||||
|
m.fitBounds(
|
||||||
|
[
|
||||||
|
[Math.min(...lons), Math.min(...lats)],
|
||||||
|
[Math.max(...lons), Math.max(...lats)],
|
||||||
|
],
|
||||||
|
{ padding: 40, duration: 0 },
|
||||||
|
);
|
||||||
|
}, points);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click the RENDERED marker position (the map draws from its own ~1 s poll, so a fresh /api/state
|
||||||
|
// fetch can be stale by tens of px) and wait for the popup. `flyingOnly` skips grounded frames —
|
||||||
|
// used right after dispatch, when the last rendered frame may predate it.
|
||||||
|
async function clickPlane(page: Page, flyingOnly: boolean): Promise<void> {
|
||||||
|
const pt = await page.evaluate(async ({ onlyFlying, starterId }: { onlyFlying: boolean; starterId: string }) => {
|
||||||
|
const m = (window as any).__flightMap;
|
||||||
|
if (!m) return null;
|
||||||
|
const deadline = Date.now() + 10_000;
|
||||||
|
for (;;) {
|
||||||
|
let feats: Array<{ properties?: Record<string, unknown>; geometry?: { coordinates: number[] } }> = [];
|
||||||
|
try {
|
||||||
|
feats = m.queryRenderedFeatures(undefined, { layers: ['planes-flying', 'planes-grounded'] });
|
||||||
|
} catch {
|
||||||
|
// map not ready yet — keep polling
|
||||||
|
}
|
||||||
|
const f = feats.find((x) => x.properties?.id === starterId && (!onlyFlying || x.properties?.flying === true));
|
||||||
|
if (f && f.geometry) {
|
||||||
|
const projected = m.project(f.geometry.coordinates);
|
||||||
|
const rect = m.getContainer().getBoundingClientRect();
|
||||||
|
return { x: rect.left + projected.x, y: rect.top + projected.y };
|
||||||
|
}
|
||||||
|
if (Date.now() >= deadline) return null;
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
}
|
||||||
|
}, { onlyFlying: flyingOnly, starterId: STARTER });
|
||||||
|
expect(pt, 'plane marker not rendered').not.toBeNull();
|
||||||
|
|
||||||
|
// Popups are created per click and never auto-close — remove any stale ones so the testids below
|
||||||
|
// stay unique.
|
||||||
|
await page.evaluate(() => document.querySelectorAll('.maplibregl-popup').forEach((el) => el.remove()));
|
||||||
|
await page.mouse.click(pt!.x, pt!.y);
|
||||||
|
const popup = page.getByTestId('plane-popup');
|
||||||
|
await expect(popup).toBeVisible({ timeout: 5_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
test('marker shows the takeoff and landing phases on a dispatched leg', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await waitForAirportCount(page);
|
||||||
|
|
||||||
|
// Self-heal to the onboarding state (starter grounded at HUB) regardless of what prior specs left.
|
||||||
|
await setScale(page, FAST);
|
||||||
|
await ensureGroundedAt(page, HUB);
|
||||||
|
|
||||||
|
// The exact phase boundaries for this leg — same composition the engine uses (v1.12.0).
|
||||||
|
const fc = (await (await page.request.get('/api/airports')).json()) as {
|
||||||
|
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
|
||||||
|
};
|
||||||
|
const hub = fc.features.find((x) => x.properties.icao === HUB)!;
|
||||||
|
const dest = fc.features.find((x) => x.properties.icao === DEST)!;
|
||||||
|
const km = haversineKm(hub.properties.lat, hub.properties.lon, dest.properties.lat, dest.properties.lon);
|
||||||
|
const ph = legPhases(km, PLANE_TYPES[STARTER_MODEL].speedKmh, HUB, DEST);
|
||||||
|
|
||||||
|
// --- Takeoff: dispatch at OBS and read the popup while the plane holds at the origin gate. ---
|
||||||
|
await setScale(page, OBS);
|
||||||
|
const fly = await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: DEST } });
|
||||||
|
expect(fly.status()).toBe(200);
|
||||||
|
const T_dep = ((await fly.json()) as StateBody).planes.find((x) => x.id === STARTER)!.departureSimTime!;
|
||||||
|
|
||||||
|
await fitToAirports(page, [HUB, DEST]);
|
||||||
|
await clickPlane(page, true); // flyingOnly: the last rendered frame may predate the dispatch
|
||||||
|
await expect(page.getByTestId('plane-status')).toHaveText('flying');
|
||||||
|
await expect(page.getByTestId('plane-phase')).toContainText('taking off');
|
||||||
|
|
||||||
|
// --- Landing: fast-forward through the cruise to just before the landing window, then drop back
|
||||||
|
// to OBS so the hold at the destination gate is observable. ---
|
||||||
|
const landingStart = T_dep + ph.takeoffMs + ph.cruiseMs;
|
||||||
|
await setScale(page, MID); // fast-forward through takeoff hold + cruise (pure arrival wait)
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const body = await getState(page);
|
||||||
|
const p = body.planes.find((x) => x.id === STARTER)!;
|
||||||
|
if (p.status !== 'flying') throw new Error('the clock jumped past the landing window — flake, retry');
|
||||||
|
return body.simState.clockMs >= landingStart - 60_000; // one game-minute before the hold begins
|
||||||
|
}, { timeout: 120_000, message: 'fast-forwarding through the cruise' }).toBe(true);
|
||||||
|
|
||||||
|
await setScale(page, OBS);
|
||||||
|
// Enter the window at a point guaranteed to be inside it (map frames lag ≤ ~1 s = 30 game-s) and
|
||||||
|
// before arrival (landingMs ≥ BASE_PHASE_MS > the offset below).
|
||||||
|
const landingTarget = landingStart + Math.min(ph.landingMs / 2, 1_000);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const body = await getState(page);
|
||||||
|
if (body.planes.find((x) => x.id === STARTER)!.status !== 'flying') throw new Error('the clock jumped past the landing window — flake, retry');
|
||||||
|
return body.simState.clockMs >= landingTarget;
|
||||||
|
}, { timeout: 120_000, message: 'waiting for the landing hold to begin' }).toBe(true);
|
||||||
|
|
||||||
|
await clickPlane(page, true);
|
||||||
|
await expect(page.getByTestId('plane-status')).toHaveText('flying');
|
||||||
|
await expect(page.getByTestId('plane-phase')).toContainText('landing');
|
||||||
|
|
||||||
|
// --- Arrival: fast-forward until the engine flips it to available at DEST. ---
|
||||||
|
await setScale(page, FAST);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === STARTER)!;
|
||||||
|
return p.status === 'available' && p.locationIcao === DEST;
|
||||||
|
}, { timeout: 60_000, message: 'waiting for the landing to complete' }).toBe(true);
|
||||||
|
|
||||||
|
// Leave the onboarding state for the other specs: starter grounded back at HUB.
|
||||||
|
await page.request.post(`/api/planes/${STARTER}/fly`, { data: { destIcao: HUB } });
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === STARTER)!;
|
||||||
|
return p.status === 'available' && p.locationIcao === HUB;
|
||||||
|
}, { timeout: 60_000, message: 'waiting for the relocation home to finish' }).toBe(true);
|
||||||
|
});
|
||||||
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => { await authenticate(page); });
|
|||||||
// works for FLYING planes — it then appends to POST /api/planes/{id}/queue instead of flying now.
|
// works for FLYING planes — it then appends to POST /api/planes/{id}/queue instead of flying now.
|
||||||
// Marker-size regression is covered by the existing e2e/map.spec.ts click tests, not here.
|
// Marker-size regression is covered by the existing e2e/map.spec.ts click tests, not here.
|
||||||
|
|
||||||
const SCALE = 1000; // test rate for fast-forwarding legs — keeps cleanup flights to seconds of real time
|
const FAST = 10_000; // pure arrival waits (no mid-leg observation) — cleanup legs land in ~1 s
|
||||||
const WORLD = 24; // the fixed world rate (ISS-117) — must match lib/worldClock.ts
|
const WORLD = 24; // the fixed world rate (ISS-117) — must match lib/worldClock.ts
|
||||||
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
|
||||||
// LFRS Nantes Atlantique — same isolated marker as e2e/map.spec.ts. The v0.70.0 default view ([0,0] z2)
|
// LFRS Nantes Atlantique — same isolated marker as e2e/map.spec.ts. The v0.70.0 default view ([0,0] z2)
|
||||||
@@ -93,8 +93,8 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
let s = await getState(page);
|
let s = await getState(page);
|
||||||
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
let plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
|
||||||
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
// Fast-forward any leftover leg / repositioning flight (~2 s real time worst case at FAST).
|
||||||
await setScale(page, SCALE);
|
await setScale(page, FAST);
|
||||||
}
|
}
|
||||||
if (plane.status === 'flying') {
|
if (plane.status === 'flying') {
|
||||||
// While flying, locationIcao stays at the DEPARTURE airport — re-read state after landing
|
// While flying, locationIcao stays at the DEPARTURE airport — re-read state after landing
|
||||||
@@ -104,8 +104,8 @@ async function flyHomeViaApi(page: Page): Promise<void> {
|
|||||||
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
plane = s.planes.find((p) => p.id === 'plane-starter')!;
|
||||||
}
|
}
|
||||||
if (plane.locationIcao !== HUB) {
|
if (plane.locationIcao !== HUB) {
|
||||||
// Make sure the world rate is back at SCALE so the return leg fast-forwards.
|
// Make sure the world rate is back at FAST so the return leg fast-forwards.
|
||||||
await setScale(page, SCALE);
|
await setScale(page, FAST);
|
||||||
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
const res = await page.request.post(`/api/planes/${plane.id}/fly`, { data: { destIcao: HUB } });
|
||||||
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
expect(res.ok()).toBeTruthy(); // repositioning needs no package (v0.12.0 manual flight)
|
||||||
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === 'plane-starter')!.locationIcao), { timeout: 240_000 }).toBe(HUB);
|
||||||
@@ -122,7 +122,7 @@ test.afterEach(async ({ page }) => {
|
|||||||
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
test.describe.configure({ mode: 'serial' }); // shared live DB — order matters within this file
|
||||||
|
|
||||||
test('left pane Relocate section relocates a grounded plane', async ({ page }) => {
|
test('left pane Relocate section relocates a grounded plane', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg
|
test.setTimeout(300_000); // self-heal (worst case ~2 s at FAST) + one short leg
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
@@ -154,7 +154,7 @@ test('left pane Relocate section relocates a grounded plane', async ({ page }) =
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('airport popup offers Relocate options for grounded planes', async ({ page }) => {
|
test('airport popup offers Relocate options for grounded planes', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one leg to LFRS
|
test.setTimeout(300_000); // self-heal (worst case ~2 s at FAST) + one leg to LFRS
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
@@ -221,7 +221,7 @@ test('airport popup offers Relocate options for grounded planes', async ({ page
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('airport popup Relocate queues a leg for a flying plane', async ({ page }) => {
|
test('airport popup Relocate queues a leg for a flying plane', async ({ page }) => {
|
||||||
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + one short leg, fast-forwarded in cleanup
|
test.setTimeout(300_000); // self-heal (worst case ~2 s at FAST) + one short leg, fast-forwarded in cleanup
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|
||||||
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
// Full tank before departure — deterministic baseline (ISS-082 hook; dispatch would auto-refuel anyway).
|
||||||
|
|||||||
+41
-25
@@ -154,39 +154,35 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string, deadl
|
|||||||
return (await created.json()) as PackageState;
|
return (await created.json()) as PackageState;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
|
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API. The end
|
||||||
|
// state is verified by ONE poll on FRESH snapshots (v1.12.0): legs now include takeoff/landing holds,
|
||||||
|
// so a leftover leg can land at its destination after an earlier snapshot was taken — deciding from a
|
||||||
|
// stale pre-flight snapshot let tests load cargo onto a plane that wasn't actually at the hub (409).
|
||||||
async function flyHomeViaApi(page: Page): Promise<void> {
|
async function flyHomeViaApi(page: Page): Promise<void> {
|
||||||
// v0.39.0 (ISS-069): wear accumulates across the shared CI DB — restore full health and clear any
|
// v0.39.0 (ISS-069): wear accumulates across the shared CI DB — restore full health and clear any
|
||||||
// active repair gate from an interrupted run before the steps below act on the starter, so the
|
// active repair gate from an interrupted run before the steps below act on the starter, so the
|
||||||
// farthest-flyable picker and fuel pins never see a worn or broken plane.
|
// farthest-flyable picker and fuel pins never see a worn or broken plane.
|
||||||
expect((await page.request.post('/api/test/set-health', { data: { planeId: 'plane-starter', health: 100, repairUntilMs: 0 } })).status()).toBe(200);
|
// ISS-127-style transient: test hooks intermittently 500 under dind load — retry briefly instead of failing.
|
||||||
const s0 = await getState(page); // ticks — a shortened gate flips the plane back to available here
|
for (let attempt = 1; ; attempt++) {
|
||||||
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
|
const healthRes = await page.request.post('/api/test/set-health', { data: { planeId: 'plane-starter', health: 100, repairUntilMs: 0 } });
|
||||||
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
|
if (healthRes.status() === 200) break;
|
||||||
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
|
if (attempt >= 3) throw new Error(`/api/test/set-health returned ${healthRes.status()} after 3 attempts`);
|
||||||
await setScale(page, SCALE);
|
await page.waitForTimeout(500);
|
||||||
}
|
}
|
||||||
if (starter.status === 'flying') {
|
// Fast-forward any leftover leg / repositioning flight (a few seconds real time worst case at 1000×).
|
||||||
await expect
|
|
||||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.status === 'available', {
|
|
||||||
timeout: 240_000,
|
|
||||||
message: 'waiting for an in-flight plane-starter to land',
|
|
||||||
})
|
|
||||||
.toBe(true);
|
|
||||||
}
|
|
||||||
if (starter.locationIcao !== HUB) {
|
|
||||||
// Make sure the world rate is back at SCALE so the return leg fast-forwards. ISS-082: dispatch
|
|
||||||
// auto-refuels, so a grounded plane can always start any full-tank-flyable leg when cash allows — no top-up retry needed.
|
|
||||||
await setScale(page, SCALE);
|
await setScale(page, SCALE);
|
||||||
|
await expect.poll(async () => {
|
||||||
|
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter')!;
|
||||||
|
if (p.status === 'available' && p.locationIcao === HUB) return 'ok';
|
||||||
|
if (p.status === 'available') {
|
||||||
|
// ISS-082: dispatch auto-refuels, so a grounded plane can always start any full-tank-flyable leg
|
||||||
|
// when cash allows — no top-up retry needed. Fail loud with the server's reason otherwise.
|
||||||
const flyHome = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
const flyHome = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
|
||||||
expect(flyHome.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
|
if (flyHome.status() !== 200) throw new Error(`reposition home failed (${flyHome.status()}): ${await flyHome.text()}`);
|
||||||
await expect
|
return `flying home from ${p.locationIcao}`;
|
||||||
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
|
|
||||||
timeout: 240_000,
|
|
||||||
message: 'waiting for plane-starter to land back at the hub',
|
|
||||||
})
|
|
||||||
.toBe(true);
|
|
||||||
}
|
}
|
||||||
|
return p.status; // flying or repairing — keep waiting (SCALE makes both finish quickly)
|
||||||
|
}, { timeout: 240_000, message: 'waiting for plane-starter to be grounded at the hub' }).toBe('ok');
|
||||||
// Abandon leftover loaded/expired packages (the baseline is captured AFTER this cleanup).
|
// Abandon leftover loaded/expired packages (the baseline is captured AFTER this cleanup).
|
||||||
const s1 = await getState(page);
|
const s1 = await getState(page);
|
||||||
for (const pkg of s1.packages) {
|
for (const pkg of s1.packages) {
|
||||||
@@ -270,6 +266,26 @@ test('open jobs only appear where a plane can take them — foreign-origin jobs
|
|||||||
await expect(page.locator(`li[data-testid="open-package-${pkg.id}"]`)).toHaveCount(0, { timeout: 15_000 });
|
await expect(page.locator(`li[data-testid="open-package-${pkg.id}"]`)).toHaveCount(0, { timeout: 15_000 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('jobs at an airport with no grounded plane stay hidden while a plane is still en route (ISS-159)', async ({ page }) => {
|
||||||
|
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
|
||||||
|
await flyHomeViaApi(page); // starter grounded at EDDF
|
||||||
|
|
||||||
|
const nearest = await nearestToHub(page);
|
||||||
|
// Dispatch the only plane toward `nearest` — while airborne its DESTINATION joins the pool (v0.65.0), so a job there
|
||||||
|
// reaches /api/state, but no GROUNDED plane sits at that airport yet: ISS-159 hides it until landing.
|
||||||
|
const flyRes = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: nearest.icao } });
|
||||||
|
expect(flyRes.status()).toBe(200);
|
||||||
|
|
||||||
|
const pkg = await createPackage(page, nearest.icao, HUB);
|
||||||
|
// The server keeps the job (its origin is in the pool)…
|
||||||
|
await expect.poll(async () => (await getState(page)).packages.some((p) => p.id === pkg.id), { timeout: 15_000 }).toBe(true);
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
// …but no row renders while the plane is still en route — no grounded plane at its origin. No landing wait needed;
|
||||||
|
// the next test's flyHomeViaApi self-heal finishes this leg.
|
||||||
|
await expect(page.locator(`li[data-testid="open-package-${pkg.id}"]`)).toHaveCount(0, { timeout: 15_000 });
|
||||||
|
});
|
||||||
|
|
||||||
test('on-board list: fly-to-destination + abandon with penalty preview; flying planes show their leg', async ({ page }) => {
|
test('on-board list: fly-to-destination + abandon with penalty preview; flying planes show their leg', async ({ page }) => {
|
||||||
test.setTimeout(240_000); // one short flight at scale 1000 (seconds of real time) plus UI steps
|
test.setTimeout(240_000); // one short flight at scale 1000 (seconds of real time) plus UI steps
|
||||||
await flyHomeViaApi(page);
|
await flyHomeViaApi(page);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { travelDurationMs } from '@/lib/sim/movement';
|
import { legPhases } from '@/lib/sim/movement';
|
||||||
import { FASTEST_CATALOG_SPEED_KMH, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
import { FASTEST_CATALOG_SPEED_KMH, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
||||||
import { SPECIALS } from './specials';
|
import { SPECIALS } from './specials';
|
||||||
import {
|
import {
|
||||||
@@ -478,7 +478,8 @@ describe('expiry floor (v0.54.0, ISS-119)', () => {
|
|||||||
const c = generatePackage({ id: `c-floor-${seed}`, airports, rng: mulberry32(seed), nowMs: NOW }); // special rolls naturally (~15% priority)
|
const c = generatePackage({ id: `c-floor-${seed}`, airports, rng: mulberry32(seed), nowMs: NOW }); // special rolls naturally (~15% priority)
|
||||||
const o = airports.find((a) => a.icao === c.originIcao)!;
|
const o = airports.find((a) => a.icao === c.originIcao)!;
|
||||||
const d = airports.find((a) => a.icao === c.destIcao)!;
|
const d = airports.find((a) => a.icao === c.destIcao)!;
|
||||||
const floorMs = travelDurationMs(haversineKm(o.lat, o.lon, d.lat, d.lon), FASTEST_CATALOG_SPEED_KMH) + EXPIRY_BUFFER_MS;
|
// v1.12.0: the floor includes the weather-scaled takeoff/landing phases (worst case for this pair).
|
||||||
|
const floorMs = legPhases(haversineKm(o.lat, o.lon, d.lat, d.lon), FASTEST_CATALOG_SPEED_KMH, o.icao, d.icao).totalMs + EXPIRY_BUFFER_MS;
|
||||||
expect(c.deadlineSimTime).toBeGreaterThanOrEqual(Math.round(NOW + floorMs));
|
expect(c.deadlineSimTime).toBeGreaterThanOrEqual(Math.round(NOW + floorMs));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -503,7 +504,8 @@ describe('expiry floor (v0.54.0, ISS-119)', () => {
|
|||||||
}
|
}
|
||||||
expect(bestKm).toBeGreaterThan(8_000); // the dataset really spans near-cap legs
|
expect(bestKm).toBeGreaterThan(8_000); // the dataset really spans near-cap legs
|
||||||
|
|
||||||
const floorMs = travelDurationMs(bestKm, FASTEST_CATALOG_SPEED_KMH) + EXPIRY_BUFFER_MS;
|
// v1.12.0: phase-inclusive floor — same composition seed.ts uses for this pair.
|
||||||
|
const floorMs = legPhases(bestKm, FASTEST_CATALOG_SPEED_KMH, airports[bestI].icao, airports[bestJ].icao).totalMs + EXPIRY_BUFFER_MS;
|
||||||
for (const special of ['priority', null] as const) {
|
for (const special of ['priority', null] as const) {
|
||||||
let clamped = 0;
|
let clamped = 0;
|
||||||
for (let seed = 1; seed <= 50; seed++) {
|
for (let seed = 1; seed <= 50; seed++) {
|
||||||
|
|||||||
+6
-4
@@ -1,5 +1,5 @@
|
|||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
import { travelDurationMs } from '@/lib/sim/movement';
|
import { legPhases } from '@/lib/sim/movement';
|
||||||
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
import { WORLD_TIME_SCALE } from '@/lib/worldClock';
|
||||||
import { FASTEST_CATALOG_SPEED_KMH, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
import { FASTEST_CATALOG_SPEED_KMH, PLANE_TYPES, repRate, STARTER_MODEL } from './catalog';
|
||||||
import { pickSpecial, SPECIALS } from './specials';
|
import { pickSpecial, SPECIALS } from './specials';
|
||||||
@@ -284,9 +284,11 @@ export function generatePackage(input: {
|
|||||||
// single uniform value, so clamping it up AFTER special scaling covers both requirements: short legs
|
// single uniform value, so clamping it up AFTER special scaling covers both requirements: short legs
|
||||||
// (drawn × scale already above the floor) are byte-identical to before, and when the raw draw falls
|
// (drawn × scale already above the floor) are byte-identical to before, and when the raw draw falls
|
||||||
// below the floor the deadline lands exactly on it — which stays ≤ the scaled ceiling for any pair of
|
// below the floor the deadline lands exactly on it — which stays ≤ the scaled ceiling for any pair of
|
||||||
// airports on Earth (max leg ~20000 km → floor ≈ 22.8 h < the 36 h priority ceiling), so no separate
|
// airports on Earth (max leg ~20000 km → floor ≈ 23.5 h incl. worst-case phases < the 36 h priority
|
||||||
// ceiling raise is needed. Forced offsets skip the floor, same as they skip the special scaling.
|
// ceiling), so no separate ceiling raise is needed. Forced offsets skip the floor, same as they skip
|
||||||
const expiryFloorMs = travelDurationMs(km, FASTEST_CATALOG_SPEED_KMH) + EXPIRY_BUFFER_MS;
|
// the special scaling. v1.12.0: the travel time includes the weather-scaled takeoff/landing phases —
|
||||||
|
// a package must be finishable even when both airports are in their worst (Fog) conditions.
|
||||||
|
const expiryFloorMs = legPhases(km, FASTEST_CATALOG_SPEED_KMH, origin.icao, dest.icao).totalMs + EXPIRY_BUFFER_MS;
|
||||||
const deadlineMs = input.deadlineOffsetMs ?? Math.max(drawnWindowMs * (mods?.deadlineScale ?? 1), expiryFloorMs);
|
const deadlineMs = input.deadlineOffsetMs ?? Math.max(drawnWindowMs * (mods?.deadlineScale ?? 1), expiryFloorMs);
|
||||||
|
|
||||||
// v0.38.0 (ISS-072): reputation bonus composed with the special multiplier, single round at the end.
|
// v0.38.0 (ISS-072): reputation bonus composed with the special multiplier, single round at the end.
|
||||||
|
|||||||
+3
-1
@@ -192,7 +192,9 @@ export async function getStateSnapshot(playerId: string): Promise<StateSnapshot>
|
|||||||
const to = coordsByIcao.get(p.destIcao);
|
const to = coordsByIcao.get(p.destIcao);
|
||||||
if (!type || !from || !to) return null;
|
if (!type || !from || !to) return null;
|
||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, simRow.clockMs);
|
// v1.12.0: piecewise cruise progress — holds at the origin during takeoff and at the
|
||||||
|
// destination during landing (weather-scaled phase durations from legPhases).
|
||||||
|
const progress = progressAt(p.departureSimTime, distanceKm, type.speedKmh, p.locationIcao, p.destIcao, simRow.clockMs);
|
||||||
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
const pos = positionAt(from.lat, from.lon, to.lat, to.lon, progress);
|
||||||
// Wind-adjusted burn (v0.36.0) — weather is a pure function of the departure ICAO, so this
|
// Wind-adjusted burn (v0.36.0) — weather is a pure function of the departure ICAO, so this
|
||||||
// recomputes exactly the factor the engine used for the leg; no stored state needed.
|
// recomputes exactly the factor the engine used for the leg; no stored state needed.
|
||||||
|
|||||||
+25
-2
@@ -1,6 +1,7 @@
|
|||||||
import type { PlaneState, StateSnapshot } from './game/state';
|
import type { PlaneState, StateSnapshot } from './game/state';
|
||||||
import { formatFuel } from './format';
|
import { formatFuel } from './format';
|
||||||
import { positionAt } from './sim/movement';
|
import { haversineKm } from './geo';
|
||||||
|
import { legPhaseAt, positionAt, type LegPhase } from './sim/movement';
|
||||||
|
|
||||||
// Pure GeoJSON builders for the map's dynamic layers (v0.11.0, package model
|
// Pure GeoJSON builders for the map's dynamic layers (v0.11.0, package model
|
||||||
// v0.12.0): one Point feature per plane, one LineString per FLYING plane's
|
// v0.12.0): one Point feature per plane, one LineString per FLYING plane's
|
||||||
@@ -14,9 +15,14 @@ export interface PlaneFeatureProps {
|
|||||||
status: 'available' | 'flying' | 'repairing';
|
status: 'available' | 'flying' | 'repairing';
|
||||||
fuelText: string; // "1234 / 6300 L"
|
fuelText: string; // "1234 / 6300 L"
|
||||||
routeText: string; // "Origin → Destination" while flying, '' when grounded
|
routeText: string; // "Origin → Destination" while flying, '' when grounded
|
||||||
|
// v1.12.0: 'taking off' | 'cruising' | 'landing' while flying (derived from the sim clock), '' when grounded.
|
||||||
|
phaseLabel: string;
|
||||||
flying: boolean;
|
flying: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v1.12.0: display text for each timed leg segment (see legPhaseAt in lib/sim/movement.ts).
|
||||||
|
const PHASE_LABELS: Record<LegPhase, string> = { takeoff: 'taking off', cruise: 'cruising', landing: 'landing' };
|
||||||
|
|
||||||
export interface RouteFeatureProps {
|
export interface RouteFeatureProps {
|
||||||
planeId: string;
|
planeId: string;
|
||||||
}
|
}
|
||||||
@@ -54,13 +60,29 @@ export function planesGeoJson(
|
|||||||
if (!state) return EMPTY_POINTS;
|
if (!state) return EMPTY_POINTS;
|
||||||
// Catalog display name ("ATR 72-600") for the popup — raw model id as fallback.
|
// Catalog display name ("ATR 72-600") for the popup — raw model id as fallback.
|
||||||
const labelByModel = new Map(state.catalog.map((e) => [e.model, e.label]));
|
const labelByModel = new Map(state.catalog.map((e) => [e.model, e.label]));
|
||||||
|
const speedByModel = new Map(state.catalog.map((e) => [e.model, e.speedKmh]));
|
||||||
|
const clockMs = state.simState.clockMs;
|
||||||
const features: MapPointFeature[] = state.planes.map((p) => {
|
const features: MapPointFeature[] = state.planes.map((p) => {
|
||||||
const flying = p.status === 'flying';
|
const flying = p.status === 'flying';
|
||||||
let lon = p.lon;
|
let lon = p.lon;
|
||||||
if (flying && p.destIcao) {
|
// v1.12.0: the marker's phase label — same legPhases composition the engine uses, derived from
|
||||||
|
// departureSimTime + clockMs (both in the snapshot) so no extra state is needed.
|
||||||
|
let phaseLabel = '';
|
||||||
|
if (flying && p.destIcao && p.departureSimTime != null) {
|
||||||
const from = airportsByIcao.get(p.locationIcao);
|
const from = airportsByIcao.get(p.locationIcao);
|
||||||
const to = airportsByIcao.get(p.destIcao);
|
const to = airportsByIcao.get(p.destIcao);
|
||||||
|
const speedKmh = speedByModel.get(p.model);
|
||||||
if (from && to) lon = unwrapLon(p.lon, from.lon);
|
if (from && to) lon = unwrapLon(p.lon, from.lon);
|
||||||
|
if (from && to && speedKmh !== undefined) {
|
||||||
|
phaseLabel = PHASE_LABELS[legPhaseAt(
|
||||||
|
p.departureSimTime,
|
||||||
|
haversineKm(from.lat, from.lon, to.lat, to.lon),
|
||||||
|
speedKmh,
|
||||||
|
p.locationIcao,
|
||||||
|
p.destIcao,
|
||||||
|
clockMs,
|
||||||
|
)];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
type: 'Feature',
|
type: 'Feature',
|
||||||
@@ -71,6 +93,7 @@ export function planesGeoJson(
|
|||||||
status: p.status,
|
status: p.status,
|
||||||
fuelText: formatFuel(p.fuel, p.maxFuel),
|
fuelText: formatFuel(p.fuel, p.maxFuel),
|
||||||
routeText: flying && p.destName ? `${p.locationName} → ${p.destName}` : '',
|
routeText: flying && p.destName ? `${p.locationName} → ${p.destName}` : '',
|
||||||
|
phaseLabel,
|
||||||
flying,
|
flying,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+19
-22
@@ -231,7 +231,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
const { inst, km, type } = await setupFlight('deliver-early.db');
|
const { inst, km, type } = await setupFlight('deliver-early.db');
|
||||||
const playerBefore = (await getLocalPlayer(inst));
|
const playerBefore = (await getLocalPlayer(inst));
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh) - 1; // one ms before arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO) - 1; // one ms before arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(0);
|
expect(await deliverPackages(inst, clock)).toBe(0);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
@@ -252,7 +252,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
{ id: 'p-elsewhere', originIcao: FROM, destIcao: 'EHAM', reward: 9_000, cargoType: 'Mail', cargoCount: 10, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
{ id: 'p-elsewhere', originIcao: FROM, destIcao: 'EHAM', reward: 9_000, cargoType: 'Mail', cargoCount: 10, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
@@ -298,7 +298,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
{ id: 'p-b', originIcao: FROM, destIcao: TO, reward: 2_500, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
{ id: 'p-b', originIcao: FROM, destIcao: TO, reward: 2_500, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh);
|
const clock = arrivalTimeFor(T0, km, PLANE_TYPES.atr72.speedKmh, FROM, TO);
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const player = (await getLocalPlayer(inst));
|
const player = (await getLocalPlayer(inst));
|
||||||
@@ -317,7 +317,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
{ id: 'p-prio', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Mail', cargoCount: 10, special: 'priority', deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
{ id: 'p-prio', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Mail', cargoCount: 10, special: 'priority', deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, PLANE_TYPES.atr72.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const player = (await getLocalPlayer(inst));
|
const player = (await getLocalPlayer(inst));
|
||||||
@@ -358,7 +358,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.set({ queue: JSON.stringify(['EHAM', 'EDDV']) })
|
.set({ queue: JSON.stringify(['EHAM', 'EDDV']) })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
@@ -383,7 +383,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
const playerBefore = (await getLocalPlayer(inst)); // seeded €20k — the top-up is affordable
|
const playerBefore = (await getLocalPlayer(inst)); // seeded €20k — the top-up is affordable
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
// Expected top-up from the SAME helpers the engine uses: landed fuel (≈ 0), wind-adjusted
|
// Expected top-up from the SAME helpers the engine uses: landed fuel (≈ 0), wind-adjusted
|
||||||
@@ -429,7 +429,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
await updateLocalPlayerEconomy(inst, { cash: 0 });
|
await updateLocalPlayerEconomy(inst, { cash: 0 });
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
@@ -445,7 +445,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
it('grounds as before when the queue is empty', async () => {
|
it('grounds as before when the queue is empty', async () => {
|
||||||
const { inst, km } = await setupFlight('chain-empty.db'); // seeded default queue '[]'
|
const { inst, km } = await setupFlight('chain-empty.db'); // seeded default queue '[]'
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(T0, km, PLANE_TYPES.atr72.speedKmh, FROM, TO))).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.status).toBe('available'); // unchanged landing behavior…
|
expect(plane.status).toBe('available'); // unchanged landing behavior…
|
||||||
@@ -473,7 +473,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.set({ queue: JSON.stringify(['FGSL']) })
|
.set({ queue: JSON.stringify(['FGSL']) })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
@@ -490,7 +490,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
.set({ queue: JSON.stringify(['LEMD', 'EHAM']) })
|
.set({ queue: JSON.stringify(['LEMD', 'EHAM']) })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(T0, km, type.speedKmh, FROM, TO))).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.status).toBe('available'); // grounded — the self-leg was dropped, not flown…
|
expect(plane.status).toBe('available'); // grounded — the self-leg was dropped, not flown…
|
||||||
@@ -514,7 +514,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
{ id: 'p-owner', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
{ id: 'p-owner', originIcao: FROM, destIcao: TO, reward: 5_000, cargoType: 'Mail', cargoCount: 1, deadlineSimTime: T0 + 24 * 3_600_000, status: 'loaded', planeId: 'plane-starter', createdSimTime: T0 },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const clock = T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, PLANE_TYPES.atr72.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
const bAfter = (await getPlayer(inst, 'player-b'));
|
const bAfter = (await getPlayer(inst, 'player-b'));
|
||||||
@@ -540,7 +540,7 @@ describe('deliverPackages (v0.12.0 arrival delivery)', () => {
|
|||||||
|
|
||||||
const localBefore = (await getPlayer(inst, LOCAL_PLAYER.id));
|
const localBefore = (await getPlayer(inst, LOCAL_PLAYER.id));
|
||||||
const bBefore = (await getPlayer(inst, 'player-b'));
|
const bBefore = (await getPlayer(inst, 'player-b'));
|
||||||
const clock = T0 + travelMs(km, type.speedKmh); // exactly at arrival
|
const clock = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // exactly at arrival
|
||||||
expect(await deliverPackages(inst, clock)).toBe(1);
|
expect(await deliverPackages(inst, clock)).toBe(1);
|
||||||
|
|
||||||
// Expected cost from the SAME helpers the engine uses — computed with B's rep discount.
|
// Expected cost from the SAME helpers the engine uses — computed with B's rep discount.
|
||||||
@@ -594,7 +594,7 @@ describe('wear on landed legs (v0.39.0, ISS-069)', () => {
|
|||||||
it('drops health by exactly WEAR_PER_KM × km on a landed leg', async () => {
|
it('drops health by exactly WEAR_PER_KM × km on a landed leg', async () => {
|
||||||
const { inst, km } = await setupFlight('wear-leg.db');
|
const { inst, km } = await setupFlight('wear-leg.db');
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, PLANE_TYPES.atr72.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(T0, km, PLANE_TYPES.atr72.speedKmh, FROM, TO))).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.health).toBeCloseTo(100 - WEAR_PER_KM * km, 9); // one mid-range hop ≈ −0.98 health (v0.43.0, ISS-085)
|
expect(plane.health).toBeCloseTo(100 - WEAR_PER_KM * km, 9); // one mid-range hop ≈ −0.98 health (v0.43.0, ISS-085)
|
||||||
@@ -607,18 +607,19 @@ describe('wear on landed legs (v0.39.0, ISS-069)', () => {
|
|||||||
.set({ health: WEAR_PER_KM * km / 2 })
|
.set({ health: WEAR_PER_KM * km / 2 })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(T0, km, type.speedKmh, FROM, TO))).toBe(1);
|
||||||
let plane = (await inst.db.select().from(schema.planes))[0];
|
let plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.health).toBe(0); // clamped — never negative…
|
expect(plane.health).toBe(0); // clamped — never negative…
|
||||||
|
|
||||||
// …and a second leg keeps it pinned at 0.
|
// …and a second leg keeps it pinned at 0.
|
||||||
const eham = (await loadAirportsGeoJson()).features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
const eham = (await loadAirportsGeoJson()).features.find((f) => f.properties.icao === 'EHAM')!.properties;
|
||||||
const nextKm = haversineKm(to.lat, to.lon, eham.lat, eham.lon);
|
const nextKm = haversineKm(to.lat, to.lon, eham.lat, eham.lon);
|
||||||
|
const arr1 = arrivalTimeFor(T0, km, type.speedKmh, FROM, TO); // leg 1's exact arrival (v1.12.0 phases)
|
||||||
await inst.db.update(schema.planes)
|
await inst.db.update(schema.planes)
|
||||||
.set({ status: 'flying', destIcao: 'EHAM', departureSimTime: T0 + travelMs(km, type.speedKmh), fuel: type.maxFuel })
|
.set({ status: 'flying', destIcao: 'EHAM', departureSimTime: arr1, fuel: type.maxFuel })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh) + travelMs(nextKm, type.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(arr1, nextKm, type.speedKmh, TO, 'EHAM'))).toBe(1);
|
||||||
plane = (await inst.db.select().from(schema.planes))[0];
|
plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.health).toBe(0); // still clamped after the second leg
|
expect(plane.health).toBe(0); // still clamped after the second leg
|
||||||
});
|
});
|
||||||
@@ -632,7 +633,7 @@ describe('wear on landed legs (v0.39.0, ISS-069)', () => {
|
|||||||
.set({ health: WEAR_PER_KM * km / 2, queue: JSON.stringify(['EHAM']) })
|
.set({ health: WEAR_PER_KM * km / 2, queue: JSON.stringify(['EHAM']) })
|
||||||
.where(eq(schema.planes.id, 'plane-starter'));
|
.where(eq(schema.planes.id, 'plane-starter'));
|
||||||
|
|
||||||
expect(await deliverPackages(inst, T0 + travelMs(km, type.speedKmh))).toBe(1);
|
expect(await deliverPackages(inst, arrivalTimeFor(T0, km, type.speedKmh, FROM, TO))).toBe(1);
|
||||||
|
|
||||||
const plane = (await inst.db.select().from(schema.planes))[0];
|
const plane = (await inst.db.select().from(schema.planes))[0];
|
||||||
expect(plane.health).toBe(0); // broken by this landing's wear…
|
expect(plane.health).toBe(0); // broken by this landing's wear…
|
||||||
@@ -1006,8 +1007,4 @@ describe('spawnPoolPackages (v0.65.0 per-airport pools)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Local helper mirroring lib/sim/movement.ts (kept private there on purpose — the
|
|
||||||
// engine composes arrivalTimeFor; tests just need the duration for fixtures).
|
|
||||||
function travelMs(km: number, speedKmh: number): number {
|
|
||||||
return (km / speedKmh) * 3_600_000;
|
|
||||||
}
|
|
||||||
|
|||||||
+2
-1
@@ -228,7 +228,8 @@ export async function deliverPackages(inst: GameDb, clockMs: number): Promise<nu
|
|||||||
if (!type || !from || !to) continue; // no route info — leave alone
|
if (!type || !from || !to) continue; // no route info — leave alone
|
||||||
|
|
||||||
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
const distanceKm = haversineKm(from.lat, from.lon, to.lat, to.lon);
|
||||||
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh)) continue;
|
// v1.12.0: the gate includes the takeoff/landing phases (weather-scaled) — see legPhases.
|
||||||
|
if (clockMs < arrivalTimeFor(p.departureSimTime, distanceKm, type.speedKmh, p.locationIcao, p.destIcao)) continue;
|
||||||
|
|
||||||
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn —
|
// Arrived: progress is exactly 1 here, so remaining fuel is the full-leg weighted burn —
|
||||||
// wind-adjusted (v0.36.0) by departure weather vs route heading, same factor flyPlane used.
|
// wind-adjusted (v0.36.0) by departure weather vs route heading, same factor flyPlane used.
|
||||||
|
|||||||
+94
-24
@@ -1,13 +1,19 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { haversineKm } from '@/lib/geo';
|
import { haversineKm } from '@/lib/geo';
|
||||||
|
import { weatherFor, type AirportWeather, type WeatherCondition } from '@/lib/weather';
|
||||||
import {
|
import {
|
||||||
arrivalTimeFor,
|
arrivalTimeFor,
|
||||||
|
BASE_PHASE_MS,
|
||||||
burnRateConstant,
|
burnRateConstant,
|
||||||
FUEL_DENSITY_KG_PER_L,
|
FUEL_DENSITY_KG_PER_L,
|
||||||
fuelAtWeighted,
|
fuelAtWeighted,
|
||||||
guaranteedRangeKm,
|
guaranteedRangeKm,
|
||||||
|
legPhases,
|
||||||
|
legPhaseAt,
|
||||||
|
MAX_PHASE_FACTOR,
|
||||||
MAX_WIND_BURN_FACTOR,
|
MAX_WIND_BURN_FACTOR,
|
||||||
maxRangeKm,
|
maxRangeKm,
|
||||||
|
phaseFactor,
|
||||||
positionAt,
|
positionAt,
|
||||||
progressAt,
|
progressAt,
|
||||||
requiredFuelFor,
|
requiredFuelFor,
|
||||||
@@ -38,36 +44,98 @@ describe('travelDurationMs / arrivalTimeFor', () => {
|
|||||||
expect(() => travelDurationMs(100, 0)).toThrow();
|
expect(() => travelDurationMs(100, 0)).toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('arrival is departure + duration', () => {
|
it('arrival is departure plus all three segments (v1.12.0)', () => {
|
||||||
const arrival = arrivalTimeFor(DEP, KM, SPEED);
|
const ph = legPhases(KM, SPEED, 'EDDF', 'LEMD');
|
||||||
expect(arrival).toBeCloseTo(DEP + (KM / SPEED) * 3_600_000, 9);
|
expect(arrivalTimeFor(DEP, KM, SPEED, 'EDDF', 'LEMD')).toBe(DEP + ph.totalMs);
|
||||||
expect(arrival).toBeGreaterThan(DEP);
|
// The cruise part is the old pure duration — phases only add on top.
|
||||||
|
expect(ph.cruiseMs).toBeCloseTo((KM / SPEED) * 3_600_000, 9);
|
||||||
|
expect(arrivalTimeFor(DEP, KM, SPEED, 'EDDF', 'LEMD')).toBeGreaterThan(DEP + ph.cruiseMs);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('progressAt', () => {
|
describe('phaseFactor / legPhases (v1.12.0)', () => {
|
||||||
const duration = travelDurationMs(KM, SPEED);
|
const mk = (condition: WeatherCondition): AirportWeather => ({ condition, windDirDeg: 90, windKt: 15, visibilityM: 8_000 });
|
||||||
|
|
||||||
it('is 0 before departure and at departure', () => {
|
it('MAX_PHASE_FACTOR is phaseFactor\'s actual maximum over the weather domain', () => {
|
||||||
expect(progressAt(DEP, KM, SPEED, DEP - 1)).toBe(0);
|
// Fog is the worst condition — the constant must track the factor function, not a copy.
|
||||||
expect(progressAt(DEP, KM, SPEED, DEP)).toBe(0);
|
expect(MAX_PHASE_FACTOR).toBe(phaseFactor(mk('Fog')));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is linear in the middle of the flight', () => {
|
it('stays within [1, MAX_PHASE_FACTOR] and is monotone in condition severity', () => {
|
||||||
|
for (const c of ['Clear', 'Cloudy', 'Rain', 'Fog'] as const) {
|
||||||
|
const f = phaseFactor(mk(c));
|
||||||
|
expect(f).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(f).toBeLessThanOrEqual(MAX_PHASE_FACTOR);
|
||||||
|
}
|
||||||
|
expect(phaseFactor(mk('Clear'))).toBe(1); // clear skies stay at 1×
|
||||||
|
expect(phaseFactor(mk('Cloudy'))).toBeGreaterThan(phaseFactor(mk('Clear')));
|
||||||
|
expect(phaseFactor(mk('Rain'))).toBeGreaterThan(phaseFactor(mk('Cloudy')));
|
||||||
|
expect(phaseFactor(mk('Fog'))).toBe(MAX_PHASE_FACTOR); // worst condition is exactly 2×
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is a deterministic function of the ICAO via weatherFor', () => {
|
||||||
|
for (const icao of ['EDDF', 'LEMD', 'EHAM', 'KSMF']) {
|
||||||
|
expect(phaseFactor(weatherFor(icao))).toBe(phaseFactor(weatherFor(icao)));
|
||||||
|
}
|
||||||
|
// KSMF is Clear in the deterministic generator — a real ICAO pinned at exactly 1×.
|
||||||
|
expect(phaseFactor(weatherFor('KSMF'))).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('takeoff scales on ORIGIN weather, landing on DESTINATION weather', () => {
|
||||||
|
const ph = legPhases(KM, SPEED, 'EDDF', 'LEMD');
|
||||||
|
expect(ph.takeoffMs).toBe(BASE_PHASE_MS * phaseFactor(weatherFor('EDDF')));
|
||||||
|
expect(ph.landingMs).toBe(BASE_PHASE_MS * phaseFactor(weatherFor('LEMD')));
|
||||||
|
// Non-vacuous: the two airports really do differ (Rain vs Cloudy), so a swapped
|
||||||
|
// origin/dest would fail these pins.
|
||||||
|
expect(phaseFactor(weatherFor('EDDF'))).not.toBe(phaseFactor(weatherFor('LEMD')));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('total is the sum of the three segments and exceeds the old pure duration', () => {
|
||||||
|
const ph = legPhases(KM, SPEED, 'EDDF', 'LEMD');
|
||||||
|
expect(ph.totalMs).toBe(ph.takeoffMs + ph.cruiseMs + ph.landingMs);
|
||||||
|
expect(ph.totalMs).toBeGreaterThan(travelDurationMs(KM, SPEED));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('legPhaseAt walks takeoff → cruise → landing over the leg', () => {
|
||||||
|
const ph = legPhases(KM, SPEED, 'EDDF', 'LEMD');
|
||||||
|
expect(legPhaseAt(DEP, KM, SPEED, 'EDDF', 'LEMD', DEP)).toBe('takeoff');
|
||||||
|
expect(legPhaseAt(DEP, KM, SPEED, 'EDDF', 'LEMD', DEP + ph.takeoffMs - 1)).toBe('takeoff');
|
||||||
|
expect(legPhaseAt(DEP, KM, SPEED, 'EDDF', 'LEMD', DEP + ph.takeoffMs)).toBe('cruise');
|
||||||
|
expect(legPhaseAt(DEP, KM, SPEED, 'EDDF', 'LEMD', DEP + ph.takeoffMs + ph.cruiseMs - 1)).toBe('cruise');
|
||||||
|
expect(legPhaseAt(DEP, KM, SPEED, 'EDDF', 'LEMD', DEP + ph.totalMs - 1)).toBe('landing');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('progressAt (piecewise, v1.12.0)', () => {
|
||||||
|
const ORIGIN = 'EDDF';
|
||||||
|
const DEST = 'LEMD';
|
||||||
|
const ph = legPhases(KM, SPEED, ORIGIN, DEST);
|
||||||
|
|
||||||
|
it('is 0 before departure and throughout the takeoff hold at the origin', () => {
|
||||||
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP - 1)).toBe(0);
|
||||||
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP + ph.takeoffMs / 2)).toBe(0);
|
||||||
|
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP + ph.takeoffMs - 1));
|
||||||
|
expect(p).toEqual({ lat: FROM.lat, lon: FROM.lon }); // still at the gate — no crawl along the route
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is linear over the cruise window', () => {
|
||||||
// Precision 9: clock values sit at ~1.75e12 ms, so (clock - DEP) loses a few
|
// Precision 9: clock values sit at ~1.75e12 ms, so (clock - DEP) loses a few
|
||||||
// ulps to cancellation — 1e-9 progress is still sub-millisecond on this leg.
|
// ulps to cancellation — 1e-9 progress is still sub-millisecond on this leg.
|
||||||
expect(progressAt(DEP, KM, SPEED, DEP + duration / 2)).toBeCloseTo(0.5, 9);
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP + ph.takeoffMs + ph.cruiseMs / 2)).toBeCloseTo(0.5, 9);
|
||||||
expect(progressAt(DEP, KM, SPEED, DEP + duration * 0.25)).toBeCloseTo(0.25, 9);
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP + ph.takeoffMs + ph.cruiseMs * 0.25)).toBeCloseTo(0.25, 9);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is exactly 1 at arrival and stays 1 after', () => {
|
it('is exactly 1 at the start of the landing hold and stays 1 through arrival', () => {
|
||||||
const arrival = DEP + duration;
|
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, ORIGIN, DEST, DEP + ph.takeoffMs + ph.cruiseMs));
|
||||||
expect(progressAt(DEP, KM, SPEED, arrival)).toBe(1);
|
expect(p).toEqual({ lat: TO.lat, lon: TO.lon }); // parked at the destination gate during landing
|
||||||
expect(progressAt(DEP, KM, SPEED, arrival + 10_000)).toBe(1);
|
const arrival = DEP + ph.totalMs;
|
||||||
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, arrival)).toBe(1);
|
||||||
|
expect(progressAt(DEP, KM, SPEED, ORIGIN, DEST, arrival + 10_000)).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('a zero-distance leg is complete immediately', () => {
|
it('a zero-distance leg has no cruise to progress through', () => {
|
||||||
expect(progressAt(DEP, 0, SPEED, DEP - 5)).toBe(1);
|
expect(progressAt(DEP, 0, SPEED, 'EDDF', 'EDDF', DEP - 5)).toBe(0); // before departure
|
||||||
|
expect(progressAt(DEP, 0, SPEED, 'EDDF', 'EDDF', DEP + 1)).toBe(1); // complete once departed
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -160,12 +228,14 @@ describe('weighted burn model (v0.16.0)', () => {
|
|||||||
expect(fuelAtWeighted(TANK, BURN, WE, TANK, 0, 1)).toBe(TANK);
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, 0, 1)).toBe(TANK);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('composes with progressAt for a just-before-arrival snapshot', () => {
|
it('composes with progressAt for a just-before-arrival snapshot (v1.12.0)', () => {
|
||||||
const duration = travelDurationMs(KM, SPEED);
|
const ph = legPhases(KM, SPEED, 'EDDF', 'LEMD');
|
||||||
const clock = DEP + duration - 1; // one ms before arrival
|
const clock = DEP + ph.totalMs - 1; // one ms before arrival — inside the landing hold
|
||||||
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progressAt(DEP, KM, SPEED, clock));
|
const progress = progressAt(DEP, KM, SPEED, 'EDDF', 'LEMD', clock);
|
||||||
expect(haversineKm(p.lat, p.lon, TO.lat, TO.lon)).toBeGreaterThan(0); // not yet at the gate
|
expect(progress).toBe(1); // cruise is done: the plane holds at the destination gate…
|
||||||
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, progressAt(DEP, KM, SPEED, clock))).toBeGreaterThan(0);
|
const p = positionAt(FROM.lat, FROM.lon, TO.lat, TO.lon, progress);
|
||||||
|
expect(p).toEqual({ lat: TO.lat, lon: TO.lon }); // …so it IS at the gate (v1.12.0 piecewise)
|
||||||
|
expect(fuelAtWeighted(TANK, BURN, WE, TANK, KM, progress)).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+83
-8
@@ -3,6 +3,8 @@
|
|||||||
// distance in game time without losing accuracy. All inputs are explicit; there
|
// distance in game time without losing accuracy. All inputs are explicit; there
|
||||||
// is no DB/IO here, which keeps this fully unit-testable with synthetic routes.
|
// is no DB/IO here, which keeps this fully unit-testable with synthetic routes.
|
||||||
|
|
||||||
|
import { weatherFor, type AirportWeather } from '@/lib/weather';
|
||||||
|
|
||||||
const toRad = (d: number) => (d * Math.PI) / 180;
|
const toRad = (d: number) => (d * Math.PI) / 180;
|
||||||
const toDeg = (r: number) => (r * 180) / Math.PI;
|
const toDeg = (r: number) => (r * 180) / Math.PI;
|
||||||
|
|
||||||
@@ -12,22 +14,95 @@ export function travelDurationMs(distanceKm: number, speedKmh: number): number {
|
|||||||
return (distanceKm / speedKmh) * 3_600_000;
|
return (distanceKm / speedKmh) * 3_600_000;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sim-clock time at which the leg completes.
|
// --- Takeoff & landing phases (v1.12.0) ---
|
||||||
export function arrivalTimeFor(departureSimTime: number, distanceKm: number, speedKmh: number): number {
|
//
|
||||||
return departureSimTime + travelDurationMs(distanceKm, speedKmh);
|
// Every leg has a 10-minute takeoff phase at the origin and a 10-minute landing phase at the
|
||||||
|
// destination, on top of the pure cruise time. Weather at the relevant airport stretches each
|
||||||
|
// phase up to 2× (bad conditions → longer rollout/approach); clear skies stay at 1×. The phases
|
||||||
|
// burn no fuel — they are pure time, so the weighted-burn model is untouched.
|
||||||
|
|
||||||
|
// One phase's duration in clear weather: 10 minutes of sim time.
|
||||||
|
export const BASE_PHASE_MS = 600_000;
|
||||||
|
|
||||||
|
// Weather → phase stretch factor, exactly [1, MAX_PHASE_FACTOR]. Simple monotone rule over the
|
||||||
|
// condition severity order Clear < Cloudy < Rain < Fog — visibility in this generator is a
|
||||||
|
// function of the condition (Fog ≤2 km, Rain 4–10 km, else 8–40 km), so it adds no independent
|
||||||
|
// signal. Each step up from Clear adds one third of the headroom; Fog lands exactly on MAX_PHASE_FACTOR.
|
||||||
|
export function phaseFactor(w: AirportWeather): number {
|
||||||
|
const step = w.condition === 'Clear' ? 0 : w.condition === 'Cloudy' ? 1 : w.condition === 'Rain' ? 2 : 3;
|
||||||
|
return 1 + step / 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flight progress in [0, 1] at a given sim-clock time — clamped to 0 before
|
// Upper end of phaseFactor over the weather domain — a Fog airport (the worst condition).
|
||||||
// departure and 1 after arrival. A zero-distance leg is complete immediately.
|
export const MAX_PHASE_FACTOR = 2;
|
||||||
|
|
||||||
|
export interface LegPhases {
|
||||||
|
takeoffMs: number; // origin weather
|
||||||
|
cruiseMs: number; // pure cruise — the old travelDurationMs value
|
||||||
|
landingMs: number; // destination weather
|
||||||
|
totalMs: number; // takeoff + cruise + landing
|
||||||
|
}
|
||||||
|
|
||||||
|
// The three timed segments of a leg. Takeoff scales on ORIGIN weather, landing on DESTINATION
|
||||||
|
// weather; both are deterministic functions of the ICAOs (weatherFor), so any site holding the
|
||||||
|
// two ICAs recomputes exactly what the engine used — no stored state needed.
|
||||||
|
export function legPhases(distanceKm: number, speedKmh: number, originIcao: string, destIcao: string): LegPhases {
|
||||||
|
const cruiseMs = travelDurationMs(distanceKm, speedKmh);
|
||||||
|
const takeoffMs = BASE_PHASE_MS * phaseFactor(weatherFor(originIcao));
|
||||||
|
const landingMs = BASE_PHASE_MS * phaseFactor(weatherFor(destIcao));
|
||||||
|
return { takeoffMs, cruiseMs, landingMs, totalMs: takeoffMs + cruiseMs + landingMs };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sim-clock time at which the leg completes — departure plus all three segments (v1.12.0).
|
||||||
|
export function arrivalTimeFor(
|
||||||
|
departureSimTime: number,
|
||||||
|
distanceKm: number,
|
||||||
|
speedKmh: number,
|
||||||
|
originIcao: string,
|
||||||
|
destIcao: string,
|
||||||
|
): number {
|
||||||
|
return departureSimTime + legPhases(distanceKm, speedKmh, originIcao, destIcao).totalMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CRUISE-segment progress in [0, 1] at a given sim-clock time (v1.12.0) — clamped to 0 before
|
||||||
|
// departure and 1 after arrival: 0 while the plane holds at the origin during takeoff, linear
|
||||||
|
// over the cruise window, 1 while it holds at the destination during landing. That keeps
|
||||||
|
// positionAt/fuel pinned to each airport during its phase instead of crawling along the whole
|
||||||
|
// route. A zero-distance leg has no cruise: complete once departed.
|
||||||
export function progressAt(
|
export function progressAt(
|
||||||
departureSimTime: number,
|
departureSimTime: number,
|
||||||
distanceKm: number,
|
distanceKm: number,
|
||||||
speedKmh: number,
|
speedKmh: number,
|
||||||
|
originIcao: string,
|
||||||
|
destIcao: string,
|
||||||
clockMs: number,
|
clockMs: number,
|
||||||
): number {
|
): number {
|
||||||
const duration = travelDurationMs(distanceKm, speedKmh);
|
const ph = legPhases(distanceKm, speedKmh, originIcao, destIcao);
|
||||||
if (duration <= 0) return 1;
|
const t = clockMs - departureSimTime;
|
||||||
return Math.min(1, Math.max(0, (clockMs - departureSimTime) / duration));
|
if (t <= 0) return 0;
|
||||||
|
if (ph.cruiseMs <= 0) return 1; // zero-distance leg — nothing to cruise
|
||||||
|
if (t >= ph.totalMs) return 1;
|
||||||
|
if (t <= ph.takeoffMs) return 0; // holding at origin during takeoff
|
||||||
|
if (t >= ph.takeoffMs + ph.cruiseMs) return 1; // holding at destination during landing
|
||||||
|
return (t - ph.takeoffMs) / ph.cruiseMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LegPhase = 'takeoff' | 'cruise' | 'landing';
|
||||||
|
|
||||||
|
// Which timed segment a leg is in at a given sim-clock time — for marker display (v1.12.0).
|
||||||
|
export function legPhaseAt(
|
||||||
|
departureSimTime: number,
|
||||||
|
distanceKm: number,
|
||||||
|
speedKmh: number,
|
||||||
|
originIcao: string,
|
||||||
|
destIcao: string,
|
||||||
|
clockMs: number,
|
||||||
|
): LegPhase {
|
||||||
|
const ph = legPhases(distanceKm, speedKmh, originIcao, destIcao);
|
||||||
|
const t = clockMs - departureSimTime;
|
||||||
|
if (t < ph.takeoffMs) return 'takeoff';
|
||||||
|
if (t < ph.takeoffMs + ph.cruiseMs) return 'cruise';
|
||||||
|
return 'landing';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Great-circle interpolation between two WGS84 points at progress t ∈ [0,1]
|
// Great-circle interpolation between two WGS84 points at progress t ∈ [0,1]
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flight-ops",
|
"name": "flight-ops",
|
||||||
"version": "1.8.0",
|
"version": "1.12.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Reference in New Issue
Block a user