// sc2k/render/terrain_render_cache.hpp — semantic, derived terrain consumed by rendering and picking. #pragma once #include "sc2k/city.hpp" #include "sc2k/hydrology/model.hpp" #include "sc2k/structure/legacy_import.hpp" #include "sc2k/terrain/model.hpp" #include "sc2k/tile_codes.hpp" #include #include #include #include #include #include namespace sc2k::render { enum class TerrainSurfaceKind : std::uint8_t { Natural, Submerged, Shore, LegacyWater, }; struct TerrainRenderFace { std::array negative_profile{}; std::array positive_profile{}; terrain::FaceMaterial material = terrain::FaceMaterial::NaturalRock; terrain::FaceOwner owner = terrain::FaceOwner::Negative; bool present = false; friend bool operator==(const TerrainRenderFace&, const TerrainRenderFace&) = default; }; // All heights use classic whole levels here. Canonical storage retains its finer fixed-point units; // conversion happens once when this derived cache is built. `presentation_code` is an intentionally // temporary sprite-selection key for the classic art banks, not terrain authority. struct TerrainRenderTile { int base_height = 0; int surface_height = 0; int water_height = 0; std::array corner_heights{}; terrain::Shape shape = terrain::Shape::Flat; TerrainSurfaceKind surface_kind = TerrainSurfaceKind::Natural; std::uint8_t presentation_code = 0; std::uint8_t raised_corner_mask = 0; std::uint8_t maximum_grade_steps = 0; bool water = false; bool water_follows_terrain = false; bool constructed_support = false; bool feature_lift = false; bool buildable = true; bool legacy_water_topology = false; TerrainRenderFace row_face; TerrainRenderFace column_face; }; class TerrainRenderCache { public: static std::optional create(const terrain::Model& terrain, const City& presentation, const hydrology::Model* hydrology = nullptr, const structure::Model* structures = nullptr, bool legacyWaterTopology = false) { if (terrain.extent() != terrain::Extent{presentation.dimension(), presentation.dimension()}) return std::nullopt; if (hydrology && hydrology->extent() != terrain.extent()) return std::nullopt; if (structures && structures->extent() != terrain.extent()) return std::nullopt; TerrainRenderCache cache; cache.extent_ = terrain.extent(); cache.legacy_presentation_ = legacyWaterTopology; cache.tiles_.resize(static_cast(cache.extent_.width) * cache.extent_.height); for (int row = 0; row < cache.extent_.height; ++row) { for (int column = 0; column < cache.extent_.width; ++column) { const std::optional corners = terrain.corners({row, column}); if (!corners) return std::nullopt; const terrain::ShapeClassification classified = terrain::classify(*corners); if (!classified) return std::nullopt; TerrainRenderTile tile; tile.base_height = classified.base_height / terrain::kHeightQuantum; tile.shape = classified.shape; tile.raised_corner_mask = classified.raised_corner_mask; for (std::size_t corner = 0; corner < tile.corner_heights.size(); ++corner) tile.corner_heights[corner] = (*corners)[corner] / terrain::kHeightQuantum; const auto [minimum, maximum] = std::minmax_element( tile.corner_heights.begin(), tile.corner_heights.end()); tile.maximum_grade_steps = static_cast(*maximum - *minimum); const std::uint8_t old_code = presentation.xter.at(row, column); const structure::Support imported_support = structures ? structures->support({row, column}) : structure::import_legacy_support(presentation, row, column); const structure::Support support = imported_support; const bool foundation_on_water = support.kind == structure::SupportKind::Foundation && xter::presents_water(support.legacy_presentation); tile.constructed_support = static_cast(support); // A submerged cube under a network is a causeway/water support: its saved anchor is // already the water surface. Applying the ordinary dry-cube +1 lift raises the lone // network tile above every adjoining span (FOURCITI 88,78). tile.feature_lift = support.kind == structure::SupportKind::Foundation && !foundation_on_water; tile.water = hydrology ? hydrology->wet({row, column}) : (presentation.xbit.at(row, column) & xbit::kWater) != 0; const hydrology::Body* water_body = hydrology ? hydrology->body_at({row, column}) : nullptr; tile.water_follows_terrain = tile.water && !legacyWaterTopology && water_body && water_body->kind == hydrology::BodyKind::SurfaceWater; if (support.obscures_water) tile.water = false; if (!tile.water) tile.water_follows_terrain = false; tile.water_height = hydrology ? static_cast(hydrology->surface_height({row, column}) / terrain::kHeightQuantum) : (presentation.altm.at(row, column) >> 5) & 0x1F; if (support) { tile.presentation_code = support.legacy_presentation; tile.surface_kind = TerrainSurfaceKind::Natural; if (support.kind == structure::SupportKind::Ramp) { tile.shape = static_cast(support.legacy_presentation); tile.raised_corner_mask = terrain::raised_corner_mask(tile.shape); tile.maximum_grade_steps = tile.raised_corner_mask ? 1 : 0; } } else if (tile.water && xter::presents_water(old_code)) { // Keep the saved compatibility shoreline while the classic sprite renderer is the // presentation path. Canonical terrain remains authoritative underneath it; edits // re-tile XTER from hydrology, and the future geometry renderer can derive its own // shore mesh without moving imported buildings or exposing repaired beds. tile.presentation_code = old_code; tile.legacy_water_topology = legacyWaterTopology; tile.surface_kind = xter::is_shore(old_code) ? TerrainSurfaceKind::Shore : xter::is_submerged(old_code) ? TerrainSurfaceKind::Submerged : TerrainSurfaceKind::LegacyWater; } else { tile.presentation_code = static_cast(tile.shape); if (tile.water) { if (tile.water_height - tile.base_height == 1) { tile.presentation_code = static_cast(tile.presentation_code + xter::kShore); tile.surface_kind = TerrainSurfaceKind::Shore; } else { tile.presentation_code = static_cast(tile.presentation_code + xter::kSubmerged); tile.surface_kind = TerrainSurfaceKind::Submerged; } } } if (support) { tile.surface_height = foundation_on_water ? tile.water_height : tile.base_height + support.elevation_offset; } else { tile.surface_height = tile.presentation_code < xter::kSubmerged ? tile.base_height : tile.water_height; } tile.buildable = tile.shape == terrain::Shape::Flat && !tile.water && !support; const auto import_face = [](const terrain::SplitEdge* split) { TerrainRenderFace face; // Row/column faces below are the two viewer-facing edges of this draw anchor. // A positive-side owner is the higher tile in front, whose connecting face faces // away in this rotation and is occluded by its top. Rotation transforms ownership, // exposing the same physical face when the camera reaches its visible side. if (!split || split->owner != terrain::FaceOwner::Negative) return face; for (std::size_t endpoint = 0; endpoint < 2; ++endpoint) { face.negative_profile[endpoint] = split->negative_profile[endpoint] / terrain::kHeightQuantum; face.positive_profile[endpoint] = split->positive_profile[endpoint] / terrain::kHeightQuantum; } face.material = split->material; face.owner = split->owner; face.present = true; return face; }; if (row + 1 < cache.extent_.height) tile.row_face = import_face(terrain.split_edge( {terrain::EdgeAxis::Row, {row + 1, column}})); if (column + 1 < cache.extent_.width) tile.column_face = import_face(terrain.split_edge( {terrain::EdgeAxis::Column, {row, column + 1}})); cache.tiles_[cache.index(row, column)] = tile; } } return cache; } terrain::Extent extent() const { return extent_; } bool legacy_presentation() const { return legacy_presentation_; } const TerrainRenderTile* tile(int row, int column) const { if (row < 0 || column < 0 || row >= extent_.height || column >= extent_.width) return nullptr; return &tiles_[index(row, column)]; } private: std::size_t index(int row, int column) const { return static_cast(row) * extent_.width + column; } terrain::Extent extent_{}; bool legacy_presentation_ = false; std::vector tiles_; }; // Uniform query wrapper used while old tests and utility callers still provide only City. Once a // cache has been constructed at the compatibility boundary, this query path never decodes XTER/ALTM; // the uncached fallback remains explicit for callers not yet carrying a model. class TerrainRenderView { public: TerrainRenderView(const City& city, const TerrainRenderCache* cache = nullptr) : city_(city), cache_(cache) {} terrain::Extent extent() const { return cache_ ? cache_->extent() : terrain::Extent{city_.dimension(), city_.dimension()}; } // A cache without legacy presentation provenance is backed by native terrain authority. The // uncached City fallback and imported classic caches deliberately stay on compatibility art. bool uses_modern_presentation() const { return cache_ && !cache_->legacy_presentation(); } TerrainRenderTile tile(int row, int column) const { if (cache_) if (const TerrainRenderTile* cached = cache_->tile(row, column)) return *cached; TerrainRenderTile result; const std::uint8_t code = city_.xter.at(row, column); const std::uint8_t building = city_.xbld.at(row, column); const std::uint16_t altitude = city_.altm.at(row, column); result.base_height = altitude & 0x1F; result.water_height = (altitude >> 5) & 0x1F; result.presentation_code = code; result.legacy_water_topology = true; // Surface-water codes 0x30..0x45 select an irregular water artwork/mask; unlike the // submerged and shore banks, their low nibble is not terrain geometry. Decoding 0x35 as // slope 5 (and so on) turns Four Cities' level ornamental ponds into raised blue prisms. const std::uint8_t base_shape = xter::is_surface_water(code) ? xter::kFlat : xter::base_shape(code); result.shape = base_shape <= xter::kSlopeLast ? static_cast(base_shape) : terrain::Shape::Flat; result.raised_corner_mask = terrain::raised_corner_mask(result.shape); for (std::size_t corner = 0; corner < result.corner_heights.size(); ++corner) result.corner_heights[corner] = result.base_height + ((result.raised_corner_mask & (1u << corner)) ? 1 : 0); result.maximum_grade_steps = result.raised_corner_mask ? 1 : 0; const bool water_foundation = structure::is_legacy_foundation( code, building) && xter::presents_water(code); const bool bridge_ramp = structure::is_legacy_bridge_ramp(city_, row, column); // XBIT is the normal wet/dry authority. A few real saves clear it beneath an open-water // cube or a bridge foundation while retaining the only surviving water presentation. // Recover those narrowly; a dry network ramp beside water must stay dry. const bool unoccupied_presented_water = building == xbld::kNone && xter::presents_water(code); result.water = (city_.xbit.at(row, column) & xbit::kWater) != 0 || water_foundation || unoccupied_presented_water; result.constructed_support = xter::is_cube(code) || water_foundation || bridge_ramp; result.feature_lift = !bridge_ramp && result.constructed_support && !water_foundation; result.surface_height = result.water ? result.water_height : result.base_height; result.surface_kind = !result.water ? TerrainSurfaceKind::Natural : xter::is_surface_water(code) ? TerrainSurfaceKind::LegacyWater : xter::is_shore(code) ? TerrainSurfaceKind::Shore : TerrainSurfaceKind::Submerged; result.buildable = result.shape == terrain::Shape::Flat && !result.water && !result.constructed_support; return result; } // Water bodies normally own a level plane. Modern shallow editor water is instead a removable // material mask over the unchanged terrain, so its height at a shared vertex is that terrain // vertex. Imported classic water deliberately retains its saved planar/topology presentation. std::optional water_height_at_vertex(int vertexRow, int vertexColumn) const { const terrain::Extent map_extent = extent(); if (vertexRow < 0 || vertexColumn < 0 || vertexRow > map_extent.height || vertexColumn > map_extent.width) return std::nullopt; std::optional result; const int first_row = std::max(0, vertexRow - 1); const int last_row = std::min(vertexRow, map_extent.height - 1); const int first_column = std::max(0, vertexColumn - 1); const int last_column = std::min(vertexColumn, map_extent.width - 1); for (int row = first_row; row <= last_row; ++row) { for (int column = first_column; column <= last_column; ++column) { const TerrainRenderTile candidate = tile(row, column); if (!candidate.water) continue; int height = candidate.water_height; if (candidate.water_follows_terrain) { const int local_row = vertexRow - row; const int local_column = vertexColumn - column; const std::size_t corner = local_row == 0 ? (local_column == 0 ? 0u : 3u) : (local_column == 0 ? 1u : 2u); height = candidate.corner_heights[corner]; } result = result ? std::max(*result, height) : height; } } return result; } private: const City& city_; const TerrainRenderCache* cache_ = nullptr; }; } // namespace sc2k::render