From b38d5d4b569f8b87030ad9b32a0fce6a677a286d Mon Sep 17 00:00:00 2001 From: Dejvino Date: Sun, 15 Nov 2026 18:21:35 +0100 Subject: [PATCH] Extract map-specific data into a generic MapSource interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One interface (nd_mapsource.h) now owns everything map-specific: tiles, rooms/doors/cameras, the network graph (nodes + edges with roles replacing the hardcoded N_AIRLK/N_DOOR/N_HIVE indices) and the entity spawn list. The scenario populates its structures once via selectMap() and never checks which map is active. - DemoMapSource: self-contained demo grid (moved out of the sketch), demo node/edge/spawn tables - GenMapSource: adapts the random MapGenerator — now with L-corridors for guaranteed connectivity, doors that lead somewhere, airlock pad, terminal and crates (never on corridor tiles); network graph derived from the room chain, marine-first spawn list with droid patrols - NetDeck.ino: all source branching removed; red trace follows the real active-link path (BFS HIVE->ROOT); reinforcement spawns near the blast door - Tests: MapTest validates 50 generated runs + demo via the interface with an airlock flood-fill; new generated-map integration journey; test node handles resolve through the source (no hardcoded indices) --- emulator/tests/e2e_tests.cpp | 2 +- emulator/tests/integration_tests.h | 47 ++- emulator/tests/sim_helpers.h | 20 ++ emulator/tests/unit_tests.h | 6 +- src/netdeck/MapTest.cpp | 146 ++++++++ src/netdeck/NetDeck.ino | 362 ++++++++++--------- src/netdeck/STATUS.md | 48 +++ src/netdeck/nd_demomap.h | 160 +++++++++ src/netdeck/nd_mapgen.h | 540 +++++++++++++++++++++++++++++ src/netdeck/nd_mapsource.h | 137 ++++++++ 10 files changed, 1296 insertions(+), 172 deletions(-) create mode 100644 src/netdeck/MapTest.cpp create mode 100644 src/netdeck/nd_demomap.h create mode 100644 src/netdeck/nd_mapgen.h create mode 100644 src/netdeck/nd_mapsource.h diff --git a/emulator/tests/e2e_tests.cpp b/emulator/tests/e2e_tests.cpp index b74277d..bf340c7 100644 --- a/emulator/tests/e2e_tests.cpp +++ b/emulator/tests/e2e_tests.cpp @@ -154,7 +154,7 @@ TEST(e2e/network_journey) EXPECT(pumpUntil(30.0, spikeSeen)); // ... trace ... feedback spike EXPECT(test::serialHas("[spawn] reinforcement droid")); stepTicks(1); - EXPECT(units[7].alive); + EXPECT(units[g_reinforceIdx].alive); EXPECT(heatT > 0); // OVERHEAT lockout engaged } diff --git a/emulator/tests/integration_tests.h b/emulator/tests/integration_tests.h index 98088ff..b7e2a0a 100644 --- a/emulator/tests/integration_tests.h +++ b/emulator/tests/integration_tests.h @@ -73,7 +73,7 @@ TEST(integration/full_network_journey) EXPECT(traceActive); stepTicks(TRACE_TICKS); EXPECT(heatT > 0); // feedback spike cooldown - EXPECT(units[7].alive); // reinforcement spawned + EXPECT(units[g_reinforceIdx].alive); // reinforcement spawned EXPECT(!nodeOnline[N_JUNC]); // spike dropped the net } @@ -105,7 +105,7 @@ TEST(integration/sever_during_trace_is_safe) handleKey('x'); // sever before arrival EXPECT(!traceActive); // trace reset safely EXPECT_EQ(heatT, 0); // no feedback spike - EXPECT(!units[7].alive); // no reinforcement + EXPECT(!units[g_reinforceIdx].alive); // no reinforcement } TEST(integration/daemon_gating_messages) @@ -120,3 +120,46 @@ TEST(integration/daemon_gating_messages) EXPECT_EQ(strcmp(msgText, "FRENZY ACTIVE"), 0); // FRENZY effect lands in M4 EXPECT(test::serialHas("[key] frenzy")); } + +TEST(integration/generated_map_source_journey) +{ + // Switch to the random generator: the SAME scenario code (spawns, node + // roles, link routing, fog) must drive it with no map-source checks. + // The generator is seedless by design (random_device); assertions are + // therefore structural — layout invariants are fuzz-covered by + // src/netdeck/MapTest.cpp. + selectMap(false); + EXPECT(g_map == &g_genSource); + EXPECT(ROOT_NODE >= 0 && HIVE_NODE >= 0 && DOOR_NODE >= 0); + EXPECT(TERM_TX >= 0 && AIRLOCK_TX >= 0); // terminal + airlock found + EXPECT(g_map->spawnCount() >= 2); + EXPECT(g_map->spawnCount() < nd::MAX_UNITS); // reinforcement slot exists + + resetScenario(); + EXPECT(units[0].alive && units[1].alive); // marines come from the spawn list + EXPECT(nodeOnline[ROOT_NODE]); // root up after reset + EXPECT(!nodeOnline[HIVE_NODE]); + + // route a link from the root to any adjacent offline node (source-agnostic) + // (the previous test may leave either view; make the mode explicit) + viewMode = VM_NETWORK; + int target = -1; + for (int e = 0; e < edgeCount() && target < 0; e++) { + int a = g_map->edge(e).a, b = g_map->edge(e).b; + if (a == ROOT_NODE && !nodeOnline[b]) target = b; + if (b == ROOT_NODE && !nodeOnline[a]) target = a; + } + EXPECT(target >= 0); + clickNode(target); + stepTicks(ICE_TICKS); // covers plain + ICE durations + EXPECT(nodeOnline[target]); // link built on a generated map + stepTicks(60); // combat/fog run a while: no crash + for (int i = 0; i < g_map->spawnCount(); i++) + EXPECT(units[i].alive || true); // slots exist (alive or KIA) + + // back to the demo map — the other tests expect it + selectMap(true); + resetScenario(); + EXPECT(nodeOnline[ROOT_NODE]); + EXPECT_EQ(nd::DEMO_MAP[7][34], 'T'); +} diff --git a/emulator/tests/sim_helpers.h b/emulator/tests/sim_helpers.h index 6ad7ec5..a8c8d1b 100644 --- a/emulator/tests/sim_helpers.h +++ b/emulator/tests/sim_helpers.h @@ -32,6 +32,26 @@ inline void clickTile(int tx, int ty) // find the active link on an edge, or -1 inline int linkIdx(int edge) { return linkOnEdge(edge); } +// --------------------------------------------------------------------------- +// Node handles resolved from the ACTIVE MAP SOURCE. The old tests hardcoded +// demo node indices (N_AIRLK/N_JUNC/...); the map source now owns the node +// tables, so the tests resolve through the same generic interface the sketch +// uses. (The fast suites run the demo map, where these are the classic nodes.) +// --------------------------------------------------------------------------- +inline int nodeByLabel(const char *label) +{ + for (int i = 0; i < nodeCount(); i++) + if (strcmp(g_map->node(i).label, label) == 0) return i; + return -1; +} +#define N_AIRLK ROOT_NODE +#define N_DOOR DOOR_NODE +#define N_HIVE HIVE_NODE +#define N_JUNC nodeByLabel("JUNC") +#define N_CAM1 nodeByLabel("CAM1") +#define N_CAM2 nodeByLabel("CAM2") +#define N_CAM3 nodeByLabel("CAM3") + // fresh deterministic scenario state for a test inline void freshScenario(unsigned seed = 0xC0FFEE) { diff --git a/emulator/tests/unit_tests.h b/emulator/tests/unit_tests.h index 69e5929..68a88bb 100644 --- a/emulator/tests/unit_tests.h +++ b/emulator/tests/unit_tests.h @@ -23,7 +23,7 @@ TEST(unit/map_queries) EXPECT(walkable(34, 7)); // objective terminal 'T' EXPECT(blocksSight(0, 0)); EXPECT(!blocksSight(20, 12)); - EXPECT_EQ(DEMO_MAP[7][34], 'T'); // the win tile really is T + EXPECT_EQ(nd::DEMO_MAP[7][34], 'T'); // the win tile really is T } TEST(unit/door_gates_movement_and_sight) @@ -158,7 +158,7 @@ TEST(unit/ice_trace_feedback_reinforcement) EXPECT(linkIdx(0) < 0 && linkIdx(1) < 0 && linkIdx(2) < 0); EXPECT(!nodeOnline[N_JUNC]); // everything past root drops EXPECT(nodeOnline[N_AIRLK]); - EXPECT(units[7].alive); // reinforcement droid spawned + EXPECT(units[g_reinforceIdx].alive); // reinforcement droid spawned } TEST(unit/overheat_gates_daemons_and_sever) @@ -215,7 +215,7 @@ TEST(unit/reset_rearms_everything) EXPECT(units[0].alive && units[1].alive); EXPECT_EQ(units[0].tx, 2); // back in the airlock EXPECT_EQ(units[0].hp, STATS[U_MARINE].maxHp); - EXPECT(!units[7].alive); // reinforcement slot cleared + EXPECT(!units[g_reinforceIdx].alive); // reinforcement slot cleared EXPECT(!doorOpen); EXPECT_EQ(heatT, 0); EXPECT(linkIdx(0) < 0 && linkIdx(1) < 0 && linkIdx(2) < 0); diff --git a/src/netdeck/MapTest.cpp b/src/netdeck/MapTest.cpp new file mode 100644 index 0000000..5b9cf2f --- /dev/null +++ b/src/netdeck/MapTest.cpp @@ -0,0 +1,146 @@ +// Minimal test for the map sources (nd_mapsource.h / nd_mapgen.h) +// Validates the generated map and the generic MapSource interface. + +#include "nd_mapgen.h" +#include "nd_demomap.h" + +static bool allPass = true; + +static void check(const char *name, bool ok) { + printf("%-42s %s\n", name, ok ? "PASS" : "FAIL"); + if (!ok) allPass = false; +} + +// every node reachable from the root over the edge list? +static bool graphConnected(const nd::MapSource &m) { + int n = m.nodeCount(); + int root = m.rootNode(); + if (n <= 0 || root < 0) return false; + bool seen[nd::MAX_NODES] = {}; + int queue[nd::MAX_NODES], qh = 0, qt = 0; + queue[qt++] = root; + seen[root] = true; + while (qh < qt) { + int cur = queue[qh++]; + for (int e = 0; e < m.edgeCount(); e++) { + int a = m.edge(e).a, b = m.edge(e).b; + int nbr = (a == cur) ? b : (b == cur) ? a : -1; + if (nbr < 0 || seen[nbr]) continue; + seen[nbr] = true; + queue[qt++] = nbr; + } + } + for (int i = 0; i < n; i++) + if (!seen[i]) return false; + return true; +} + +// walkable flood fill from the airlock ('+' doors treated as open): +// the terminal and every entity spawn must be reachable on foot +static bool tilesConnected(const nd::MapSource &m) { + static bool seen[nd::TILE_COLS * nd::TILE_ROWS]; + for (int i = 0; i < nd::TILE_COLS * nd::TILE_ROWS; i++) seen[i] = false; + int ax, ay; + if (!m.findTile('A', ax, ay)) return false; + int queue[nd::TILE_COLS * nd::TILE_ROWS], qh = 0, qt = 0; + queue[qt++] = ay * nd::TILE_COLS + ax; + seen[queue[0]] = true; + while (qh < qt) { + int cur = queue[qh++]; + int cx = cur % nd::TILE_COLS, cy = cur / nd::TILE_COLS; + static const int DX[4] = { 1, -1, 0, 0 }; + static const int DY[4] = { 0, 0, 1, -1 }; + for (int d = 0; d < 4; d++) { + int nx = cx + DX[d], ny = cy + DY[d]; + if (nx < 0 || ny < 0 || nx >= nd::TILE_COLS || ny >= nd::TILE_ROWS) continue; + char t = m.tileAt(nx, ny); + bool pass = (t == '.' || t == 'A' || t == 'T' || t == '+'); + if (!pass || seen[ny * nd::TILE_COLS + nx]) continue; + seen[ny * nd::TILE_COLS + nx] = true; + queue[qt++] = ny * nd::TILE_COLS + nx; + } + } + int tx, ty; + if (!m.findTile('T', tx, ty) || !seen[ty * nd::TILE_COLS + tx]) return false; + for (int s = 0; s < m.spawnCount(); s++) { + const nd::UnitSpawn &sp = m.spawn(s); + if (!seen[sp.ty * nd::TILE_COLS + sp.tx]) return false; + } + return true; +} + +static void testGeneratedSource(int seed) { + nd::MapGenerator gen; + nd::GenMapSource src(gen); + src.generate(); + + char title[64]; + printf("--- generated map (run %d) ---\n", seed); + + // structural tiles exist + int tx, ty; + snprintf(title, sizeof(title), "airlock + terminal tiles present"); + check(title, src.findTile('A', tx, ty) && src.findTile('T', tx, ty)); + + // room count (4-6) + snprintf(title, sizeof(title), "room count 4-6 (got %zu)", + src.getRooms().size()); + check(title, src.getRooms().size() >= 4 && src.getRooms().size() <= 6); + + // marines: spawns 0/1 must be marines (the squad) + check("spawns 0/1 are marines", + src.spawnCount() >= 2 && + src.spawn(0).kind == 0 && src.spawn(1).kind == 0); + + // spawn budget: leaves room for the reinforcement droid + snprintf(title, sizeof(title), "spawn count %d <= MAX_UNITS-1", src.spawnCount()); + check(title, src.spawnCount() > 0 && src.spawnCount() < nd::MAX_UNITS); + + // roles present + check("root/hive/door nodes present", + src.rootNode() >= 0 && src.hiveNode() >= 0 && src.doorNode() >= 0); + + // node node(0) is the online root + check("root node online", src.node(src.rootNode()).online); + + // network graph connected + check("network graph connected from root", graphConnected(src)); + + // physical walkability: terminal + all spawns reachable from the airlock + check("tiles connected (airlock flood)", tilesConnected(src)); + + // node/edge pools within bounds + snprintf(title, sizeof(title), "nodes %d<=%d, edges %d<=%d", + src.nodeCount(), nd::MAX_NODES, src.edgeCount(), nd::MAX_EDGES); + check(title, src.nodeCount() <= nd::MAX_NODES && src.edgeCount() <= nd::MAX_EDGES); +} + +static void testDemoSource() { + printf("--- demo map ---\n"); + nd::DemoMapSource demo; + + check("demo terminal tile at (34,7)", demo.tileAt(34, 7) == 'T'); + check("demo airlock tile at (2,21)", demo.tileAt(2, 21) == 'A'); + check("demo blast door at (28,12)", demo.tileAt(28, 12) == '+'); + check("demo node count 7", demo.nodeCount() == 7); + check("demo roles root/door/hive", + demo.rootNode() == 0 && demo.doorNode() == 2 && demo.hiveNode() == 3); + check("demo spawns 11, marines first", + demo.spawnCount() == 11 && demo.spawn(0).kind == 0 && demo.spawn(1).kind == 0); + check("demo patrol endpoints set", demo.spawn(2).patA >= 0 && demo.spawn(2).patB >= 0); + check("demo graph connected", graphConnected(demo)); + check("demo tiles connected (airlock flood)", tilesConnected(demo)); +} + +int main() { + for (int i = 0; i < 50; i++) testGeneratedSource(i); + testDemoSource(); + + printf("\n"); + if (allPass) { + printf("ALL TESTS PASSED\n"); + return 0; + } + printf("SOME TESTS FAILED\n"); + return 1; +} diff --git a/src/netdeck/NetDeck.ino b/src/netdeck/NetDeck.ino index 62ac34c..b8b7435 100644 --- a/src/netdeck/NetDeck.ino +++ b/src/netdeck/NetDeck.ino @@ -45,6 +45,8 @@ #include "utilities.h" #include "TouchDrvGT911.hpp" #include "nd_layout.h" +#include "nd_demomap.h" +#include "nd_mapgen.h" #include "sound_engine.h" // --------------------------------------------------------------------------- @@ -92,47 +94,53 @@ static uint32_t simAcc = 0; static uint32_t lastFrameMs = 0; // --------------------------------------------------------------------------- -// Floorplan (MVP.md §1): 40x24 tiles, 3 rooms -// '#' wall '.' floor 'o' cover crate '+' blast door 'A' airlock 'T' terminal -// Room 1 airlock (bottom-left), Room 2 main corridor (L-shaped middle), -// Room 3 server room (right). The '+' door is the Room2/Room3 blast door. +// Map source: everything map-specific comes from one MapSource interface +// (nd_mapsource.h). The scenario populates its structures from the source +// exactly once (selectMap) and afterwards never checks which map is active — +// the demo floorplan and the random MapGenerator are interchangeable. // --------------------------------------------------------------------------- -static const char *const DEMO_MAP[nd::TILE_ROWS] = { - "########################################", - "#.........#.................#..........#", - "#.........#......#..........#..........#", - "#...#.....#......#..........#.....o....#", - "#....o....#......#..........#..........#", - "#...#.....#......#..........#..........#", - "#.........#.................#..........#", - "#.........#.................#.....T....#", - "#...........................#..........#", - "#...........................#..........#", - "#.........#...#.....o.......#..........#", - "#.........#...#.............#..........#", - "#.........#.................+..........#", - "###########.................#..........#", - "#.........#.................#..........#", - "#....#....#...........o.....#....#.....#", - "#.........#.................#..........#", - "#...........................#..........#", - "#...........................#..........#", - "#.........#.....#...........#..........#", - "#.........#.....#...........#.....o....#", - "#.A.......#.................#..........#", - "#.........#.................#..........#", - "########################################", -}; +static nd::DemoMapSource g_demoSource; +static nd::MapGenerator g_mapGenerator; +static nd::GenMapSource g_genSource(g_mapGenerator); +static nd::MapSource *g_map = &g_demoSource; // active map source +static bool g_mapSelected = false; -static const int DOOR_TX = 28, DOOR_TY = 12; // the Room2/Room3 blast door -static const int AIRLOCK_TX = 2, AIRLOCK_TY = 21; +// map-anchored specials + node roles + free unit slot — filled by selectMap() +static int AIRLOCK_TX = -1, AIRLOCK_TY = -1; // 'A' airlock pad +static int TERM_TX = -1, TERM_TY = -1; // 'T' objective terminal +static int ROOT_NODE = -1; // always-online uplink node +static int HIVE_NODE = -1; // ICE-protected hive node +static int DOOR_NODE = -1; // blast-door control node +static int g_reinforceIdx = -1; // reinforcement droid unit slot static bool doorOpen = false; +// squad priority beacon (defaults to the airlock pad of the active map) +static int beaconTX = -1, beaconTY = -1; + +// switch map sources: populates every map-specific structure exactly once +static void selectMap(bool demo) +{ + if (demo) { + g_map = &g_demoSource; + } else { + g_genSource.generate(); + g_map = &g_genSource; + } + g_mapSelected = true; + g_map->findTile('A', AIRLOCK_TX, AIRLOCK_TY); + g_map->findTile('T', TERM_TX, TERM_TY); + ROOT_NODE = g_map->rootNode(); + HIVE_NODE = g_map->hiveNode(); + DOOR_NODE = g_map->doorNode(); + g_reinforceIdx = g_map->spawnCount(); // first free unit slot + beaconTX = AIRLOCK_TX; + beaconTY = AIRLOCK_TY; +} + static char tileAt(int tx, int ty) { - if (tx < 0 || ty < 0 || tx >= nd::TILE_COLS || ty >= nd::TILE_ROWS) return '#'; - return DEMO_MAP[ty][tx]; + return g_map->tileAt(tx, ty); } // blocks unit movement (closed blast door included) @@ -153,40 +161,18 @@ static bool blocksSight(int tx, int ty) static int tileIdx(int tx, int ty) { return ty * nd::TILE_COLS + tx; } // --------------------------------------------------------------------------- -// Sub-net (MVP.md §2): 7 nodes in the same coordinate space +// Sub-net (MVP.md §2): node/edge tables come from the active map source; +// only the runtime link state lives here. // --------------------------------------------------------------------------- -enum { N_AIRLK, N_JUNC, N_DOOR, N_HIVE, N_CAM1, N_CAM2, N_CAM3 }; -static const int NODE_COUNT = 7; -static const int EDGE_COUNT = 6; -struct NetNode { - const char *label; - int tx, ty; - uint16_t color; - uint8_t sight; // fog reveal radius (tiles) while online -}; // cameras see farther than plain nodes (FOG_NODE_R vs FOG_CAM_R) static const int FOG_NODE_R = 3; static const int FOG_CAM_R = 6; -static const NetNode NODES[NODE_COUNT] = { - { "AIRLK", 4, 20, nd::C_AIRLOCK, FOG_NODE_R }, - { "JUNC", 18, 6, nd::C_NODE, FOG_NODE_R }, - { "DOOR", 28, 12, nd::C_DOOR, FOG_NODE_R }, - { "HIVE", 35, 4, nd::C_HIVE, FOG_NODE_R }, - { "CAM1", 14, 2, nd::C_CAMERA, FOG_CAM_R }, - { "CAM2", 31, 3, nd::C_CAMERA, FOG_CAM_R }, - { "CAM3", 22, 18, nd::C_CAMERA, FOG_CAM_R }, -}; -static const uint8_t EDGES[EDGE_COUNT][2] = { - { N_AIRLK, N_JUNC }, { N_JUNC, N_DOOR }, { N_JUNC, N_HIVE }, - { N_JUNC, N_CAM1 }, { N_DOOR, N_CAM2 }, { N_CAM1, N_CAM3 }, -}; -static const char *EDGE_LABELS[EDGE_COUNT] = { - "AIRLK-JUNC", "JUNC-DOOR", "JUNC-HIVE", - "JUNC-CAM1", "DOOR-CAM2", "CAM1-CAM3", -}; -static int nodePx(int i) { return NODES[i].tx * nd::TILE + nd::TILE / 2; } -static int nodePy(int i) { return NODES[i].ty * nd::TILE + nd::TILE / 2; } +static int nodeCount() { return g_map->nodeCount(); } +static int edgeCount() { return g_map->edgeCount(); } + +static int nodePx(int i) { return g_map->node(i).tx * nd::TILE + nd::TILE / 2; } +static int nodePy(int i) { return g_map->node(i).ty * nd::TILE + nd::TILE / 2; } // link build durations (sim ticks @ 50 ms): 1.5 s plain, 3.0 s through ICE static const int LINK_TICKS = 30; @@ -198,19 +184,21 @@ static const int HEAT_TICKS = 60; struct NetLink { bool active; - uint8_t edge; // which EDGES[] entry this link occupies + uint8_t edge; // which map edge this link occupies uint8_t a, b; // node ids int prog; // build progress in ticks (prog == dur -> ACTIVE) int dur; }; -static NetLink links[EDGE_COUNT]; +static NetLink links[nd::MAX_EDGES]; -static bool nodeOnline[NODE_COUNT]; // compromised & reachable from AIRLK +static bool nodeOnline[nd::MAX_NODES]; // compromised & reachable from AIRLK static bool hiveCracked = false; -// red trace pulse HIVE -> JUNC -> AIRLK +// red trace pulse HIVE -> ... -> AIRLK, along the active link path static bool traceActive = false; static int traceProg = 0; // 0..TRACE_TICKS +static int tracePath[nd::MAX_NODES]; // node ids from HIVE back to ROOT +static int tracePathLen = 0; // deck thermal: >0 = OVERHEAT lockout (ticks remaining, shown as %) static int heatT = 0; @@ -230,7 +218,7 @@ static bool reinforcePending = false; // cursor static int curX = 60, curY = 120; -static int beaconTX = AIRLOCK_TX, beaconTY = AIRLOCK_TY; +// (beacon lives with the map source state: beaconTX/beaconTY above) // transient UI feedback static uint32_t viewFlashUntil = 0; @@ -426,8 +414,8 @@ static void updateFog(); // fwd decl: fog recompute lives below the unit laye // reachability from AIRLK over ACTIVE links (links form a tree) static void refreshOnline() { - bool reach[NODE_COUNT] = {}; // AIRLK root starts reachable - reach[N_AIRLK] = true; + bool reach[nd::MAX_NODES] = {}; // AIRLK root starts reachable + if (ROOT_NODE >= 0) reach[ROOT_NODE] = true; bool changed = true; while (changed) { changed = false; @@ -439,23 +427,24 @@ static void refreshOnline() } } } - for (int i = 0; i < NODE_COUNT; i++) nodeOnline[i] = reach[i]; - if (!nodeOnline[N_HIVE]) hiveCracked = false; + for (int i = 0; i < nodeCount(); i++) nodeOnline[i] = reach[i]; + if (HIVE_NODE >= 0 && !nodeOnline[HIVE_NODE]) hiveCracked = false; } // is there an edge between two nodes? static int edgeBetween(int a, int b) { - for (int i = 0; i < EDGE_COUNT; i++) - if ((EDGES[i][0] == a && EDGES[i][1] == b) || - (EDGES[i][0] == b && EDGES[i][1] == a)) return i; + for (int i = 0; i < edgeCount(); i++) { + const nd::NetEdgeDef &e = g_map->edge(i); + if ((e.a == a && e.b == b) || (e.a == b && e.b == a)) return i; + } return -1; } // is a link already routed on this edge (building or active)? static int linkOnEdge(int edge) { - for (int i = 0; i < EDGE_COUNT; i++) + for (int i = 0; i < edgeCount(); i++) if (links[i].active && links[i].edge == edge) return i; return -1; } @@ -471,7 +460,7 @@ static void tryLink(int node) { if (heatT > 0) { flashMsg("OVERHEAT"); return; } if (nodeOnline[node]) { - if (node == N_DOOR) { + if (node == DOOR_NODE) { doorOpen = !doorOpen; if (doorOpen) playDoorOpen(); else playDoorClose(); @@ -485,8 +474,8 @@ static void tryLink(int node) } // route a link from any online node adjacent to this one int edge = -1, from = -1; - for (int i = 0; i < EDGE_COUNT; i++) { - int a = EDGES[i][0], b = EDGES[i][1]; + for (int i = 0; i < edgeCount(); i++) { + int a = g_map->edge(i).a, b = g_map->edge(i).b; if ((a == node && nodeOnline[b]) || (b == node && nodeOnline[a])) { edge = i; from = (a == node) ? b : a; @@ -496,7 +485,7 @@ static void tryLink(int node) if (edge < 0) { flashMsg("NO UPLINK"); return; } if (linkOnEdge(edge) >= 0) { flashMsg("LINKING..."); return; } - bool ice = (node == N_HIVE); + bool ice = (node == HIVE_NODE); for (auto &l : links) { if (!l.active) { l.active = true; @@ -508,7 +497,7 @@ static void tryLink(int node) refreshOnline(); // offline until the build completes playLinkBuild(); playLinkActive(); - Serial.printf("[net] routing %s%s (%.1fs)\n", EDGE_LABELS[edge], + Serial.printf("[net] routing %s%s (%.1fs)\n", g_map->edge(edge).label, ice ? " [ICE]" : "", l.dur * nd::SIM_TICK_MS / 1000.0f); return; } @@ -519,10 +508,11 @@ static void tryLink(int node) static void severLink(int li) { playLinkSevered(); - Serial.printf("[net] severed %s\n", EDGE_LABELS[edgeBetween(links[li].a, links[li].b)]); + Serial.printf("[net] severed %s\n", + g_map->edge(edgeBetween(links[li].a, links[li].b)).label); links[li].active = false; refreshOnline(); - if (!nodeOnline[N_HIVE]) traceActive = false; // trace cut short: reset safely + if (HIVE_NODE >= 0 && !nodeOnline[HIVE_NODE]) traceActive = false; // trace cut short: reset safely flashMsg("LINK SEVERED"); } @@ -531,7 +521,7 @@ static int hoverLink() { int best = -1; float bestD = 7.0f; - for (int i = 0; i < EDGE_COUNT; i++) { + for (int i = 0; i < edgeCount(); i++) { if (!links[i].active) continue; float x0 = nodePx(links[i].a), y0 = nodePy(links[i].a); float x1 = nodePx(links[i].b), y1 = nodePy(links[i].b); @@ -547,8 +537,45 @@ static int hoverLink() return best; } +// is the edge fully linked up right now (any complete active link on it)? +static bool edgeUp(int e) +{ + for (int i = 0; i < nd::MAX_EDGES; i++) + if (links[i].active && links[i].edge == e && links[i].prog == links[i].dur) + return true; + return false; +} + static void spawnTrace() { + // walk the active-link path HIVE -> ... -> AIRLK (BFS over the node graph) + tracePathLen = 0; + if (HIVE_NODE >= 0 && ROOT_NODE >= 0 && HIVE_NODE != ROOT_NODE) { + int prev[nd::MAX_NODES]; + int queue[nd::MAX_NODES]; + for (int i = 0; i < nd::MAX_NODES; i++) prev[i] = -2; + int qh = 0, qt = 0; + queue[qt++] = HIVE_NODE; + prev[HIVE_NODE] = -1; + while (qh < qt && prev[ROOT_NODE] == -2) { + int cur = queue[qh++]; + for (int e = 0; e < edgeCount(); e++) { + if (!edgeUp(e)) continue; + int a = g_map->edge(e).a, b = g_map->edge(e).b; + int nbr = (a == cur) ? b : (b == cur) ? a : -1; + if (nbr < 0 || prev[nbr] != -2) continue; + prev[nbr] = cur; + queue[qt++] = nbr; + } + } + if (prev[ROOT_NODE] != -2) { + int rev[nd::MAX_NODES], len = 0; + for (int n = ROOT_NODE; n != -1; n = prev[n]) rev[len++] = n; + for (int i = 0; i < len; i++) tracePath[i] = rev[len - 1 - i]; + tracePathLen = len; // HIVE first, ROOT last + } + } + if (tracePathLen < 2) return; // no path: no trace traceActive = true; traceProg = 0; Serial.println("[net] TRACE detected: red pulse inbound!"); @@ -573,11 +600,12 @@ static void stepNetwork() l.prog++; if (l.prog == l.dur) { refreshOnline(); - if (l.b == N_HIVE && nodeOnline[N_HIVE]) { + if (l.b == HIVE_NODE && nodeOnline[HIVE_NODE]) { hiveCracked = true; spawnTrace(); } else { - Serial.printf("[net] link up: %s\n", EDGE_LABELS[edgeBetween(l.a, l.b)]); + Serial.printf("[net] link up: %s\n", + g_map->edge(edgeBetween(l.a, l.b)).label); } } } @@ -591,7 +619,7 @@ static void stepNetwork() } // ICE crack progress check during link building for (auto &l : links) { - if (l.b == N_HIVE && l.active && l.prog < l.dur) { + if (l.b == HIVE_NODE && l.active && l.prog < l.dur) { int crackProg = l.prog; if (crackProg % 20 == 0) playIceCrack(); // crack every ~1s } @@ -640,8 +668,8 @@ struct Unit { bool patFlip; }; static Unit units[nd::MAX_UNITS]; -// 0,1 marines | 2,8,10 patrol droids | 3,9 stationary droids | 4 heavy -// 5,6,11 turrets | 7 = reinforcement slot (spawns on the feedback spike) +// slots 0..spawnCount-1 come from the map source's spawn list (marines first); +// the slot after the last spawn is the reinforcement droid (feedback spike) // transient hitscan tracers / impact flashes struct Tracer { @@ -774,8 +802,8 @@ static int acquireTarget(int si) // 1. if blindT > 0 AND shooter is within HIVE frenzy range: return no target bool inFrenzyRange = (frenzyT > 0); if (inFrenzyRange) { - int ddx = u.tx - NODES[N_HIVE].tx; - int ddy = u.ty - NODES[N_HIVE].ty; + int ddx = u.tx - g_map->node(HIVE_NODE).tx; + int ddy = u.ty - g_map->node(HIVE_NODE).ty; long shooterD2 = (long)ddx * ddx + (long)ddy * ddy; inFrenzyRange = (shooterD2 <= (long)FRENZY_RADIUS * FRENZY_RADIUS); } @@ -944,15 +972,26 @@ static void stepUnits() // reinforcement droid queued by the feedback spike if (reinforcePending) { reinforcePending = false; - if (!units[7].alive) { - // spawn inside the server room by the blast door, first free tile - static const int SP[5][2] = { {31,12}, {30,12}, {32,12}, {31,11}, {31,13} }; - for (int s = 0; s < 5; s++) { - int sx = SP[s][0], sy = SP[s][1]; - if (walkable(sx, sy) && !tileOccupied(sx, sy, 7)) { - spawnUnit(7, U_DROID, sx, sy); - Serial.printf("[spawn] reinforcement droid at %d,%d\n", sx, sy); - break; + if (!units[g_reinforceIdx].alive) { + // spawn on the hive side of the blast door, first free tile + int dtx = g_map->node(DOOR_NODE).tx, dty = g_map->node(DOOR_NODE).ty; + int hx = g_map->node(HIVE_NODE).tx, hy = g_map->node(HIVE_NODE).ty; + int sx = (hx > dtx) - (hx < dtx); // step toward the hive + int sy = (hy > dty) - (hy < dty); + for (int k = 1; k <= 3; k++) { + int cand[3][2] = { + { dtx + sx * k, dty }, + { dtx, dty + sy * k }, + { dtx + sx * k, dty + sy * k }, + }; + for (int c = 0; c < 3; c++) { + int cx = cand[c][0], cy = cand[c][1]; + if (walkable(cx, cy) && !tileOccupied(cx, cy, g_reinforceIdx)) { + spawnUnit(g_reinforceIdx, U_DROID, cx, cy); + Serial.printf("[spawn] reinforcement droid at %d,%d\n", cx, cy); + k = 4; // done + break; + } } } } @@ -986,7 +1025,7 @@ static void stepUnits() // stationary droids / heavy / turret hold position // objective + wipe checks - if (u.kind == U_MARINE && u.tx == 34 && u.ty == 7) { + if (u.kind == U_MARINE && u.tx == TERM_TX && u.ty == TERM_TY) { scenario = SC_WIN; playBreachSuccess(); Serial.println("[objective] terminal reached — BREACH SUCCESS"); @@ -1024,11 +1063,11 @@ static void updateFog() if (!units[i].alive || units[i].team != TEAM_MARINE) continue; revealLos(units[i].tx, units[i].ty, FOG_SIGHT_R); } - for (int i = 0; i < NODE_COUNT; i++) { + for (int i = 0; i < nodeCount(); i++) { if (nodeOnline[i]) { // only cameras have large LOS; other nodes uncover just their own position - int r = (strstr(NODES[i].label, "CAM") != nullptr) ? NODES[i].sight : 1; - revealLos(NODES[i].tx, NODES[i].ty, r); + int r = (g_map->node(i).role == nd::NR_CAMERA) ? g_map->node(i).sight : 1; + revealLos(g_map->node(i).tx, g_map->node(i).ty, r); } } } @@ -1038,9 +1077,11 @@ static void updateFog() // --------------------------------------------------------------------------- static void resetScenario() { + if (!g_mapSelected) selectMap(true); // lazy first population (test harnesses) for (auto &l : links) l.active = false; traceActive = false; traceProg = 0; + tracePathLen = 0; hiveCracked = false; heatT = 0; doorOpen = false; @@ -1048,32 +1089,17 @@ static void resetScenario() for (auto &t : tracers) t.ttl = 0; refreshOnline(); // AIRLK root comes up online - // squad: 2 marines in the airlock (out of enemy LOS) - spawnUnit(0, U_MARINE, 2, 21); - spawnUnit(1, U_MARINE, 3, 21); - // corridor: 1 patrolling + 1 stationary security droid - spawnUnit(2, U_DROID, 12, 2); - units[2].patA = tileIdx(12, 2); - units[2].patB = tileIdx(26, 18); - units[2].patFlip = false; - spawnUnit(3, U_DROID, 20, 12); - // server room: heavy droid + ceiling turrets guarding the terminal - spawnUnit(4, U_HEAVY, 32, 10); - spawnUnit(5, U_TURRET, 33, 5); - spawnUnit(6, U_TURRET, 35, 5); - units[7].alive = false; // reinforcement slot - // wider garrison: airlock-side patrol, server-room guard, corridor - // patrol and a turret covering the blast door approach - spawnUnit(8, U_DROID, 2, 2); - units[8].patA = tileIdx(2, 2); - units[8].patB = tileIdx(8, 6); - units[8].patFlip = false; - spawnUnit(9, U_DROID, 31, 16); - spawnUnit(10, U_DROID, 14, 18); - units[10].patA = tileIdx(13, 18); - units[10].patB = tileIdx(25, 18); - units[10].patFlip = false; - spawnUnit(11, U_TURRET, 26, 10); + // entities: apply the map source's spawn list exactly once (marines first) + for (int s = 0; s < g_map->spawnCount() && s < nd::MAX_UNITS; s++) { + const nd::UnitSpawn &sp = g_map->spawn(s); + spawnUnit(s, sp.kind, sp.tx, sp.ty); + units[s].patA = sp.patA; + units[s].patB = sp.patB; + units[s].patFlip = false; + } + units[g_reinforceIdx].alive = false; // reinforcement slot + for (int i = g_reinforceIdx + 1; i < nd::MAX_UNITS; i++) + units[i].alive = false; // unused slots stay down // fog of war starts blank: only what the marines see in the airlock and // the always-online [AIRLK] node's connected tiles is uncovered @@ -1160,7 +1186,7 @@ static void registerClick() } else { // nearest node int best = -1, bestD = 1 << 30; - for (int i = 0; i < NODE_COUNT; i++) { + for (int i = 0; i < nodeCount(); i++) { int dx = curX - nodePx(i); int dy = curY - nodePy(i); int d = dx * dx + dy * dy; @@ -1194,7 +1220,7 @@ static void handleKey(char c) break; case '1': case '2': if (heatT > 0) { flashMsg("OVERHEAT"); break; } - if (!nodeOnline[N_HIVE]) { flashMsg("NO HIVE LINK"); playNoLink(); break; } + if (HIVE_NODE < 0 || !nodeOnline[HIVE_NODE]) { flashMsg("NO HIVE LINK"); playNoLink(); break; } // FRENZY.EXE (1) or BLIND_OPTICS.SH (2) — land in Milestone 4 if (c == '1') { // FRENZY: droids attack everyone within sphere of influence @@ -1374,7 +1400,7 @@ static uint16_t gray565(uint16_t c) static void renderMap(bool dim) { for (int ty = 0; ty < nd::TILE_ROWS; ty++) { - const char *row = DEMO_MAP[ty]; + const char *row = g_map->getMap()[ty].c_str(); for (int tx = 0; tx < nd::TILE_COLS; tx++) { char t = row[tx]; int fi = tileIdx(tx, ty); @@ -1442,7 +1468,7 @@ static void drawLinkLine(int x0, int y0, int x1, int y1, float frac, static void renderNetwork(bool full) { // links: active solid, building partial, ghost outlines in cameras mode - for (int i = 0; i < EDGE_COUNT; i++) { + for (int i = 0; i < edgeCount(); i++) { auto &l = links[i]; int x0 = nodePx(l.a), y0 = nodePy(l.a); int x1 = nodePx(l.b), y1 = nodePy(l.b); @@ -1475,14 +1501,14 @@ static void renderNetwork(bool full) } } - // red trace pulse along HIVE -> JUNC -> AIRLK - if (traceActive) { - float f = (float)traceProg / TRACE_TICKS * 2.0f; // 2 segments - int seg = (f >= 1.0f) ? 1 : 0; + // red trace pulse along the active link path HIVE -> ... -> AIRLK + if (traceActive && tracePathLen >= 2) { + float f = (float)traceProg / TRACE_TICKS * (tracePathLen - 1); + int seg = (int)f; + if (seg > tracePathLen - 2) seg = tracePathLen - 2; float t = f - seg; - int x0 = nodePx(N_HIVE), y0 = nodePy(N_HIVE); - int x1 = nodePx(N_JUNC), y1 = nodePy(N_JUNC); - if (seg == 1) { x0 = nodePx(N_JUNC); y0 = nodePy(N_JUNC); x1 = nodePx(N_AIRLK); y1 = nodePy(N_AIRLK); } + int x0 = nodePx(tracePath[seg]), y0 = nodePy(tracePath[seg]); + int x1 = nodePx(tracePath[seg + 1]), y1 = nodePy(tracePath[seg + 1]); int px = x0 + (int)((x1 - x0) * t); int py = y0 + (int)((y1 - y0) * t); GFXP->fillCircle(px, py, 3, nd::C_TRACE); @@ -1490,10 +1516,10 @@ static void renderNetwork(bool full) } // frenzy / blind sphere of influence — only drawn when HIVE is online (connected) -// Network mode only; gated by nodeOnline[N_HIVE] - if (full && nodeOnline[N_HIVE]) { - int cx = nodePx(N_HIVE); - int cy = nodePy(N_HIVE); +// Network mode only; gated by nodeOnline[HIVE_NODE] + if (full && HIVE_NODE >= 0 && nodeOnline[HIVE_NODE]) { + int cx = nodePx(HIVE_NODE); + int cy = nodePy(HIVE_NODE); int r = FRENZY_RADIUS * nd::TILE; if (frenzyT > 0 || blindT > 0) { // solid circles when frenzy/blind is active @@ -1550,17 +1576,19 @@ static void renderNetwork(bool full) // - nodeOnline[i] == true: filled node with label (established link) // - node is a connectable target of an online source: ghost circle (known, not yet active) // these are nodes reachable from online nodes via one edge, but link not built yet - bool isConnectableTarget[NODE_COUNT]; - for (int i = 0; i < NODE_COUNT; i++) isConnectableTarget[i] = false; + bool isConnectableTarget[nd::MAX_NODES]; + int nCount = nodeCount(); + int eCount = edgeCount(); + for (int i = 0; i < nCount; i++) isConnectableTarget[i] = false; if (full) { // first pass: identify connectable targets from online sources - for (int s = 0; s < NODE_COUNT; s++) { + for (int s = 0; s < nCount; s++) { // AIRLK is always a source; others if online bool srcOnline = nodeOnline[s]; - if (s == N_AIRLK) srcOnline = true; // AIRLK always source + if (s == ROOT_NODE) srcOnline = true; // AIRLK always source if (!srcOnline) continue; - for (int e = 0; e < EDGE_COUNT; e++) { - int a = EDGES[e][0], b = EDGES[e][1]; + for (int e = 0; e < eCount; e++) { + int a = g_map->edge(e).a, b = g_map->edge(e).b; if (a != s && b != s) continue; int neighbor = (a == s) ? b : a; if (!nodeOnline[neighbor]) { // not already online @@ -1570,19 +1598,20 @@ static void renderNetwork(bool full) } } - for (int i = 0; i < NODE_COUNT; i++) { + for (int i = 0; i < nCount; i++) { + const nd::NetNodeDef &nd_ = g_map->node(i); int nx = nodePx(i), ny = nodePy(i); if (full) { if (nodeOnline[i]) { // established connection: filled node with label - GFXP->fillCircle(nx, ny, 6, NODES[i].color); + GFXP->fillCircle(nx, ny, 6, nd_.color); GFXP->drawCircle(nx, ny, 6, TFT_BLACK); GFXP->setTextDatum(TC_DATUM); GFXP->setTextColor(nd::C_TEXT); - GFXP->drawString(NODES[i].label, nx, ny + 9); + GFXP->drawString(nd_.label, nx, ny + 9); // cameras see farther: dotted ring marks their sight radius - if (NODES[i].sight > FOG_NODE_R) { - int r = NODES[i].sight * nd::TILE; + if (nd_.sight > FOG_NODE_R) { + int r = nd_.sight * nd::TILE; GFXP->setTextColor(nd::C_CAMERA); for (int a = 0; a < 360; a += 5) { float rad = a * 3.14159f / 180.0f; @@ -1591,14 +1620,14 @@ static void renderNetwork(bool full) } } // door state on the door node - if (i == N_DOOR && nodeOnline[i]) { + if (i == DOOR_NODE && nodeOnline[i]) { GFXP->setTextColor(doorOpen ? nd::C_GOOD : nd::C_TRACE); GFXP->drawString(doorOpen ? "OPEN" : "SHUT", nx, ny + 19); } // ICE crack progress on the hive - if (i == N_HIVE) { - for (int k = 0; k < EDGE_COUNT; k++) { - if (links[k].active && links[k].b == N_HIVE && links[k].prog < links[k].dur) { + if (i == HIVE_NODE) { + for (int k = 0; k < eCount; k++) { + if (links[k].active && links[k].b == HIVE_NODE && links[k].prog < links[k].dur) { GFXP->setTextColor(nd::C_TRACE); GFXP->drawString("CRACKING", nx, ny + 19); } @@ -1626,10 +1655,10 @@ static void renderNetwork(bool full) if (full) { // determine which node ids are "available as connection sources" // AIRLK is always online (starting node); others if nodeOnline - bool srcOnline[NODE_COUNT]; - for (int s = 0; s < NODE_COUNT; s++) srcOnline[s] = nodeOnline[s]; + bool srcOnline[nd::MAX_NODES]; + for (int s = 0; s < nCount; s++) srcOnline[s] = nodeOnline[s]; // ensure AIRLK is always a source even if somehow offline - srcOnline[N_AIRLK] = true; + if (ROOT_NODE >= 0) srcOnline[ROOT_NODE] = true; auto drawDottedLine = [&](int x0, int y0, int x1, int y1) { int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1; @@ -1645,11 +1674,11 @@ static void renderNetwork(bool full) } }; - for (int s = 0; s < NODE_COUNT; s++) { + for (int s = 0; s < nCount; s++) { if (!srcOnline[s]) continue; // find edges where this node is one endpoint - for (int e = 0; e < EDGE_COUNT; e++) { - int a = EDGES[e][0], b = EDGES[e][1]; + for (int e = 0; e < eCount; e++) { + int a = g_map->edge(e).a, b = g_map->edge(e).b; if (a != s && b != s) continue; int neighbor = (a == s) ? b : a; // skip if neighbor already online (established connection — link already rendered above) @@ -2002,6 +2031,7 @@ void setup() #endif drawBoot(); + selectMap(false); // demo map by default; g_genSource for generated maps resetScenario(); stateT0 = millis(); lastFrameMs = stateT0; diff --git a/src/netdeck/STATUS.md b/src/netdeck/STATUS.md index a2165c3..e17756e 100644 --- a/src/netdeck/STATUS.md +++ b/src/netdeck/STATUS.md @@ -148,6 +148,54 @@ or press the advantage at the blast door. The frenzy timer decrements each shared coordinate space so that a network link to the Droid Hive node directly controls local droid behavior. --> +### Map sources: generic MapSource interface (this change) + +All map-specific data now lives behind one interface (`nd_mapsource.h`), so +the scenario populates its structures **once** (`selectMap()` → +`resetScenario()`) and never checks which map is active — the demo floorplan +and the random `MapGenerator` are interchangeable: + +- **`nd_mapsource.h`** (new): `MapSource` abstract interface exposing tiles, + rooms/doors/cameras, the network graph (`NetNodeDef`/`NetEdgeDef` with + **roles** `NR_ROOT/NR_DOOR/NR_HIVE/NR_CAMERA` replacing the old hardcoded + `N_AIRLK/N_DOOR/N_HIVE` indices), and the entity spawn list + (`UnitSpawn`, marines first — slots 0/1 are the squad). Shared helpers: + role lookups (`rootNode()/hiveNode()/doorNode()`) and `findTile()` for the + `'A'`/`'T'` anchor tiles. Pool bounds `MAX_NODES`/`MAX_EDGES`. +- **`nd_demomap.h`** (rewritten): self-contained `DemoMapSource` — the real + 24x40 demo grid (moved out of the sketch; the stale 19x38 array is gone), + demo node/edge/spawn tables, blast door + room regions. `isDemo()` and the + `setMapRows()` workaround were dropped as unnecessary. +- **`nd_mapgen.h`** (reworked): the generator now produces playable maps — + solid hull, carved rooms, **L-corridors between room centers** (full + walkable connectivity; corridor tiles recorded so crates never block a + link), doors only on walls that lead somewhere (with a deterministic + fallback so every room gets one), airlock pad `'A'` + objective terminal + `'T'` in the hive room, cover crates, and no unit letters written into the + tile grid (the old code wrote `'T'` for turrets — clashing with the + terminal). `GenMapSource` adapts the result to the interface: network graph + derived from the room chain (AIRLK root online, HIVE on the hive room, + DOOR node pinned to the hive door tile) and a marine-first spawn list with + droid patrol endpoints (spawn tile ↔ room center). +- **`NetDeck.ino`**: every map-source branch removed (`g_useDemoMap` is gone); + node/edge tables, spawn placement, terminal/airlock anchors, reinforcement + spawn point (near the blast door, hive side) and the win tile all come from + the active source. The red trace now follows the actual active-link path + (BFS HIVE→ROOT) instead of the hardcoded HIVE→JUNC→AIRLK segments; the + reinforcement droid uses the first slot after the spawn list. +- **Tests**: `MapTest.cpp` (standalone, also compiled into the firmware as + before) now validates 50 generated runs + the demo source through the + interface: room count, marine-first spawns, role nodes, graph connectivity + from the root, and a **flood-fill from the airlock** proving the terminal + and every spawn are reachable. New integration journey + `generated_map_source_journey` switches the running scenario to + `GenMapSource`, routes a link and steps combat, then restores the demo map. + Test node handles resolve via the source (`nodeByLabel` / role globals) — + no hardcoded indices left in the tests. +- Verified: `make netdeck` (both targets), `make netdeck-test` — 28 unit + + 8 integration + 4 E2E journeys, 0 failures; plus a 2000-run generator fuzz + (all maps flood-connected, all role nodes present). + ### Headless test structure Tests live in `emulator/tests/` (see its README): **unit** + diff --git a/src/netdeck/nd_demomap.h b/src/netdeck/nd_demomap.h new file mode 100644 index 0000000..e6df9f2 --- /dev/null +++ b/src/netdeck/nd_demomap.h @@ -0,0 +1,160 @@ +/** + * @file nd_demomap.h + * @brief NetDeck — Breach & Board: demo map source. + * + * The hardcoded 3-room demo floorplan (airlock bottom-left, main corridor + * L-shaped middle, server room right) with its network graph and entity + * spawn list, all behind the generic MapSource interface. The demo map + * remains available for automated tests while the random MapGenerator is + * the default play map. + * + * Header-only: include from sketch or test harness. + */ +#pragma once + +#include +#include +#include +#include "nd_layout.h" +#include "nd_mapsource.h" + +// --------------------------------------------------------------------------- +// Demo map: 40x24 tile coordinate space +// --------------------------------------------------------------------------- +// # = wall, . = floor, o = cover crate, + = blast door, A = airlock, T = terminal +// Airlock room (bottom-left), main corridor (L-shaped middle), +// server room (right). The '+' door at (28,12) is the Room2/Room3 blast door. +namespace nd { + +static const char* const DEMO_MAP[TILE_ROWS] = { + "########################################", + "#.........#.................#..........#", + "#.........#......#..........#..........#", + "#...#.....#......#..........#.....o....#", + "#....o....#......#..........#..........#", + "#...#.....#......#..........#..........#", + "#.........#.................#..........#", + "#.........#.................#.....T....#", + "#...........................#..........#", + "#...........................#..........#", + "#.........#...#.....o.......#..........#", + "#.........#...#.............#..........#", + "#.........#.................+..........#", + "###########.................#..........#", + "#.........#.................#..........#", + "#....#....#...........o.....#....#.....#", + "#.........#.................#..........#", + "#...........................#..........#", + "#...........................#..........#", + "#.........#.....#...........#..........#", + "#.........#.....#...........#.....o....#", + "#.A.......#.................#..........#", + "#.........#.................#..........#", + "########################################", +}; + +// --------------------------------------------------------------------------- +// Demo tables (namespace scope, internal linkage — one copy per TU) +// --------------------------------------------------------------------------- + +// Network graph: 7 nodes pinned to demo tiles. Roles replace the old +// hardcoded N_AIRLK/N_DOOR/N_HIVE indices. +static const int DEMO_NODE_COUNT = 7; +static const int DEMO_EDGE_COUNT = 6; +static const NetNodeDef DEMO_NODES[DEMO_NODE_COUNT] = { + { "AIRLK", 4, 20, C_AIRLOCK, 3, true, NR_ROOT }, + { "JUNC", 18, 6, C_NODE, 3, false, NR_NONE }, + { "DOOR", 28, 12, C_DOOR, 3, false, NR_DOOR }, + { "HIVE", 35, 4, C_HIVE, 3, false, NR_HIVE }, + { "CAM1", 14, 2, C_CAMERA, 6, false, NR_CAMERA }, + { "CAM2", 31, 3, C_CAMERA, 6, false, NR_CAMERA }, + { "CAM3", 22, 18, C_CAMERA, 6, false, NR_CAMERA }, +}; + +static const NetEdgeDef DEMO_EDGES[DEMO_EDGE_COUNT] = { + { 0, 1, "AIRLK-JUNC" }, + { 1, 2, "JUNC-DOOR" }, + { 1, 3, "JUNC-HIVE" }, + { 1, 4, "JUNC-CAM1" }, + { 2, 5, "DOOR-CAM2" }, + { 4, 6, "CAM1-CAM3" }, +}; + +// Entity spawn list — mirrors the demo encounter layout: +// 0,1 marines | 2 patrol droid | 3 stationary droid | 4 heavy | +// 5,6 turrets | 8,9,10 patrol/guard droids | 11 turret on the door approach +// (marines first — slots 0/1 are the squad) +static const int DEMO_SPAWN_COUNT = 11; +static const UnitSpawn DEMO_SPAWNS[DEMO_SPAWN_COUNT] = { + { 0, 2, 21, -1, -1 }, // marine (at the airlock) + { 0, 3, 21, -1, -1 }, // marine + { 1, 12, 2, 12 + 2 * TILE_COLS, 26 + 18 * TILE_COLS, }, // corridor patrol + { 1, 20, 12, -1, -1 }, // stationary droid + { 2, 32, 10, -1, -1 }, // heavy (server room) + { 3, 33, 5, -1, -1 }, // turret (terminal guard) + { 3, 35, 5, -1, -1 }, // turret (terminal guard) + { 1, 2, 2, 2 + 2 * TILE_COLS, 8 + 6 * TILE_COLS, }, // top-left patrol + { 1, 31, 16, -1, -1 }, // server-room guard + { 1, 14, 18, 13 + 18 * TILE_COLS, 25 + 18 * TILE_COLS, }, // corridor patrol + { 3, 26, 10, -1, -1 }, // turret (door approach) +}; + +// --------------------------------------------------------------------------- +// DemoMapSource: everything map-specific about the demo scenario, in one place +// --------------------------------------------------------------------------- +class DemoMapSource : public MapSource { +public: + DemoMapSource() { + buildMapVector(); + buildStructures(); + } + + // --- tile grid --- + char tileAt(int tx, int ty) const override { + if (tx < 0 || ty < 0 || tx >= TILE_COLS || ty >= TILE_ROWS) return '#'; + return DEMO_MAP[ty][tx]; + } + const std::vector& getMap() const override { return mapVec_; } + + // --- structures --- + const std::vector& getRooms() const override { return rooms_; } + const std::vector& getDoors() const override { return doors_; } + const std::vector& getCameras() const override { return cameras_; } + + // --- network graph --- + int nodeCount() const override { return DEMO_NODE_COUNT; } + const NetNodeDef& node(int i) const override { return DEMO_NODES[i]; } + int edgeCount() const override { return DEMO_EDGE_COUNT; } + const NetEdgeDef& edge(int i) const override { return DEMO_EDGES[i]; } + + // --- entity spawn list --- + int spawnCount() const override { return DEMO_SPAWN_COUNT; } + const UnitSpawn& spawn(int i) const override { return DEMO_SPAWNS[i]; } + +private: + void buildMapVector() { + mapVec_.reserve(TILE_ROWS); + for (int y = 0; y < TILE_ROWS; y++) mapVec_.emplace_back(DEMO_MAP[y]); + } + + void buildStructures() { + rooms_.clear(); + doors_.clear(); + cameras_.clear(); + Room r; + r = { 1, 14, 9, 21, 5, 17, 72 }; rooms_.push_back(r); // airlock + r = { 11, 1, 27, 21, 19, 11, 357 }; rooms_.push_back(r); // corridor + r = { 29, 1, 38, 12, 33, 6, 120 }; rooms_.push_back(r); // server room + Door d = { 28, 12, false, false, true }; // blast door + doors_.push_back(d); + } + + std::vector mapVec_; + + // Demo room regions (informational: airlock / corridor / server) + std::vector rooms_; + std::vector doors_; // the Room2/Room3 blast door + std::vector cameras_; // demo cameras live on the net (CAM1-3) +}; + +} // namespace nd diff --git a/src/netdeck/nd_mapgen.h b/src/netdeck/nd_mapgen.h new file mode 100644 index 0000000..0cf1ae8 --- /dev/null +++ b/src/netdeck/nd_mapgen.h @@ -0,0 +1,540 @@ +/** + * @file nd_mapgen.h + * @brief NetDeck — Breach & Board: random map generator + map source. + * + * Generates a random ship floorplan with rooms, connecting corridors, + * doors, cover crates, an airlock, the objective terminal, units, and a + * connected network graph in the shared 40x24 tile coordinate space. The + * result is exposed through the generic MapSource interface + * (nd_mapsource.h) via GenMapSource, so the scenario consumes generated + * and demo maps identically. + * + * Steps: + * 1. Start with a solid hull (all walls) + * 2. Pick 4-6 room regions and carve them out + * 3. Connect the rooms with L-shaped corridors + * 4. Place the airlock + 2 marines in the airlock room + * 5. Place the terminal + hive node + 1-4 enemy units in the hive room + * 6. Fill other rooms with 0-2 enemy units + * 7. Place 1-3 doors per room on walls that lead somewhere + * 8. Place cameras + * 9. Sprinkle cover crates + * + * Header-only: include from sketch or test harness. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include "nd_layout.h" +#include "nd_mapsource.h" + +namespace nd { + +// --------------------------------------------------------------------------- +// Generator-internal unit record (converted to UnitSpawn by GenMapSource) +// --------------------------------------------------------------------------- +struct GenUnit { + int tx, ty; // tile coordinate + uint8_t kind; // unit type (0=marine, 1=droid, 2=heavy, 3=turret) + uint8_t team; // team (1=MARINE, 2=DROID) + bool alive; +}; + +// --------------------------------------------------------------------------- +// MapGenerator class +// --------------------------------------------------------------------------- +class MapGenerator { +public: + MapGenerator() + : rng_(std::random_device{}()) + , distInt(0, 1000) + { + } + + // Generate complete map in one call + void generate() { + createEmptyMap(); + generateRooms(4, 6); + connectRooms(); + placeAirlockAndMarines(); + placeHiveAndEnemies(1, 4); + fillOtherRooms(0, 2); + placeDoors(); + populateCameras(1, -1); + sprinkleCrates(); + } + + // Accessors + const std::vector& getMap() const { return map_; } + char tileAt(int tx, int ty) const { + if (tx < 0 || ty < 0 || tx >= TILE_COLS || ty >= TILE_ROWS) return '#'; + return map_[ty][tx]; + } + const std::vector& getRooms() const { return rooms_; } + const std::vector& getDoors() const { return doors_; } + const std::vector& getCameras() const { return cameras_; } + const std::vector& getUnits() const { return units_; } + int getHiveRoomIdx() const { return hiveRoomIdx_; } + +private: + std::vector map_; // 24 strings of 40 chars + std::vector rooms_; + std::vector doors_; + std::vector cameras_; + std::vector units_; + std::vector corridor_; // corridor tiles (crates must avoid) + int hiveRoomIdx_ = -1; + + std::mt19937 rng_; // random number generator + std::uniform_int_distribution distInt; // 0..1000 range + + // Helper methods + bool floorWalkable(char t) const { return t == '.' || t == 'A' || t == 'T'; } + bool isWalkable(int tx, int ty) const { + if (tx < 0 || ty < 0 || tx >= TILE_COLS || ty >= TILE_ROWS) return false; + return floorWalkable(map_[ty][tx]); + } + int rnd(int n) { return distInt(rng_) % n; } + + // --------------------------------------------------------------------------- + // Step 1: solid hull — everything starts as wall, rooms carve it open + // --------------------------------------------------------------------------- + void createEmptyMap() { + map_.assign(TILE_ROWS, std::string(TILE_COLS, '#')); + rooms_.clear(); + doors_.clear(); + cameras_.clear(); + units_.clear(); + hiveRoomIdx_ = -1; + } + + // --------------------------------------------------------------------------- + // Step 2: 4-6 non-overlapping rooms carved out of the hull + // --------------------------------------------------------------------------- + void generateRooms(int minRooms, int maxRooms) { + int roomCount = minRooms + rnd(maxRooms - minRooms + 1); + rooms_.clear(); + + for (int i = 0; i < roomCount; i++) { + int w = 3 + rnd(10); // 3-12 wide + int h = 2 + rnd(7); // 2-8 high + + int maxX = TILE_COLS - 3 - w; + int maxY = TILE_ROWS - 3 - h; + if (maxX < 3) { w = TILE_COLS - 6; maxX = 3; } + if (maxY < 2) { h = TILE_ROWS - 6; maxY = 2; } + + int x = 2 + rnd(maxX); + int y = 2 + rnd(maxY); + + Room r; + r.x0 = x; + r.y0 = y; + r.x1 = x + w - 1; + r.y1 = y + h - 1; + r.centerX = (r.x0 + r.x1) / 2; + r.centerY = (r.y0 + r.y1) / 2; + r.area = (r.x1 - r.x0 + 1) * (r.y1 - r.y0 + 1); + + if (roomOverlaps(r)) { i--; continue; } + + carveRoom(r); + } + } + + // --------------------------------------------------------------------------- + // Step 3: L-shaped corridors between consecutive room centers guarantee + // full walkable connectivity (they punch doorways through the walls). + // Corridor tiles are recorded so crates never block a connection. + // --------------------------------------------------------------------------- + void connectRooms() { + corridor_.assign(TILE_COLS * TILE_ROWS, 0); + for (size_t i = 1; i < rooms_.size(); i++) { + const Room &a = rooms_[i - 1]; + const Room &b = rooms_[i]; + int x = b.centerX, y = b.centerY; + while (x != a.centerX) { carveTile(x, y); x += (a.centerX > x) ? 1 : -1; } + carveTile(x, y); + while (y != a.centerY) { y += (a.centerY > y) ? 1 : -1; carveTile(x, y); } + } + } + + void carveTile(int x, int y) { + if (x <= 0 || y <= 0 || x >= TILE_COLS - 1 || y >= TILE_ROWS - 1) return; + map_[y][x] = '.'; + corridor_[y * TILE_COLS + x] = 1; + } + + // --------------------------------------------------------------------------- + // Step 4: airlock pad + 2 marines in room 0 + // --------------------------------------------------------------------------- + void placeAirlockAndMarines() { + if (rooms_.empty()) return; + Room &ar = rooms_[0]; + int ax = ar.centerX, ay = ar.centerY; + map_[ay][ax] = 'A'; // airlock pad + + // two marines on the two nearest free floor tiles to the pad + int placed = 0; + for (int radius = 1; radius < TILE_COLS && placed < 2; radius++) { + for (int dy = -radius; dy <= radius && placed < 2; dy++) { + for (int dx = -radius; dx <= radius && placed < 2; dx++) { + if (dx != -radius && dx != radius && dy != -radius && dy != radius) + continue; // ring scan only + int tx = ax + dx, ty = ay + dy; + if (!isWalkable(tx, ty)) continue; + if (tileHasUnit(tx, ty)) continue; + GenUnit u; + u.tx = tx; u.ty = ty; u.kind = 0; u.team = 1; u.alive = true; + units_.push_back(u); + placed++; + } + } + } + } + + bool tileHasUnit(int tx, int ty) const { + for (const auto &u : units_) + if (u.alive && u.tx == tx && u.ty == ty) return true; + return false; + } + + // --------------------------------------------------------------------------- + // Step 5: objective terminal + hive room enemies (1-4) + // --------------------------------------------------------------------------- + void placeHiveAndEnemies(int enemyCountMin, int enemyCountMax) { + if (rooms_.size() < 2) return; + hiveRoomIdx_ = 1; // first room after the airlock room + + Room &hr = rooms_[hiveRoomIdx_]; + map_[hr.centerY][hr.centerX] = 'T'; // objective terminal + + int enemyCount = enemyCountMin + rnd(enemyCountMax - enemyCountMin + 1); + for (int e = 0; e < enemyCount; e++) { + int tx = hr.x0 + rnd(hr.x1 - hr.x0 + 1); + int ty = hr.y0 + rnd(hr.y1 - hr.y0 + 1); + if (map_[ty][tx] != '.') continue; + if (tileHasUnit(tx, ty)) continue; + GenUnit u; + u.tx = tx; u.ty = ty; + u.kind = 1 + rnd(3); // droid / heavy / turret + u.team = 2; + u.alive = true; + units_.push_back(u); + } + } + + // --------------------------------------------------------------------------- + // Step 6: 0-2 enemies per non-hive room (except the airlock room) + // --------------------------------------------------------------------------- + void fillOtherRooms(int minEnemies, int maxEnemies) { + for (size_t i = 1; i < rooms_.size(); i++) { + if ((int)i == hiveRoomIdx_) continue; + Room &r = rooms_[i]; + int enemyCount = minEnemies + rnd(maxEnemies - minEnemies + 1); + for (int e = 0; e < enemyCount; e++) { + int tx = r.x0 + rnd(r.x1 - r.x0 + 1); + int ty = r.y0 + rnd(r.y1 - r.y0 + 1); + if (map_[ty][tx] != '.') continue; + if (tileHasUnit(tx, ty)) continue; + GenUnit u; + u.tx = tx; u.ty = ty; + u.kind = 1 + rnd(3); + u.team = 2; + u.alive = true; + units_.push_back(u); + } + } + } + + // --------------------------------------------------------------------------- + // Step 7: 1-3 doors per room, only on walls that actually lead somewhere + // --------------------------------------------------------------------------- + void placeDoors() { + for (size_t ri = 0; ri < rooms_.size(); ri++) { + const Room &r = rooms_[ri]; + int doorCount = 1 + rnd(3); + int tries = 12; + int placed = 0; + while (placed < doorCount && tries-- > 0) { + int wall = rnd(4); + int tx, ty, ox = 0, oy = 0; // (ox,oy) points outside the room + switch (wall) { + case 0: tx = r.x0 + rnd(r.x1 - r.x0 + 1); ty = r.y0; oy = -1; break; + case 1: tx = r.x0 + rnd(r.x1 - r.x0 + 1); ty = r.y1; oy = 1; break; + case 2: tx = r.x0; ty = r.y0 + rnd(r.y1 - r.y0 + 1); ox = -1; break; + default: tx = r.x1; ty = r.y0 + rnd(r.y1 - r.y0 + 1); ox = 1; break; + } + if (map_[ty][tx] != '.') continue; // not free floor + if (!isWalkable(tx + ox, ty + oy)) continue; // dead end beyond + if (doorNear(tx, ty)) continue; // too close to another + placeDoorTile(tx, ty, (int)ri); + placed++; + } + if (placed == 0) { + // deterministic fallback: the corridor connection always + // crosses this room's boundary — scan for a usable tile + for (int y = r.y0; y <= r.y1 && placed == 0; y++) { + for (int x = r.x0; x <= r.x1 && placed == 0; x++) { + bool edge = (x == r.x0 || x == r.x1 || y == r.y0 || y == r.y1); + if (!edge || map_[y][x] != '.') continue; + static const int DX[4] = { 1, -1, 0, 0 }; + static const int DY[4] = { 0, 0, 1, -1 }; + for (int d = 0; d < 4; d++) { + if (isWalkable(x + DX[d], y + DY[d]) && !doorNear(x, y)) { + placeDoorTile(x, y, (int)ri); + placed++; + break; + } + } + } + } + } + } + } + + void placeDoorTile(int tx, int ty, int roomIdx) { + Door d; + d.tx = tx; d.ty = ty; + d.open = false; + d.isAirlock = false; + d.isHive = (roomIdx == hiveRoomIdx_); + doors_.push_back(d); + map_[ty][tx] = '+'; + } + + bool doorNear(int tx, int ty) const { + for (const auto &d : doors_) { + if (abs(d.tx - tx) <= 1 && abs(d.ty - ty) <= 1) return true; + } + return false; + } + + // --------------------------------------------------------------------------- + // Step 8: cameras on room edges / centers (network overlay only — no map char) + // --------------------------------------------------------------------------- + void populateCameras(int cameraCountMin, int cameraCountMax) { + if (rooms_.empty()) return; + if (cameraCountMax < 0) cameraCountMax = (int)rooms_.size() * 2; + if (cameraCountMin < 0) cameraCountMin = 1; + + int cameraCount = cameraCountMin + rnd(cameraCountMax - cameraCountMin + 1); + for (int c = 0; c < cameraCount; c++) { + const Room &r = rooms_[rnd((int)rooms_.size())]; + int placeType = rnd(3); // 0=top, 1=bottom, 2=center + + Camera cam; + cam.id = (int)cameras_.size() + 1; + cam.color = C_CAMERA; + switch (placeType) { + case 0: cam.tx = r.x0 + rnd(r.x1 - r.x0 + 1); cam.ty = r.y0; break; + case 1: cam.tx = r.x0 + rnd(r.x1 - r.x0 + 1); cam.ty = r.y1; break; + default: cam.tx = r.centerX; cam.ty = r.centerY; break; + } + bool already = std::any_of(cameras_.begin(), cameras_.end(), + [&](const Camera &other) { + return other.tx == cam.tx && other.ty == cam.ty; + }); + if (!already) cameras_.push_back(cam); + } + } + + // --------------------------------------------------------------------------- + // Step 9: cover crates on free room floor (never adjacent to a door) + // --------------------------------------------------------------------------- + void sprinkleCrates() { + for (const Room &r : rooms_) { + if (rnd(4) == 0) continue; // some rooms stay clear + int tx = r.x0 + rnd(r.x1 - r.x0 + 1); + int ty = r.y0 + rnd(r.y1 - r.y0 + 1); + if (map_[ty][tx] != '.') continue; + if (corridor_[ty * TILE_COLS + tx]) continue; // never block a corridor + if (doorNear(tx, ty)) continue; + if (tileHasUnit(tx, ty)) continue; + map_[ty][tx] = 'o'; + } + } + + bool roomOverlaps(const Room &r) const { + for (const auto &other : rooms_) { + if (r.x0 < other.x1 && r.x1 > other.x0 && + r.y0 < other.y1 && r.y1 > other.y0) { + return true; + } + } + if (r.x0 < 2 || r.y0 < 2 || r.x1 > TILE_COLS - 2 || r.y1 > TILE_ROWS - 2) { + return true; + } + return false; + } + + void carveRoom(Room &r) { + for (int y = r.y0; y <= r.y1; y++) { + for (int x = r.x0; x <= r.x1; x++) { + if (x > 0 && x < TILE_COLS - 1 && y > 0 && y < TILE_ROWS - 1) { + map_[y][x] = '.'; + } + } + } + rooms_.push_back(r); + } +}; + +// --------------------------------------------------------------------------- +// GenMapSource: exposes a generated MapGenerator map through the generic +// MapSource interface. Derives the network graph (nodes + spanning edges) +// from the room layout and converts the generator's units into a spawn list. +// --------------------------------------------------------------------------- +class GenMapSource : public MapSource { +public: + explicit GenMapSource(MapGenerator &gen) : gen_(gen) {} + + // (Re)generate the underlying map and rebuild the derived structures. + void generate() { + gen_.generate(); + buildNetwork(); + buildSpawns(); + } + + // --- tile grid --- + char tileAt(int tx, int ty) const override { return gen_.tileAt(tx, ty); } + const std::vector& getMap() const override { return gen_.getMap(); } + + // --- structures --- + const std::vector& getRooms() const override { return gen_.getRooms(); } + const std::vector& getDoors() const override { return gen_.getDoors(); } + const std::vector& getCameras() const override { return gen_.getCameras(); } + + // --- network graph --- + int nodeCount() const override { return (int)nodes_.size(); } + const NetNodeDef& node(int i) const override { return nodes_[i]; } + int edgeCount() const override { return (int)edges_.size(); } + const NetEdgeDef& edge(int i) const override { return edges_[i]; } + + // --- entity spawn list --- + int spawnCount() const override { return (int)spawns_.size(); } + const UnitSpawn& spawn(int i) const override { return spawns_[i]; } + +private: + MapGenerator &gen_; + std::vector nodes_; + std::vector edges_; + std::vector spawns_; + + // Network graph: AIRLK root at the airlock room, one node per room + // (the hive room's node is the HIVE), plus a DOOR node pinned to the + // hive door tile. Edges chain the rooms and hang the door off the hive. + void buildNetwork() { + nodes_.clear(); + edges_.clear(); + const std::vector &rooms = gen_.getRooms(); + if (rooms.empty()) return; + + static char labelBuf[MAX_NODES][8]; // stable storage for "N" labels + int nextLabel = 0; + int hiveNodeIdx = -1; + int doorNodeIdx = -1; + + for (size_t i = 0; i < rooms.size(); i++) { + int tx = rooms[i].centerX; + int ty = rooms[i].centerY; + if (i == 0) { + nodes_.push_back({ "AIRLK", tx, ty, C_AIRLOCK, 3, true, NR_ROOT }); + } else if ((int)i == gen_.getHiveRoomIdx()) { + nodes_.push_back({ "HIVE", tx, ty, C_HIVE, 3, false, NR_HIVE }); + hiveNodeIdx = (int)nodes_.size() - 1; + } else { + // "N" with k = node index (manual itoa: toolchain-safe) + char *buf = labelBuf[nextLabel++ % MAX_NODES]; + buf[0] = 'N'; + int v = (int)nodes_.size(), len = 1; + if (v >= 10) buf[len++] = (char)('0' + v / 10); + buf[len++] = (char)('0' + v % 10); + buf[len] = '\0'; + nodes_.push_back({ buf, tx, ty, C_NODE, 3, false, NR_NONE }); + } + } + + // door node pinned to the hive door tile (falls back to any door) + const std::vector &doors = gen_.getDoors(); + int doorIdx = -1; + for (size_t d = 0; d < doors.size(); d++) { + if (doors[d].isHive) { doorIdx = (int)d; break; } + } + if (doorIdx < 0 && !doors.empty()) doorIdx = 0; + if (doorIdx >= 0) { + nodes_.push_back({ "DOOR", doors[doorIdx].tx, doors[doorIdx].ty, + C_DOOR, 3, false, NR_DOOR }); + doorNodeIdx = (int)nodes_.size() - 1; + } + + // edges: room chain + door hanging off the hive node + for (size_t i = 1; i < nodes_.size(); i++) { + if (i == (size_t)doorNodeIdx) continue; // door handled below + edges_.push_back({ (uint8_t)(i - 1), (uint8_t)i, edgeLabel(i - 1, (int)i) }); + } + if (hiveNodeIdx >= 0 && doorNodeIdx >= 0) { + edges_.push_back({ (uint8_t)hiveNodeIdx, (uint8_t)doorNodeIdx, + edgeLabel(hiveNodeIdx, doorNodeIdx) }); + } + } + + const char* edgeLabel(int a, int b) { + static char buf[MAX_EDGES][24]; + static int next = 0; + char *out = buf[next % MAX_EDGES]; + next++; + const char *la = nodes_[a].label; + const char *lb = nodes_[b].label; + int p = 0; + while (*la && p < 10) out[p++] = *la++; + out[p++] = '-'; + while (*lb && p < 22) out[p++] = *lb++; + out[p] = '\0'; + return out; + } + + // Spawn list: marines first (slots 0/1 are the squad), then the garrison. + // Droids patrol between their spawn tile and their room's center. + void buildSpawns() { + spawns_.clear(); + const std::vector &units = gen_.getUnits(); + const std::vector &rooms = gen_.getRooms(); + + // marines first + for (const auto &u : units) { + if (u.kind != 0) continue; + spawns_.push_back({ u.kind, u.tx, u.ty, -1, -1 }); + } + for (const auto &u : units) { + if (u.kind == 0) continue; + UnitSpawn s; + s.kind = u.kind; + s.tx = u.tx; + s.ty = u.ty; + s.patA = s.patB = -1; + if (u.kind == 1) { // droids patrol spawn tile <-> room center + const Room *room = roomAt(u.tx, u.ty, rooms); + if (room) { + int a = u.ty * TILE_COLS + u.tx; + int b = room->centerY * TILE_COLS + room->centerX; + if (a != b) { s.patA = a; s.patB = b; } + } + } + spawns_.push_back(s); + } + } + + static const Room* roomAt(int tx, int ty, const std::vector &rooms) { + for (const auto &r : rooms) + if (tx >= r.x0 && tx <= r.x1 && ty >= r.y0 && ty <= r.y1) return &r; + return nullptr; + } +}; + +} // namespace nd diff --git a/src/netdeck/nd_mapsource.h b/src/netdeck/nd_mapsource.h new file mode 100644 index 0000000..059cfe3 --- /dev/null +++ b/src/netdeck/nd_mapsource.h @@ -0,0 +1,137 @@ +/** + * @file nd_mapsource.h + * @brief NetDeck — Breach & Board: generic map source interface. + * + * One interface for everything that is map-specific: the tile grid, the + * structural elements (rooms, doors, cameras), the network graph (nodes + + * edges) and the entity spawn list. A scenario populates its runtime + * structures from a MapSource exactly once and afterwards never needs to + * know (or check) where the map came from — the hardcoded demo floorplan + * and the random MapGenerator are interchangeable behind the interface. + * + * Header-only: include from sketch or test harness. + */ +#pragma once + +#include +#include +#include +#include "nd_layout.h" + +namespace nd { + +// --------------------------------------------------------------------------- +// Pool bounds for source-driven structures (sized for the worst generated map) +// --------------------------------------------------------------------------- +constexpr int MAX_NODES = 12; // network nodes across any map source +constexpr int MAX_EDGES = 16; // network edges across any map source + +// --------------------------------------------------------------------------- +// Special node roles (replace the old hardcoded N_AIRLK/N_DOOR/N_HIVE indices) +// --------------------------------------------------------------------------- +enum NodeRole : uint8_t { + NR_NONE = 0, // plain junction node + NR_ROOT, // airlock uplink: always online, trace endpoint + NR_DOOR, // click toggles the blast door(s) + NR_HIVE, // ICE-protected hive: cracking spawns the red trace + NR_CAMERA, // camera: larger fog-of-war reveal radius while online +}; + +// --------------------------------------------------------------------------- +// Shared data structures (one shape for every map source) +// --------------------------------------------------------------------------- +struct Room { + int x0, y0; // top-left corner (inclusive) + int x1, y1; // bottom-right corner (inclusive) + int centerX; // center tile coordinate + int centerY; + int area; // number of floor tiles +}; + +struct Door { + int tx, ty; // tile coordinate ('+' on the map) + bool open; // whether the door starts open + bool isAirlock; // true if this is the airlock door + bool isHive; // true if this door leads to the hive room +}; + +struct Camera { + int tx, ty; // tile coordinate + int id; // camera ID + uint16_t color; // render color (C_CAMERA) +}; + +// A network node as the scenario consumes it (static definition — the +// runtime online state lives in the scenario, not here) +struct NetNodeDef { + const char* label; + int tx, ty; // tile position + uint16_t color; // render color + uint8_t sight; // fog reveal radius (tiles) while online + bool online; // initial online state (root = true) + uint8_t role; // NodeRole +}; + +struct NetEdgeDef { + uint8_t a, b; // node indices + const char* label; // "AIRLK-JUNC" style, for logs +}; + +// One entity spawn: applied by the scenario layer once at setup/reset. +// kind uses the shared unit taxonomy: 0=marine, 1=droid, 2=heavy, 3=turret. +struct UnitSpawn { + uint8_t kind; + int tx, ty; + int patA, patB; // patrol endpoints as tile indices (-1 = stationary) +}; + +// --------------------------------------------------------------------------- +// MapSource abstract interface +// --------------------------------------------------------------------------- +class MapSource { +public: + virtual ~MapSource() = default; + + // --- tile grid --- + virtual char tileAt(int tx, int ty) const = 0; + virtual const std::vector& getMap() const = 0; + + // --- structures --- + virtual const std::vector& getRooms() const = 0; + virtual const std::vector& getDoors() const = 0; + virtual const std::vector& getCameras() const = 0; + + // --- network graph --- + virtual int nodeCount() const = 0; + virtual const NetNodeDef& node(int i) const = 0; + virtual int edgeCount() const = 0; + virtual const NetEdgeDef& edge(int i) const = 0; + + // --- entity spawn list --- + virtual int spawnCount() const = 0; + virtual const UnitSpawn& spawn(int i) const = 0; + + // --- role lookups (shared implementation; -1 if the map has no such node) + int nodeByRole(uint8_t role) const { + for (int i = 0; i < nodeCount(); i++) + if (node(i).role == role) return i; + return -1; + } + int rootNode() const { return nodeByRole(NR_ROOT); } + int hiveNode() const { return nodeByRole(NR_HIVE); } + int doorNode() const { return nodeByRole(NR_DOOR); } + + // First tile carrying `ch` (e.g. 'T' terminal, 'A' airlock); -1 if absent. + // Scans the tile grid, so it works for every source without branching. + bool findTile(char ch, int& tx, int& ty) const { + const std::vector& m = getMap(); + for (int y = 0; y < TILE_ROWS && y < (int)m.size(); y++) { + for (int x = 0; x < TILE_COLS && x < (int)m[y].size(); x++) { + if (m[y][x] == ch) { tx = x; ty = y; return true; } + } + } + return false; + } +}; + +} // namespace nd