From 1198a780916e65cae048dd3478f614c1d18db846 Mon Sep 17 00:00:00 2001 From: hop311 Date: Thu, 6 Jun 2024 23:20:58 +0100 Subject: Separated MapDefinition and MapInstance --- src/openvic-simulation/map/Map.cpp | 971 ---------------------- src/openvic-simulation/map/Map.hpp | 133 --- src/openvic-simulation/map/MapDefinition.cpp | 830 ++++++++++++++++++ src/openvic-simulation/map/MapDefinition.hpp | 112 +++ src/openvic-simulation/map/MapInstance.cpp | 148 ++++ src/openvic-simulation/map/MapInstance.hpp | 56 ++ src/openvic-simulation/map/Mapmode.cpp | 54 +- src/openvic-simulation/map/Mapmode.hpp | 8 +- src/openvic-simulation/map/ProvinceDefinition.cpp | 10 +- src/openvic-simulation/map/ProvinceDefinition.hpp | 8 +- src/openvic-simulation/map/ProvinceInstance.hpp | 5 +- src/openvic-simulation/map/Region.hpp | 4 +- src/openvic-simulation/map/State.cpp | 17 +- src/openvic-simulation/map/State.hpp | 6 +- 14 files changed, 1212 insertions(+), 1150 deletions(-) delete mode 100644 src/openvic-simulation/map/Map.cpp delete mode 100644 src/openvic-simulation/map/Map.hpp create mode 100644 src/openvic-simulation/map/MapDefinition.cpp create mode 100644 src/openvic-simulation/map/MapDefinition.hpp create mode 100644 src/openvic-simulation/map/MapInstance.cpp create mode 100644 src/openvic-simulation/map/MapInstance.hpp (limited to 'src/openvic-simulation/map') diff --git a/src/openvic-simulation/map/Map.cpp b/src/openvic-simulation/map/Map.cpp deleted file mode 100644 index 11b940f..0000000 --- a/src/openvic-simulation/map/Map.cpp +++ /dev/null @@ -1,971 +0,0 @@ -#include "Map.hpp" - -#include -#include - -#include "openvic-simulation/history/ProvinceHistory.hpp" -#include "openvic-simulation/types/Colour.hpp" -#include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/utility/BMP.hpp" -#include "openvic-simulation/utility/Logger.hpp" - -using namespace OpenVic; -using namespace OpenVic::NodeTools; - -Map::Map() - : dims { 0, 0 }, max_provinces { ProvinceDefinition::MAX_INDEX }, selected_province { nullptr }, - highest_province_population { 0 }, total_map_population { 0 } {} - -bool Map::add_province_definition(std::string_view identifier, colour_t colour) { - if (province_definitions.size() >= max_provinces) { - Logger::error( - "The map's province list is full - maximum number of provinces is ", max_provinces, " (this can be at most ", - ProvinceDefinition::MAX_INDEX, ")" - ); - return false; - } - if (identifier.empty()) { - Logger::error("Invalid province identifier - empty!"); - return false; - } - if (!valid_basic_identifier(identifier)) { - Logger::error( - "Invalid province identifier: ", identifier, " (can only contain alphanumeric characters and underscores)" - ); - return false; - } - if (colour.is_null()) { - Logger::error("Invalid province colour for ", identifier, " - null! (", colour, ")"); - return false; - } - ProvinceDefinition new_province { - identifier, colour, static_cast(province_definitions.size() + 1) - }; - const ProvinceDefinition::index_t index = get_index_from_colour(colour); - if (index != ProvinceDefinition::NULL_INDEX) { - Logger::error( - "Duplicate province colours: ", get_province_definition_by_index(index)->to_string(), " and ", - new_province.to_string() - ); - return false; - } - colour_index_map[new_province.get_colour()] = new_province.get_index(); - return province_definitions.add_item(std::move(new_province)); -} - -ProvinceInstance* Map::get_province_instance_from_const(ProvinceDefinition const* province) { - if (province != nullptr) { - return get_province_instance_by_index(province->get_index()); - } else { - return nullptr; - } -} - -ProvinceInstance const* Map::get_province_instance_from_const(ProvinceDefinition const* province) const { - if (province != nullptr) { - return get_province_instance_by_index(province->get_index()); - } else { - return nullptr; - } -} - -ProvinceDefinition::distance_t Map::calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to -) const { - const fvec2_t to_pos = to.get_unit_position(); - const fvec2_t from_pos = from.get_unit_position(); - - const fixed_point_t min_x = std::min( - (to_pos.x - from_pos.x).abs(), - std::min( - (to_pos.x - from_pos.x + get_width()).abs(), - (to_pos.x - from_pos.x - get_width()).abs() - ) - ); - - return fvec2_t { min_x, to_pos.y - from_pos.y }.length_squared().sqrt(); -} - -using adjacency_t = ProvinceDefinition::adjacency_t; - -/* This is called for all adjacent pixel pairs and returns whether or not a new adjacency was add, - * hence the lack of error messages in the false return cases. */ -bool Map::add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to) const { - if (from == to) { - return false; - } - - const bool from_needs_adjacency = !from.is_adjacent_to(&to); - const bool to_needs_adjacency = !to.is_adjacent_to(&from); - - if (!from_needs_adjacency && !to_needs_adjacency) { - return false; - } - - const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); - - using enum adjacency_t::type_t; - - /* Default land-to-land adjacency */ - adjacency_t::type_t type = LAND; - if (from.is_water() != to.is_water()) { - /* Land-to-water adjacency */ - type = COASTAL; - - /* Mark the land province as coastal */ - from.coastal = !from.is_water(); - to.coastal = !to.is_water(); - } else if (from.is_water()) { - /* Water-to-water adjacency */ - type = WATER; - } - - if (from_needs_adjacency) { - from.adjacencies.emplace_back(&to, distance, type, nullptr, 0); - } - if (to_needs_adjacency) { - to.adjacencies.emplace_back(&from, distance, type, nullptr, 0); - } - return true; -} - -bool Map::add_special_adjacency( - ProvinceDefinition& from, ProvinceDefinition& to, adjacency_t::type_t type, ProvinceDefinition const* through, - adjacency_t::data_t data -) const { - if (from == to) { - Logger::error("Trying to add ", adjacency_t::get_type_name(type), " adjacency from province ", from, " to itself!"); - return false; - } - - using enum adjacency_t::type_t; - - /* Check end points */ - switch (type) { - case LAND: - case STRAIT: - if (from.is_water() || to.is_water()) { - Logger::error(adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has water endpoint(s)!"); - return false; - } - break; - case WATER: - case CANAL: - if (!from.is_water() || !to.is_water()) { - Logger::error(adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has land endpoint(s)!"); - return false; - } - break; - case COASTAL: - if (from.is_water() == to.is_water()) { - Logger::error("Coastal adjacency from ", from, " to ", to, " has both land or water endpoints!"); - return false; - } - break; - case IMPASSABLE: - /* Impassable is valid for all combinations of land and water: - * - land-land = replace existing land adjacency with impassable adjacency (blue borders) - * - land-water = delete existing coastal adjacency, preventing armies and navies from moving between the provinces - * - water-water = delete existing water adjacency, preventing navies from moving between the provinces */ - break; - default: - Logger::error("Invalid adjacency type ", static_cast(type)); - return false; - } - - /* Check through province */ - if (type == STRAIT || type == CANAL) { - const bool water_expected = type == STRAIT; - if (through == nullptr || through->is_water() != water_expected) { - Logger::error( - adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has a ", - (through == nullptr ? "null" : water_expected ? "land" : "water"), " through province ", through - ); - return false; - } - } else if (through != nullptr) { - Logger::warning( - adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has a non-null through province ", - through - ); - through = nullptr; - } - - /* Check canal data */ - if (data != adjacency_t::NO_CANAL && type != CANAL) { - Logger::warning( - adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has invalid data ", - static_cast(data) - ); - data = adjacency_t::NO_CANAL; - } - - const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); - - const auto add_adjacency = [distance, type, through, data]( - ProvinceDefinition& from, ProvinceDefinition const& to - ) -> bool { - const std::vector::iterator existing_adjacency = std::find_if( - from.adjacencies.begin(), from.adjacencies.end(), - [&to](adjacency_t const& adj) -> bool { return adj.get_to() == &to; } - ); - if (existing_adjacency != from.adjacencies.end()) { - if (type == existing_adjacency->get_type()) { - Logger::warning( - "Adjacency from ", from, " to ", to, " already has type ", adjacency_t::get_type_name(type), "!" - ); - if (type != STRAIT && type != CANAL) { - /* Straits and canals might change through or data, otherwise we can exit early */ - return true; - } - } - if (type == IMPASSABLE) { - if (existing_adjacency->get_type() == WATER || existing_adjacency->get_type() == COASTAL) { - from.adjacencies.erase(existing_adjacency); - return true; - } - } else { - if (type != STRAIT && type != CANAL) { - Logger::error( - "Provinces ", from, " and ", to, " already have an existing ", - adjacency_t::get_type_name(existing_adjacency->get_type()), " adjacency, cannot create a ", - adjacency_t::get_type_name(type), " adjacency!" - ); - return false; - } - if (type != existing_adjacency->get_type() && existing_adjacency->get_type() != (type == CANAL ? WATER : LAND)) { - Logger::error( - "Cannot convert ", adjacency_t::get_type_name(existing_adjacency->get_type()), " adjacency from ", from, - " to ", to, " to type ", adjacency_t::get_type_name(type), "!" - ); - return false; - } - } - *existing_adjacency = { &to, distance, type, through, data }; - return true; - } else if (type == IMPASSABLE) { - Logger::warning( - "Provinces ", from, " and ", to, " do not have an existing adjacency to make impassable!" - ); - return true; - } else { - from.adjacencies.emplace_back(&to, distance, type, through, data); - return true; - } - }; - - return add_adjacency(from, to) & add_adjacency(to, from); -} - -bool Map::set_water_province(std::string_view identifier) { - if (water_provinces.is_locked()) { - Logger::error("The map's water provinces have already been locked!"); - return false; - } - - ProvinceDefinition* province = get_province_definition_by_identifier(identifier); - - if (province == nullptr) { - Logger::error("Unrecognised water province identifier: ", identifier); - return false; - } - if (province->has_region()) { - Logger::error("Province ", identifier, " cannot be water as it belongs to region \"", province->get_region(), "\""); - return false; - } - if (province->is_water()) { - Logger::warning("Province ", identifier, " is already a water province!"); - return true; - } - if (!water_provinces.add_province(province)) { - Logger::error("Failed to add province ", identifier, " to water province set!"); - return false; - } - province->water = true; - return true; -} - -bool Map::set_water_province_list(std::vector const& list) { - if (water_provinces.is_locked()) { - Logger::error("The map's water provinces have already been locked!"); - return false; - } - bool ret = true; - water_provinces.reserve_more(list.size()); - for (std::string_view const& identifier : list) { - ret &= set_water_province(identifier); - } - lock_water_provinces(); - return ret; -} - -void Map::lock_water_provinces() { - water_provinces.lock(); - Logger::info("Locked water provinces after registering ", water_provinces.size()); -} - -bool Map::add_region(std::string_view identifier, std::vector&& provinces, colour_t colour) { - if (identifier.empty()) { - Logger::error("Invalid region identifier - empty!"); - return false; - } - - bool ret = true; - - std::erase_if(provinces, [identifier, &ret](ProvinceDefinition const* province) -> bool { - if (province->is_water()) { - Logger::error( - "Province ", province->get_identifier(), " cannot be added to region \"", identifier, - "\" as it is a water province!" - ); - ret = false; - return true; - } else { - return false; - } - }); - - const bool meta = provinces.empty() || std::any_of( - provinces.begin(), provinces.end(), std::bind_front(&ProvinceDefinition::has_region) - ); - - Region region { identifier, colour, meta }; - ret &= region.add_provinces(provinces); - region.lock(); - if (regions.add_item(std::move(region))) { - if (!meta) { - Region const& last_region = regions.get_items().back(); - for (ProvinceDefinition const* province : last_region.get_provinces()) { - remove_province_definition_const(province)->region = &last_region; - } - } - } else { - ret = false; - } - return ret; -} - -ProvinceDefinition::index_t Map::get_index_from_colour(colour_t colour) const { - const colour_index_map_t::const_iterator it = colour_index_map.find(colour); - if (it != colour_index_map.end()) { - return it->second; - } - return ProvinceDefinition::NULL_INDEX; -} - -ProvinceDefinition::index_t Map::get_province_index_at(ivec2_t pos) const { - if (pos.nonnegative() && pos.less_than(dims)) { - return province_shape_image[get_pixel_index_from_pos(pos)].index; - } - return ProvinceDefinition::NULL_INDEX; -} - -ProvinceDefinition* Map::get_province_definition_at(ivec2_t pos) { - return get_province_definition_by_index(get_province_index_at(pos)); -} - -ProvinceDefinition const* Map::get_province_definition_at(ivec2_t pos) const { - return get_province_definition_by_index(get_province_index_at(pos)); -} - -bool Map::set_max_provinces(ProvinceDefinition::index_t new_max_provinces) { - if (new_max_provinces <= ProvinceDefinition::NULL_INDEX) { - Logger::error( - "Trying to set max province count to an invalid value ", new_max_provinces, " (must be greater than ", - ProvinceDefinition::NULL_INDEX, ")" - ); - return false; - } - if (!province_definitions.empty() || province_definitions.is_locked()) { - Logger::error( - "Trying to set max province count to ", new_max_provinces, " after provinces have already been added and/or locked" - ); - return false; - } - max_provinces = new_max_provinces; - return true; -} - -void Map::set_selected_province(ProvinceDefinition::index_t index) { - if (index == ProvinceDefinition::NULL_INDEX) { - selected_province = nullptr; - } else { - selected_province = get_province_instance_by_index(index); - if (selected_province == nullptr) { - Logger::error( - "Trying to set selected province to an invalid index ", index, " (max index is ", - get_province_instance_count(), ")" - ); - } - } -} - -ProvinceInstance* Map::get_selected_province() { - return selected_province; -} - -ProvinceDefinition::index_t Map::get_selected_province_index() const { - return selected_province != nullptr ? selected_province->get_province_definition().get_index() - : ProvinceDefinition::NULL_INDEX; -} - -bool Map::reset(BuildingTypeManager const& building_type_manager) { - if (!province_definitions_are_locked()) { - Logger::error("Cannot reset map - province consts are not locked!"); - return false; - } - - bool ret = true; - - // TODO - ensure all references to old ProvinceInstances are safely cleared - state_manager.reset(); - selected_province = nullptr; - - province_instances.reset(); - - province_instances.reserve(province_definitions.size()); - - for (ProvinceDefinition const& province : province_definitions.get_items()) { - ret &= province_instances.add_item({ province }); - } - - province_instances.lock(); - - for (ProvinceInstance& province : province_instances.get_items()) { - ret &= province.reset(building_type_manager); - } - - if (get_province_instance_count() != get_province_definition_count()) { - Logger::error( - "ProvinceInstance count (", get_province_instance_count(), ") does not match ProvinceDefinition count (", - get_province_definition_count(), ")!" - ); - return false; - } - - return ret; -} - -bool Map::apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, Date date, IdeologyManager const& ideology_manager, - IssueManager const& issue_manager, Country const& country -) { - bool ret = true; - - for (ProvinceInstance& province : province_instances.get_items()) { - ProvinceDefinition const& province_definition = province.get_province_definition(); - if (!province_definition.is_water()) { - ProvinceHistoryMap const* history_map = history_manager.get_province_history(&province_definition); - - if (history_map != nullptr) { - ProvinceHistoryEntry const* pop_history_entry = nullptr; - - for (ProvinceHistoryEntry const* entry : history_map->get_entries_up_to(date)) { - province.apply_history_to_province(entry); - - if (!entry->get_pops().empty()) { - pop_history_entry = entry; - } - } - - if (pop_history_entry != nullptr) { - province.add_pop_vec(pop_history_entry->get_pops()); - - province.setup_pop_test_values(ideology_manager, issue_manager, country); - } - } - } - } - - return ret; -} - -void Map::update_gamestate(Date today) { - for (ProvinceInstance& province : province_instances.get_items()) { - province.update_gamestate(today); - } - state_manager.update_gamestate(); - - // Update population stats - highest_province_population = 0; - total_map_population = 0; - - for (ProvinceInstance const& province : province_instances.get_items()) { - const Pop::pop_size_t province_population = province.get_total_population(); - - if (highest_province_population < province_population) { - highest_province_population = province_population; - } - - total_map_population += province_population; - } -} - -void Map::tick(Date today) { - for (ProvinceInstance& province : province_instances.get_items()) { - province.tick(today); - } -} - -using namespace ovdl::csv; - -static bool _validate_province_definitions_header(LineObject const& header) { - static const std::vector standard_header { "province", "red", "green", "blue" }; - for (size_t i = 0; i < standard_header.size(); ++i) { - const std::string_view val = header.get_value_for(i); - if (i == 0 && val.empty()) { - break; - } - if (val != standard_header[i]) { - return false; - } - } - return true; -} - -static bool _parse_province_colour(colour_t& colour, std::array components) { - bool ret = true; - for (size_t i = 0; i < 3; ++i) { - std::string_view& component = components[i]; - if (component.ends_with('.')) { - component.remove_suffix(1); - } - bool successful = false; - const uint64_t val = StringUtils::string_to_uint64(component, &successful, 10); - if (successful && val <= colour_t::max_value) { - colour[i] = val; - } else { - ret = false; - } - } - return ret; -} - -bool Map::load_province_definitions(std::vector const& lines) { - if (lines.empty()) { - Logger::error("No header or entries in province definition file!"); - return false; - } - - { - LineObject const& header = lines.front(); - if (!_validate_province_definitions_header(header)) { - Logger::error( - "Non-standard province definition file header - make sure this is not a province definition: ", header - ); - } - } - - if (lines.size() <= 1) { - Logger::error("No entries in province definition file!"); - return false; - } - - reserve_more_province_definitions(lines.size() - 1); - - bool ret = true; - std::for_each(lines.begin() + 1, lines.end(), [this, &ret](LineObject const& line) -> void { - const std::string_view identifier = line.get_value_for(0); - if (!identifier.empty()) { - colour_t colour = colour_t::null(); - if (!_parse_province_colour(colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) })) { - Logger::error("Error reading colour in province definition: ", line); - ret = false; - } - ret &= add_province_definition(identifier, colour); - } - }); - - lock_province_definitions(); - - return ret; -} - -bool Map::load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root) { - return expect_province_definition_dictionary( - [this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { - return province.load_positions(*this, building_type_manager, node); - } - )(root); -} - -bool Map::load_region_colours(ast::NodeCPtr root, std::vector& colours) { - return expect_dictionary_reserve_length( - colours, - [&colours](std::string_view key, ast::NodeCPtr value) -> bool { - if (key != "color") { - Logger::error("Invalid key in region colours: \"", key, "\""); - return false; - } - return expect_colour(vector_callback(colours))(value); - })(root); -} - -bool Map::load_region_file(ast::NodeCPtr root, std::vector const& colours) { - const bool ret = expect_dictionary_reserve_length( - regions, - [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { - std::vector provinces; - - bool ret = expect_list_reserve_length( - provinces, expect_province_definition_identifier(vector_callback_pointer(provinces)) - )(region_node); - - ret &= add_region(region_identifier, std::move(provinces), colours[regions.size() % colours.size()]); - - return ret; - } - )(root); - - lock_regions(); - - return ret; -} - -static constexpr colour_t colour_at(uint8_t const* colour_data, int32_t idx) { - /* colour_data is filled with BGR byte triplets - to get pixel idx as a - * single RGB value, multiply idx by 3 to get the index of the corresponding - * triplet, then combine the bytes in reverse order. - */ - idx *= 3; - return { colour_data[idx + 2], colour_data[idx + 1], colour_data[idx] }; -} - -bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain_path, bool detailed_errors) { - if (!province_definitions_are_locked()) { - Logger::error("Province index image cannot be generated until after provinces are locked!"); - return false; - } - if (!terrain_type_manager.terrain_type_mappings_are_locked()) { - Logger::error("Province index image cannot be generated until after terrain type mappings are locked!"); - return false; - } - - BMP province_bmp; - if (!(province_bmp.open(province_path) && province_bmp.read_header() && province_bmp.read_pixel_data())) { - Logger::error("Failed to read BMP for compatibility mode province image: ", province_path); - return false; - } - static constexpr uint16_t expected_province_bpp = 24; - if (province_bmp.get_bits_per_pixel() != expected_province_bpp) { - Logger::error( - "Invalid province BMP bits per pixel: ", province_bmp.get_bits_per_pixel(), " (expected ", expected_province_bpp, - ")" - ); - return false; - } - - BMP terrain_bmp; - if (!(terrain_bmp.open(terrain_path) && terrain_bmp.read_header() && terrain_bmp.read_pixel_data())) { - Logger::error("Failed to read BMP for compatibility mode terrain image: ", terrain_path); - return false; - } - static constexpr uint16_t expected_terrain_bpp = 8; - if (terrain_bmp.get_bits_per_pixel() != expected_terrain_bpp) { - Logger::error( - "Invalid terrain BMP bits per pixel: ", terrain_bmp.get_bits_per_pixel(), " (expected ", expected_terrain_bpp, ")" - ); - return false; - } - - if (province_bmp.get_width() != terrain_bmp.get_width() || province_bmp.get_height() != terrain_bmp.get_height()) { - Logger::error( - "Mismatched province and terrain BMP dims: ", province_bmp.get_width(), "x", province_bmp.get_height(), " vs ", - terrain_bmp.get_width(), "x", terrain_bmp.get_height() - ); - return false; - } - - dims.x = province_bmp.get_width(); - dims.y = province_bmp.get_height(); - province_shape_image.resize(dims.x * dims.y); - - uint8_t const* province_data = province_bmp.get_pixel_data().data(); - uint8_t const* terrain_data = terrain_bmp.get_pixel_data().data(); - - std::vector> terrain_type_pixels_list(province_definitions.size()); - - bool ret = true; - ordered_set unrecognised_province_colours; - - std::vector pixels_per_province(province_definitions.size()); - std::vector pixel_position_sum_per_province(province_definitions.size()); - - for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { - for (pos.x = 0; pos.x < get_width(); ++pos.x) { - const size_t pixel_index = get_pixel_index_from_pos(pos); - const colour_t province_colour = colour_at(province_data, pixel_index); - ProvinceDefinition::index_t province_index = ProvinceDefinition::NULL_INDEX; - - if (pos.x > 0) { - const size_t jdx = pixel_index - 1; - if (colour_at(province_data, jdx) == province_colour) { - province_index = province_shape_image[jdx].index; - goto index_found; - } - } - - if (pos.y > 0) { - const size_t jdx = pixel_index - get_width(); - if (colour_at(province_data, jdx) == province_colour) { - province_index = province_shape_image[jdx].index; - goto index_found; - } - } - - province_index = get_index_from_colour(province_colour); - - if (province_index == ProvinceDefinition::NULL_INDEX && !unrecognised_province_colours.contains(province_colour)) { - unrecognised_province_colours.insert(province_colour); - if (detailed_errors) { - Logger::warning( - "Unrecognised province colour ", province_colour, " at ", pos - ); - } - } - - index_found: - province_shape_image[pixel_index].index = province_index; - - if (province_index != ProvinceDefinition::NULL_INDEX) { - const ProvinceDefinition::index_t array_index = province_index - 1; - pixels_per_province[array_index]++; - pixel_position_sum_per_province[array_index] += static_cast(pos); - } - - const TerrainTypeMapping::index_t terrain = terrain_data[pixel_index]; - TerrainTypeMapping const* mapping = terrain_type_manager.get_terrain_type_mapping_for(terrain); - if (mapping != nullptr) { - if (province_index != ProvinceDefinition::NULL_INDEX) { - terrain_type_pixels_list[province_index - 1][&mapping->get_type()]++; - } - if (mapping->get_has_texture() && terrain < terrain_type_manager.get_terrain_texture_limit()) { - province_shape_image[pixel_index].terrain = terrain + 1; - } else { - province_shape_image[pixel_index].terrain = 0; - } - } else { - province_shape_image[pixel_index].terrain = 0; - } - } - } - - if (!unrecognised_province_colours.empty()) { - Logger::warning("Province image contains ", unrecognised_province_colours.size(), " unrecognised province colours"); - } - - size_t missing = 0; - for (size_t array_index = 0; array_index < province_definitions.size(); ++array_index) { - ProvinceDefinition* province = province_definitions.get_item_by_index(array_index); - - fixed_point_map_t const& terrain_type_pixels = terrain_type_pixels_list[array_index]; - const fixed_point_map_const_iterator_t largest = get_largest_item(terrain_type_pixels); - province->default_terrain_type = largest != terrain_type_pixels.end() ? largest->first : nullptr; - - const fixed_point_t pixel_count = pixels_per_province[array_index]; - province->on_map = pixel_count > 0; - - if (province->on_map) { - province->centre = pixel_position_sum_per_province[array_index] / pixel_count; - } else { - if (detailed_errors) { - Logger::warning("Province missing from shape image: ", province->to_string()); - } - missing++; - } - } - if (missing > 0) { - Logger::warning("Province image is missing ", missing, " province colours"); - } - - return ret; -} - -/* REQUIREMENTS: - * MAP-19, MAP-84 - */ -bool Map::_generate_standard_province_adjacencies() { - bool changed = false; - - const auto generate_adjacency = [this](ProvinceDefinition* current, ivec2_t pos) -> bool { - ProvinceDefinition* neighbour = get_province_definition_at(pos); - if (neighbour != nullptr) { - return add_standard_adjacency(*current, *neighbour); - } - return false; - }; - - for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { - for (pos.x = 0; pos.x < get_width(); ++pos.x) { - ProvinceDefinition* cur = get_province_definition_at(pos); - - if (cur != nullptr) { - changed |= generate_adjacency(cur, { (pos.x + 1) % get_width(), pos.y }); - changed |= generate_adjacency(cur, { pos.x, pos.y + 1 }); - } - } - } - - return changed; -} - -bool Map::generate_and_load_province_adjacencies(std::vector const& additional_adjacencies) { - bool ret = _generate_standard_province_adjacencies(); - if (!ret) { - Logger::error("Failed to generate standard province adjacencies!"); - } - /* Skip first line containing column headers */ - if (additional_adjacencies.size() <= 1) { - Logger::error("No entries in province adjacencies file!"); - return false; - } - std::for_each( - additional_adjacencies.begin() + 1, additional_adjacencies.end(), [this, &ret](LineObject const& adjacency) -> void { - const std::string_view from_str = adjacency.get_value_for(0); - if (from_str.empty() || from_str.front() == '#') { - return; - } - ProvinceDefinition* const from = get_province_definition_by_identifier(from_str); - if (from == nullptr) { - Logger::error("Unrecognised adjacency from province identifier: \"", from_str, "\""); - ret = false; - return; - } - - const std::string_view to_str = adjacency.get_value_for(1); - ProvinceDefinition* const to = get_province_definition_by_identifier(to_str); - if (to == nullptr) { - Logger::error("Unrecognised adjacency to province identifier: \"", to_str, "\""); - ret = false; - return; - } - - using enum adjacency_t::type_t; - static const string_map_t type_map { - { "land", LAND }, { "sea", STRAIT }, { "impassable", IMPASSABLE }, { "canal", CANAL } - }; - const std::string_view type_str = adjacency.get_value_for(2); - const string_map_t::const_iterator it = type_map.find(type_str); - if (it == type_map.end()) { - Logger::error("Invalid adjacency type: \"", type_str, "\""); - ret = false; - return; - } - const adjacency_t::type_t type = it->second; - - ProvinceDefinition const* const through = get_province_definition_by_identifier(adjacency.get_value_for(3)); - - const std::string_view data_str = adjacency.get_value_for(4); - bool successful = false; - const uint64_t data_uint = StringUtils::string_to_uint64(data_str, &successful); - if (!successful || data_uint > std::numeric_limits::max()) { - Logger::error("Invalid adjacency data: \"", data_str, "\""); - ret = false; - return; - } - const adjacency_t::data_t data = data_uint; - - ret &= add_special_adjacency(*from, *to, type, through, data); - } - ); - return ret; -} - -bool Map::load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - bool ret = expect_dictionary_reserve_length( - climates, - [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { - if (identifier.empty()) { - Logger::error("Invalid climate identifier - empty!"); - return false; - } - - bool ret = true; - Climate* cur_climate = climates.get_item_by_identifier(identifier); - if (cur_climate == nullptr) { - ModifierValue values; - ret &= modifier_manager.expect_modifier_value(move_variable_callback(values))(node); - ret &= climates.add_item({ identifier, std::move(values) }); - } else { - ret &= expect_list_reserve_length(*cur_climate, expect_province_definition_identifier( - [cur_climate, &identifier](ProvinceDefinition& province) { - if (province.climate != cur_climate) { - cur_climate->add_province(&province); - if (province.climate != nullptr) { - Climate* old_climate = const_cast(province.climate); - old_climate->remove_province(&province); - Logger::warning( - "Province with id ", province.get_identifier(), - " found in multiple climates: ", identifier, - " and ", old_climate->get_identifier() - ); - } - province.climate = cur_climate; - } else { - Logger::warning( - "Province with id ", province.get_identifier(), - " defined twice in climate ", identifier - ); - } - return true; - } - ))(node); - } - return ret; - } - )(root); - - for (Climate& climate : climates.get_items()) { - climate.lock(); - } - - lock_climates(); - - return ret; -} - -bool Map::load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - bool ret = expect_dictionary_reserve_length( - continents, - [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { - if (identifier.empty()) { - Logger::error("Invalid continent identifier - empty!"); - return false; - } - - ModifierValue values; - std::vector prov_list; - bool ret = modifier_manager.expect_modifier_value_and_keys(move_variable_callback(values), - "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier( - [&prov_list](ProvinceDefinition const& province) -> bool { - if (province.continent == nullptr) { - prov_list.emplace_back(&province); - } else { - Logger::warning("Province ", province, " found in multiple continents"); - } - return true; - } - )) - )(node); - - Continent continent = { identifier, std::move(values) }; - continent.add_provinces(prov_list); - continent.lock(); - - if (continents.add_item(std::move(continent))) { - Continent const& moved_continent = continents.get_items().back(); - for (ProvinceDefinition const* prov : moved_continent.get_provinces()) { - remove_province_definition_const(prov)->continent = &moved_continent; - } - } else { - ret = false; - } - - return ret; - } - )(root); - - lock_continents(); - - return ret; -} diff --git a/src/openvic-simulation/map/Map.hpp b/src/openvic-simulation/map/Map.hpp deleted file mode 100644 index 12c9de4..0000000 --- a/src/openvic-simulation/map/Map.hpp +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once - -#include - -#include - -#include "openvic-simulation/map/ProvinceDefinition.hpp" -#include "openvic-simulation/map/ProvinceInstance.hpp" -#include "openvic-simulation/map/Region.hpp" -#include "openvic-simulation/map/State.hpp" -#include "openvic-simulation/map/TerrainType.hpp" -#include "openvic-simulation/types/Colour.hpp" -#include "openvic-simulation/types/OrderedContainers.hpp" - -namespace OpenVic { - namespace fs = std::filesystem; - - struct GoodManager; - struct ProvinceHistoryManager; - - /* REQUIREMENTS: - * MAP-4 - */ - struct Map { -#pragma pack(push, 1) - /* Used to represent tightly packed 3-byte integer pixel information. */ - struct shape_pixel_t { - ProvinceDefinition::index_t index; - TerrainTypeMapping::index_t terrain; - }; -#pragma pack(pop) - private: - using colour_index_map_t = ordered_map; - - IdentifierRegistry IDENTIFIER_REGISTRY_CUSTOM_INDEX_OFFSET(province_definition, 1); - IdentifierRegistry IDENTIFIER_REGISTRY_CUSTOM_INDEX_OFFSET(province_instance, 1); - IdentifierRegistry IDENTIFIER_REGISTRY(region); - IdentifierRegistry IDENTIFIER_REGISTRY(climate); - IdentifierRegistry IDENTIFIER_REGISTRY(continent); - ProvinceSet water_provinces; - TerrainTypeManager PROPERTY_REF(terrain_type_manager); - - ivec2_t PROPERTY(dims); - std::vector PROPERTY(province_shape_image); - colour_index_map_t colour_index_map; - - ProvinceDefinition::index_t PROPERTY(max_provinces); - ProvinceInstance* PROPERTY(selected_province); // is it right for this to be mutable? how about using an index instead? - Pop::pop_size_t PROPERTY(highest_province_population); - Pop::pop_size_t PROPERTY(total_map_population); - - ProvinceDefinition::index_t get_index_from_colour(colour_t colour) const; - bool _generate_standard_province_adjacencies(); - - StateManager PROPERTY_REF(state_manager); - - inline constexpr int32_t get_pixel_index_from_pos(ivec2_t pos) const { - return pos.x + pos.y * dims.x; - } - - public: - Map(); - - inline constexpr int32_t get_width() const { return dims.x; } - inline constexpr int32_t get_height() const { return dims.y; } - - bool add_province_definition(std::string_view identifier, colour_t colour); - - private: - IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_INDEX_OFFSET(province_definition, 1); - - public: - IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_INDEX_OFFSET(province_instance, 1); - - ProvinceInstance* get_province_instance_from_const(ProvinceDefinition const* province); - ProvinceInstance const* get_province_instance_from_const(ProvinceDefinition const* province) const; - - ProvinceDefinition::distance_t calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to - ) const; - bool add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to) const; - bool add_special_adjacency( - ProvinceDefinition& from, ProvinceDefinition& to, ProvinceDefinition::adjacency_t::type_t type, - ProvinceDefinition const* through, ProvinceDefinition::adjacency_t::data_t data - ) const; - - bool set_water_province(std::string_view identifier); - bool set_water_province_list(std::vector const& list); - void lock_water_provinces(); - - ProvinceDefinition::index_t get_province_index_at(ivec2_t pos) const; - - private: - ProvinceDefinition* get_province_definition_at(ivec2_t pos); - - /* This provides a safe way to remove the const qualifier of a ProvinceDefinition const*, via a non-const Map. - * It uses a const_cast (the fastest/simplest solution), but this could also be done without it by looking up the - * ProvinceDefinition* using the ProvinceDefinition const*'s index. Requiring a non-const Map ensures that this - * function can only be used where the ProvinceDefinition* could already be accessed by other means, such as the - * index method, preventing misleading code, or in the worst case undefined behaviour. */ - constexpr ProvinceDefinition* remove_province_definition_const(ProvinceDefinition const* province) { - return const_cast(province); - } - - public: - ProvinceDefinition const* get_province_definition_at(ivec2_t pos) const; - bool set_max_provinces(ProvinceDefinition::index_t new_max_provinces); - void set_selected_province(ProvinceDefinition::index_t index); - ProvinceInstance* get_selected_province(); - ProvinceDefinition::index_t get_selected_province_index() const; - - bool add_region(std::string_view identifier, std::vector&& provinces, colour_t colour); - - bool reset(BuildingTypeManager const& building_type_manager); - bool apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, Date date, IdeologyManager const& ideology_manager, - IssueManager const& issue_manager, Country const& country - ); - - void update_gamestate(Date today); - void tick(Date today); - - bool load_province_definitions(std::vector const& lines); - /* Must be loaded after adjacencies so we know what provinces are coastal, and so can have a port */ - bool load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root); - static bool load_region_colours(ast::NodeCPtr root, std::vector& colours); - bool load_region_file(ast::NodeCPtr root, std::vector const& colours); - bool load_map_images(fs::path const& province_path, fs::path const& terrain_path, bool detailed_errors); - bool generate_and_load_province_adjacencies(std::vector const& additional_adjacencies); - bool load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); - bool load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); - }; -} diff --git a/src/openvic-simulation/map/MapDefinition.cpp b/src/openvic-simulation/map/MapDefinition.cpp new file mode 100644 index 0000000..f3bb619 --- /dev/null +++ b/src/openvic-simulation/map/MapDefinition.cpp @@ -0,0 +1,830 @@ +#include "MapDefinition.hpp" + +#include + +#include "openvic-simulation/types/Colour.hpp" +#include "openvic-simulation/types/OrderedContainers.hpp" +#include "openvic-simulation/utility/BMP.hpp" +#include "openvic-simulation/utility/Logger.hpp" + +using namespace OpenVic; +using namespace OpenVic::NodeTools; + +MapDefinition::MapDefinition() : dims { 0, 0 }, max_provinces { ProvinceDefinition::MAX_INDEX } {} + +bool MapDefinition::add_province_definition(std::string_view identifier, colour_t colour) { + if (province_definitions.size() >= max_provinces) { + Logger::error( + "The map's province list is full - maximum number of provinces is ", max_provinces, " (this can be at most ", + ProvinceDefinition::MAX_INDEX, ")" + ); + return false; + } + if (identifier.empty()) { + Logger::error("Invalid province identifier - empty!"); + return false; + } + if (!valid_basic_identifier(identifier)) { + Logger::error( + "Invalid province identifier: ", identifier, " (can only contain alphanumeric characters and underscores)" + ); + return false; + } + if (colour.is_null()) { + Logger::error("Invalid province colour for ", identifier, " - null! (", colour, ")"); + return false; + } + ProvinceDefinition new_province { + identifier, colour, static_cast(province_definitions.size() + 1) + }; + const ProvinceDefinition::index_t index = get_index_from_colour(colour); + if (index != ProvinceDefinition::NULL_INDEX) { + Logger::error( + "Duplicate province colours: ", get_province_definition_by_index(index)->to_string(), " and ", + new_province.to_string() + ); + return false; + } + colour_index_map[new_province.get_colour()] = new_province.get_index(); + return province_definitions.add_item(std::move(new_province)); +} + +ProvinceDefinition::distance_t MapDefinition::calculate_distance_between( + ProvinceDefinition const& from, ProvinceDefinition const& to +) const { + const fvec2_t to_pos = to.get_unit_position(); + const fvec2_t from_pos = from.get_unit_position(); + + const fixed_point_t min_x = std::min( + (to_pos.x - from_pos.x).abs(), + std::min( + (to_pos.x - from_pos.x + get_width()).abs(), + (to_pos.x - from_pos.x - get_width()).abs() + ) + ); + + return fvec2_t { min_x, to_pos.y - from_pos.y }.length_squared().sqrt(); +} + +using adjacency_t = ProvinceDefinition::adjacency_t; + +/* This is called for all adjacent pixel pairs and returns whether or not a new adjacency was add, + * hence the lack of error messages in the false return cases. */ +bool MapDefinition::add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to) const { + if (from == to) { + return false; + } + + const bool from_needs_adjacency = !from.is_adjacent_to(&to); + const bool to_needs_adjacency = !to.is_adjacent_to(&from); + + if (!from_needs_adjacency && !to_needs_adjacency) { + return false; + } + + const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); + + using enum adjacency_t::type_t; + + /* Default land-to-land adjacency */ + adjacency_t::type_t type = LAND; + if (from.is_water() != to.is_water()) { + /* Land-to-water adjacency */ + type = COASTAL; + + /* Mark the land province as coastal */ + from.coastal = !from.is_water(); + to.coastal = !to.is_water(); + } else if (from.is_water()) { + /* Water-to-water adjacency */ + type = WATER; + } + + if (from_needs_adjacency) { + from.adjacencies.emplace_back(&to, distance, type, nullptr, 0); + } + if (to_needs_adjacency) { + to.adjacencies.emplace_back(&from, distance, type, nullptr, 0); + } + return true; +} + +bool MapDefinition::add_special_adjacency( + ProvinceDefinition& from, ProvinceDefinition& to, adjacency_t::type_t type, ProvinceDefinition const* through, + adjacency_t::data_t data +) const { + if (from == to) { + Logger::error("Trying to add ", adjacency_t::get_type_name(type), " adjacency from province ", from, " to itself!"); + return false; + } + + using enum adjacency_t::type_t; + + /* Check end points */ + switch (type) { + case LAND: + case STRAIT: + if (from.is_water() || to.is_water()) { + Logger::error(adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has water endpoint(s)!"); + return false; + } + break; + case WATER: + case CANAL: + if (!from.is_water() || !to.is_water()) { + Logger::error(adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has land endpoint(s)!"); + return false; + } + break; + case COASTAL: + if (from.is_water() == to.is_water()) { + Logger::error("Coastal adjacency from ", from, " to ", to, " has both land or water endpoints!"); + return false; + } + break; + case IMPASSABLE: + /* Impassable is valid for all combinations of land and water: + * - land-land = replace existing land adjacency with impassable adjacency (blue borders) + * - land-water = delete existing coastal adjacency, preventing armies and navies from moving between the provinces + * - water-water = delete existing water adjacency, preventing navies from moving between the provinces */ + break; + default: + Logger::error("Invalid adjacency type ", static_cast(type)); + return false; + } + + /* Check through province */ + if (type == STRAIT || type == CANAL) { + const bool water_expected = type == STRAIT; + if (through == nullptr || through->is_water() != water_expected) { + Logger::error( + adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has a ", + (through == nullptr ? "null" : water_expected ? "land" : "water"), " through province ", through + ); + return false; + } + } else if (through != nullptr) { + Logger::warning( + adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has a non-null through province ", + through + ); + through = nullptr; + } + + /* Check canal data */ + if (data != adjacency_t::NO_CANAL && type != CANAL) { + Logger::warning( + adjacency_t::get_type_name(type), " adjacency from ", from, " to ", to, " has invalid data ", + static_cast(data) + ); + data = adjacency_t::NO_CANAL; + } + + const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); + + const auto add_adjacency = [distance, type, through, data]( + ProvinceDefinition& from, ProvinceDefinition const& to + ) -> bool { + const std::vector::iterator existing_adjacency = std::find_if( + from.adjacencies.begin(), from.adjacencies.end(), + [&to](adjacency_t const& adj) -> bool { return adj.get_to() == &to; } + ); + if (existing_adjacency != from.adjacencies.end()) { + if (type == existing_adjacency->get_type()) { + Logger::warning( + "Adjacency from ", from, " to ", to, " already has type ", adjacency_t::get_type_name(type), "!" + ); + if (type != STRAIT && type != CANAL) { + /* Straits and canals might change through or data, otherwise we can exit early */ + return true; + } + } + if (type == IMPASSABLE) { + if (existing_adjacency->get_type() == WATER || existing_adjacency->get_type() == COASTAL) { + from.adjacencies.erase(existing_adjacency); + return true; + } + } else { + if (type != STRAIT && type != CANAL) { + Logger::error( + "Provinces ", from, " and ", to, " already have an existing ", + adjacency_t::get_type_name(existing_adjacency->get_type()), " adjacency, cannot create a ", + adjacency_t::get_type_name(type), " adjacency!" + ); + return false; + } + if (type != existing_adjacency->get_type() && existing_adjacency->get_type() != (type == CANAL ? WATER : LAND)) { + Logger::error( + "Cannot convert ", adjacency_t::get_type_name(existing_adjacency->get_type()), " adjacency from ", from, + " to ", to, " to type ", adjacency_t::get_type_name(type), "!" + ); + return false; + } + } + *existing_adjacency = { &to, distance, type, through, data }; + return true; + } else if (type == IMPASSABLE) { + Logger::warning( + "Provinces ", from, " and ", to, " do not have an existing adjacency to make impassable!" + ); + return true; + } else { + from.adjacencies.emplace_back(&to, distance, type, through, data); + return true; + } + }; + + return add_adjacency(from, to) & add_adjacency(to, from); +} + +bool MapDefinition::set_water_province(std::string_view identifier) { + if (water_provinces.is_locked()) { + Logger::error("The map's water provinces have already been locked!"); + return false; + } + + ProvinceDefinition* province = get_province_definition_by_identifier(identifier); + + if (province == nullptr) { + Logger::error("Unrecognised water province identifier: ", identifier); + return false; + } + if (province->has_region()) { + Logger::error("Province ", identifier, " cannot be water as it belongs to region \"", province->get_region(), "\""); + return false; + } + if (province->is_water()) { + Logger::warning("Province ", identifier, " is already a water province!"); + return true; + } + if (!water_provinces.add_province(province)) { + Logger::error("Failed to add province ", identifier, " to water province set!"); + return false; + } + province->water = true; + return true; +} + +bool MapDefinition::set_water_province_list(std::vector const& list) { + if (water_provinces.is_locked()) { + Logger::error("The map's water provinces have already been locked!"); + return false; + } + bool ret = true; + water_provinces.reserve_more(list.size()); + for (std::string_view const& identifier : list) { + ret &= set_water_province(identifier); + } + lock_water_provinces(); + return ret; +} + +void MapDefinition::lock_water_provinces() { + water_provinces.lock(); + Logger::info("Locked water provinces after registering ", water_provinces.size()); +} + +bool MapDefinition::add_region(std::string_view identifier, std::vector&& provinces, colour_t colour) { + if (identifier.empty()) { + Logger::error("Invalid region identifier - empty!"); + return false; + } + + bool ret = true; + + std::erase_if(provinces, [identifier, &ret](ProvinceDefinition const* province) -> bool { + if (province->is_water()) { + Logger::error( + "Province ", province->get_identifier(), " cannot be added to region \"", identifier, + "\" as it is a water province!" + ); + ret = false; + return true; + } else { + return false; + } + }); + + const bool meta = provinces.empty() || std::any_of( + provinces.begin(), provinces.end(), std::bind_front(&ProvinceDefinition::has_region) + ); + + Region region { identifier, colour, meta }; + ret &= region.add_provinces(provinces); + region.lock(); + if (regions.add_item(std::move(region))) { + if (!meta) { + Region const& last_region = regions.get_items().back(); + for (ProvinceDefinition const* province : last_region.get_provinces()) { + remove_province_definition_const(province)->region = &last_region; + } + } + } else { + ret = false; + } + return ret; +} + +ProvinceDefinition::index_t MapDefinition::get_index_from_colour(colour_t colour) const { + const colour_index_map_t::const_iterator it = colour_index_map.find(colour); + if (it != colour_index_map.end()) { + return it->second; + } + return ProvinceDefinition::NULL_INDEX; +} + +ProvinceDefinition::index_t MapDefinition::get_province_index_at(ivec2_t pos) const { + if (pos.nonnegative() && pos.less_than(dims)) { + return province_shape_image[get_pixel_index_from_pos(pos)].index; + } + return ProvinceDefinition::NULL_INDEX; +} + +ProvinceDefinition* MapDefinition::get_province_definition_at(ivec2_t pos) { + return get_province_definition_by_index(get_province_index_at(pos)); +} + +ProvinceDefinition const* MapDefinition::get_province_definition_at(ivec2_t pos) const { + return get_province_definition_by_index(get_province_index_at(pos)); +} + +bool MapDefinition::set_max_provinces(ProvinceDefinition::index_t new_max_provinces) { + if (new_max_provinces <= ProvinceDefinition::NULL_INDEX) { + Logger::error( + "Trying to set max province count to an invalid value ", new_max_provinces, " (must be greater than ", + ProvinceDefinition::NULL_INDEX, ")" + ); + return false; + } + if (!province_definitions.empty() || province_definitions.is_locked()) { + Logger::error( + "Trying to set max province count to ", new_max_provinces, " after provinces have already been added and/or locked" + ); + return false; + } + max_provinces = new_max_provinces; + return true; +} + +using namespace ovdl::csv; + +static bool _validate_province_definitions_header(LineObject const& header) { + static const std::vector standard_header { "province", "red", "green", "blue" }; + for (size_t i = 0; i < standard_header.size(); ++i) { + const std::string_view val = header.get_value_for(i); + if (i == 0 && val.empty()) { + break; + } + if (val != standard_header[i]) { + return false; + } + } + return true; +} + +static bool _parse_province_colour(colour_t& colour, std::array components) { + bool ret = true; + for (size_t i = 0; i < 3; ++i) { + std::string_view& component = components[i]; + if (component.ends_with('.')) { + component.remove_suffix(1); + } + bool successful = false; + const uint64_t val = StringUtils::string_to_uint64(component, &successful, 10); + if (successful && val <= colour_t::max_value) { + colour[i] = val; + } else { + ret = false; + } + } + return ret; +} + +bool MapDefinition::load_province_definitions(std::vector const& lines) { + if (lines.empty()) { + Logger::error("No header or entries in province definition file!"); + return false; + } + + { + LineObject const& header = lines.front(); + if (!_validate_province_definitions_header(header)) { + Logger::error( + "Non-standard province definition file header - make sure this is not a province definition: ", header + ); + } + } + + if (lines.size() <= 1) { + Logger::error("No entries in province definition file!"); + return false; + } + + reserve_more_province_definitions(lines.size() - 1); + + bool ret = true; + std::for_each(lines.begin() + 1, lines.end(), [this, &ret](LineObject const& line) -> void { + const std::string_view identifier = line.get_value_for(0); + if (!identifier.empty()) { + colour_t colour = colour_t::null(); + if (!_parse_province_colour(colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) })) { + Logger::error("Error reading colour in province definition: ", line); + ret = false; + } + ret &= add_province_definition(identifier, colour); + } + }); + + lock_province_definitions(); + + return ret; +} + +bool MapDefinition::load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root) { + return expect_province_definition_dictionary( + [this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { + return province.load_positions(*this, building_type_manager, node); + } + )(root); +} + +bool MapDefinition::load_region_colours(ast::NodeCPtr root, std::vector& colours) { + return expect_dictionary_reserve_length( + colours, + [&colours](std::string_view key, ast::NodeCPtr value) -> bool { + if (key != "color") { + Logger::error("Invalid key in region colours: \"", key, "\""); + return false; + } + return expect_colour(vector_callback(colours))(value); + })(root); +} + +bool MapDefinition::load_region_file(ast::NodeCPtr root, std::vector const& colours) { + const bool ret = expect_dictionary_reserve_length( + regions, + [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { + std::vector provinces; + + bool ret = expect_list_reserve_length( + provinces, expect_province_definition_identifier(vector_callback_pointer(provinces)) + )(region_node); + + ret &= add_region(region_identifier, std::move(provinces), colours[regions.size() % colours.size()]); + + return ret; + } + )(root); + + lock_regions(); + + return ret; +} + +static constexpr colour_t colour_at(uint8_t const* colour_data, int32_t idx) { + /* colour_data is filled with BGR byte triplets - to get pixel idx as a + * single RGB value, multiply idx by 3 to get the index of the corresponding + * triplet, then combine the bytes in reverse order. + */ + idx *= 3; + return { colour_data[idx + 2], colour_data[idx + 1], colour_data[idx] }; +} + +bool MapDefinition::load_map_images(fs::path const& province_path, fs::path const& terrain_path, bool detailed_errors) { + if (!province_definitions_are_locked()) { + Logger::error("Province index image cannot be generated until after provinces are locked!"); + return false; + } + if (!terrain_type_manager.terrain_type_mappings_are_locked()) { + Logger::error("Province index image cannot be generated until after terrain type mappings are locked!"); + return false; + } + + BMP province_bmp; + if (!(province_bmp.open(province_path) && province_bmp.read_header() && province_bmp.read_pixel_data())) { + Logger::error("Failed to read BMP for compatibility mode province image: ", province_path); + return false; + } + static constexpr uint16_t expected_province_bpp = 24; + if (province_bmp.get_bits_per_pixel() != expected_province_bpp) { + Logger::error( + "Invalid province BMP bits per pixel: ", province_bmp.get_bits_per_pixel(), " (expected ", expected_province_bpp, + ")" + ); + return false; + } + + BMP terrain_bmp; + if (!(terrain_bmp.open(terrain_path) && terrain_bmp.read_header() && terrain_bmp.read_pixel_data())) { + Logger::error("Failed to read BMP for compatibility mode terrain image: ", terrain_path); + return false; + } + static constexpr uint16_t expected_terrain_bpp = 8; + if (terrain_bmp.get_bits_per_pixel() != expected_terrain_bpp) { + Logger::error( + "Invalid terrain BMP bits per pixel: ", terrain_bmp.get_bits_per_pixel(), " (expected ", expected_terrain_bpp, ")" + ); + return false; + } + + if (province_bmp.get_width() != terrain_bmp.get_width() || province_bmp.get_height() != terrain_bmp.get_height()) { + Logger::error( + "Mismatched province and terrain BMP dims: ", province_bmp.get_width(), "x", province_bmp.get_height(), " vs ", + terrain_bmp.get_width(), "x", terrain_bmp.get_height() + ); + return false; + } + + dims.x = province_bmp.get_width(); + dims.y = province_bmp.get_height(); + province_shape_image.resize(dims.x * dims.y); + + uint8_t const* province_data = province_bmp.get_pixel_data().data(); + uint8_t const* terrain_data = terrain_bmp.get_pixel_data().data(); + + std::vector> terrain_type_pixels_list(province_definitions.size()); + + bool ret = true; + ordered_set unrecognised_province_colours; + + std::vector pixels_per_province(province_definitions.size()); + std::vector pixel_position_sum_per_province(province_definitions.size()); + + for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { + for (pos.x = 0; pos.x < get_width(); ++pos.x) { + const size_t pixel_index = get_pixel_index_from_pos(pos); + const colour_t province_colour = colour_at(province_data, pixel_index); + ProvinceDefinition::index_t province_index = ProvinceDefinition::NULL_INDEX; + + if (pos.x > 0) { + const size_t jdx = pixel_index - 1; + if (colour_at(province_data, jdx) == province_colour) { + province_index = province_shape_image[jdx].index; + goto index_found; + } + } + + if (pos.y > 0) { + const size_t jdx = pixel_index - get_width(); + if (colour_at(province_data, jdx) == province_colour) { + province_index = province_shape_image[jdx].index; + goto index_found; + } + } + + province_index = get_index_from_colour(province_colour); + + if (province_index == ProvinceDefinition::NULL_INDEX && !unrecognised_province_colours.contains(province_colour)) { + unrecognised_province_colours.insert(province_colour); + if (detailed_errors) { + Logger::warning( + "Unrecognised province colour ", province_colour, " at ", pos + ); + } + } + + index_found: + province_shape_image[pixel_index].index = province_index; + + if (province_index != ProvinceDefinition::NULL_INDEX) { + const ProvinceDefinition::index_t array_index = province_index - 1; + pixels_per_province[array_index]++; + pixel_position_sum_per_province[array_index] += static_cast(pos); + } + + const TerrainTypeMapping::index_t terrain = terrain_data[pixel_index]; + TerrainTypeMapping const* mapping = terrain_type_manager.get_terrain_type_mapping_for(terrain); + if (mapping != nullptr) { + if (province_index != ProvinceDefinition::NULL_INDEX) { + terrain_type_pixels_list[province_index - 1][&mapping->get_type()]++; + } + if (mapping->get_has_texture() && terrain < terrain_type_manager.get_terrain_texture_limit()) { + province_shape_image[pixel_index].terrain = terrain + 1; + } else { + province_shape_image[pixel_index].terrain = 0; + } + } else { + province_shape_image[pixel_index].terrain = 0; + } + } + } + + if (!unrecognised_province_colours.empty()) { + Logger::warning("Province image contains ", unrecognised_province_colours.size(), " unrecognised province colours"); + } + + size_t missing = 0; + for (size_t array_index = 0; array_index < province_definitions.size(); ++array_index) { + ProvinceDefinition* province = province_definitions.get_item_by_index(array_index); + + fixed_point_map_t const& terrain_type_pixels = terrain_type_pixels_list[array_index]; + const fixed_point_map_const_iterator_t largest = get_largest_item(terrain_type_pixels); + province->default_terrain_type = largest != terrain_type_pixels.end() ? largest->first : nullptr; + + const fixed_point_t pixel_count = pixels_per_province[array_index]; + province->on_map = pixel_count > 0; + + if (province->on_map) { + province->centre = pixel_position_sum_per_province[array_index] / pixel_count; + } else { + if (detailed_errors) { + Logger::warning("Province missing from shape image: ", province->to_string()); + } + missing++; + } + } + if (missing > 0) { + Logger::warning("Province image is missing ", missing, " province colours"); + } + + return ret; +} + +/* REQUIREMENTS: + * MAP-19, MAP-84 + */ +bool MapDefinition::_generate_standard_province_adjacencies() { + bool changed = false; + + const auto generate_adjacency = [this](ProvinceDefinition* current, ivec2_t pos) -> bool { + ProvinceDefinition* neighbour = get_province_definition_at(pos); + if (neighbour != nullptr) { + return add_standard_adjacency(*current, *neighbour); + } + return false; + }; + + for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { + for (pos.x = 0; pos.x < get_width(); ++pos.x) { + ProvinceDefinition* cur = get_province_definition_at(pos); + + if (cur != nullptr) { + changed |= generate_adjacency(cur, { (pos.x + 1) % get_width(), pos.y }); + changed |= generate_adjacency(cur, { pos.x, pos.y + 1 }); + } + } + } + + return changed; +} + +bool MapDefinition::generate_and_load_province_adjacencies(std::vector const& additional_adjacencies) { + bool ret = _generate_standard_province_adjacencies(); + if (!ret) { + Logger::error("Failed to generate standard province adjacencies!"); + } + /* Skip first line containing column headers */ + if (additional_adjacencies.size() <= 1) { + Logger::error("No entries in province adjacencies file!"); + return false; + } + std::for_each( + additional_adjacencies.begin() + 1, additional_adjacencies.end(), [this, &ret](LineObject const& adjacency) -> void { + const std::string_view from_str = adjacency.get_value_for(0); + if (from_str.empty() || from_str.front() == '#') { + return; + } + ProvinceDefinition* const from = get_province_definition_by_identifier(from_str); + if (from == nullptr) { + Logger::error("Unrecognised adjacency from province identifier: \"", from_str, "\""); + ret = false; + return; + } + + const std::string_view to_str = adjacency.get_value_for(1); + ProvinceDefinition* const to = get_province_definition_by_identifier(to_str); + if (to == nullptr) { + Logger::error("Unrecognised adjacency to province identifier: \"", to_str, "\""); + ret = false; + return; + } + + using enum adjacency_t::type_t; + static const string_map_t type_map { + { "land", LAND }, { "sea", STRAIT }, { "impassable", IMPASSABLE }, { "canal", CANAL } + }; + const std::string_view type_str = adjacency.get_value_for(2); + const string_map_t::const_iterator it = type_map.find(type_str); + if (it == type_map.end()) { + Logger::error("Invalid adjacency type: \"", type_str, "\""); + ret = false; + return; + } + const adjacency_t::type_t type = it->second; + + ProvinceDefinition const* const through = get_province_definition_by_identifier(adjacency.get_value_for(3)); + + const std::string_view data_str = adjacency.get_value_for(4); + bool successful = false; + const uint64_t data_uint = StringUtils::string_to_uint64(data_str, &successful); + if (!successful || data_uint > std::numeric_limits::max()) { + Logger::error("Invalid adjacency data: \"", data_str, "\""); + ret = false; + return; + } + const adjacency_t::data_t data = data_uint; + + ret &= add_special_adjacency(*from, *to, type, through, data); + } + ); + return ret; +} + +bool MapDefinition::load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { + bool ret = expect_dictionary_reserve_length( + climates, + [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + if (identifier.empty()) { + Logger::error("Invalid climate identifier - empty!"); + return false; + } + + bool ret = true; + Climate* cur_climate = climates.get_item_by_identifier(identifier); + if (cur_climate == nullptr) { + ModifierValue values; + ret &= modifier_manager.expect_modifier_value(move_variable_callback(values))(node); + ret &= climates.add_item({ identifier, std::move(values) }); + } else { + ret &= expect_list_reserve_length(*cur_climate, expect_province_definition_identifier( + [cur_climate, &identifier](ProvinceDefinition& province) { + if (province.climate != cur_climate) { + cur_climate->add_province(&province); + if (province.climate != nullptr) { + Climate* old_climate = const_cast(province.climate); + old_climate->remove_province(&province); + Logger::warning( + "Province with id ", province.get_identifier(), + " found in multiple climates: ", identifier, + " and ", old_climate->get_identifier() + ); + } + province.climate = cur_climate; + } else { + Logger::warning( + "Province with id ", province.get_identifier(), + " defined twice in climate ", identifier + ); + } + return true; + } + ))(node); + } + return ret; + } + )(root); + + for (Climate& climate : climates.get_items()) { + climate.lock(); + } + + lock_climates(); + + return ret; +} + +bool MapDefinition::load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { + bool ret = expect_dictionary_reserve_length( + continents, + [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + if (identifier.empty()) { + Logger::error("Invalid continent identifier - empty!"); + return false; + } + + ModifierValue values; + std::vector prov_list; + bool ret = modifier_manager.expect_modifier_value_and_keys(move_variable_callback(values), + "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier( + [&prov_list](ProvinceDefinition const& province) -> bool { + if (province.continent == nullptr) { + prov_list.emplace_back(&province); + } else { + Logger::warning("Province ", province, " found in multiple continents"); + } + return true; + } + )) + )(node); + + Continent continent = { identifier, std::move(values) }; + continent.add_provinces(prov_list); + continent.lock(); + + if (continents.add_item(std::move(continent))) { + Continent const& moved_continent = continents.get_items().back(); + for (ProvinceDefinition const* prov : moved_continent.get_provinces()) { + remove_province_definition_const(prov)->continent = &moved_continent; + } + } else { + ret = false; + } + + return ret; + } + )(root); + + lock_continents(); + + return ret; +} diff --git a/src/openvic-simulation/map/MapDefinition.hpp b/src/openvic-simulation/map/MapDefinition.hpp new file mode 100644 index 0000000..9ec4367 --- /dev/null +++ b/src/openvic-simulation/map/MapDefinition.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include +#include +#include + +#include + +#include "openvic-simulation/map/ProvinceDefinition.hpp" +#include "openvic-simulation/map/Region.hpp" +#include "openvic-simulation/map/TerrainType.hpp" +#include "openvic-simulation/types/Colour.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" +#include "openvic-simulation/types/OrderedContainers.hpp" +#include "openvic-simulation/types/Vector.hpp" + +namespace OpenVic { + namespace fs = std::filesystem; + + struct BuildingTypeManager; + struct ModifierManager; + + /* REQUIREMENTS: + * MAP-4 + */ + struct MapDefinition { + +#pragma pack(push, 1) + /* Used to represent tightly packed 3-byte integer pixel information. */ + struct shape_pixel_t { + ProvinceDefinition::index_t index; + TerrainTypeMapping::index_t terrain; + }; +#pragma pack(pop) + + private: + using colour_index_map_t = ordered_map; + + IdentifierRegistry IDENTIFIER_REGISTRY_CUSTOM_INDEX_OFFSET(province_definition, 1); + IdentifierRegistry IDENTIFIER_REGISTRY(region); + IdentifierRegistry IDENTIFIER_REGISTRY(climate); + IdentifierRegistry IDENTIFIER_REGISTRY(continent); + ProvinceSet water_provinces; + TerrainTypeManager PROPERTY_REF(terrain_type_manager); + + ivec2_t PROPERTY(dims); + std::vector PROPERTY(province_shape_image); + colour_index_map_t colour_index_map; + + ProvinceDefinition::index_t PROPERTY(max_provinces); + + ProvinceDefinition::index_t get_index_from_colour(colour_t colour) const; + bool _generate_standard_province_adjacencies(); + + inline constexpr int32_t get_pixel_index_from_pos(ivec2_t pos) const { + return pos.x + pos.y * dims.x; + } + + IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_INDEX_OFFSET(province_definition, 1); + + public: + MapDefinition(); + + inline constexpr int32_t get_width() const { return dims.x; } + inline constexpr int32_t get_height() const { return dims.y; } + + bool add_province_definition(std::string_view identifier, colour_t colour); + + ProvinceDefinition::distance_t calculate_distance_between( + ProvinceDefinition const& from, ProvinceDefinition const& to + ) const; + bool add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to) const; + bool add_special_adjacency( + ProvinceDefinition& from, ProvinceDefinition& to, ProvinceDefinition::adjacency_t::type_t type, + ProvinceDefinition const* through, ProvinceDefinition::adjacency_t::data_t data + ) const; + + bool set_water_province(std::string_view identifier); + bool set_water_province_list(std::vector const& list); + void lock_water_provinces(); + + ProvinceDefinition::index_t get_province_index_at(ivec2_t pos) const; + + private: + ProvinceDefinition* get_province_definition_at(ivec2_t pos); + + /* This provides a safe way to remove the const qualifier of a ProvinceDefinition const*, via a non-const Map. + * It uses a const_cast (the fastest/simplest solution), but this could also be done without it by looking up the + * ProvinceDefinition* using the ProvinceDefinition const*'s index. Requiring a non-const Map ensures that this + * function can only be used where the ProvinceDefinition* could already be accessed by other means, such as the + * index method, preventing misleading code, or in the worst case undefined behaviour. */ + constexpr ProvinceDefinition* remove_province_definition_const(ProvinceDefinition const* province) { + return const_cast(province); + } + + public: + ProvinceDefinition const* get_province_definition_at(ivec2_t pos) const; + bool set_max_provinces(ProvinceDefinition::index_t new_max_provinces); + + bool add_region(std::string_view identifier, std::vector&& provinces, colour_t colour); + + bool load_province_definitions(std::vector const& lines); + /* Must be loaded after adjacencies so we know what provinces are coastal, and so can have a port */ + bool load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root); + static bool load_region_colours(ast::NodeCPtr root, std::vector& colours); + bool load_region_file(ast::NodeCPtr root, std::vector const& colours); + bool load_map_images(fs::path const& province_path, fs::path const& terrain_path, bool detailed_errors); + bool generate_and_load_province_adjacencies(std::vector const& additional_adjacencies); + bool load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); + bool load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); + }; +} diff --git a/src/openvic-simulation/map/MapInstance.cpp b/src/openvic-simulation/map/MapInstance.cpp new file mode 100644 index 0000000..23fe6a3 --- /dev/null +++ b/src/openvic-simulation/map/MapInstance.cpp @@ -0,0 +1,148 @@ +#include "MapInstance.hpp" + +#include "openvic-simulation/history/ProvinceHistory.hpp" +#include "openvic-simulation/map/MapDefinition.hpp" +#include "openvic-simulation/utility/Logger.hpp" + +using namespace OpenVic; + +MapInstance::MapInstance(MapDefinition const& new_map_definition) + : map_definition { new_map_definition }, selected_province { nullptr }, highest_province_population { 0 }, + total_map_population { 0 } {} + +ProvinceInstance* MapInstance::get_province_instance_from_const(ProvinceDefinition const* province) { + if (province != nullptr) { + return get_province_instance_by_index(province->get_index()); + } else { + return nullptr; + } +} + +ProvinceInstance const* MapInstance::get_province_instance_from_const(ProvinceDefinition const* province) const { + if (province != nullptr) { + return get_province_instance_by_index(province->get_index()); + } else { + return nullptr; + } +} + +void MapInstance::set_selected_province(ProvinceDefinition::index_t index) { + if (index == ProvinceDefinition::NULL_INDEX) { + selected_province = nullptr; + } else { + selected_province = get_province_instance_by_index(index); + if (selected_province == nullptr) { + Logger::error( + "Trying to set selected province to an invalid index ", index, " (max index is ", + get_province_instance_count(), ")" + ); + } + } +} + +ProvinceInstance* MapInstance::get_selected_province() { + return selected_province; +} + +ProvinceDefinition::index_t MapInstance::get_selected_province_index() const { + return selected_province != nullptr ? selected_province->get_province_definition().get_index() + : ProvinceDefinition::NULL_INDEX; +} + +bool MapInstance::reset(BuildingTypeManager const& building_type_manager) { + if (!map_definition.province_definitions_are_locked()) { + Logger::error("Cannot reset map - province consts are not locked!"); + return false; + } + + bool ret = true; + + // TODO - ensure all references to old ProvinceInstances are safely cleared + state_manager.reset(); + selected_province = nullptr; + + province_instances.reset(); + + province_instances.reserve(map_definition.get_province_definition_count()); + + for (ProvinceDefinition const& province : map_definition.get_province_definitions()) { + ret &= province_instances.add_item({ province }); + } + + province_instances.lock(); + + for (ProvinceInstance& province : province_instances.get_items()) { + ret &= province.reset(building_type_manager); + } + + if (get_province_instance_count() != map_definition.get_province_definition_count()) { + Logger::error( + "ProvinceInstance count (", get_province_instance_count(), ") does not match ProvinceDefinition count (", + map_definition.get_province_definition_count(), ")!" + ); + return false; + } + + return ret; +} + +bool MapInstance::apply_history_to_provinces( + ProvinceHistoryManager const& history_manager, Date date, IdeologyManager const& ideology_manager, + IssueManager const& issue_manager, Country const& country +) { + bool ret = true; + + for (ProvinceInstance& province : province_instances.get_items()) { + ProvinceDefinition const& province_definition = province.get_province_definition(); + if (!province_definition.is_water()) { + ProvinceHistoryMap const* history_map = history_manager.get_province_history(&province_definition); + + if (history_map != nullptr) { + ProvinceHistoryEntry const* pop_history_entry = nullptr; + + for (ProvinceHistoryEntry const* entry : history_map->get_entries_up_to(date)) { + province.apply_history_to_province(entry); + + if (!entry->get_pops().empty()) { + pop_history_entry = entry; + } + } + + if (pop_history_entry != nullptr) { + province.add_pop_vec(pop_history_entry->get_pops()); + + province.setup_pop_test_values(ideology_manager, issue_manager, country); + } + } + } + } + + return ret; +} + +void MapInstance::update_gamestate(Date today) { + for (ProvinceInstance& province : province_instances.get_items()) { + province.update_gamestate(today); + } + state_manager.update_gamestate(); + + // Update population stats + highest_province_population = 0; + total_map_population = 0; + + for (ProvinceInstance const& province : province_instances.get_items()) { + const Pop::pop_size_t province_population = province.get_total_population(); + + if (highest_province_population < province_population) { + highest_province_population = province_population; + } + + total_map_population += province_population; + } +} + +void MapInstance::tick(Date today) { + for (ProvinceInstance& province : province_instances.get_items()) { + province.tick(today); + } +} diff --git a/src/openvic-simulation/map/MapInstance.hpp b/src/openvic-simulation/map/MapInstance.hpp new file mode 100644 index 0000000..1f87326 --- /dev/null +++ b/src/openvic-simulation/map/MapInstance.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "openvic-simulation/map/ProvinceDefinition.hpp" +#include "openvic-simulation/map/ProvinceInstance.hpp" +#include "openvic-simulation/map/State.hpp" +#include "openvic-simulation/types/Date.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" + +namespace OpenVic { + struct MapDefinition; + struct BuildingTypeManager; + struct ProvinceHistoryManager; + struct IdeologyManager; + struct IssueManager; + struct Country; + + /* REQUIREMENTS: + * MAP-4 + */ + struct MapInstance { + MapDefinition const& PROPERTY(map_definition); + + IdentifierRegistry IDENTIFIER_REGISTRY_CUSTOM_INDEX_OFFSET(province_instance, 1); + + ProvinceInstance* PROPERTY(selected_province); // is it right for this to be mutable? how about using an index instead? + Pop::pop_size_t PROPERTY(highest_province_population); + Pop::pop_size_t PROPERTY(total_map_population); + + StateManager PROPERTY_REF(state_manager); + + public: + MapInstance(MapDefinition const& new_map_definition); + + inline explicit constexpr operator MapDefinition const&() const { + return map_definition; + } + + IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_INDEX_OFFSET(province_instance, 1); + + ProvinceInstance* get_province_instance_from_const(ProvinceDefinition const* province); + ProvinceInstance const* get_province_instance_from_const(ProvinceDefinition const* province) const; + + void set_selected_province(ProvinceDefinition::index_t index); + ProvinceInstance* get_selected_province(); + ProvinceDefinition::index_t get_selected_province_index() const; + + bool reset(BuildingTypeManager const& building_type_manager); + bool apply_history_to_provinces( + ProvinceHistoryManager const& history_manager, Date date, IdeologyManager const& ideology_manager, + IssueManager const& issue_manager, Country const& country + ); + + void update_gamestate(Date today); + void tick(Date today); + }; +} diff --git a/src/openvic-simulation/map/Mapmode.cpp b/src/openvic-simulation/map/Mapmode.cpp index d2acd84..6f8e606 100644 --- a/src/openvic-simulation/map/Mapmode.cpp +++ b/src/openvic-simulation/map/Mapmode.cpp @@ -3,7 +3,10 @@ #include #include "openvic-simulation/country/Country.hpp" -#include "openvic-simulation/map/Map.hpp" +#include "openvic-simulation/map/MapDefinition.hpp" +#include "openvic-simulation/map/MapInstance.hpp" +#include "openvic-simulation/map/ProvinceDefinition.hpp" +#include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/utility/Utility.hpp" using namespace OpenVic; @@ -16,13 +19,15 @@ Mapmode::Mapmode( } const Mapmode Mapmode::ERROR_MAPMODE { - "mapmode_error", 0, [](Map const& map, ProvinceInstance const& province) -> base_stripe_t { + "mapmode_error", 0, [](MapInstance const&, ProvinceInstance const& province) -> base_stripe_t { return { 0xFFFF0000_argb, colour_argb_t::null() }; } }; -Mapmode::base_stripe_t Mapmode::get_base_stripe_colours(Map const& map, ProvinceInstance const& province) const { - return colour_func ? colour_func(map, province) : colour_argb_t::null(); +Mapmode::base_stripe_t Mapmode::get_base_stripe_colours( + MapInstance const& map_instance, ProvinceInstance const& province +) const { + return colour_func ? colour_func(map_instance, province) : colour_argb_t::null(); } bool MapmodeManager::add_mapmode(std::string_view identifier, Mapmode::colour_func_t colour_func) { @@ -37,7 +42,7 @@ bool MapmodeManager::add_mapmode(std::string_view identifier, Mapmode::colour_fu return mapmodes.add_item({ identifier, mapmodes.size(), colour_func }); } -bool MapmodeManager::generate_mapmode_colours(Map const& map, Mapmode::index_t index, uint8_t* target) const { +bool MapmodeManager::generate_mapmode_colours(MapInstance const& map_instance, Mapmode::index_t index, uint8_t* target) const { if (target == nullptr) { Logger::error("Mapmode colour target pointer is null!"); return false; @@ -60,12 +65,17 @@ bool MapmodeManager::generate_mapmode_colours(Map const& map, Mapmode::index_t i target_stripes[ProvinceDefinition::NULL_INDEX] = colour_argb_t::null(); - if (map.province_instances_are_locked()) { - for (ProvinceInstance const& province : map.get_province_instances()) { - target_stripes[province.get_province_definition().get_index()] = mapmode->get_base_stripe_colours(map, province); + if (map_instance.province_instances_are_locked()) { + for (ProvinceInstance const& province : map_instance.get_province_instances()) { + target_stripes[province.get_province_definition().get_index()] = + mapmode->get_base_stripe_colours(map_instance, province); } } else { - for (size_t index = ProvinceDefinition::NULL_INDEX + 1; index <= map.get_province_definition_count(); ++index) { + for ( + size_t index = ProvinceDefinition::NULL_INDEX + 1; + index <= map_instance.get_map_definition().get_province_definition_count(); + ++index + ) { target_stripes[index] = colour_argb_t::null(); } } @@ -83,7 +93,7 @@ static constexpr colour_argb_t DEFAULT_COLOUR_GREY = (0x7F7F7F_argb).with_alpha( template T, typename P> requires(std::same_as || std::same_as) static constexpr auto get_colour_mapmode(T const*(P::*get_item)() const) { - return [get_item](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + return [get_item](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.get_province_definition(); T const* item = ([&province, &province_definition]() -> P const& { @@ -124,7 +134,7 @@ static constexpr Mapmode::base_stripe_t shaded_mapmode(fixed_point_map_t T> static constexpr auto shaded_mapmode(fixed_point_map_t const&(ProvinceInstance::*get_map)() const) { - return [get_map](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + return [get_map](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { return shaded_mapmode((province.*get_map)()); }; } @@ -136,7 +146,7 @@ bool MapmodeManager::setup_mapmodes() { const std::vector mapmodes { { "mapmode_terrain", - [](Map const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + [](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { return colour_argb_t::null(); } }, @@ -146,7 +156,7 @@ bool MapmodeManager::setup_mapmodes() { { /* TEST MAPMODE, TO BE REMOVED */ "mapmode_province", - [](Map const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + [](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { return colour_argb_t { province.get_province_definition().get_colour(), ALPHA_VALUE }; } }, @@ -156,9 +166,10 @@ bool MapmodeManager::setup_mapmodes() { { /* TEST MAPMODE, TO BE REMOVED */ "mapmode_index", - [](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province) -> Mapmode::base_stripe_t { const colour_argb_t::value_type f = colour_argb_t::colour_traits::component_from_fraction( - province.get_province_definition().get_index(), map.get_province_definition_count() + 1 + province.get_province_definition().get_index(), + map_instance.get_map_definition().get_province_definition_count() + 1 ); return colour_argb_t::fill_as(f).with_alpha(ALPHA_VALUE); } @@ -172,7 +183,7 @@ bool MapmodeManager::setup_mapmodes() { }, { "mapmode_infrastructure", - [](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + [](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { BuildingInstance const* railroad = province.get_building_by_identifier("railroad"); if (railroad != nullptr) { const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( @@ -192,13 +203,13 @@ bool MapmodeManager::setup_mapmodes() { }, { "mapmode_population", - [](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province) -> Mapmode::base_stripe_t { // TODO - explore non-linear scaling to have more variation among non-massive provinces // TODO - when selecting a province, only show the population of provinces controlled (or owned?) // by the same country, relative to the most populous province in that set of provinces if (!province.get_province_definition().is_water()) { const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( - province.get_total_population(), map.get_highest_province_population() + 1, 0.1f, 1.0f + province.get_total_population(), map_instance.get_highest_province_population() + 1, 0.1f, 1.0f ); return colour_argb_t { 0, val, 0, ALPHA_VALUE }; } else { @@ -215,8 +226,9 @@ bool MapmodeManager::setup_mapmodes() { }, { /* TEST MAPMODE, TO BE REMOVED */ - "mapmode_adjacencies", [](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { - ProvinceInstance const* selected_province = map.get_selected_province(); + "mapmode_adjacencies", + [](MapInstance const& map_instance, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + ProvinceInstance const* selected_province = map_instance.get_selected_province(); if (selected_province != nullptr) { ProvinceDefinition const& selected_province_definition = selected_province->get_province_definition(); @@ -258,7 +270,7 @@ bool MapmodeManager::setup_mapmodes() { } }, { - "mapmode_port", [](Map const& map, ProvinceInstance const& province) -> Mapmode::base_stripe_t { + "mapmode_port", [](MapInstance const&, ProvinceInstance const& province) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.get_province_definition(); if (province_definition.has_port()) { diff --git a/src/openvic-simulation/map/Mapmode.hpp b/src/openvic-simulation/map/Mapmode.hpp index fa306e9..d514f7a 100644 --- a/src/openvic-simulation/map/Mapmode.hpp +++ b/src/openvic-simulation/map/Mapmode.hpp @@ -8,7 +8,7 @@ namespace OpenVic { struct MapmodeManager; - struct Map; + struct MapInstance; struct ProvinceInstance; struct Mapmode : HasIdentifier { @@ -23,7 +23,7 @@ namespace OpenVic { : base_colour { base }, stripe_colour { stripe } {} constexpr base_stripe_t(colour_argb_t both) : base_stripe_t { both, both } {} }; - using colour_func_t = std::function; + using colour_func_t = std::function; using index_t = size_t; private: @@ -37,7 +37,7 @@ namespace OpenVic { Mapmode(Mapmode&&) = default; - base_stripe_t get_base_stripe_colours(Map const& map, ProvinceInstance const& province) const; + base_stripe_t get_base_stripe_colours(MapInstance const& map_instance, ProvinceInstance const& province) const; }; struct MapmodeManager { @@ -54,7 +54,7 @@ namespace OpenVic { * and A = 255 is fully the RGB colour packaged with A. The base and stripe colours for each province are packed * together adjacently, so each province's entry is 8 bytes long. The list contains ProvinceDefinition::MAX_INDEX + 1 * entries, that is the maximum allowed number of provinces plus one for the index-zero "null province". */ - bool generate_mapmode_colours(Map const& map, Mapmode::index_t index, uint8_t* target) const; + bool generate_mapmode_colours(MapInstance const& map_instance, Mapmode::index_t index, uint8_t* target) const; bool setup_mapmodes(); }; diff --git a/src/openvic-simulation/map/ProvinceDefinition.cpp b/src/openvic-simulation/map/ProvinceDefinition.cpp index bb8ad59..c40f8f0 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.cpp +++ b/src/openvic-simulation/map/ProvinceDefinition.cpp @@ -2,7 +2,7 @@ #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/economy/BuildingType.hpp" -#include "openvic-simulation/map/Map.hpp" +#include "openvic-simulation/map/MapDefinition.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -26,8 +26,10 @@ std::string ProvinceDefinition::to_string() const { return stream.str(); } -bool ProvinceDefinition::load_positions(Map const& map, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root) { - const fixed_point_t map_height = map.get_height(); +bool ProvinceDefinition::load_positions( + MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root +) { + const fixed_point_t map_height = map_definition.get_height(); const bool ret = expect_dictionary_keys( "text_position", ZERO_OR_ONE, @@ -70,7 +72,7 @@ bool ProvinceDefinition::load_positions(Map const& map, BuildingTypeManager cons const fvec2_t port_dir { -rotation.cos(), rotation.sin() }; const ivec2_t port_facing_position = static_cast(*port_position + port_dir / 4); - ProvinceDefinition const* province = map.get_province_definition_at(port_facing_position); + ProvinceDefinition const* province = map_definition.get_province_definition_at(port_facing_position); if (province != nullptr) { if (province->is_water() && is_adjacent_to(province)) { diff --git a/src/openvic-simulation/map/ProvinceDefinition.hpp b/src/openvic-simulation/map/ProvinceDefinition.hpp index a4076fe..c66323c 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.hpp +++ b/src/openvic-simulation/map/ProvinceDefinition.hpp @@ -11,7 +11,7 @@ namespace OpenVic { - struct Map; + struct MapDefinition; struct Region; struct TerrainType; struct ProvinceSetModifier; @@ -25,7 +25,7 @@ namespace OpenVic { * POP-22 */ struct ProvinceDefinition : HasIdentifierAndColour { - friend struct Map; + friend struct MapDefinition; using index_t = uint16_t; using distance_t = fixed_point_t; // should this go inside adjacency_t? @@ -114,7 +114,9 @@ namespace OpenVic { } /* The positions' y coordinates need to be inverted. */ - bool load_positions(Map const& map, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root); + bool load_positions( + MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root + ); fvec2_t get_text_position() const; fixed_point_t get_text_rotation() const; diff --git a/src/openvic-simulation/map/ProvinceInstance.hpp b/src/openvic-simulation/map/ProvinceInstance.hpp index 2dbc4e3..3292575 100644 --- a/src/openvic-simulation/map/ProvinceInstance.hpp +++ b/src/openvic-simulation/map/ProvinceInstance.hpp @@ -7,6 +7,7 @@ #include "openvic-simulation/types/OrderedContainers.hpp" namespace OpenVic { + struct MapInstance; struct ProvinceDefinition; struct TerrainType; struct State; @@ -24,7 +25,7 @@ namespace OpenVic { struct IssueManager; struct ProvinceInstance : HasIdentifier { - friend struct Map; + friend struct MapInstance; using life_rating_t = int8_t; @@ -63,7 +64,7 @@ namespace OpenVic { public: ProvinceInstance(ProvinceInstance&&) = default; - inline constexpr operator ProvinceDefinition const&() const { + inline explicit constexpr operator ProvinceDefinition const&() const { return province_definition; } diff --git a/src/openvic-simulation/map/Region.hpp b/src/openvic-simulation/map/Region.hpp index f532400..1152dab 100644 --- a/src/openvic-simulation/map/Region.hpp +++ b/src/openvic-simulation/map/Region.hpp @@ -46,7 +46,7 @@ namespace OpenVic { }; struct ProvinceSetModifier : Modifier, ProvinceSet { - friend struct Map; + friend struct MapDefinition; private: ProvinceSetModifier(std::string_view new_identifier, ModifierValue&& new_values); public: @@ -57,7 +57,7 @@ namespace OpenVic { * MAP-6, MAP-44, MAP-48 */ struct Region : HasIdentifierAndColour, ProvinceSet { - friend struct Map; + friend struct MapDefinition; private: /* A meta region cannot be the template for a state. diff --git a/src/openvic-simulation/map/State.cpp b/src/openvic-simulation/map/State.cpp index 1c49ed7..46ff11d 100644 --- a/src/openvic-simulation/map/State.cpp +++ b/src/openvic-simulation/map/State.cpp @@ -1,7 +1,8 @@ #include "State.hpp" #include "openvic-simulation/country/Country.hpp" -#include "openvic-simulation/map/Map.hpp" +#include "openvic-simulation/map/MapDefinition.hpp" +#include "openvic-simulation/map/MapInstance.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/map/Region.hpp" @@ -39,7 +40,7 @@ void StateSet::update_gamestate() { } } -bool StateManager::add_state_set(Map& map, Region const& region) { +bool StateManager::add_state_set(MapInstance& map_instance, Region const& region) { if (region.get_meta()) { Logger::error("Cannot use meta region \"", region.get_identifier(), "\" as state template!"); return false; @@ -54,7 +55,7 @@ bool StateManager::add_state_set(Map& map, Region const& region) { for (ProvinceDefinition const* province : region.get_provinces()) { - ProvinceInstance* province_instance = map.get_province_instance_from_const(province); + ProvinceInstance* province_instance = map_instance.get_province_instance_from_const(province); // add to existing state if shared owner & status... for (std::vector& provinces : temp_provinces) { @@ -98,16 +99,18 @@ bool StateManager::add_state_set(Map& map, Region const& region) { return true; } -bool StateManager::generate_states(Map& map) { +bool StateManager::generate_states(MapInstance& map_instance) { + MapDefinition const& map_definition = map_instance.get_map_definition(); + state_sets.clear(); - state_sets.reserve(map.get_region_count()); + state_sets.reserve(map_definition.get_region_count()); bool ret = true; size_t state_count = 0; - for (Region const& region : map.get_regions()) { + for (Region const& region : map_definition.get_regions()) { if (!region.get_meta()) { - if (add_state_set(map, region)) { + if (add_state_set(map_instance, region)) { state_count += state_sets.back().get_state_count(); } else { ret = false; diff --git a/src/openvic-simulation/map/State.hpp b/src/openvic-simulation/map/State.hpp index e030a0b..ff8acfa 100644 --- a/src/openvic-simulation/map/State.hpp +++ b/src/openvic-simulation/map/State.hpp @@ -53,20 +53,20 @@ namespace OpenVic { void update_gamestate(); }; - struct Map; + struct MapInstance; /* Contains all current states.*/ struct StateManager { private: std::vector PROPERTY(state_sets); - bool add_state_set(Map& map, Region const& region); + bool add_state_set(MapInstance& map_instance, Region const& region); public: /* Creates states from current province gamestate & regions, sets province state value. * After this function, the `regions` property is unmanaged and must be carefully updated and * validated by functions that modify it. */ - bool generate_states(Map& map); + bool generate_states(MapInstance& map_instance); void reset(); -- cgit v1.2.3-56-ga3b1