// sc2k/sim/network_path.hpp — the faithful network-drawing PATH SOLVER (Phase 1 of the network-drawing // reimplementation; see docs/ref/re/reimpl/08-network-drawing.md). PURE: it reads the City and returns the // tile sequence a road/rail/power/pipe/subway drag would lay from an anchor to an end tile — it does NOT // mutate anything. The commit + per-tile place/autotile (Phase 2) and the live preview (Phase 3) build on // this. // // A direct port of the original's shared drag engine: // walk-init (validate the start, store the end, pick the initial direction, set the clip box) // stepper (advance one tile toward the end, choosing the piece direction + checking legality) // dir choose (primary axis / minor axis — the L-bend logic) // with its six data tables. Layer addressing and // every legality branch are transcribed exactly; the only deviations are bounds guards where // the original relied on the unbuilt 1-tile map border. #pragma once #include #include #include #include #include "sc2k/city.hpp" #include "sc2k/terrain/query.hpp" #include "sc2k/tile_codes.hpp" #include "sc2k/sim/water_network.hpp" namespace sc2k::sim { // Network type = the original's drag-state byte. <3 = surface (reads/blocks on XBLD); // ≥3 = underground (reads/blocks on XUND). Verified from the five commit handlers. enum class NetType : int { Road = 0, Rail = 1, Power = 2, Subway = 3, Pipe = 4 }; // One tile the path visits. `dir` is the step direction used to reach it (0=W,1=S,2=E,3=N); the final // XBLD/XUND code is decided later by the autotiler from neighbours, so the solver only carries direction. struct PathStep { int row; int col; int dir; }; struct NetworkPath { bool valid = false; // start tile was buildable std::vector steps; // anchor first, then every stepped tile until the path stops int endRow = -1, endCol = -1; // the last tile actually reachable (== steps.back()) }; // The underground floor can present mains on flat ground and the four cardinal ramps. Corner and terrace // shapes need geometry the pipe artwork does not contain, so they may retain imported mains but cannot // receive new ones. inline bool pipe_terrain_supported(const terrain::TileQuery& tile) { return static_cast(tile.shape) <= 4; } namespace netdetail { // dRow / dCol — direction 0=W,1=S,2=E,3=N. inline constexpr int DR[4] = {0, 1, 0, -1}; inline constexpr int DC[4] = {-1, 0, 1, 0}; // RAMP[XTER&0xF]: 1 ⇒ "continue straight / ramp" branch in the stepper (slope shapes the network // rides along); 0 (incl. flat shape 0) ⇒ the bendable branch. inline constexpr int RAMP[16] = {0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0}; // ALTRISE[XTER&0xF]: slope shapes that raise the network one altitude level (the grade continuity term). inline constexpr int ALTRISE[16] = {0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0}; // TERRACE[XTER&0xF]: shapes needing terracing — each adds the $25 terraform surcharge (cost model). inline constexpr int TERRACE[16] = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0}; // SLOPEBLK[XTER&0xF * 4 + dir]: nonzero ⇒ a network in `dir` is forbidden on this slope shape ⇒ a sloped // piece may only run ALONG the gradient. Shapes 1-4 block the cross-gradient pair; 14/15 block W/E. // clang-format off inline constexpr std::uint8_t SLOPEBLK[64] = { 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 2, 0, 1, 0, }; // clang-format on inline bool on_map(const City& city, int r, int c) { return city.on_map(r, c); } // Primary-axis direction toward (er,ec): step whichever axis has the greater remaining distance. inline int dir_primary(int r, int c, int er, int ec) { const int rd = std::abs(r - er), cd = std::abs(c - ec); if (cd >= rd) return (ec < c) ? 0 : 2; // col dominates → W / E return (er >= r) ? 1 : 3; // row dominates → S / N } // Minor-axis direction (the bend's second leg / reroute when the primary step is illegal). inline int dir_minor(int r, int c, int er, int ec) { const int rd = std::abs(r - er), cd = std::abs(c - ec); if (cd >= rd) { if (rd <= 0) return (ec < c) ? 0 : 2; return (er >= r) ? 1 : 3; } if (cd <= 0) return (er >= r) ? 1 : 3; return (ec < c) ? 0 : 2; } // The drag state the engine threads through walk-init + every step. struct DragState { int net = 0; // [+144] network type int dir = 0; // [+104] current piece direction int endRow = 0, endCol = 0; // [+132]/[+136] destination int loR = 0, hiR = 0, loC = 0, hiC = 0; // [+112]/[+120]/[+116]/[+124] clip box }; inline bool pipe_subway_crossing(int xundCode, int dir) { return ((dir & 1) + xundCode) == 2; } inline bool pipe_tile_buildable(int xundCode, int dir) { return xundCode == xund::kNone || xund::is_pipe(std::uint8_t(xundCode)) || pipe_subway_crossing(xundCode, dir); } inline bool pipe_ground_available(const City& city, const terrain::TileQuery& tile, int row, int column) { return has_water_main(city, row, column) || pipe_terrain_supported(tile); } // Walk init — validate the anchor, store the end, choose the initial direction, set the clip box. // Returns false if the anchor itself is not buildable (the whole drag is then rejected). inline bool walk_init(const City& c, const terrain::Query& terrainQuery, DragState& st, int r, int col, int er, int ec, NetType net, bool prepareSurface) { st.net = static_cast(net); const int xb = c.xbld.at(r, col); if (st.net <= 2) { // surface: road/rail/power if (xb >= 0x51 || !terrainQuery.dry({r, col})) return false; // bridge/elevated, or water terrain if (xb == 13) return false; } if (st.net != 4 && st.net != 3 && xb == 5) return false; // radioactive (allowed only for pipe/subway) if (st.net != 6 && (c.xzon.at(r, col) & 0x0F) == 7) return false; // military zone st.endRow = er; st.endCol = ec; st.dir = dir_primary(r, col, er, ec); const terrain::TileQuery anchorTerrain = terrainQuery.tile({r, col}); if (net == NetType::Pipe && !pipe_ground_available(c, anchorTerrain, r, col)) return false; const int shape = prepareSurface && net == NetType::Road ? 0 : static_cast(anchorTerrain.shape); if (shape >= 1 && shape <= 4) { // anchor on a cardinal slope 1-4 const int base = 4 * shape; if (SLOPEBLK[st.dir + base]) { // initial dir runs across the gradient st.dir = dir_minor(r, col, er, ec); // try the other axis if (SLOPEBLK[st.dir + base]) { st.endRow = r; st.endCol = col; } // still illegal → single tile } } st.loR = std::min(r, er); st.hiR = std::max(r, er); st.loC = std::min(col, ec); st.hiC = std::max(col, ec); return true; } // Stepper — advance (r,col) one tile toward the end, choosing the direction and validating legality. // Returns false to STOP (end reached or blocked); on true, (r,col) hold the next tile and st.dir the // direction used. `r,col` are passed by reference. inline bool step(const City& c, const terrain::Query& terrainQuery, DragState& st, int& r, int& col, bool prepareSurface) { if (st.endRow == r && st.endCol == col) return false; // reached the destination // Is the CURRENT tile a same-network crossing/continuation? (lets a ramp/crossing keep its direction.) int crossing = 0; if (st.net < 3) { // surface → XBLD const int xb = c.xbld.at(r, col); if (xb >= 0x0E) { const int v = (st.dir & 1) + xb; if (v == 30 || v == 45 || v == 15 || v == 74) crossing = 1; } } else { // underground → XUND const int xu = c.xund.at(r, col); if (st.net == static_cast(NetType::Pipe)) { // Native mains have their own layer, so subway occupancy never constrains a pipe drag. } else if (xu) { const int v = (st.dir & 1) + xu; if (v == 17 || v == 2) crossing = 1; } } const terrain::TileQuery currentTerrain = terrainQuery.tile({r, col}); const bool preparedRoad = prepareSurface && st.net == static_cast(NetType::Road); const int curShape = preparedRoad ? 0 : static_cast(currentTerrain.shape); const int curAlt = preparedRoad ? 0 : currentTerrain.base_level(); if (st.net == static_cast(NetType::Pipe) && has_water_main(c, r, col) && !pipe_terrain_supported(currentTerrain)) crossing = 1; // compatibility main: follow it without applying surface-grade rules int nr, nc; if (crossing || RAMP[curShape]) { // Continue-straight branch: keep st.dir; the clip box is what stops an overshoot here. nr = r + DR[st.dir]; nc = col + DC[st.dir]; if (nr < st.loR || nc < st.loC || nr > st.hiR || nc > st.hiC) return false; // outside clip box if (!on_map(c, nr, nc)) return false; const terrain::TileQuery nextTerrain = terrainQuery.tile({nr, nc}); const int nextShape = preparedRoad ? 0 : static_cast(nextTerrain.shape); if (st.net == static_cast(NetType::Pipe) && !pipe_ground_available(c, nextTerrain, nr, nc)) return false; if (st.net == 1 && !nextTerrain.flat() && nextTerrain.base_level() != curAlt) return false; // rail: sloped + level mismatch if (SLOPEBLK[4 * nextShape + st.dir]) return false; // next slope forbids this dir } else { // Bendable branch: choose the direction toward the end, with an altitude/slope reroute to the minor // axis. gradeHeight = the running grade height the next tile must continue. const int gradeHeight = ALTRISE[curShape] + curAlt; auto blocked = [&](int d, int& or_, int& oc_) { or_ = r + DR[d]; oc_ = col + DC[d]; if (!on_map(c, or_, oc_)) return true; const terrain::TileQuery nextTerrain = terrainQuery.tile({or_, oc_}); const int nShape = preparedRoad ? 0 : static_cast(nextTerrain.shape); const int nAlt = preparedRoad ? 0 : nextTerrain.base_level(); if (st.net == static_cast(NetType::Pipe) && !pipe_ground_available(c, nextTerrain, or_, oc_)) return true; if (st.net == static_cast(NetType::Pipe) && has_water_main(c, or_, oc_) && !pipe_terrain_supported(nextTerrain)) return false; // compatibility main: its imported route outranks surface-grade rules if (SLOPEBLK[4 * nShape + d]) return true; // slope forbids this direction if (ALTRISE[nShape] && (nAlt == gradeHeight || nAlt - gradeHeight == -2)) return true; // grade discontinuity if (nextTerrain.flat() && nAlt - gradeHeight == -1) return true; return false; }; int d = dir_primary(r, col, st.endRow, st.endCol); if (blocked(d, nr, nc)) { // primary step illegal → try the minor axis d = dir_minor(r, col, st.endRow, st.endCol); if (blocked(d, nr, nc)) return false; // both illegal → stop } if (st.net == 1 && st.dir != d && !terrainQuery.flat({nr, nc})) return false; // rail can't turn onto sloped terrain st.dir = d; } if (!on_map(c, nr, nc)) return false; // Common tail: validate the destination tile (nr,nc). if (st.net != 6 && (c.xzon.at(nr, nc) & 0x0F) == 7) return false; // military zone if (st.net < 3) { // surface if (!terrainQuery.dry({nr, nc}) && c.xbld.at(nr, nc) < 0x40) return false; // open water (bridge is separate) const int xbN = c.xbld.at(nr, nc); if (xbN == 5 || xbN == 13) return false; // radioactive / code 13 if (xbN >= 0x0D) { // occupied — only a perpendicular crossing passes const int v = (st.dir & 1) + xbN; if (v != 30 && v != 45 && v != 15 && v != 74) return false; } } else { // underground const int depth = (c.altm.at(nr, nc) & 0x7C00) >> 10; // tunnel depth bits if (depth == 1 || depth == 2) return false; const int xuN = c.xund.at(nr, nc); if (st.net == static_cast(NetType::Pipe)) { // Water mains and subways are independent native layers. } else if (xuN) { const int v = (st.dir & 1) + xuN; if (v != 17 && v != 2) return false; } } r = nr; col = nc; return true; } } // namespace netdetail // Solve the path a drag of `net` from (anchorR,anchorC) to (endR,endC) would lay. The returned `steps` // begin at the anchor and run to wherever the path stops (the end tile, or earlier if blocked) — exactly the // tiles the original's commit walk places. inline NetworkPath solve_network_path(const City& c, int anchorR, int anchorC, int endR, int endC, NetType net, const terrain::Model* terrainModel = nullptr, bool prepareSurface = false) { NetworkPath p; if (!netdetail::on_map(c, anchorR, anchorC) || !netdetail::on_map(c, endR, endC)) return p; const terrain::Query terrainQuery(c, terrainModel); netdetail::DragState st; if (!netdetail::walk_init(c, terrainQuery, st, anchorR, anchorC, endR, endC, net, prepareSurface)) return p; // valid stays false p.valid = true; int r = anchorR, col = anchorC; p.steps.push_back({r, col, st.dir}); while (netdetail::step(c, terrainQuery, st, r, col, prepareSurface)) p.steps.push_back({r, col, st.dir}); p.endRow = r; p.endCol = col; return p; } inline NetworkPath solve_construction_network_path(const City& city, int anchorRow, int anchorColumn, int endRow, int endColumn, NetType net, const terrain::Model* terrainModel = nullptr) { return solve_network_path(city, anchorRow, anchorColumn, endRow, endColumn, net, terrainModel, net == NetType::Road); } // The terraform-surcharge tile count for the cost model (cost = 25·terrace + perTile·total). A tile counts // if its terrain slope shape needs terracing (TERRACE) — the same set the original's cost pass accumulates. inline int path_terrace_tiles(const City& c, const NetworkPath& p, const terrain::Model* terrainModel = nullptr) { const terrain::Query terrainQuery(c, terrainModel); int n = 0; for (const auto& s : p.steps) if (netdetail::TERRACE[static_cast(terrainQuery.tile({s.row, s.col}).shape)]) ++n; return n; } // Underground networks do not terrace the surface. Keep this distinction beside the shared cost helper so // preview and commit cannot drift: pipes/subways pay only their per-tile price, regardless of the landscape // above them; road/rail/power retain the surface-network terraform surcharge. inline int network_terrace_tiles(const City& c, const NetworkPath& p, NetType net, const terrain::Model* terrainModel = nullptr) { if (net == NetType::Pipe || net == NetType::Subway) return 0; return path_terrace_tiles(c, p, terrainModel); } // Pipe painting is idempotent: existing player-built mains are traversed but not purchased again. // Compatibility-only XBIT capillaries are not mains, so painting over one still counts as construction. inline int network_chargeable_tiles(const City& c, const NetworkPath& p, NetType net) { if (net != NetType::Pipe) return static_cast(p.steps.size()); int count = 0; for (const auto& s : p.steps) if (!has_water_main(c, s.row, s.col)) ++count; return count; } inline int network_path_cost(const City& c, const NetworkPath& p, NetType net, int perTileCost, const terrain::Model* terrainModel = nullptr) { return 25 * network_terrace_tiles(c, p, net, terrainModel) + perTileCost * network_chargeable_tiles(c, p, net); } } // namespace sc2k::sim