Spaces:
Paused
Paused
Claude Claude Sonnet 5 commited on
Let workers load/unload freighters and add an AI-logistics freighter mode
Browse filesWorkers can now physically ferry cargo to and from a landed freighter
(right-click it, like assigning a worker to service a building) — the
freighter becomes a mobile collection point for nearby production instead
of every load detouring through the Command Center.
Also adds a new Datacenter research, Autonomous Freight AI, that lets a
freighter join the local haul/service logistics chain on its own, like a
worker but at its own much larger cargo capacity. Running autonomously
burns AI Cores from the treasury while active; out of AI Cores it just
pauses in place instead of losing its job or cargo.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AdsYZQyGk32n8x3UBiPGup
Files changed (11)
- docs/logistics-design.md+56-6
- engine/commands.js+27
- engine/entities.js+16
- engine/galaxy.js+6-13
- engine/haul.js+182-21
- engine/sim.js+29-2
- engine/techtree.js+7
- engine/types.js+4-1
- hudSelection.js+44-2
- input.js+10-1
- test/ferry.test.jsAdded+297
94 unmodified lines959697989910010168 unmodified lines17017117217317417517617717817918018118218318418594 unmodified linesin the HUD, not as "the market is broken".10. **Freighters.** Interplanetary freight already exists (`unit.freight`); keep itorthogonal — freighters move goods *between worlds*, workers move goods *within* aworld. Don't conflate.### 2.4 Phased plan (each phase is its own merge, suite-green + determinism-verified)68 unmodified lineswalk (confirmed identical on the pre-Phase-C code). It's a movement/separation bug, outof scope here; a real placement keeps the drop-off far enough from the node to avoid it.---## OutcomeAll three phases shipped. Storage is finite end-to-end — collection (forward drop-offs),production output (rig + factories), and factory inputs — and workers move every goodbetween them (gather → drop-off → haul → CC → supply → factory → haul → CC). Logistics isnow a standing demand on labour to the end of the game, with the Command Center as the onebottomless warehouse. Energy stays a placement decision (grid efficiency), no workers.Everything player-only and deterministic; the AI and skirmish replays are byte-identical.### 2.5 Recommended order & risk94 unmodified lines959697989910010110210310410510610768 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423594 unmodified linesin the HUD, not as "the market is broken".10. **Freighters.** Interplanetary freight already exists (`unit.freight`); keep itorthogonal — freighters move goods *between worlds*, workers move goods *within* aworld. Don't conflate. **Superseded by Phase D below**, which deliberately DOESconnect the two: workers can now physically load/unload a landed freighter's hold(the ship becomes a mobile collection point *within* a world), and a researchedfreighter can join the *within-world* haul/service chain itself. The panel-drivenload/unload (this section) and the interplanetary jump (`unit.freight`, moved*between* worlds) are untouched — Phase D adds a THIRD, physical path onto the samehold, it doesn't replace the first two.### 2.4 Phased plan (each phase is its own merge, suite-green + determinism-verified)68 unmodified lineswalk (confirmed identical on the pre-Phase-C code). It's a movement/separation bug, outof scope here; a real placement keeps the drop-off far enough from the node to avoid it.**Phase D — Freighters join the local logistics chain. ✅ DONE (player-only, Odyssey-only).**Revisits item 10 above: a landed freighter (`hauler`/`heavyhauler`/`bulkfreighter`) is now a*physical* object on the world map, not just a menu-driven hold, in two ways:- **Workers can load/unload it — FERRY (`engine/haul.js updateFerry`).** Right-click afriendly freighter with workers selected (`engine/commands.js issueFerryFreighter`,`input.js`) to assign them to it, the same idiom as `issueServiceBuilding`. A ferryworker keeps carrying the nearest own producer's backlog straight onto the freighter's`freight` hold — the freighter becomes its own **collection point**, no detour throughthe Command Center — and once there's nothing left to load, draws some of the hold backout and banks it at the treasury instead. Any freighter qualifies, no research needed:this is a worker loading a crate onto a ship, not the ship acting on its own. Shares`nearestBacklogProducer` with `assignHaul` (parameterised: a fresh auto-haul still waitsfor a ≥34%-full buffer; a worker already dedicated to a freighter takes any backlog) andthe same per-producer `haulers` cap, so it can't out-compete regular haulage for labour.- **A freighter can BE the logistics chain — AI-LOGISTICS (`FREIGHTER_AI_TECH`).** A newDatacenter tech, `freighterai` (requires `aicores`, costs AI Cores to research), unlocksa per-freighter toggle (`unit.aiLogistics`, HUD button, `engine/commands.jsissueSetAILogistics`). Toggled on, a freighter offers itself to the SAME`assignHaul`/`assignService` idle-worker logic every tick (`engine/sim.js`) — it grabsa haul or service job exactly like a worker would, but at its own trip capacity: with no`cargoCap` of its own, `tripCapacity()` falls back to the ship's whole `cargoHold`(250/650/1600 vs. a worker's 10), so one autonomous run clears a backlog a worker wouldneed many trips for. Running this way isn't free: every tick an autonomous job is activeit burns AI Cores from the treasury (`payAIUpkeep`, rate scaled by the ship's own`cargoHold` — a bigger hold costs more to run unmanned). Out of AI Cores, it just pausesin place for the tick (order and cargo untouched) rather than stranding anything;toggling AI-logistics off stands it down immediately. A freighter with no AI Cores instock also never *claims* a fresh job in the first place, so it doesn't sit there hoggingone of a producer's ≤2 hauler slots while unable to move.- Both paths reuse the SAME `loadFrom`/cargo machinery workers already use (generalised totake a plain commodity→qty store instead of a building, so it works against either abuilding's `store` or a freighter's `freight`) — no parallel implementation to keep insync. `freightUsed`/`freightRoom` moved from `engine/galaxy.js` to `engine/entities.js`(re-exported from galaxy.js for every existing caller) so `engine/haul.js` can read afreighter's room without an import cycle (`galaxy.js` → `sim.js` → `haul.js`).- Player-only and Odyssey-only by construction (freighters are `odysseyOnly`, the tech isgated behind the Datacenter/`aicores`, and the sim only ever offers this to`owner === "player"`) — the AI never builds a freighter, so the skirmish AI and itsbyte-identical replay are untouched. Tests in `test/ferry.test.js`.---## OutcomeAll four phases shipped. Storage is finite end-to-end — collection (forward drop-offs),production output (rig + factories), and factory inputs — and workers move every goodbetween them (gather → drop-off → haul → CC → supply → factory → haul → CC). A landedfreighter now sits IN that chain too — a physical collection point workers can ferry todirectly, or (once teched) a large-capacity autonomous hauler in its own right, paid forin AI Cores while it runs. Logistics is a standing demand on labour (and, for an automatedfleet, on AI Cores) to the end of the game, with the Command Center as the one bottomlesswarehouse. Energy stays a placement decision (grid efficiency), no workers. Everythingplayer-only and deterministic; the AI and skirmish replays are byte-identical.### 2.5 Recommended order & risk
9 unmodified lines101112131415144 unmodified lines1601611621631641659 unmodified linesimport { canPlaceBuilding } from "./colliders.js";import { makeBuilding } from "./state.js";import { formationSlots } from "./formation.js";// Give a unit an order, either replacing what it's doing (a plain command)// or appending it as a waypoint (queue = true, the Ctrl+command from input.js).144 unmodified lines});}// Only ARMED units (or a support drone, whose 'attack' order updateSupport reinterprets// as "advance on that foe" and mend nearby, dealing no damage) accept an attack order.// A weaponless rider — a colony ship, a freighter — has no `attack` stat, so routing an9 unmodified lines10111213141516144 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911929 unmodified linesimport { canPlaceBuilding } from "./colliders.js";import { makeBuilding } from "./state.js";import { formationSlots } from "./formation.js";import { FREIGHTER_AI_TECH } from "./haul.js";// Give a unit an order, either replacing what it's doing (a plain command)// or appending it as a waypoint (queue = true, the Ctrl+command from input.js).144 unmodified lines});}// Assign workers to FERRY a landed freighter — a standing loop that carries nearby producer// backlog onto its hold (so it becomes its own mobile collection point) and, once there's nothing// left to load, carries some of that hold back to the treasury (engine/haul.js updateFerry). Any// freighter qualifies — this is a worker physically loading a ship, not the ship acting on its// own; see issueSetAILogistics for that separate, research-gated mode.export function issueFerryFreighter(units, freighterId, queue = false) {units.forEach(u => {if (UNITS[u.type]?.role === "worker") dispatch(u, { type: "ferry", freighterId, phase: "plan", manual: true }, queue);});}// Toggle a freighter's AI-LOGISTICS mode: put to work in the local haul/service chain like a// worker (engine/sim.js updateUnit), but at its own far larger cargo capacity, burning AI Cores// from the treasury while active (engine/haul.js payAIUpkeep). Turning it OFF always works (stand// down is never gated); turning it ON requires its owner to have researched FREIGHTER_AI_TECH —// unresearched freighters in the selection are silently skipped rather than the whole call failing,// so a mixed selection still does what it can.export function issueSetAILogistics(units, on, state) {units.forEach(u => {if (UNITS[u.type]?.role !== "freighter") return;if (on && !state.players[u.owner]?.upgrades[FREIGHTER_AI_TECH]) return;u.aiLogistics = on;if (on && !u.cargo) u.cargo = { com: null, qty: 0 };});}// Only ARMED units (or a support drone, whose 'attack' order updateSupport reinterprets// as "advance on that foe" and mend nearby, dealing no damage) accept an attack order.// A weaponless rider — a colony ship, a freighter — has no `attack` stat, so routing an
335 unmodified lines336337338339340341335 unmodified linesreturn Math.max(0, inputCapOf(building.type) - inputTotal(building));}// One-time, player-wide Refinery upgrades, arranged as two MUTUALLY EXCLUSIVE// doctrines of two tiers each. You commit to Assault (offense) OR Bulwark// (defense) — researching any upgrade of one doctrine locks the other — and can335 unmodified lines336337338339340341342343344345346347348349350351352353354355356357335 unmodified linesreturn Math.max(0, inputCapOf(building.type) - inputTotal(building));}// ---- Freighter cargo hold (Odyssey freight) ------------------------------------// A freighter's `freight` is a multi-commodity hold (unlike a worker's single-slot `cargo`),// capped by `def.cargoHold`. Lives here (not engine/galaxy.js, where the player-manual// load/unload panel logic lives) so engine/haul.js can read a freighter's room/fill too — the// worker↔freighter physical loading path — without importing galaxy.js, which itself imports// engine/sim.js -> engine/haul.js and would otherwise be a cycle. galaxy.js re-exports both./** How much is currently aboard a freighter's hold (0 for a non-freighter unit). */export function freightUsed(unit) { return unit ? bufTotal(unit.freight) : 0; }/** A freighter's remaining hold room = its cargoHold minus what's aboard (0 for a non-freighter). */export function freightRoom(unit) {const cap = unit ? (UNITS[unit.type]?.cargoHold || 0) : 0;return Math.max(0, cap - freightUsed(unit));}// One-time, player-wide Refinery upgrades, arranged as two MUTUALLY EXCLUSIVE// doctrines of two tiers each. You commit to Assault (offense) OR Bulwark// (defense) — researching any upgrade of one doctrine locks the other — and can
25 unmodified lines26272829303132683 unmodified lines71671771871972072172272372472572672772872973073173273325 unmodified linesimport { tick } from "./sim.js";import { createMarket } from "./market.js";import { createDiplomacy, aiDevelopment } from "./diplomacy.js";import { UNITS, BUILDINGS } from "./entities.js";import { hasColonyShip } from "./colony.js";import { PLANET_ARCHETYPE, ODYSSEY_EXTRA_ARCHETYPE, archetypeFor } from "./aiArchetypes.js";import { PLANETS, COM } from "../data.js";683 unmodified linesreturn manifest;}// How full a freighter's hold is (sum of its commodity quantities). 0 for a non-freighter.export function freightUsed(unit) {let n = 0;if (unit && unit.freight) for (const com in unit.freight) n += unit.freight[com] || 0;return n;}// A freighter's remaining hold room = its cargoHold minus what's aboard.export function freightRoom(unit) {const cap = unit ? (UNITS[unit.type]?.cargoHold || 0) : 0;return Math.max(0, cap - freightUsed(unit));}// Load up to `qty` of commodity `com` from the CURRENT world's player stockpile into a freighter's// hold, clamped to the hold's room and what's actually in stock. Returns the amount loaded (0 if25 unmodified lines26272829303132683 unmodified lines71671771871972072172272372472572625 unmodified linesimport { tick } from "./sim.js";import { createMarket } from "./market.js";import { createDiplomacy, aiDevelopment } from "./diplomacy.js";import { UNITS, BUILDINGS, freightUsed, freightRoom } from "./entities.js";import { hasColonyShip } from "./colony.js";import { PLANET_ARCHETYPE, ODYSSEY_EXTRA_ARCHETYPE, archetypeFor } from "./aiArchetypes.js";import { PLANETS, COM } from "../data.js";683 unmodified linesreturn manifest;}// freightUsed/freightRoom (how full a freighter's hold is, and its remaining room) now live in// entities.js — engine/haul.js needs them for the worker↔freighter physical loading path and can't// import this module (galaxy.js -> sim.js -> haul.js would cycle back here). Re-exported (imported// above) so every existing caller of these two from "./galaxy.js" is unaffected.export { freightUsed, freightRoom };// Load up to `qty` of commodity `com` from the CURRENT world's player stockpile into a freighter's// hold, clamped to the hold's room and what's actually in stock. Returns the amount loaded (0 if
2 unmodified lines34567895 unmodified lines1516171819202122232425262728293 unmodified lines33343536373812 unmodified lines5152535455565758596061626364656622 unmodified lines899091929394959697989910010110210310410510610710810911042 unmodified lines15315415515615715815957 unmodified lines2172182192202212222237 unmodified lines23123223323423523623719 unmodified lines2572582592 unmodified linesWORKER LOGISTICS (Odyssey) — the muscle behind finite storage.Buildings buffer goods locally (engine/entities.js store/input) and workers movethem. Two jobs:- HAUL: a one-way run for a PURE producer (the Plasma Rig; the forward drop-offs) —buildings that only OUTPUT. The worker walks there, loads a cargo, and banks it into5 unmodified linesboth by auto-assignment and when the player manually assigns a worker to a building(`order.manual`, which makes it keep serving that one building instead of going idle).Deterministic and DOM-free: nearest-target picks are distance-then-id, the per-tickjob tallies are frozen before assignment, no wall clock or unseeded randomness. Player-only — the AI builds no producers/factories, so its replay is byte-identical.============================================================ */"use strict";import { stepToward } from "./movement.js";import { UNITS, storeTotal, storeCapOf, inputRoom } from "./entities.js";import { nearestCommandCenter } from "./gather.js";import { recipeOf } from "./industry.js";3 unmodified linesconst ASSIGN_FRACTION = 0.34; // act once an output buffer is this full — wait for a worthwhile backlogconst SUPPLY_BATCHES = 12; // keep a factory topped up to ~this many batches of each input/*** Tally, per building, how many workers are hauling from it (`haulers`) or servicing it* (`servers`) — the caps ASSIGN reads. Frozen at tick start (before any assignment) so every idle12 unmodified linesif (!b) continue;if (o.type === "haul") b.haulers = (b.haulers || 0) + 1;else if (o.type === "service") b.servers = (b.servers || 0) + 1;}}const reached = (unit, b) => Math.hypot(b.x - unit.x, b.y - unit.y) <= REACH;// Load one commodity from a building's OUTPUT buffer into the worker's cargo (single-commodity, like// a gatherer's). Drains the biggest pile first, deterministic tiebreak by name./** @param {Building} src @param {Unit} unit @param {number} cargoCap @returns {boolean} loaded anything */function loadFrom(src, unit, cargoCap) {const s = src.store || {};let com = null, most = 0;for (const c of Object.keys(s).sort()) if ((s[c] || 0) > most) { most = s[c]; com = c; }if (!com || most <= 0 || !unit.cargo) return false;22 unmodified linesreturn want;}/*** Give an idle worker a HAUL job on a PURE producer (an output buffer, no recipe: the Plasma Rig,* the forward drop-offs) whose buffer is ≥ ASSIGN_FRACTION full and isn't already served by* MAX_HAULERS. Claims a slot for the tick. Deterministic: nearest by distance, ties broken by id.* @param {State} state @param {Unit} unit*/export function assignHaul(state, unit) {let best = null, bestD = Infinity;for (const b of state.buildings.values()) {if (b.owner !== unit.owner || b.constructing || recipeOf(b)) continue; // factories are serviced, not hauledconst cap = storeCapOf(b.type);if (cap <= 0 || storeTotal(b) < cap * ASSIGN_FRACTION) continue;if ((b.haulers || 0) >= MAX_HAULERS) continue;const d = Math.hypot(b.x - unit.x, b.y - unit.y);if (d < bestD || (d === bestD && best && b.id < best.id)) { bestD = d; best = b; }}if (!best) return;best.haulers = (best.haulers || 0) + 1;unit.order = { type: "haul", buildingId: best.id, phase: "toSource" };42 unmodified lines}if (order.phase === "loading") {if (!src) { unit.order = null; return; }loadFrom(src, unit, def.cargoCap);order.phase = "toDrop";if (!unit.cargo || unit.cargo.qty <= 0) unit.order = null;return;57 unmodified linesconst cc = nearestCommandCenter(state, unit.owner, unit.x, unit.y);if (!cc) { unit.order = null; return; }if (reached(unit, cc)) {const want = Math.min(def.cargoCap, res[order.com] || 0, inputRoom(b));if (want > 0) { res[order.com] -= want; unit.cargo.com = order.com; unit.cargo.qty = want; order.phase = "toBuilding"; }else order.phase = "plan"; // treasury dried up → re-plan} else stepToward(state, unit, cc.x, cc.y, def.speed, dt);7 unmodified linesif (give > 0) { b.input = b.input || {}; b.input[unit.cargo.com] = (b.input[unit.cargo.com] || 0) + give; unit.cargo.qty -= give; }if (unit.cargo.qty <= 1e-9) { unit.cargo.qty = 0; unit.cargo.com = null; }}if (!unit.cargo || unit.cargo.qty <= 0) loadFrom(b, unit, def.cargoCap); // pick up the finished goodsorder.phase = (unit.cargo && unit.cargo.qty > 0) ? "toReturn" : endOrLoop(order);if (order.phase === null) unit.order = null;} else stepToward(state, unit, b.x, b.y, def.speed, dt);19 unmodified linesfunction parkNear(state, unit, b, def, dt) {if (Math.hypot(b.x - unit.x, b.y - unit.y) > REACH + b.radius) stepToward(state, unit, b.x, b.y, def.speed, dt);}2 unmodified lines34567895 unmodified lines15161718192021222324252627282930313233343536373839404142434445463 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929312 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813922 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419542 unmodified lines23823924024124224324457 unmodified lines3023033043053063073087 unmodified lines31631731831932032132219 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194202 unmodified linesWORKER LOGISTICS (Odyssey) — the muscle behind finite storage.Buildings buffer goods locally (engine/entities.js store/input) and workers movethem. Three jobs:- HAUL: a one-way run for a PURE producer (the Plasma Rig; the forward drop-offs) —buildings that only OUTPUT. The worker walks there, loads a cargo, and banks it into5 unmodified linesboth by auto-assignment and when the player manually assigns a worker to a building(`order.manual`, which makes it keep serving that one building instead of going idle).- FERRY: a worker manually assigned to a specific landed FREIGHTER (right-click it,like a building — engine/commands.js issueFerryFreighter). It carries a nearbyproducer's backlog straight onto the ship's hold — a freighter parked out at aremote claim becomes its own COLLECTION POINT, without every load detouring throughthe Command Center — and, once there's nothing left to load, carries some of theship's hold back to the treasury instead. Any landed freighter qualifies; noresearch needed — this is a worker loading a crate onto a ship, not the ship actingon its own (that's the separate AI-logistics mode below).A freighter can ALSO be folded into the SAME auto-assigned HAUL/SERVICE chain a workerruns — "Autonomous Freight AI" (engine/techtree.js FREIGHTER_AI_TECH) lets the playertoggle `unit.aiLogistics` on a hauler/heavy hauler/bulk freighter (engine/sim.js), atwhich point it grabs haul/service jobs on its own just like an idle worker, but at itsown (far larger) cargo capacity — see `tripCapacity`. Running autonomously burns AICores from the treasury every tick (`payAIUpkeep`, called from sim.js): out of stockjust pauses it in place for the tick, nothing lost, rather than stranding its cargo.Deterministic and DOM-free: nearest-target picks are distance-then-id, the per-tickjob tallies are frozen before assignment, no wall clock or unseeded randomness. Player-only — the AI builds no producers/factories/freighters, so its replay is byte-identical.============================================================ */"use strict";import { stepToward } from "./movement.js";import { UNITS, storeTotal, storeCapOf, inputRoom, freightUsed, freightRoom } from "./entities.js";import { nearestCommandCenter } from "./gather.js";import { recipeOf } from "./industry.js";3 unmodified linesconst ASSIGN_FRACTION = 0.34; // act once an output buffer is this full — wait for a worthwhile backlogconst SUPPLY_BATCHES = 12; // keep a factory topped up to ~this many batches of each input// The research node (engine/techtree.js TECHS) that unlocks a freighter's AI-logistics mode.// Referenced by id here (not imported from techtree.js) to keep haul.js/sim.js free of a// dependency on the tech tree — a plain flag on player.upgrades either way.export const FREIGHTER_AI_TECH = "freighterai";// AI Cores burned per second by an AUTONOMOUS freighter (aiLogistics on), scaled by its own// cargoHold — a bigger hold is a bigger crew/compute footprint to run unmanned. At this rate a// Hauler (250) costs ~0.1/s, a Heavy Hauler (650) ~0.26/s, a Bulk Freighter (1600) ~0.64/s: a real,// tunable tax on the same scarce strategic good the AI Foundry cultivates, not a token cost.const AI_UPKEEP_PER_CAPACITY_PER_SEC = 1 / 2500;/** AI Cores/sec an autonomous freighter burns while actively working a haul/service job. */export function aiUpkeepRate(unit) {return (UNITS[unit.type]?.cargoHold || 0) * AI_UPKEEP_PER_CAPACITY_PER_SEC;}/*** Charge this tick's AI-Cores upkeep for an autonomous freighter's job, clamped to what's in* stock. Returns false (and charges nothing) when the treasury can't cover it — the caller then* just pauses the unit in place for the tick instead of advancing its order.* @param {State} state @param {Unit} unit @param {number} dt*/export function payAIUpkeep(state, unit, dt) {const cost = aiUpkeepRate(unit) * dt;if (cost <= 0) return true;const res = state.players[unit.owner].resources;if ((res.ai || 0) < cost) return false;res.ai -= cost;return true;}// A worker's single-trip capacity is its own UNITS[type].cargoCap. A freighter has no cargoCap of// its own (its normal role carries a multi-commodity `freight` hold instead, engine/galaxy.js) —// folded into the haul/service/ferry chain, it reuses its whole cargoHold as this trip's// SINGLE-commodity size, so "larger capacity" falls out of the same def field its freight panel// already shows, no duplicated number to keep in sync.function tripCapacity(def) { return def.cargoCap ?? def.cargoHold ?? 0; }/*** Tally, per building, how many workers are hauling from it (`haulers`) or servicing it* (`servers`) — the caps ASSIGN reads. Frozen at tick start (before any assignment) so every idle12 unmodified linesif (!b) continue;if (o.type === "haul") b.haulers = (b.haulers || 0) + 1;else if (o.type === "service") b.servers = (b.servers || 0) + 1;// A FERRY worker's "toSource" leg draws on the same producer backlog auto-haulers do (and// clears its buildingId once it moves past that leg — see updateFerry), so it counts against// the SAME per-producer hauler cap, keeping the ≤MAX_HAULERS rule fair across both job types.else if (o.type === "ferry") b.haulers = (b.haulers || 0) + 1;}}const reached = (unit, b) => Math.hypot(b.x - unit.x, b.y - unit.y) <= REACH;// Deposit a worker's cargo into a freighter's hold, clamped to its remaining room — whatever// doesn't fit stays aboard the worker for the next leg (updateFerry re-plans from there). Mirrors// bankCargo's shape but targets a finite ship's hold instead of the bottomless treasury./** @param {Unit} f @param {Unit} unit */function depositToFreighter(f, unit) {if (!unit.cargo || unit.cargo.qty <= 0) return;const move = Math.min(unit.cargo.qty, freightRoom(f));if (move <= 0) return;f.freight[unit.cargo.com] = (f.freight[unit.cargo.com] || 0) + move;unit.cargo.qty -= move;if (unit.cargo.qty <= 1e-9) { unit.cargo.qty = 0; unit.cargo.com = null; }}// Load one commodity from a commodity->qty STORE (a building's output buffer, or a freighter's// freight hold) into the worker's cargo (single-commodity, like a gatherer's). Drains the biggest// pile first, deterministic tiebreak by name./** @param {Object.<string, number>} store @param {Unit} unit @param {number} cargoCap @returns {boolean} loaded anything */function loadFrom(store, unit, cargoCap) {const s = store || {};let com = null, most = 0;for (const c of Object.keys(s).sort()) if ((s[c] || 0) > most) { most = s[c]; com = c; }if (!com || most <= 0 || !unit.cargo) return false;22 unmodified linesreturn want;}// The nearest own PURE producer (an output buffer, no recipe: the Plasma Rig, the forward// drop-offs) whose buffer is at least `minFraction` full and isn't already served by MAX_HAULERS —// shared by assignHaul's auto-assignment (minFraction defaults to ASSIGN_FRACTION: don't pull a// fresh worker off other work for a trivial backlog) and a FERRY worker's "plan" phase (which// passes 0: a worker already dedicated to a freighter, with nothing else to do, should pick up// ANY backlog rather than abandon a producer the moment its buffer dips under the "worth starting"// bar). Deterministic: nearest by distance, ties broken by id./** @param {State} state @param {string} owner @param {number} x @param {number} y @param {number} [minFraction] @returns {Building|null} */function nearestBacklogProducer(state, owner, x, y, minFraction = ASSIGN_FRACTION) {let best = null, bestD = Infinity;for (const b of state.buildings.values()) {if (b.owner !== owner || b.constructing || recipeOf(b)) continue; // factories are serviced, not hauledconst cap = storeCapOf(b.type);if (cap <= 0 || storeTotal(b) < cap * minFraction) continue;if ((b.haulers || 0) >= MAX_HAULERS) continue;const d = Math.hypot(b.x - x, b.y - y);if (d < bestD || (d === bestD && best && b.id < best.id)) { bestD = d; best = b; }}return best;}/*** Give an idle worker (or an autonomous freighter, see FREIGHTER_AI_TECH) a HAUL job on the* nearest backed-up producer. Claims a slot for the tick.* @param {State} state @param {Unit} unit*/export function assignHaul(state, unit) {const best = nearestBacklogProducer(state, unit.owner, unit.x, unit.y);if (!best) return;best.haulers = (best.haulers || 0) + 1;unit.order = { type: "haul", buildingId: best.id, phase: "toSource" };42 unmodified lines}if (order.phase === "loading") {if (!src) { unit.order = null; return; }loadFrom(src.store, unit, tripCapacity(def));order.phase = "toDrop";if (!unit.cargo || unit.cargo.qty <= 0) unit.order = null;return;57 unmodified linesconst cc = nearestCommandCenter(state, unit.owner, unit.x, unit.y);if (!cc) { unit.order = null; return; }if (reached(unit, cc)) {const want = Math.min(tripCapacity(def), res[order.com] || 0, inputRoom(b));if (want > 0) { res[order.com] -= want; unit.cargo.com = order.com; unit.cargo.qty = want; order.phase = "toBuilding"; }else order.phase = "plan"; // treasury dried up → re-plan} else stepToward(state, unit, cc.x, cc.y, def.speed, dt);7 unmodified linesif (give > 0) { b.input = b.input || {}; b.input[unit.cargo.com] = (b.input[unit.cargo.com] || 0) + give; unit.cargo.qty -= give; }if (unit.cargo.qty <= 1e-9) { unit.cargo.qty = 0; unit.cargo.com = null; }}if (!unit.cargo || unit.cargo.qty <= 0) loadFrom(b.store, unit, tripCapacity(def)); // pick up the finished goodsorder.phase = (unit.cargo && unit.cargo.qty > 0) ? "toReturn" : endOrLoop(order);if (order.phase === null) unit.order = null;} else stepToward(state, unit, b.x, b.y, def.speed, dt);19 unmodified linesfunction parkNear(state, unit, b, def, dt) {if (Math.hypot(b.x - unit.x, b.y - unit.y) > REACH + b.radius) stepToward(state, unit, b.x, b.y, def.speed, dt);}/*** Advance a FERRY job: a worker manually assigned to a specific landed freighter* (engine/commands.js issueFerryFreighter). While the freighter has room, it keeps ferrying the* nearest own producer's backlog straight onto its hold (the freighter IS the collection point —* no CC detour); once there's nothing left to load, it instead draws some of the freighter's hold* and carries it home to the treasury. Loops forever like a manually-assigned SERVICE job — only* re-ordering the worker elsewhere ends it. Salvages gracefully if the freighter jumps away/dies* (carries home whatever's already aboard) or the CC is gone.* @param {State} state @param {Unit} unit @param {number} dt*/export function updateFerry(state, unit, dt) {const def = UNITS[unit.type];const order = unit.order;let f = order.freighterId ? state.units.get(order.freighterId) : null;if (f && (f.owner !== unit.owner || !UNITS[f.type]?.cargoHold)) f = null;if (!f) { // target gone/jumped away → salvage, then drop the jobif (unit.cargo && unit.cargo.qty > 0) { order.phase = "toReturn"; order.freighterId = null; }else { unit.order = null; return; }}if (!order.phase) order.phase = "plan";if (order.phase === "plan") {if (unit.cargo && unit.cargo.qty > 0) { // finish whatever's aboard firstorder.phase = (f && freightRoom(f) > 0) ? "toFreighter" : "toReturn";return;}if (f && freightRoom(f) > 0) {const src = nearestBacklogProducer(state, unit.owner, unit.x, unit.y, 0);if (src) { src.haulers = (src.haulers || 0) + 1; order.buildingId = src.id; order.phase = "toSource"; return; }}if (f && freightUsed(f) > 0) { order.phase = "toPickup"; return; } // nothing to load → bring some cargo home insteadif (f) { // nothing to do → wait by the shipconst fr = UNITS[f.type]?.radius || 0;if (Math.hypot(f.x - unit.x, f.y - unit.y) > REACH + fr) stepToward(state, unit, f.x, f.y, def.speed, dt);}return;}if (order.phase === "toSource") { // walk to the producer, load a cargoconst src = order.buildingId ? state.buildings.get(order.buildingId) : null;if (!src || src.constructing || storeTotal(src) <= 0) { order.buildingId = null; order.phase = "plan"; return; }if (reached(unit, src)) {loadFrom(src.store, unit, tripCapacity(def));order.buildingId = null;order.phase = (unit.cargo && unit.cargo.qty > 0) ? "toFreighter" : "plan";} else stepToward(state, unit, src.x, src.y, def.speed, dt);return;}if (order.phase === "toFreighter") { // deliver the load into the freighter's holdif (!f) { order.phase = "plan"; return; }if (reached(unit, f)) { depositToFreighter(f, unit); order.phase = "plan"; }else stepToward(state, unit, f.x, f.y, def.speed, dt);return;}if (order.phase === "toPickup") { // draw some of the freighter's holdif (!f) { order.phase = "plan"; return; }if (reached(unit, f)) {loadFrom(f.freight, unit, tripCapacity(def));order.phase = (unit.cargo && unit.cargo.qty > 0) ? "toReturn" : "plan";} else stepToward(state, unit, f.x, f.y, def.speed, dt);return;}if (order.phase === "toReturn") { // bank it at the treasuryconst cc = nearestCommandCenter(state, unit.owner, unit.x, unit.y);if (!cc) { unit.order = null; return; }if (reached(unit, cc)) {bankCargo(state, unit);order.phase = "plan";} else stepToward(state, unit, cc.x, cc.y, def.speed, dt);}}
8 unmodified lines9101112131415138 unmodified lines1541551561571581591601611621631641659 unmodified lines1751761771781791808 unmodified linesimport { stepToward, keepEscortStation, keepFormationStation, keepFollowingLeader, orderedSpeed } from "./movement.js";import { buildUnitGrid } from "./grid.js";import { updateGather } from "./gather.js";import { updateHaul, assignHaul, updateService, assignService, countLogistics } from "./haul.js";import { updateScoutMode } from "./scout.js";import { updateRepair } from "./repair.js";import { updateCombat, updateBuildingCombat, updateWorkerCombat } from "./combat.js";138 unmodified lines// pure producer's backed-up output to a Command Center (haul — the Rig, the drop-offs), else it// runs a factory a round-trip service (carry inputs in, output back). Player-only — the AI builds// no producers/factories, so its workers never do this and its replay is unchanged.if (!unit.order && def.role === "worker" && unit.owner === "player") {assignHaul(state, unit);if (!unit.order) assignService(state, unit);}if (!unit.order) return;switch (unit.order.type) {case "move": {const arrived = stepToward(state, unit, unit.order.x, unit.order.y, orderedSpeed(def.speed, unit.order), dt);9 unmodified linescase "service":updateService(state, unit, dt);break;case "escort":// A non-combat escort (worker) just keeps station on the ring around the guarded ship.keepEscortStation(state, unit, def.speed, dt);8 unmodified lines9101112131415138 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881899 unmodified lines1992002012022032042052062078 unmodified linesimport { stepToward, keepEscortStation, keepFormationStation, keepFollowingLeader, orderedSpeed } from "./movement.js";import { buildUnitGrid } from "./grid.js";import { updateGather } from "./gather.js";import { updateHaul, assignHaul, updateService, assignService, updateFerry, countLogistics, payAIUpkeep, FREIGHTER_AI_TECH } from "./haul.js";import { updateScoutMode } from "./scout.js";import { updateRepair } from "./repair.js";import { updateCombat, updateBuildingCombat, updateWorkerCombat } from "./combat.js";138 unmodified lines// pure producer's backed-up output to a Command Center (haul — the Rig, the drop-offs), else it// runs a factory a round-trip service (carry inputs in, output back). Player-only — the AI builds// no producers/factories, so its workers never do this and its replay is unchanged.//// A freighter the player has toggled into AI-logistics mode (`aiLogistics`, HUD button — requires// the FREIGHTER_AI_TECH research) offers itself the SAME way, at its own far larger cargo capacity// (engine/haul.js tripCapacity) — the order it lands is stamped `aiJob` so the upkeep check below// knows to bill it. Regular freighters (aiLogistics off) are untouched — fully player-controlled,// same as before. Claiming a NEW job also requires at least SOME AI Cores in stock: a freighter// that can't afford to move shouldn't still reserve one of a producer's scarce ≤MAX_HAULERS// slots doing nothing — an already-running job is a separate case, handled by the upkeep check// below, which pauses it in place rather than dropping it the instant the treasury dips dry.const aiFreighter = def.role === "freighter" && unit.owner === "player" && unit.aiLogistics&& !!state.players[unit.owner].upgrades[FREIGHTER_AI_TECH]&& (state.players[unit.owner].resources.ai || 0) > 0;if (!unit.order && (def.role === "worker" || aiFreighter) && unit.owner === "player") {assignHaul(state, unit);if (!unit.order) assignService(state, unit);if (unit.order && aiFreighter) unit.order.aiJob = true;}if (!unit.order) return;// An autonomous freighter's job burns AI Cores from the treasury every tick it's active// (engine/haul.js payAIUpkeep). Toggling AI-logistics off mid-job stands it down immediately (its// cargo, if any, just sits aboard until reassigned); running dry of AI Cores pauses it in place// for the tick — nothing lost, it resumes the moment the treasury can cover it again. A plain// worker's order never carries `aiJob`, so this is a no-op for the whole worker roster.if (unit.order.aiJob) {if (!unit.aiLogistics || !state.players[unit.owner].upgrades[FREIGHTER_AI_TECH]) { unit.order = null; return; }if (!payAIUpkeep(state, unit, dt)) return;}switch (unit.order.type) {case "move": {const arrived = stepToward(state, unit, unit.order.x, unit.order.y, orderedSpeed(def.speed, unit.order), dt);9 unmodified linescase "service":updateService(state, unit, dt);break;case "ferry":updateFerry(state, unit, dt);break;case "escort":// A non-combat escort (worker) just keeps station on the ring around the guarded ship.keepEscortStation(state, unit, def.speed, dt);
52 unmodified lines53545556575852 unmodified lines// Antimatter Gate and the Leviathan capital ship.aicores: { id: "aicores", name: "Machine Minds", ico: "🧠", cost: { crystals: 260, radioactives: 130 }, time: 48, requires: ["antimatter"],desc: "Unlock the AI Foundry and Torpedo Works — cultivate AI Cores and Plasma Torpedoes." },};// Research develops faster on a high-tech world (data.js PLANETS.tech, 1..10) and52 unmodified lines5354555657585960616263646552 unmodified lines// Antimatter Gate and the Leviathan capital ship.aicores: { id: "aicores", name: "Machine Minds", ico: "🧠", cost: { crystals: 260, radioactives: 130 }, time: 48, requires: ["antimatter"],desc: "Unlock the AI Foundry and Torpedo Works — cultivate AI Cores and Plasma Torpedoes." },// engine/haul.js FREIGHTER_AI_TECH — the string id here MUST match that constant. An unlock node// like metallurgy/electronics/machining above (no multiplier field: it gates a CAPABILITY, read// directly off player.upgrades by id in sim.js/commands.js/hudSelection.js, not through techMult).// Priced partly in the very good it lets a freighter burn to run itself (engine/haul.js// payAIUpkeep) — cultivating the Cores to spend on automation IS the cost of automating.freighterai: { id: "freighterai", name: "Autonomous Freight AI", ico: "🧠", cost: { ai: 60, electronics: 90 }, time: 40, requires: ["aicores"],desc: "Freighters can be toggled into the local logistics chain like a worker — far greater capacity per trip — while burning AI Cores to run themselves." },};// Research develops faster on a high-tech world (data.js PLANETS.tech, 1..10) and
42 unmodified lines434445464748495051525341 unmodified lines959697989910042 unmodified lines* @property {string} [targetId]* @property {string} [nodeId]* @property {string} [buildingId]* @property {string} [com]* @property {number} [slot]* @property {number} [slots]* @property {string} [phase]* @property {boolean} [manual] a player-assigned service order sticks to its building (engine/haul.js)* @property {number} [anchorX] hold-formation: this unit's own fixed anchor point (engine/commands.js issueHoldFormation)* @property {number} [anchorY]* @property {number} [offsetX] hold-formation/follow-leader: this unit's fixed offset from the anchor/leader (engine/formation.js)41 unmodified lines* @property {string|null} [repairTargetId] transient: the friendly an auto-repair Mender is committed to (engine/sim.js)* @property {string|null} [targetId] aim target (combat.js / render.js)* @property {Object.<string, number>} [freight] a freighter's player-managed cargo hold, commodity → qty (engine/galaxy.js)* @property {boolean} [armed] a Helium Bomb set to detonate on attack/enemy presence/command (engine/bomb.js)* @property {number} [fuseUntil] the state.time an ARMED Helium Bomb's lit fuse detonates at — set by lightFuse, absent while unlit (engine/bomb.js)* @property {Unit} [squadLeader] transient, NEVER persisted: the leader this unit is following, if any (engine/commands.js setSquadLeader) — a live object reference42 unmodified lines4344454647484950515253545541 unmodified lines97989910010110210342 unmodified lines* @property {string} [targetId]* @property {string} [nodeId]* @property {string} [buildingId]* @property {string} [freighterId] ferry: the specific landed freighter a worker is assigned to load/unload (engine/haul.js updateFerry)* @property {string} [com]* @property {number} [slot]* @property {number} [slots]* @property {string} [phase]* @property {boolean} [manual] a player-assigned service/ferry order sticks to its building/freighter (engine/haul.js)* @property {boolean} [aiJob] haul/service: this order was auto-assigned to an AI-logistics freighter, not a worker — bills AI Cores upkeep (engine/sim.js, engine/haul.js payAIUpkeep)* @property {number} [anchorX] hold-formation: this unit's own fixed anchor point (engine/commands.js issueHoldFormation)* @property {number} [anchorY]* @property {number} [offsetX] hold-formation/follow-leader: this unit's fixed offset from the anchor/leader (engine/formation.js)41 unmodified lines* @property {string|null} [repairTargetId] transient: the friendly an auto-repair Mender is committed to (engine/sim.js)* @property {string|null} [targetId] aim target (combat.js / render.js)* @property {Object.<string, number>} [freight] a freighter's player-managed cargo hold, commodity → qty (engine/galaxy.js)* @property {boolean} [aiLogistics] a freighter toggled into autonomous haul/service work, like a worker (engine/commands.js issueSetAILogistics, engine/sim.js) — requires FREIGHTER_AI_TECH researched, burns AI Cores while active (engine/haul.js payAIUpkeep)* @property {boolean} [armed] a Helium Bomb set to detonate on attack/enemy presence/command (engine/bomb.js)* @property {number} [fuseUntil] the state.time an ARMED Helium Bomb's lit fuse detonates at — set by lightFuse, absent while unlit (engine/bomb.js)* @property {Unit} [squadLeader] transient, NEVER persisted: the leader this unit is following, if any (engine/commands.js setSquadLeader) — a live object reference
21 unmodified lines222324252627184 unmodified lines212213214215216217238 unmodified lines456457458459460461561 unmodified lines10231024102510261027102810291030103121 unmodified linesstarmapBtn, saveBtn, loadBtn, groupChipsEl, pauseBtn,} from "./dom.js";import { queueProduction, cancelProduction, researchUpgrade } from "./engine/production.js";import { supplyUsed, supplyCap } from "./engine/supply.js";import { powerCap, powerDraw, recipeOf, powerThrottle, planetIndustryScale, powerEfficiency, onPowerGrid, electrifyBoost, ELECTRIFY_POWER } from "./engine/industry.js";import { storeTotal, storeCapOf, storeRoom, inputTotal, inputCapOf, isElectrifiable } from "./engine/entities.js";184 unmodified linesconst res = state.players.player.resources;return freightUsed(f) + ":" + JSON.stringify(f.freight) + ":" + loadableComs(state, f).map(c => Math.floor(res[c] || 0)).join(",");})()// Rebuild a selected Plasma Rig's status as it digs — its progress, last strike (each dig// increments digCount), and its power/nuclear situation — without a per-tick rebuild.+ "|" + (() => {238 unmodified lines}}// Why a selected factory is (or isn't) producing — the answer to "my antimatter// isn't going up." Checks the same limits updateProduction (engine/industry.js)// applies, in priority order: no Power at all, then a missing input, then a Power561 unmodified linestip: "Settle: the colony ship becomes a Command Center on this spot (it can't move again). Colonists disembark as workers." }));}// Freighter (Odyssey cargo ship): a load/unload cargo panel for the first one selected.const freighter = game.galaxy && sel.find(e => e.kind === "unit" && UNITS[e.type].cargoHold);if (freighter) renderFreight(state, freighter);// Mender: an auto-repair toggle (roam and mend on its own) + its Odyssey power state (it heals at// full rate only on the powered grid, near a Reactor/Generator).21 unmodified lines2223242526272829184 unmodified lines214215216217218219220221222223224225226238 unmodified lines465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502561 unmodified lines106410651066106710681069107010711072107321 unmodified linesstarmapBtn, saveBtn, loadBtn, groupChipsEl, pauseBtn,} from "./dom.js";import { queueProduction, cancelProduction, researchUpgrade } from "./engine/production.js";import { issueSetAILogistics } from "./engine/commands.js";import { FREIGHTER_AI_TECH, aiUpkeepRate } from "./engine/haul.js";import { supplyUsed, supplyCap } from "./engine/supply.js";import { powerCap, powerDraw, recipeOf, powerThrottle, planetIndustryScale, powerEfficiency, onPowerGrid, electrifyBoost, ELECTRIFY_POWER } from "./engine/industry.js";import { storeTotal, storeCapOf, storeRoom, inputTotal, inputCapOf, isElectrifiable } from "./engine/entities.js";184 unmodified linesconst res = state.players.player.resources;return freightUsed(f) + ":" + JSON.stringify(f.freight) + ":" + loadableComs(state, f).map(c => Math.floor(res[c] || 0)).join(",");})()// Rebuild the freighter AI-logistics toggle when it flips or the treasury's AI Cores count// changes by a whole unit (quantised, like the rig/factory buffers above), so the ON/OFF// label and the burning/stalled note stay live without a per-tick rebuild.+ "|" + (() => {const f = game.galaxy && sel.find(e => e.kind === "unit" && UNITS[e.type].cargoHold);return f ? `${!!f.aiLogistics}:${Math.round(state.players.player.resources.ai || 0)}` : "";})()// Rebuild a selected Plasma Rig's status as it digs — its progress, last strike (each dig// increments digCount), and its power/nuclear situation — without a per-tick rebuild.+ "|" + (() => {238 unmodified lines}}// A freighter's AI-LOGISTICS toggle: once FREIGHTER_AI_TECH is researched (a Datacenter node —// engine/techtree.js), fold it into the local haul/service chain like a worker (engine/sim.js// updateUnit), at its own cargoHold-sized capacity per trip — routed through issueSetAILogistics// (engine/commands.js) rather than a bare direct mutation (the Mender/Bomb toggles' usual idiom)// because turning it ON has to re-check the research gate.function renderAILogistics(state, f) {const upgrades = state.players.player.upgrades;if (!upgrades[FREIGHTER_AI_TECH]) {const hint = document.createElement("p");hint.className = "hint";hint.textContent = "Research Autonomous Freight AI at a Datacenter to fold this ship into your local logistics chain like a worker.";panelEl.appendChild(hint);return;}const on = !!f.aiLogistics;panelEl.appendChild(makeButton(on ? "🤖 AI Logistics: ON" : "🤖 AI Logistics: OFF",() => { issueSetAILogistics([f], !on, state); renderHUD(); },{ tip: on ? "Stand down — it stops auto-hauling and waits for your orders": `Put it to work in the local haul/service chain like a worker, at its full ${UNITS[f.type].cargoHold} cargo hold per trip` }));if (on) {const res = state.players.player.resources;const rate = aiUpkeepRate(f);const stalled = (res.ai || 0) <= 1e-6;const row = document.createElement("div");row.className = "sel-note " + (stalled ? "bad" : "good");row.textContent = stalled? `⚠ STALLED — out of AI Cores (burns ${rate.toFixed(2)}/s while active)`: `Autonomous — burning ${rate.toFixed(2)} AI Cores/s (${Math.floor(res.ai || 0)} in reserve)`;panelEl.appendChild(row);}}// Why a selected factory is (or isn't) producing — the answer to "my antimatter// isn't going up." Checks the same limits updateProduction (engine/industry.js)// applies, in priority order: no Power at all, then a missing input, then a Power561 unmodified linestip: "Settle: the colony ship becomes a Command Center on this spot (it can't move again). Colonists disembark as workers." }));}// Freighter (Odyssey cargo ship): a load/unload cargo panel for the first one selected, plus its// AI-logistics toggle once FREIGHTER_AI_TECH is researched.const freighter = game.galaxy && sel.find(e => e.kind === "unit" && UNITS[e.type].cargoHold);if (freighter) { renderFreight(state, freighter); renderAILogistics(state, freighter); }// Mender: an auto-repair toggle (roam and mend on its own) + its Odyssey power state (it heals at// full rate only on the powered grid, near a Reactor/Generator).
8 unmodified lines9101112131415226 unmodified lines2422432442452462478 unmodified lines"use strict";import { game } from "./session.js";import { issueMove, issueGather, issueAttack, issueAttackMove, issueBuild, issueAssistBuild, issueSetRally, issueStop, issueScout, issueHold, issueEscort, issueServiceBuilding, issueHoldFormation } from "./engine/commands.js";import { UNITS, BUILDINGS, storeCapOf } from "./engine/entities.js";import { recipeOf } from "./engine/industry.js";import { isVisibleAt, isNodeDiscovered } from "./engine/fog.js";226 unmodified linesif (attackers.length) { issueAttack(attackers, target.id, queue); sound.playOrder(); onChange(); }return;}// A friendly SHIP as the target: the selection forms a protective escort ring around it and// follows it wherever it's ordered (engine/commands.js issueEscort). The target itself is// excluded, so right-clicking a ship that's part of the selection escorts it with the rest.8 unmodified lines9101112131415226 unmodified lines2422432442452462472482492502512522532542552568 unmodified lines"use strict";import { game } from "./session.js";import { issueMove, issueGather, issueAttack, issueAttackMove, issueBuild, issueAssistBuild, issueSetRally, issueStop, issueScout, issueHold, issueEscort, issueServiceBuilding, issueFerryFreighter, issueHoldFormation } from "./engine/commands.js";import { UNITS, BUILDINGS, storeCapOf } from "./engine/entities.js";import { recipeOf } from "./engine/industry.js";import { isVisibleAt, isNodeDiscovered } from "./engine/fog.js";226 unmodified linesif (attackers.length) { issueAttack(attackers, target.id, queue); sound.playOrder(); onChange(); }return;}// A friendly, landed FREIGHTER as the target: selected WORKERS are assigned to FERRY it — carry// nearby producer backlog onto its hold (engine/haul.js updateFerry), so it becomes its own// mobile collection point — instead of escorting it. Any non-worker selection (or a selection// with no workers at all) falls through to the general friendly-ship escort branch below, so// e.g. combat ships still escort a freighter through hostile space.if (target && target.owner === "player" && target.kind === "unit" && UNITS[target.type]?.role === "freighter") {const workers = selected.filter(u => UNITS[u.type]?.role === "worker");if (workers.length) { issueFerryFreighter(workers, target.id, queue); sound.playOrder(); onChange(); return; }}// A friendly SHIP as the target: the selection forms a protective escort ring around it and// follows it wherever it's ordered (engine/commands.js issueEscort). The target itself is// excluded, so right-clicking a ship that's part of the selection escorts it with the rest.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297import { test } from "node:test";import assert from "node:assert/strict";import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";import { tick } from "../engine/sim.js";import { updateFerry, updateHaul, countLogistics, assignHaul, FREIGHTER_AI_TECH, aiUpkeepRate, payAIUpkeep } from "../engine/haul.js";import { issueFerryFreighter, issueSetAILogistics } from "../engine/commands.js";import { storeTotal, freightUsed, freightRoom } from "../engine/entities.js";import { TECHS } from "../engine/techtree.js";import { serializeGame, deserializeGame } from "../engine/persist.js";import { mulberry32 } from "./_helpers.js";
const near = (a, b, eps = 1e-3) => Math.abs(a - b) < eps;
// A skirmish world seeds a finished Command Center + 3 workers, same fixture as test/haul.test.js.function base(seed = 1) { const s = createGameState({ planetId: "ferros", rng: mulberry32(seed) }); const cc = [...s.buildings.values()].find(b => b.owner === "player" && b.type === "command"); const workers = [...s.units.values()].filter(u => u.owner === "player" && u.type === "worker"); return { s, cc, workers };}// A player Plasma Rig, pre-loaded with `store` and paused (don't dig — isolate the ferry/haul logic).function plantRig(s, cc, store, dx = 50, dy = 0) { const rig = makeBuilding("plasmarig", "player", cc.x + dx, cc.y + dy); rig.store = { ...store }; rig.paused = true; s.buildings.set(rig.id, rig); return rig;}function plantFreighter(s, type, x, y) { const f = makeUnit(type, "player", x, y); s.units.set(f.id, f); return f;}// Strip the seeded 3 idle workers so a freighter's own auto-logistics is the ONLY labour in// play — otherwise a worker (also idle, also eligible) can beat the freighter to a nearby backlog// and the test would stop proving what it claims to.function removeSeededWorkers(s, workers) { for (const w of workers) s.units.delete(w.id);}
// ---- FERRY: workers physically load/unload a landed freighter ------------------------------
test("a ferry worker carries a producer's backlog straight onto the assigned freighter's hold", () => { const { s, cc, workers } = base(1); const rig = plantRig(s, cc, { ore: 60 }); const f = plantFreighter(s, "hauler", cc.x - 60, cc.y); const w = workers[0]; w.x = f.x; w.y = f.y; w.order = { type: "ferry", freighterId: f.id, phase: "plan", manual: true }; const oreBefore = s.players.player.resources.ore || 0; // the skirmish seed starts with 300 ore
// countLogistics resets/re-tallies the per-producer hauler cap each tick in the real sim loop // (engine/sim.js) — replicated here since this test drives updateFerry directly rather than // through tick(), and the "claim a slot for the tick" bump in the "plan" phase relies on that // periodic reset (otherwise repeat visits to the SAME producer across many calls would just keep // incrementing a count nothing ever brings back down). for (let i = 0; i < 8000 && (storeTotal(rig) > 0 || (w.cargo && w.cargo.qty > 0)); i++) { countLogistics(s); updateFerry(s, w, 0.05); }
assert.equal(storeTotal(rig), 0, "the rig's whole buffer was carried away"); assert.equal(freightUsed(f), 60, "…and all 60 landed on the freighter's hold"); assert.equal(s.players.player.resources.ore || 0, oreBefore, "the treasury's own ore never moved — it went straight into the ship");});
test("issueFerryFreighter assigns the order (workers only), and freightRoom bounds what fits", () => { const { s, workers } = base(2); const f = plantFreighter(s, "hauler", 0, 0); const ranger = makeUnit("ranger", "player", 0, 0); s.units.set(ranger.id, ranger);
issueFerryFreighter([workers[0], ranger], f.id);
assert.equal(workers[0].order.type, "ferry", "the worker is assigned"); assert.equal(workers[0].order.freighterId, f.id); assert.equal(ranger.order, null, "a non-worker is ignored — ferrying is worker labour, not any unit's"); assert.equal(freightRoom(f), 250, "an empty Hauler's room is its whole cargoHold");});
test("with nothing left to load, a ferry worker instead drains the freighter's hold home", () => { const { s, cc, workers } = base(3); const f = plantFreighter(s, "hauler", cc.x + 60, cc.y); f.freight = { alloys: 40 }; const w = workers[0]; w.x = f.x; w.y = f.y; w.order = { type: "ferry", freighterId: f.id, phase: "plan", manual: true };
for (let i = 0; i < 8000 && (freightUsed(f) > 0 || (w.cargo && w.cargo.qty > 0)); i++) updateFerry(s, w, 0.05);
assert.equal(freightUsed(f), 0, "the hold was fully drawn down"); assert.ok((s.players.player.resources.alloys || 0) >= 40 - 1e-6, "…and banked into the treasury");});
test("a ferry job releases a razed/jumped-away freighter gracefully, salvaging any cargo aboard", () => { const { s, cc, workers } = base(4); const f = plantFreighter(s, "hauler", cc.x + 40, cc.y); const w = workers[0]; w.x = f.x; w.y = f.y; w.cargo = { com: "ore", qty: 25 }; w.order = { type: "ferry", freighterId: f.id, phase: "toFreighter", manual: true };
s.units.delete(f.id); // the freighter is gone (razed, or jumped to another world) for (let i = 0; i < 8000 && w.order; i++) updateFerry(s, w, 0.05);
assert.equal(w.order, null, "the job ends once there's nothing left to carry"); assert.ok((s.players.player.resources.ore || 0) >= 25 - 1e-6, "…but the cargo it was carrying still made it to the treasury");});
test("a FERRY worker's producer visit counts against the same per-producer hauler cap as a HAUL worker", () => { const { s, cc } = base(5); const rig = plantRig(s, cc, { ore: 120 }); // a full buffer → maximum pull const f = plantFreighter(s, "hauler", cc.x - 80, cc.y); // Pile candidates for BOTH job types right on the rig, so every one is a candidate this tick. const haulers = []; for (let i = 0; i < 4; i++) { const w = makeUnit("worker", "player", rig.x, rig.y); s.units.set(w.id, w); haulers.push(w); } const ferriers = []; for (let i = 0; i < 4; i++) { const w = makeUnit("worker", "player", rig.x, rig.y); s.units.set(w.id, w); ferriers.push(w); } countLogistics(s); for (const w of haulers) assignHaul(s, w); for (const w of ferriers) { w.order = { type: "ferry", freighterId: f.id, phase: "plan", manual: true }; updateFerry(s, w, 0); }
const onRig = [...s.units.values()].filter(u => (u.order?.type === "haul" && u.order.buildingId === rig.id) || (u.order?.type === "ferry" && u.order.buildingId === rig.id)).length; assert.ok(onRig <= 2, `at most 2 workers (of either job) draw from one producer at once (got ${onRig})`);});
// ---- FREIGHTER AI-LOGISTICS: an autonomous freighter folded into the haul/service chain -----
test("the freighterai tech id matches FREIGHTER_AI_TECH and requires AI Cores + the aicores tech", () => { assert.ok(TECHS[FREIGHTER_AI_TECH], "the tech tree carries a node under the exact id haul.js references"); assert.ok(TECHS[FREIGHTER_AI_TECH].cost.ai > 0, "researching it costs AI Cores — automation is built FROM the good it burns"); assert.ok(TECHS[FREIGHTER_AI_TECH].requires.includes("aicores"), "gated behind having unlocked AI Cores production");});
test("issueSetAILogistics won't switch a freighter on without the research, but always allows standing down", () => { const { s } = base(6); const f = plantFreighter(s, "hauler", 0, 0);
issueSetAILogistics([f], true, s); assert.equal(!!f.aiLogistics, false, "no FREIGHTER_AI_TECH researched yet — the toggle is refused");
s.players.player.upgrades[FREIGHTER_AI_TECH] = true; issueSetAILogistics([f], true, s); assert.equal(f.aiLogistics, true, "researched — now it can be switched on"); assert.deepEqual(f.cargo, { com: null, qty: 0 }, "a single-slot cargo hold is created for the haul/service chain to use");
issueSetAILogistics([f], false, s); assert.equal(f.aiLogistics, false, "standing down is never gated");});
test("without aiLogistics toggled on, an idle freighter is never auto-assigned a haul/service job", () => { const { s, cc, workers } = base(7); removeSeededWorkers(s, workers); plantRig(s, cc, { ore: 100 }); const f = plantFreighter(s, "hauler", cc.x + 45, cc.y); // right next to the backed-up rig s.players.player.upgrades[FREIGHTER_AI_TECH] = true; // researched, but never switched on
for (let i = 0; i < 300; i++) tick(s, 0.1);
assert.equal(f.order, null, "a plain freighter stays fully player-controlled");});
test("an AI-logistics freighter auto-hauls a producer's backlog at its OWN (far larger) capacity, burning AI Cores while it works", () => { const { s, cc, workers } = base(8); removeSeededWorkers(s, workers); const rig = plantRig(s, cc, { ore: 100 }); const f = plantFreighter(s, "hauler", cc.x + 45, cc.y); s.players.player.upgrades[FREIGHTER_AI_TECH] = true; issueSetAILogistics([f], true, s); s.players.player.resources.ai = 500; const aiBefore = s.players.player.resources.ai; const oreBefore = s.players.player.resources.ore || 0; // the skirmish seed starts with 300 ore
for (let i = 0; i < 1500; i++) tick(s, 0.1);
assert.equal(storeTotal(rig), 0, "the freighter alone cleared the whole 100-ore buffer"); assert.ok(near((s.players.player.resources.ore || 0) - oreBefore, 100, 1e-3), "…and banked it to the treasury, just like a worker's haul"); assert.ok((s.players.player.resources.ai || 0) < aiBefore, "running autonomously burned AI Cores from the treasury");});
test("a freighter's single-trip haul capacity is its own cargoHold — a 100-unit backlog moves in one load, not ten", () => { const { s, cc } = base(9); const rig = plantRig(s, cc, { ore: 100 }); // well under the Hauler's 250 hold const f = plantFreighter(s, "hauler", rig.x, rig.y); f.cargo = { com: null, qty: 0 }; f.order = { type: "haul", buildingId: rig.id, phase: "toSource" };
updateHaul(s, f, 0.05); // "toSource": already reached → flips to "loading" updateHaul(s, f, 0.05); // "loading": one load, capped by tripCapacity (its own cargoHold)
assert.equal(f.cargo.qty, 100, "the WHOLE 100-ore backlog fit in a single load — a worker (cargoCap 10) would need ten trips"); assert.equal(storeTotal(rig), 0, "…draining the rig's buffer in one visit");});
test("toggling AI logistics off mid-job stands the freighter down immediately, without losing its cargo", () => { const { s, cc } = base(10); const f = plantFreighter(s, "hauler", cc.x, cc.y); s.players.player.upgrades[FREIGHTER_AI_TECH] = true; f.aiLogistics = true; f.cargo = { com: "ore", qty: 40 }; f.order = { type: "haul", buildingId: null, phase: "toDrop", aiJob: true };
f.aiLogistics = false; tick(s, 0.1);
assert.equal(f.order, null, "the job is dropped the instant AI-logistics is switched off"); assert.deepEqual(f.cargo, { com: "ore", qty: 40 }, "…but whatever it was carrying just sits aboard, nothing lost");});
test("an autonomous freighter pauses in place (job + cargo intact) when the treasury runs dry of AI Cores, and resumes once resupplied", () => { const { s, cc, workers } = base(11); removeSeededWorkers(s, workers); const rig = plantRig(s, cc, { ore: 100 }); const f = plantFreighter(s, "hauler", cc.x + 200, cc.y); // far from the rig — several ticks of walking ahead s.players.player.upgrades[FREIGHTER_AI_TECH] = true; issueSetAILogistics([f], true, s); s.players.player.resources.ai = 0; // dry from the start
const x0 = f.x, y0 = f.y; for (let i = 0; i < 50; i++) tick(s, 0.1); assert.equal(f.x, x0, "no AI Cores in stock → it never even starts moving"); assert.equal(f.y, y0); assert.equal(f.order, null, "…and never claims a job it can't afford to run, so nothing is stuck mid-plan");
s.players.player.resources.ai = 500; // resupplied for (let i = 0; i < 1500; i++) tick(s, 0.1); assert.equal(storeTotal(rig), 0, "now it goes to work and clears the backlog");});
test("AI-logistics haulage is deterministic: two same-seed runs bank identical treasuries and spend identical AI Cores", () => { const run = () => { const { s, cc, workers } = base(12); removeSeededWorkers(s, workers); plantRig(s, cc, { ore: 90, crystals: 30 }); const f = plantFreighter(s, "hauler", cc.x + 45, cc.y); s.players.player.upgrades[FREIGHTER_AI_TECH] = true; issueSetAILogistics([f], true, s); s.players.player.resources.ai = 500; for (let i = 0; i < 1500; i++) tick(s, 0.1); return { ore: s.players.player.resources.ore || 0, crystals: s.players.player.resources.crystals || 0, ai: s.players.player.resources.ai || 0, }; }; assert.deepEqual(run(), run());});
test("a freighter's aiLogistics flag, an in-progress aiJob haul order, and a worker's ferry order all survive a save/load round-trip", () => { const { s, cc, workers } = base(14); const rig = plantRig(s, cc, { ore: 80 }); const f = plantFreighter(s, "hauler", cc.x + 45, cc.y); s.players.player.upgrades[FREIGHTER_AI_TECH] = true; issueSetAILogistics([f], true, s); s.players.player.resources.ai = 500;
const ferryTarget = plantFreighter(s, "heavyhauler", cc.x - 80, cc.y); const w = workers[1]; removeSeededWorkers(s, [workers[0], workers[2]]); // isolate: only the freighter and w compete for the rig issueFerryFreighter([w], ferryTarget.id);
// Just ONE tick: rig and CC both sit within the freighter's own REACH of its start position, and // its 250-cargoHold trip capacity clears the whole 80-ore buffer in a single load — so it's // already mid-job (and would FINISH within a handful more ticks) rather than needing to travel. tick(s, 0.1); assert.equal(f.order?.aiJob, true, "sanity: the freighter is mid-job before we save");
const b = deserializeGame(JSON.parse(JSON.stringify(serializeGame(s)))); const f2 = b.units.get(f.id), w2 = b.units.get(w.id);
assert.equal(f2.aiLogistics, true, "the AI-logistics toggle survives"); assert.equal(f2.order?.type, "haul", "…and its in-progress autonomous job survives"); assert.equal(f2.order?.aiJob, true); assert.equal(w2.order?.type, "ferry", "the worker's ferry assignment survives too"); assert.equal(w2.order?.freighterId, ferryTarget.id);
// And the reloaded game keeps working exactly as before: the freighter finishes the haul it was // mid-way through when the save was taken. for (let i = 0; i < 1500; i++) tick(b, 0.1); assert.equal(storeTotal(b.buildings.get(rig.id)), 0, "the reloaded freighter completes the haul");});
test("payAIUpkeep is a no-op (always succeeds) for a non-freighter unit — cargoHold-scaled, zero for anything without one", () => { const { s, workers } = base(13); const before = s.players.player.resources.ai || 0; assert.equal(payAIUpkeep(s, workers[0], 1), true, "a worker has no cargoHold, so its upkeep rate is zero"); assert.equal(s.players.player.resources.ai || 0, before, "…and nothing was charged"); assert.equal(aiUpkeepRate(workers[0]), 0); assert.ok(aiUpkeepRate({ type: "hauler" }) > 0, "a freighter's rate scales with its own cargoHold");});docs/logistics-design.md+56-6
engine/commands.js+27
engine/entities.js+16
engine/galaxy.js+6-13
engine/haul.js+182-21
engine/sim.js+29-2
engine/techtree.js+7
engine/types.js+4-1
hudSelection.js+44-2
input.js+10-1
test/ferry.test.jsAdded+297