// commute.cpp — out-of-line bodies for sc2k/sim/commute.hpp (see the header for the RE notes + contracts). // Split out of the header so editing an implementation recompiles just this TU (Task 5). #include "sc2k/sim/commute.hpp" #include "sc2k/sim/region.hpp" #include "sc2k/terrain/query.hpp" #include "sc2k/tile_codes.hpp" #include #include #include namespace sc2k { CommuteStep commute_transition(int mode, int xbld, int zoneNibble, int xund, int altmHi, int sourceZone) { CommuteStep s; const bool job = ((1u << (zoneNibble & 0xF)) & kCommuteAcceptMask[sourceZone & 0xF]) != 0; auto step = [&](int m, int c) { s.moved = true; s.mode = m; s.cost = c; }; switch (mode) { case 0: // surface road, low-priority network if (job) { s.found = s.moved = true; } else if (xbld >= 0x3F && xbld < 0x43) step(2, 3); else if ((xbld >= 0x51 && xbld < 0x5D) || xbld == 106 || xbld == 107) step(3, 3); else if (xbld >= 0x5D && xbld < 0x61) step(1, 2); else if (is_commute_road(xbld)) step(0, 3); else if (xbld == 0xEC) step(8, 4); else if (xbld == sc2k::xbld::kRailDepot) step(10, 4); else if (xbld == sc2k::xbld::kSubwayStation) step(11, 4); else if (xbld > 0xFA) { s.found = s.moved = true; } break; case 1: // leg off a road onto a connector if (sc2k::xbld::is_highway(std::uint8_t(xbld))) step(1, 1); else if (xbld >= 0x5D && xbld < 0x61) step(0, 1); break; case 2: // bridge/tunnel leg (ALTM flag bits) if ((altmHi & 0x7C) != 0) step(2, 3); else if (is_commute_road(xbld)) step(0, 3); break; case 3: // ramp/connector leg back to road if ((xbld >= 0x51 && xbld < 0x5D) || xbld == 106 || xbld == 107) step(3, 3); else if (is_commute_road(xbld)) step(0, 3); break; case 4: // high-priority road network (cheaper) if (job) { s.found = s.moved = true; } else if (xbld >= 0x3F && xbld < 0x43) step(6, 2); else if ((xbld >= 0x51 && xbld < 0x5D) || xbld == 106 || xbld == 107) step(7, 2); else if (xbld >= 0x5D && xbld < 0x61) step(5, 2); else if (is_commute_road(xbld)) step(4, 2); else if (xbld == 0xEC) step(9, 4); else if (xbld == sc2k::xbld::kRailDepot) step(10, 4); else if (xbld == sc2k::xbld::kSubwayStation) step(11, 4); else if (xbld > 0xFA) { s.found = s.moved = true; } break; case 5: if (sc2k::xbld::is_highway(std::uint8_t(xbld))) step(5, 1); else if (xbld >= 0x5D && xbld < 0x61) step(4, 1); break; case 6: if ((altmHi & 0x7C) != 0) step(6, 2); else if (is_commute_road(xbld)) step(4, 2); break; case 7: if ((xbld >= 0x51 && xbld < 0x5D) || xbld == 106 || xbld == 107) step(7, 2); else if (is_commute_road(xbld)) step(4, 2); break; case 8: // rail leg (code 236) if (job) { s.found = s.moved = true; } else if (xbld == 236) step(8, 4); else if (is_commute_road(xbld)) step(4, 2); break; case 9: // rail leg (codes 236/237) if (job) { s.found = s.moved = true; } else if (xbld == 236 || xbld == 237) step(9, 4); else if (is_commute_road(xbld)) step(0, 3); break; case 10: // rail along the rail-bed (code 237) if (xbld == 237) step(10, 4); else if (is_commute_railbed(xbld)) step(12, 1); break; case 11: // subway leg (XUND) if (is_commute_subway(xund)) step(13, 1); break; case 12: // rail-bed surface leg if (xbld == 237) step(9, 4); else if (is_commute_railbed(xbld)) step(12, 1); else if (xbld > 0xFA) { s.found = s.moved = true; } break; case 13: // subway leg, may surface to rail (233) if (xbld == sc2k::xbld::kSubwayStation) step(9, 4); else if (is_commute_subway(xund)) step(13, 1); break; default: break; } return s; } } // namespace sc2k namespace sc2k { CommuteTravelMode commute_travel_mode(int automatonMode) { if (automatonMode >= 0 && automatonMode <= 3) return CommuteTravelMode::Car; if (automatonMode >= 4 && automatonMode <= 9) return CommuteTravelMode::Bus; if (automatonMode == 10 || automatonMode == 12) return CommuteTravelMode::Rail; if (automatonMode == 11 || automatonMode == 13) return CommuteTravelMode::Subway; return CommuteTravelMode::Count; } int commute_access_distance(int sourceZone) { if (sourceZone == 1 || sourceZone == 2) return 5; if (sourceZone == 3 || sourceZone == 4) return 4; if (sourceZone == 5 || sourceZone == 6) return 6; return 0; } namespace { int access_seed_mode(std::uint8_t building) { if (is_commute_road(building)) return 0; if (building == xbld::kBusDepot) return 8; if (building == xbld::kRailDepot) return 10; if (building == xbld::kSubwayStation) return 11; return -1; } } // namespace bool has_commute_access(const City& city, int row, int column, int sourceZone) { const int maximumDistance = commute_access_distance(sourceZone); for (int distance = 1; distance <= maximumDistance; ++distance) { for (int dr = -distance; dr <= distance; ++dr) { const int dc = distance - std::abs(dr); const int candidateColumns[2] = {column - dc, column + dc}; const int count = dc == 0 ? 1 : 2; for (int index = 0; index < count; ++index) { const int candidateRow = row + dr; const int candidateColumn = candidateColumns[index]; if (!city.on_map(candidateRow, candidateColumn)) continue; if (access_seed_mode(city.xbld.at(candidateRow, candidateColumn)) >= 0) return true; } } } return false; } int commute_generalized_step_cost(int automatonMode, int building, int underground, std::uint8_t density) { (void)underground; const bool station = building == xbld::kBusDepot || building == xbld::kRailDepot || building == xbld::kSubwayStation; if (station) return 5 + density / 128; switch (commute_travel_mode(automatonMode)) { case CommuteTravelMode::Car: return (xbld::is_highway(static_cast(building)) ? 2 : 4) + density / 32; case CommuteTravelMode::Bus: return (xbld::is_highway(static_cast(building)) ? 1 : 3) + density / 32; case CommuteTravelMode::Rail: return 2 + density / 255; case CommuteTravelMode::Subway: return 1 + density / 255; case CommuteTravelMode::Count: break; } return 0; } std::optional commute_funded_step_cost_basis_points( int nominalCost, std::int32_t efficiencyBasisPoints) noexcept { if (nominalCost < 0 || efficiencyBasisPoints <= 0 || efficiencyBasisPoints > sim::kMaximumOperatingEfficiencyBasisPoints) return std::nullopt; const std::int64_t numerator = std::int64_t(nominalCost) * sim::kFullOperatingEfficiencyBasisPoints * sim::kFullOperatingEfficiencyBasisPoints; return (numerator + efficiencyBasisPoints - 1) / efficiencyBasisPoints; } void accumulate_commute_diagnostics(CommutePeriodDiagnostics& diagnostics, bool success, const CommuteRouteProbe& probe) { ++diagnostics.attempts; diagnostics.successes += success; diagnostics.generalizedCost += probe.generalizedCost; diagnostics.generalizedCostBasisPoints += probe.generalizedCostBasisPoints; diagnostics.expandedStates += probe.expandedStates; diagnostics.maximumExpandedStates = std::max( diagnostics.maximumExpandedStates, probe.expandedStates); diagnostics.trafficCellsStamped += probe.trafficCellsStamped; const std::size_t stop = static_cast(probe.stop); if (stop < diagnostics.stops.size()) ++diagnostics.stops[stop]; for (std::size_t mode = 0; mode < diagnostics.modeSteps.size(); ++mode) { diagnostics.modeSteps[mode] += probe.modeSteps[mode]; if (probe.modeSteps[mode] > 0) ++diagnostics.modeTrips[mode]; } } void CommuteRouteHistory::consider(CommuteRouteTrace trace) { const bool accepted = trace.stop == CommuteRouteStop::Destination || trace.stop == CommuteRouteStop::BorderConnection; std::vector& routes = accepted ? accepted_ : failed_; const std::size_t maximum = accepted ? kMaximumAcceptedRoutes : kMaximumFailedRoutes; const auto less = [](const CommuteRouteTrace& left, const CommuteRouteTrace& right) { return std::tie(left.sampleKey, left.originRow, left.originColumn, left.stop) < std::tie(right.sampleKey, right.originRow, right.originColumn, right.stop); }; const auto position = std::lower_bound(routes.begin(), routes.end(), trace, less); if (routes.size() == maximum && position == routes.end()) return; routes.insert(position, std::move(trace)); if (routes.size() > maximum) routes.pop_back(); } } // namespace sc2k namespace sc2k { namespace { struct AccessSeed { int row = 0; int column = 0; int mode = -1; int distance = 0; }; std::vector gather_access_seeds(const City& city, int row, int column, int sourceZone) { std::array nearest; nearest.fill(std::numeric_limits::max()); std::vector seeds; const int maximumDistance = commute_access_distance(sourceZone); for (int distance = 1; distance <= maximumDistance; ++distance) { for (int dr = -distance; dr <= distance; ++dr) { const int dc = distance - std::abs(dr); const int candidateColumns[2] = {column - dc, column + dc}; const int count = dc == 0 ? 1 : 2; for (int index = 0; index < count; ++index) { const int candidateRow = row + dr; const int candidateColumn = candidateColumns[index]; if (!city.on_map(candidateRow, candidateColumn)) continue; const int mode = access_seed_mode(city.xbld.at(candidateRow, candidateColumn)); if (mode < 0 || distance > nearest[mode]) continue; if (distance < nearest[mode]) { nearest[mode] = distance; std::erase_if(seeds, [mode](const AccessSeed& seed) { return seed.mode == mode; }); } seeds.push_back({candidateRow, candidateColumn, mode, distance}); } } } std::sort(seeds.begin(), seeds.end(), [](const AccessSeed& left, const AccessSeed& right) { return std::tie(left.distance, left.row, left.column, left.mode) < std::tie(right.distance, right.row, right.column, right.mode); }); return seeds; } std::uint32_t mix_route_key(std::uint32_t value) { value ^= value >> 16; value *= 0x7feb352du; value ^= value >> 15; value *= 0x846ca68bu; return value ^ (value >> 16); } std::uint32_t route_tie(std::uint32_t nonce, int state) { return mix_route_key(nonce ^ (static_cast(state) * 0x9e3779b9u)); } CommuteTravelMode route_state_travel_mode( const City& city, int row, int column, int automatonMode) { if (automatonMode != 9) return commute_travel_mode(automatonMode); const std::uint8_t building = city.xbld.at(row, column); if (building == xbld::kRailDepot) return CommuteTravelMode::Rail; if (building == xbld::kSubwayStation) return CommuteTravelMode::Subway; return CommuteTravelMode::Bus; } std::optional border_kind_for_state( const City& city, int row, int column, int mode) { const CommuteTravelMode travelMode = route_state_travel_mode(city, row, column, mode); if (travelMode == CommuteTravelMode::Rail) return sim::BorderConnectionKind::Rail; if (travelMode == CommuteTravelMode::Subway) return std::nullopt; const std::uint8_t building = city.xbld.at(row, column); if (xbld::is_highway(building)) return sim::BorderConnectionKind::Highway; if (is_commute_road(building)) return sim::BorderConnectionKind::Road; return std::nullopt; } bool compatible_border_connection(const City& city, int row, int column, int direction, int mode, std::span connections) { const int edgeSlotByDirection[4] = {3, 0, 1, 2}; const int edgeSlot = edgeSlotByDirection[direction]; const int offset = sim::border_offset(edgeSlot, row, column); const std::optional required = border_kind_for_state(city, row, column, mode); if (!required || offset < 0) return false; return std::any_of(connections.begin(), connections.end(), [&](const sim::BorderConnection& connection) { return connection.edge_slot == edgeSlot && connection.kind == *required && offset >= connection.offset && offset < connection.offset + connection.footprint; }); } } // namespace namespace { bool commute_route_impl(const City& city, City* trafficTarget, int row, int column, int sourceZone, int weight, int maxCost, MsRand& rng, std::span connections, CommuteRouteProbe* probe, CommuteRouteTrace* trace, CommuteRouteConfig config) { if (probe != nullptr) *probe = {}; if (trace != nullptr) { *trace = {}; trace->originRow = static_cast(row); trace->originColumn = static_cast(column); trace->terminalRow = static_cast(row); trace->terminalColumn = static_cast(column); } const bool validServiceEfficiency = std::all_of( config.serviceEfficiency.modeBasisPoints.begin(), config.serviceEfficiency.modeBasisPoints.end(), [](std::int32_t efficiency) { return efficiency >= 0 && efficiency <= sim::kMaximumOperatingEfficiencyBasisPoints; }) && config.serviceEfficiency.basis_points(CommuteTravelMode::Car) == sim::kFullOperatingEfficiencyBasisPoints; if (config.version != kCommuteRouteConfigurationVersion || config.maximumExpandedStates <= 0 || config.accessCostPerTile < 0 || config.accessCostPerTile > std::numeric_limits::max() / 6 || maxCost < 0 || sourceZone < 1 || sourceZone > 6 || !city.on_map(row, column) || weight < 0 || !validServiceEfficiency) { if (probe != nullptr) probe->stop = CommuteRouteStop::InvalidConfiguration; return false; } if (probe != nullptr) probe->effectiveMaxCost = maxCost; const std::vector seeds = gather_access_seeds(city, row, column, sourceZone); if (probe != nullptr) { probe->accessCandidates = static_cast(seeds.size()); if (!seeds.empty()) probe->minimumAccessDistance = seeds.front().distance; } if (seeds.empty()) return false; const bool hasUnavailableSeed = std::any_of(seeds.begin(), seeds.end(), [&](const AccessSeed& seed) { const CommuteTravelMode travelMode = route_state_travel_mode( city, seed.row, seed.column, seed.mode); return config.serviceEfficiency.basis_points(travelMode) == 0; }); if (hasUnavailableSeed && std::all_of(seeds.begin(), seeds.end(), [&](const AccessSeed& seed) { const CommuteTravelMode travelMode = route_state_travel_mode( city, seed.row, seed.column, seed.mode); return config.serviceEfficiency.basis_points(travelMode) == 0; })) { if (probe != nullptr) probe->stop = CommuteRouteStop::ServiceUnavailable; return false; } const std::uint32_t nonce = rng.next(); const terrain::Query terrainQuery(city); if (probe != nullptr) { probe->randomDraws = 1; probe->routeNonce = nonce; } const int dimension = city.dimension(); const std::size_t stateCount = static_cast(city.tile_count()) * 16; static thread_local std::vector stamp; static thread_local std::vector best; static thread_local std::vector parent; static thread_local int generation = 0; if (stamp.size() != stateCount) { stamp.assign(stateCount, 0); best.resize(stateCount); parent.resize(stateCount); generation = 0; } if (generation == std::numeric_limits::max()) { std::fill(stamp.begin(), stamp.end(), 0); generation = 1; } else { ++generation; } auto stateId = [dimension](int stateRow, int stateColumn, int mode) { return (stateRow * dimension + stateColumn) * 16 + mode; }; using FrontierNode = std::tuple; std::priority_queue, std::greater> frontier; for (const AccessSeed& seed : seeds) { const CommuteTravelMode travelMode = route_state_travel_mode( city, seed.row, seed.column, seed.mode); if (config.serviceEfficiency.basis_points(travelMode) == 0) continue; const int state = stateId(seed.row, seed.column, seed.mode); const std::int64_t cost = std::int64_t(seed.distance) * config.accessCostPerTile * sim::kFullOperatingEfficiencyBasisPoints; if (stamp[state] == generation && best[state] <= cost) continue; stamp[state] = generation; best[state] = cost; parent[state] = -1; frontier.emplace(cost, route_tie(nonce, state), state); } if (probe != nullptr) probe->frontierPeak = static_cast(frontier.size()); bool exceededCost = false; bool encounteredUnavailableService = hasUnavailableSeed; int expandedStates = 0; int terminalState = -1; std::int64_t terminalCost = 0; int terminalRow = row; int terminalColumn = column; CommuteRouteStop successStop = CommuteRouteStop::Destination; const std::int64_t maximumCostBasisPoints = std::int64_t(maxCost) * sim::kFullOperatingEfficiencyBasisPoints; while (!frontier.empty()) { const auto [cost, tie, state] = frontier.top(); (void)tie; frontier.pop(); if (stamp[state] != generation || best[state] != cost) continue; if (expandedStates >= config.maximumExpandedStates) { if (probe != nullptr) probe->stop = CommuteRouteStop::WorkLimit; return false; } if (cost > maximumCostBasisPoints) { exceededCost = true; break; } ++expandedStates; if (probe != nullptr) probe->expandedStates = expandedStates; const int tile = state >> 4; const int mode = state & 15; const int currentRow = tile / dimension; const int currentColumn = tile % dimension; for (int direction = 0; direction < 4; ++direction) { const int nextRow = currentRow + kCommuteDirRow[direction]; const int nextColumn = currentColumn + kCommuteDirCol[direction]; if (!city.on_map(nextRow, nextColumn)) { if (compatible_border_connection(city, currentRow, currentColumn, direction, mode, connections)) { terminalState = state; terminalCost = cost; terminalRow = currentRow; terminalColumn = currentColumn; successStop = CommuteRouteStop::BorderConnection; break; } continue; } const std::size_t next = city.index(nextRow, nextColumn); const int building = city.xbld.cells[next]; const int zone = city.xzon.cells[next] & 0xF; const int underground = city.xund.cells[next]; const int altitudeFlags = terrainQuery.legacy_tunnel_depth({nextRow, nextColumn}) != 0 ? 4 : 0; const CommuteStep step = commute_transition( mode, building, zone, underground, altitudeFlags, sourceZone); if (step.found) { terminalState = state; terminalCost = cost; terminalRow = nextRow; terminalColumn = nextColumn; successStop = CommuteRouteStop::Destination; break; } if (!step.moved) continue; const int density = city.xtrf.at(nextRow / 2, nextColumn / 2); const int nominalStepCost = commute_generalized_step_cost( step.mode, building, underground, static_cast(density)); const CommuteTravelMode travelMode = route_state_travel_mode( city, nextRow, nextColumn, step.mode); const std::int32_t efficiency = config.serviceEfficiency.basis_points(travelMode); const std::optional stepCost = commute_funded_step_cost_basis_points( nominalStepCost, efficiency); if (!stepCost) { encounteredUnavailableService = true; continue; } if (*stepCost > maximumCostBasisPoints - cost) { exceededCost = true; continue; } const std::int64_t nextCost = cost + *stepCost; const int nextState = stateId(nextRow, nextColumn, step.mode); if (stamp[nextState] == generation && best[nextState] <= nextCost) continue; stamp[nextState] = generation; best[nextState] = nextCost; parent[nextState] = state; frontier.emplace(nextCost, route_tie(nonce, nextState), nextState); if (probe != nullptr) { ++probe->relaxedStates; probe->frontierPeak = std::max( probe->frontierPeak, static_cast(frontier.size())); } } if (terminalState >= 0) break; } if (terminalState < 0) { if (probe != nullptr) { if (exceededCost) probe->stop = CommuteRouteStop::CostLimit; else if (encounteredUnavailableService) probe->stop = CommuteRouteStop::ServiceUnavailable; else probe->stop = CommuteRouteStop::SearchExhausted; } return false; } std::vector path; for (int state = terminalState; state >= 0; state = parent[state]) path.push_back(state); std::reverse(path.begin(), path.end()); if (trace != nullptr) trace->points.reserve(path.size()); std::uint32_t pathHash = 2166136261u; for (int state : path) { const int tile = state >> 4; const int mode = state & 15; const int pathRow = tile / dimension; const int pathColumn = tile % dimension; pathHash = (pathHash ^ static_cast(state)) * 16777619u; const CommuteTravelMode travelMode = route_state_travel_mode(city, pathRow, pathColumn, mode); if (trace != nullptr) trace->points.push_back({static_cast(pathRow), static_cast(pathColumn), travelMode}); if (probe != nullptr) ++probe->modeSteps[static_cast(travelMode)]; if (weight <= 0 || trafficTarget == nullptr) continue; const std::uint8_t building = city.xbld.at(pathRow, pathColumn); if ((travelMode == CommuteTravelMode::Car || travelMode == CommuteTravelMode::Bus) && is_commute_road(building)) { std::uint8_t& traffic = trafficTarget->xtrf.at(pathRow / 2, pathColumn / 2); const long long increased = static_cast(traffic) + weight; traffic = static_cast(std::min(255LL, increased)); if (probe != nullptr) ++probe->trafficCellsStamped; } } if (probe != nullptr) { probe->stop = successStop; probe->generalizedCostBasisPoints = terminalCost; probe->generalizedCost = static_cast((terminalCost + sim::kFullOperatingEfficiencyBasisPoints - 1) / sim::kFullOperatingEfficiencyBasisPoints); probe->pathLength = static_cast(path.size()); probe->pathHash = pathHash; } if (trace != nullptr) { trace->terminalRow = static_cast(terminalRow); trace->terminalColumn = static_cast(terminalColumn); trace->stop = successStop; trace->generalizedCost = static_cast((terminalCost + sim::kFullOperatingEfficiencyBasisPoints - 1) / sim::kFullOperatingEfficiencyBasisPoints); } return true; } } // namespace bool commute_route(City& city, int row, int column, int sourceZone, int weight, int maxCost, MsRand& rng, std::span connections, CommuteRouteProbe* probe, CommuteRouteConfig config, CommutePeriodDiagnostics* periodDiagnostics, CommuteRouteHistory* routeHistory) { CommuteRouteProbe localProbe; CommuteRouteProbe* activeProbe = probe != nullptr ? probe : (periodDiagnostics != nullptr || routeHistory != nullptr) ? &localProbe : nullptr; CommuteRouteTrace trace; const bool success = commute_route_impl(city, &city, row, column, sourceZone, weight, maxCost, rng, connections, activeProbe, routeHistory != nullptr ? &trace : nullptr, config); if (periodDiagnostics != nullptr) accumulate_commute_diagnostics(*periodDiagnostics, success, *activeProbe); if (routeHistory != nullptr) { trace.stop = activeProbe->stop; trace.generalizedCost = activeProbe->generalizedCost; trace.sampleKey = mix_route_key(activeProbe->routeNonce ^ (static_cast(row) * 0x9e3779b9u) ^ (static_cast(column) * 0x85ebca6bu) ^ static_cast(activeProbe->stop)); routeHistory->consider(std::move(trace)); } return success; } bool commute_route_assess(const City& city, int row, int column, int sourceZone, int weight, int maxCost, std::span connections, CommuteRouteProbe* probe, CommuteRouteConfig config) { const std::uint32_t seed = mix_route_key(static_cast(city.days()) ^ (static_cast(row) * 0x9e3779b9u) ^ (static_cast(column) * 0x85ebca6bu) ^ static_cast(sourceZone)); MsRand rng(seed); return commute_route_impl(city, nullptr, row, column, sourceZone, weight, maxCost, rng, connections, probe, nullptr, config); } } // namespace sc2k namespace sc2k { bool commute_trace(City& c, int row, int col, int sourceZone, int weight, int maxCost, MsRand& rng, CommuteTraceProbe* probe) { if (probe != nullptr) *probe = {}; const int dim = c.dimension(); // Seed: first adjacent transit tile + its start mode (the original's 24-iteration scan). int curR = -1, curC = -1, mode = -1; for (const auto& d : kNeighborScan) { unsigned r = static_cast(row + d[0]), cc = static_cast(col + d[1]); if (r >= static_cast(dim) || cc >= static_cast(dim)) continue; int code = c.xbld.cells[c.index(r, cc)]; if (is_commute_road(code)) { mode = 0; curR = r; curC = cc; break; } if (code == 0xEC) { mode = 8; curR = r; curC = cc; break; } if (code == 0xED) { mode = 10; curR = r; curC = cc; break; } if (code == sc2k::xbld::kSubwayStation) { mode = 11; curR = r; curC = cc; break; } } if (mode < 0) { if (probe != nullptr) probe->effectiveMaxCost = maxCost; return false; // no adjacent transit } std::uint8_t buf[1536] = {}; // the original's two adjacent buffers CommutePathRing ring; ring.init(curR, curC); buf[0] = static_cast(mode); // mode ring: slot 0 = seed mode buf[512] = 15; // avail ring: slot 0 = 15 int depth = 1, cost = 0, avail = 15; const int turnBias = 2 * (static_cast(rng.next()) & 1) + 1; // 1 or 3 if (probe != nullptr) { probe->initialMode = mode; probe->randomDraws = 1; probe->maxDepth = depth; } if (weight == 1) maxCost -= maxCost >> 2; // weight 1 → −25%, as the original if (probe != nullptr) probe->effectiveMaxCost = maxCost; bool found = false; bool borderFound = false; while (cost < maxCost) { bool moved = false; int dirStart = static_cast(rng.next()) & 3, usedDir = 0, nr = 0, nc = 0; if (probe != nullptr) ++probe->randomDraws; for (int j = 0; j < 4 && !moved; ++j) { int dir = (dirStart + turnBias) & 3; dirStart = dir; if (!(avail & (1 << dir))) continue; if (probe != nullptr) ++probe->candidateDirections; avail &= ~(1 << dir); usedDir = dir; nr = curR + kCommuteDirRow[dir]; nc = curC + kCommuteDirCol[dir]; if (!c.on_map(nr, nc)) { // Stepping OFF the map from a neighbour-city connection tile (XTXT 0xFA) reaches an // off-map job → success (the original: when the neighbour coord is >=0x80 it // tests dwMapXTXT[cur]==0xFA and sets the found flag). Without this, residents next to a // road/rail link to a neighbour city can't "commute out", so edge zones near a connection // wrongly fail job-access and abandon. The marker is the same XTXT 0xFA the demand update // counts as conn1000/conn1500. if (c.xtxt.cells[c.index(curR, curC)] == 0xFA) { found = moved = borderFound = true; } continue; // dir consumed; off-map = no in-map step } const std::size_t next = c.index(nr, nc); int xb = c.xbld.cells[next]; int zn = c.xzon.cells[next] & 0xF; int xu = c.xund.cells[next]; int altmHi = (c.altm.cells[next] >> 8) & 0xFF; CommuteStep s = commute_transition(mode, xb, zn, xu, altmHi, sourceZone); cost += s.cost; if (s.found) { found = moved = true; } else if (s.moved) { moved = true; mode = s.mode; } if (s.moved && probe != nullptr) ++probe->validSteps; } if (found) break; if (moved) { const int old = depth; // advance to a new node buf[old + 511] = static_cast(avail); // W1: untried dirs left at `old` ring.push(nr, nc); curR = nr; curC = nc; int newAvail; if (mode == 3 || mode == 7) newAvail = 1 << usedDir; // locked to the entry direction else if (mode == 11) newAvail = 15; // free else newAvail = kCommuteNoUturn[usedDir]; avail = newAvail; ++depth; if (probe != nullptr && depth > probe->maxDepth) probe->maxDepth = depth; buf[512 + old] = static_cast(newAvail); // W2 buf[1024 + old] = static_cast(cost); // W3: cost on arrival at new node buf[old] = static_cast(mode); // W4: mode at new node } else { do { // backtrack if (--depth > 0) { if (probe != nullptr) ++probe->backtracks; int rr, cc2; ring.pop(rr, cc2); ring.peek(curR, curC); mode = buf[depth - 1]; // R1: parent mode cost = buf[1023 + depth]; // R2: parent cost-on-arrival avail = buf[depth + 511]; // R3: this frame's untried dirs } } while (avail == 0 && depth > 0); if (depth == 0) break; // stack exhausted → give up } } if (probe != nullptr) { probe->stop = found ? (borderFound ? CommuteTraceStop::BorderMarker : CommuteTraceStop::Destination) : (depth == 0 ? CommuteTraceStop::SearchExhausted : CommuteTraceStop::CostLimit); probe->finalCost = cost; probe->finalDepth = depth; } if (found && weight > 0 && !ring.empty()) { // walk the path back, stamp XTRF while (!ring.empty()) { int rr, cc2; ring.pop(rr, cc2); int m = buf[--depth]; if (m < 2 || m == 3) { // road/highway legs carry traffic std::uint8_t& t = c.xtrf.at(rr / 2, cc2 / 2); int v = t + weight; t = static_cast(v > 255 ? 255 : v); if (probe != nullptr) ++probe->trafficCellsStamped; } } } return found; } } // namespace sc2k namespace sc2k { bool commute_reachable(const City& c, int row, int col, int sourceZone, int maxCost) { const int dim = c.dimension(); int sr = -1, sc = -1, seedMode = -1; // seed at the first adjacent transit tile for (const auto& d : kNeighborScan) { unsigned r = static_cast(row + d[0]), cc = static_cast(col + d[1]); if (r >= static_cast(dim) || cc >= static_cast(dim)) continue; int code = c.xbld.cells[c.index(r, cc)]; if (is_commute_road(code)) { seedMode = 0; sr = r; sc = cc; break; } if (code == 0xEC) { seedMode = 8; sr = r; sc = cc; break; } if (code == 0xED) { seedMode = 10; sr = r; sc = cc; break; } if (code == sc2k::xbld::kSubwayStation) { seedMode = 11; sr = r; sc = cc; break; } } if (seedMode < 0) return false; // no adjacent transit → cannot commute // Stamped best-cost table over (tile, mode) states — reused across calls (a generation counter avoids // re-zeroing the runtime-sized table per call. CONTRACT: `best[sid]` is only read when // `stamp[sid] == gen`, and `gen` is bumped once per call, so any value left by a previous call — or a // previous city — is ignored (its stamp is an older generation). No reset hook is needed across a city // load; the only theoretical hazard is `gen` overflowing INT_MAX (~2·10⁹ commute calls), far past any run. const std::size_t states = std::size_t(c.tile_count()) * 16; static thread_local std::vector stamp, best; static thread_local int gen = 0; if (stamp.size() != states) { stamp.assign(states, 0); best.resize(states); gen = 0; } ++gen; auto sid = [dim](int r, int cc, int m) { return (r * dim + cc) * 16 + m; }; using Node = std::pair; // (cost, stateId) — min-heap by cost std::priority_queue, std::greater> pq; const int s0 = sid(sr, sc, seedMode); stamp[s0] = gen; best[s0] = 0; pq.push({0, s0}); while (!pq.empty()) { const auto [cost, st] = pq.top(); pq.pop(); if (cost > maxCost) break; // every remaining state is over budget if (stamp[st] == gen && best[st] < cost) continue; // a cheaper route to this state was found const int tile = st >> 4, m = st & 15, r = tile / dim, cc = tile % dim; for (int dir = 0; dir < 4; ++dir) { const int nr = r + kCommuteDirRow[dir], nc = cc + kCommuteDirCol[dir]; if (!c.on_map(nr, nc)) { if (c.xtxt.cells[c.index(r, cc)] == 0xFA) return true; // step off-map at a neighbour-city link = a job continue; } const std::size_t next = c.index(nr, nc); const int xb = c.xbld.cells[next], zn = c.xzon.cells[next] & 0xF; const int xu = c.xund.cells[next], ah = (c.altm.cells[next] >> 8) & 0xFF; const CommuteStep s = commute_transition(m, xb, zn, xu, ah, sourceZone); if (s.found) return true; // reached a job zone within budget if (!s.moved) continue; const int ncost = cost + s.cost; if (ncost > maxCost) continue; const int ns = sid(nr, nc, s.mode); if (stamp[ns] != gen || best[ns] > ncost) { stamp[ns] = gen; best[ns] = ncost; pq.push({ncost, ns}); } } } return false; } } // namespace sc2k