From 164264b047921dbe1567d2af183e1cffb200a8cb Mon Sep 17 00:00:00 2001 From: hop311 Date: Sat, 28 Oct 2023 10:39:08 +0100 Subject: Astyle formatting (with manual cleanup) --- .astylesrc | 217 ++++++++ astyle.sh | 6 + src/headless/main.cpp | 8 +- src/openvic-simulation/GameAdvancementHook.cpp | 15 +- src/openvic-simulation/GameAdvancementHook.hpp | 3 +- src/openvic-simulation/GameManager.cpp | 98 ++-- src/openvic-simulation/Modifier.cpp | 41 +- src/openvic-simulation/Modifier.hpp | 61 ++- src/openvic-simulation/country/Country.cpp | 33 +- src/openvic-simulation/dataloader/Dataloader.cpp | 238 +++++---- src/openvic-simulation/dataloader/Dataloader.hpp | 25 +- .../dataloader/Dataloader_Windows.hpp | 47 +- src/openvic-simulation/dataloader/NodeTools.cpp | 44 +- src/openvic-simulation/dataloader/NodeTools.hpp | 50 +- src/openvic-simulation/economy/Building.cpp | 57 ++- src/openvic-simulation/economy/Building.hpp | 4 +- src/openvic-simulation/economy/Good.cpp | 9 +- src/openvic-simulation/economy/ProductionType.cpp | 12 +- src/openvic-simulation/economy/ProductionType.hpp | 8 +- src/openvic-simulation/history/Bookmark.hpp | 3 +- src/openvic-simulation/history/CountryHistory.cpp | 168 +++++-- src/openvic-simulation/history/ProvinceHistory.cpp | 547 +++++++++++---------- src/openvic-simulation/history/ProvinceHistory.hpp | 153 +++--- src/openvic-simulation/map/Map.cpp | 75 ++- src/openvic-simulation/map/Province.cpp | 18 +- src/openvic-simulation/map/Region.cpp | 8 +- src/openvic-simulation/map/TerrainType.hpp | 3 +- src/openvic-simulation/military/Deployment.cpp | 175 ++++--- src/openvic-simulation/military/Deployment.hpp | 6 +- src/openvic-simulation/military/LeaderTrait.cpp | 3 +- src/openvic-simulation/military/Unit.cpp | 139 +++--- src/openvic-simulation/military/Unit.hpp | 16 +- src/openvic-simulation/misc/Define.cpp | 60 +-- src/openvic-simulation/politics/Government.cpp | 11 +- src/openvic-simulation/politics/Government.hpp | 6 +- src/openvic-simulation/politics/Ideology.cpp | 11 +- src/openvic-simulation/politics/Ideology.hpp | 6 +- src/openvic-simulation/politics/Issue.cpp | 5 +- src/openvic-simulation/pop/Culture.cpp | 15 +- src/openvic-simulation/pop/Culture.hpp | 12 +- src/openvic-simulation/pop/Pop.cpp | 23 +- src/openvic-simulation/pop/Pop.hpp | 3 +- src/openvic-simulation/pop/Religion.cpp | 3 +- src/openvic-simulation/testing/Requirement.cpp | 52 +- src/openvic-simulation/testing/TestScript.cpp | 60 ++- src/openvic-simulation/testing/Testing.cpp | 6 +- .../testing/test_scripts/A_001_file_tests.cpp | 80 +-- .../testing/test_scripts/A_002_economy_tests.cpp | 198 ++++---- src/openvic-simulation/types/Colour.hpp | 4 +- src/openvic-simulation/types/Date.cpp | 179 +++++-- .../types/IdentifierRegistry.cpp | 4 +- .../types/IdentifierRegistry.hpp | 33 +- src/openvic-simulation/types/Vector.cpp | 1 - .../types/fixed_point/FixedPoint.hpp | 28 +- src/openvic-simulation/utility/BMP.cpp | 6 +- src/openvic-simulation/utility/Logger.cpp | 24 +- src/openvic-simulation/utility/Logger.hpp | 24 +- src/openvic-simulation/utility/StringUtils.hpp | 42 +- 58 files changed, 2004 insertions(+), 1182 deletions(-) create mode 100644 .astylesrc create mode 100644 astyle.sh diff --git a/.astylesrc b/.astylesrc new file mode 100644 index 0000000..7891dcc --- /dev/null +++ b/.astylesrc @@ -0,0 +1,217 @@ +# @file Astyle code automatic formatting settings +# @see http://astyle.sourceforge.net/astyle.html#_General_Information + +# +# Java style uses attached braces. +# +# int Foo(bool isBar) { +# if (isBar) { +# bar(); +# return 1; +# } else +# return 0; +# } +# +--style=attach + +# +# Indent using all tab characters, if possible. If a continuation line is not an even number of tabs, +# spaces will be added at the end. Treat each tab as # spaces (e.g. -T6 / --indent=force-tab=6). +# # must be between 2 and 20. If no # is set, treats tabs as 4 spaces. +# +--indent=force-tab=4 + +# +# Add extra indentation to namespace blocks. This option has no effect on Java files. +# +--indent-namespaces + +# +# Indent multi-line preprocessor definitions ending with a backslash. Should be used with --convert-tabs for proper results. +# Does a pretty good job, but cannot perform miracles in obfuscated preprocessor definitions. +# Without this option the preprocessor statements remain unchanged. +# +--indent-preproc-define + +# +# Indent C++ comments beginning in column one. By default C++ comments beginning in column one are assumed to be +# commented-out code and not indented. This option will allow the comments to be indented with the code. +# +--indent-col1-comments + +# +# Indent, instead of align, continuation lines following lines that contain an opening paren '(' or an assignment '='. +# This includes function definitions and declarations and return statements. +# The indentation can be modified by using the following indent-continuation option. +# This option may be preferred for editors displaying proportional fonts. +# +--indent-after-parens + +# +# Set the continuation indent for a line that ends with an opening paren '(' or an assignment '='. +# This includes function definitions and declarations. It will also modify the previous indent-after-paren option. +# The value for # indicates a number of indents. The valid values are the integer values from 0 thru 4. +# If this option is not used, the default value of 1 is used. +# +--indent-continuation=1 + +# +# Set the minimal indent that is added when a header is built of multiple lines. +# This indent helps to easily separate the header from the command statements that follow. +# The value for # indicates a number of indents and is a minimum value. +# The indent may be greater to align with the data on the previous line. +# The valid values are: +# 0 - no minimal indent. The lines will be aligned with the paren on the preceding line. +# 1 - indent at least one additional indent. +# 2 - indent at least two additional indents. +# 3 - indent at least one-half an additional indent. This is intended for large indents (e.g. 8). +# The default value is 2, two additional indents. +# +--min-conditional-indent=0 + +# +# Set the maximum of # spaces to indent a continuation line. The # indicates a number of columns and +# must not be less than 40 or greater than 120. If no value is set, the default value of 40 will be used. +# This option will prevent continuation lines from extending too far to the right. +# Setting a larger value will allow the code to be extended further to the right. +# +#--max-continuation-indent=40 + +# +# Indent labels so that they appear one indent less than +# the current indentation level, rather than being +# flushed completely to the left (which is the default). +# +--indent-labels + +# +# This option improves indentation of C++ lambda functions. As it currently does not work well with +# complex lambda function bodies, this feature is not enabled by default. +# +#--lambda-indent + +# +# Attach a pointer or reference operator (*, &, or ^) to either the variable type (left) or variable name (right), or place it between the type and name (middle). +# +--align-pointer=type + +# +# This option will align references separate from pointers. Pointers are not changed by this option. +# If pointers and references are to be aligned the same, use the previous align-pointer option. +# +--align-reference=type + +# +# Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', 'while'...). +# The statement must be on a single line. The brackets will be added according to the currently requested predefined style or bracket type. +# If no style or bracket type is requested the brackets will be attached. +# If --add-one-line-brackets is also used the result will be one line brackets. +# +--add-braces + +# Don't break complex statements and multiple statements residing on a single line. +# +#--keep-one-line-statements + +# +# The option max?code?length will break a line if the code exceeds # characters. +# The valid values are 50 thru 200. Lines without logical conditionals will break on a logical conditional (||, &&, ...), comma, paren, semicolon, or space. +# Some code will not be broken, such as comments, quotes, and arrays. If used with keep?one?line?blocks or add-one-line-brackets the blocks will NOT be broken. +# If used with keep?one?line?statements the statements will be broken at a semicolon if the line goes over the maximum length. +# If there is no available break point within the max code length, the line will be broken at the first available break point after the max code length. +# +--max-code-length=128 + +# +# By default logical conditionals will be placed first on the new line. +# The option break?after?logical will cause the logical conditionals to be placed last on the previous line. This option has no effect without max?code?length. +# +#--break-after-logical + +# +# Indent a C type, C#, or Java file. C type files are C, C++, C++/CLI, and Objective-C. The option is usually set from the file extension for each file. +# +--mode=c + +# +# Verbose display mode. Display optional information, such as release number, date, option file locations, and statistical data. +# +--verbose + +# +# Formatted files display mode. Display only the files that have been formatted. Do not display files that are unchanged. +# +--formatted + +# +# Force use of the specified line end style. Valid options are windows (CRLF), linux (LF), and macold (CR). +# MacOld style is the format for Mac OS 9 and earlier. OS X uses the Linux style. +# If one of these options is not used the line ends will be determined automatically from the input file. +# When redirection is used on Windows the output will always have Windows line ends. This option will be ignored. +# +--lineend=linux + +# +# Insert space padding around operators. This will also pad commas. Any end of line comments will remain +# in the original column, if possible. Note that there is no option to unpad. Once padded, they stay padded. +# +--pad-oper + +# +# Insert space padding between a header (e.g. 'if', 'for', 'while'...) and the following paren. +# Any end of line comments will remain in the original column, if possible. +# This can be used with unpad-paren to remove unwanted spaces. +# +--pad-header + +# +# Remove extra space padding around parens on the inside and outside. Any end of line comments will remain in the original +# column, if possible. This option can be used in combination with the paren padding options pad-paren, pad-paren-out, +# pad-paren-in, and pad-header above. Only padding that has not been requested by other options will be removed. +# For example, if a source has parens padded on both the inside and outside, and you want inside only. +# You need to use unpad-paren to remove the outside padding, and pad-paren-in to retain the inside padding. +# Using only pad-paren-in> would not remove the outside padding. +# +--unpad-paren + +# +# Remove padding around square brackets on both the outside and the inside. +# +--unpad-brackets + +# +# Remove superfluous empty lines exceeding the given number. +# +--squeeze-lines=1 + +# +# Remove superfluous whitespace +# +--squeeze-ws + +# +# Attach the return type to the function name. The two options are for the function definitions (-xf), +# and the function declarations or signatures (-xh). They are intended to undo the --break-return-type options. +# If used with --break-return-type, the result will be to break the return type. +# This option has no effect on Objective-C functions. +# +--attach-return-type + +# +# Closes whitespace between the ending angle brackets of template definitions. +# Closing the ending angle brackets is now allowed by the C++11 standard. +# Be sure your compiler supports this before making the changes. +# +--close-templates + +# +# Do not retain a backup of the original file. The original file is purged after it is formatted. +# +--suffix=none + +# +# Preserve the original file's date and time modified. +# The time modified will be changed a few microseconds to force the changed files to compile. +# This option is not effective if redirection is used to rename the input file. +# +--preserve-date diff --git a/astyle.sh b/astyle.sh new file mode 100644 index 0000000..b7ac65e --- /dev/null +++ b/astyle.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +echo "\n\nFormatting openvic-simulation with astyle:\n" +astyle --options=.astylesrc --recursive ./src/*.?pp + +exit 0 diff --git a/src/headless/main.cpp b/src/headless/main.cpp index 6cb6661..04bfc7b 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -82,15 +82,17 @@ int main(int argc, char const* argv[]) { /* Reads the next argument and converts it to a path via path_transform. If reading or converting fails, an error * message and the help text are displayed, along with returning false to signify the program should exit. */ - const auto _read = [&root, &argn, argc, argv, program_name](std::string_view command, std::string_view path_use, auto path_transform) -> bool { - if (root.empty()) { + const auto _read = [&root, &argn, argc, argv, program_name]( + std::string_view command, std::string_view path_use, auto path_transform) -> bool { + if (root.empty()) { if (++argn < argc) { char const* path = argv[argn]; root = path_transform(path); if (!root.empty()) { return true; } else { - std::cerr << "Empty path after giving \"" << path << "\" to " << path_use << " command line argument \"" << command << "\"." << std::endl; + std::cerr << "Empty path after giving \"" << path << "\" to " << path_use + << " command line argument \"" << command << "\"." << std::endl; } } else { std::cerr << "Missing path after " << path_use << " command line argument \"" << command << "\"." << std::endl; diff --git a/src/openvic-simulation/GameAdvancementHook.cpp b/src/openvic-simulation/GameAdvancementHook.cpp index ac16158..d48a1c2 100644 --- a/src/openvic-simulation/GameAdvancementHook.cpp +++ b/src/openvic-simulation/GameAdvancementHook.cpp @@ -21,12 +21,13 @@ GameAdvancementHook::GameAdvancementHook(AdvancementFunction tickFunction, } void GameAdvancementHook::setSimulationSpeed(speed_t speed) { - if (speed < 0) + if (speed < 0) { currentSpeed = 0; - else if (speed >= GAME_SPEEDS.size()) + } else if (speed >= GAME_SPEEDS.size()) { currentSpeed = GAME_SPEEDS.size() - 1; - else + } else { currentSpeed = speed; + } } GameAdvancementHook::speed_t GameAdvancementHook::getSimulationSpeed() const { @@ -64,10 +65,14 @@ void GameAdvancementHook::conditionallyAdvanceGame() { time_point_t currentTime = std::chrono::high_resolution_clock::now(); if (std::chrono::duration_cast(currentTime - lastPolledTime) >= GAME_SPEEDS[currentSpeed]) { lastPolledTime = currentTime; - if (triggerFunction) triggerFunction(); + if (triggerFunction) { + triggerFunction(); + } } } - if (refreshFunction) refreshFunction(); + if (refreshFunction) { + refreshFunction(); + } } void GameAdvancementHook::reset() { diff --git a/src/openvic-simulation/GameAdvancementHook.hpp b/src/openvic-simulation/GameAdvancementHook.hpp index 59e43a4..9d19948 100644 --- a/src/openvic-simulation/GameAdvancementHook.hpp +++ b/src/openvic-simulation/GameAdvancementHook.hpp @@ -28,7 +28,8 @@ namespace OpenVic { public: bool isPaused; - GameAdvancementHook(AdvancementFunction tickFunction, RefreshFunction updateFunction, bool startPaused = true, speed_t startingSpeed = 0); + GameAdvancementHook(AdvancementFunction tickFunction, RefreshFunction updateFunction, + bool startPaused = true, speed_t startingSpeed = 0); void setSimulationSpeed(speed_t speed); speed_t getSimulationSpeed() const; diff --git a/src/openvic-simulation/GameManager.cpp b/src/openvic-simulation/GameManager.cpp index 1c4efb3..c1710f6 100644 --- a/src/openvic-simulation/GameManager.cpp +++ b/src/openvic-simulation/GameManager.cpp @@ -3,18 +3,28 @@ using namespace OpenVic; GameManager::GameManager(state_updated_func_t state_updated_callback) - : clock { [this]() { tick(); }, [this]() { update_state(); } }, - state_updated { state_updated_callback } {} + : clock { + [this]() { + tick(); + }, + [this]() { + update_state(); + } +}, state_updated { state_updated_callback } {} void GameManager::set_needs_update() { needs_update = true; } void GameManager::update_state() { - if (!needs_update) return; + if (!needs_update) { + return; + } Logger::info("Update: ", today); map.update_state(today); - if (state_updated) state_updated(); + if (state_updated) { + state_updated(); + } needs_update = false; } @@ -46,7 +56,8 @@ bool GameManager::expand_building(Province::index_t province_index, std::string_ set_needs_update(); Province* province = map.get_province_by_index(province_index); if (province == nullptr) { - Logger::error("Invalid province index ", province_index, " while trying to expand building ", building_type_identifier); + Logger::error("Invalid province index ", province_index, + " while trying to expand building ", building_type_identifier); return false; } return province->expand_building(building_type_identifier); @@ -67,65 +78,92 @@ bool GameManager::load_hardcoded_defines() { using mapmode_t = std::pair; const std::vector mapmodes { - { "mapmode_terrain", + { + "mapmode_terrain", [](Map const&, Province const& province) -> colour_t { return default_colour(province); - } }, - { "mapmode_province", + } + }, + { + "mapmode_province", [](Map const&, Province const& province) -> colour_t { return HIGH_ALPHA_VALUE | province.get_colour(); - } }, - { "mapmode_region", + } + }, + { + "mapmode_region", [](Map const&, Province const& province) -> colour_t { Region const* region = province.get_region(); return region != nullptr ? HIGH_ALPHA_VALUE | region->get_colour() : default_colour(province); - } }, - { "mapmode_index", + } + }, + { + "mapmode_index", [](Map const& map, Province const& province) -> colour_t { const colour_t f = fraction_to_colour_byte(province.get_index(), map.get_province_count() + 1); return HIGH_ALPHA_VALUE | (f << 16) | (f << 8) | f; - } }, - { "mapmode_terrain_type", + } + }, + { + "mapmode_terrain_type", [](Map const& map, Province const& province) -> colour_t { TerrainType const* terrarin_type = province.get_terrain_type(); return terrarin_type != nullptr ? HIGH_ALPHA_VALUE | terrarin_type->get_colour() : default_colour(province); - } }, - { "mapmode_rgo", + } + }, + { + "mapmode_rgo", [](Map const& map, Province const& province) -> colour_t { Good const* rgo = province.get_rgo(); return rgo != nullptr ? HIGH_ALPHA_VALUE | rgo->get_colour() : default_colour(province); - } }, - { "mapmode_infrastructure", + } + }, + { + "mapmode_infrastructure", [](Map const& map, Province const& province) -> colour_t { BuildingInstance const* railroad = province.get_building_by_identifier("building_railroad"); if (railroad != nullptr) { - colour_t val = fraction_to_colour_byte(railroad->get_current_level(), railroad->get_building().get_max_level() + 1, 0.5f, 1.0f); + colour_t val = fraction_to_colour_byte(railroad->get_current_level(), + railroad->get_building().get_max_level() + 1, 0.5f, 1.0f); switch (railroad->get_expansion_state()) { - case ExpansionState::CannotExpand: val <<= 16; break; - case ExpansionState::CanExpand: break; - default: val <<= 8; break; + case ExpansionState::CannotExpand: + val <<= 16; + break; + case ExpansionState::CanExpand: + break; + default: + val <<= 8; + break; } return HIGH_ALPHA_VALUE | val; } return default_colour(province); - } }, - { "mapmode_population", + } + }, + { + "mapmode_population", [](Map const& map, Province const& province) -> colour_t { return HIGH_ALPHA_VALUE | (fraction_to_colour_byte(province.get_total_population(), map.get_highest_province_population() + 1, 0.1f, 1.0f) << 8); - } }, - { "mapmode_culture", + } + }, + { + "mapmode_culture", [](Map const& map, Province const& province) -> colour_t { HasIdentifierAndColour const* largest = get_largest_item(province.get_culture_distribution()).first; return largest != nullptr ? HIGH_ALPHA_VALUE | largest->get_colour() : default_colour(province); - } }, - { "mapmode_religion", + } + }, + { + "mapmode_religion", [](Map const& map, Province const& province) -> colour_t { HasIdentifierAndColour const* largest = get_largest_item(province.get_religion_distribution()).first; return largest != nullptr ? HIGH_ALPHA_VALUE | largest->get_colour() : default_colour(province); - } } + } + } }; - for (mapmode_t const& mapmode : mapmodes) + for (mapmode_t const& mapmode : mapmodes) { ret &= map.add_mapmode(mapmode.first, mapmode.second); + } map.lock_mapmodes(); return ret; diff --git a/src/openvic-simulation/Modifier.cpp b/src/openvic-simulation/Modifier.cpp index f5f7337..32f68f7 100644 --- a/src/openvic-simulation/Modifier.cpp +++ b/src/openvic-simulation/Modifier.cpp @@ -35,10 +35,14 @@ size_t ModifierValue::get_effect_count() const { fixed_point_t ModifierValue::get_effect(ModifierEffect const* effect, bool* successful) { const effect_map_t::const_iterator it = values.find(effect); if (it != values.end()) { - if (successful != nullptr) *successful = true; + if (successful != nullptr) { + *successful = true; + } return it->second; } - if (successful != nullptr) *successful = false; + if (successful != nullptr) { + *successful = false; + } return fixed_point_t::_0(); } @@ -167,7 +171,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= add_modifier_effect("mobilisation_impact", false); ret &= add_modifier_effect("mobilisation_size", true); ret &= add_modifier_effect("naval_organisation", true); - ret &= add_modifier_effect("naval_unit_start_experience", true); // weird, naval_unit_start_experience = 15 would give a 15% boost + // weird, naval_unit_start_experience = 15 would give a 15% boost + ret &= add_modifier_effect("naval_unit_start_experience", true); ret &= add_modifier_effect("non_accepted_pop_consciousness_modifier", false, RAW_DECIMAL); ret &= add_modifier_effect("non_accepted_pop_militancy_modifier", false, RAW_DECIMAL); ret &= add_modifier_effect("org_regain", true); @@ -191,7 +196,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= add_modifier_effect("ruling_party_support", true); ret &= add_modifier_effect("social_reform_desire", false); ret &= add_modifier_effect("supply_consumption", false); - ret &= add_modifier_effect("unit_start_experience", true); // weird, naval_unit_start_experience = 15 would give a 15% boost + // weird, naval_unit_start_experience = 15 would give a 15% boost + ret &= add_modifier_effect("unit_start_experience", true); ret &= add_modifier_effect("war_exhaustion", false); // TODO: make technology group modifiers dynamic ret &= add_modifier_effect("army_tech_research_bonus", true); @@ -280,7 +286,8 @@ key_value_callback_t ModifierManager::_modifier_effect_callback( }; } -node_callback_t ModifierManager::expect_validated_modifier_value_and_default(callback_t modifier_callback, key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const { +node_callback_t ModifierManager::expect_validated_modifier_value_and_default(callback_t modifier_callback, + key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const { return [this, modifier_callback, default_callback, effect_validator](ast::NodeCPtr root) -> bool { ModifierValue modifier; bool ret = expect_dictionary(_modifier_effect_callback(modifier, default_callback, effect_validator))(root); @@ -288,29 +295,36 @@ node_callback_t ModifierManager::expect_validated_modifier_value_and_default(cal return ret; }; } -node_callback_t ModifierManager::expect_validated_modifier_value(callback_t modifier_callback, ModifierEffectValidator auto effect_validator) const { +node_callback_t ModifierManager::expect_validated_modifier_value(callback_t modifier_callback, + ModifierEffectValidator auto effect_validator) const { return expect_validated_modifier_value_and_default(modifier_callback, key_value_invalid_callback, effect_validator); } -node_callback_t ModifierManager::expect_modifier_value_and_default(callback_t modifier_callback, key_value_callback_t default_callback) const { - return expect_validated_modifier_value_and_default(modifier_callback, default_callback, [](ModifierEffect const&) -> bool { return true; }); +node_callback_t ModifierManager::expect_modifier_value_and_default(callback_t modifier_callback, + key_value_callback_t default_callback) const { + return expect_validated_modifier_value_and_default(modifier_callback, default_callback, + [](ModifierEffect const&) -> bool { return true; }); } node_callback_t ModifierManager::expect_modifier_value(callback_t modifier_callback) const { return expect_modifier_value_and_default(modifier_callback, key_value_invalid_callback); } -node_callback_t ModifierManager::expect_whitelisted_modifier_value_and_default(callback_t modifier_callback, string_set_t const& whitelist, key_value_callback_t default_callback) const { - return expect_validated_modifier_value_and_default(modifier_callback, default_callback, [&whitelist](ModifierEffect const& effect) -> bool { +node_callback_t ModifierManager::expect_whitelisted_modifier_value_and_default(callback_t modifier_callback, + string_set_t const& whitelist, key_value_callback_t default_callback) const { + return expect_validated_modifier_value_and_default(modifier_callback, + default_callback, [&whitelist](ModifierEffect const& effect) -> bool { return whitelist.contains(effect.get_identifier()); }); } -node_callback_t ModifierManager::expect_whitelisted_modifier_value(callback_t modifier_callback, string_set_t const& whitelist) const { +node_callback_t ModifierManager::expect_whitelisted_modifier_value(callback_t modifier_callback, + string_set_t const& whitelist) const { return expect_whitelisted_modifier_value_and_default(modifier_callback, whitelist, key_value_invalid_callback); } -node_callback_t ModifierManager::expect_modifier_value_and_key_map_and_default(callback_t modifier_callback, key_value_callback_t default_callback, key_map_t&& key_map) const { +node_callback_t ModifierManager::expect_modifier_value_and_key_map_and_default(callback_t modifier_callback, + key_value_callback_t default_callback, key_map_t&& key_map) const { return [this, modifier_callback, key_map = std::move(key_map)](ast::NodeCPtr node) mutable -> bool { bool ret = expect_modifier_value_and_default( modifier_callback, dictionary_keys_callback(key_map, key_value_invalid_callback) @@ -320,7 +334,8 @@ node_callback_t ModifierManager::expect_modifier_value_and_key_map_and_default(c }; } -node_callback_t ModifierManager::expect_modifier_value_and_key_map(callback_t modifier_callback, key_map_t&& key_map) const { +node_callback_t ModifierManager::expect_modifier_value_and_key_map(callback_t modifier_callback, + key_map_t&& key_map) const { return expect_modifier_value_and_key_map_and_default(modifier_callback, key_value_invalid_callback, std::move(key_map)); } diff --git a/src/openvic-simulation/Modifier.hpp b/src/openvic-simulation/Modifier.hpp index f936e5d..3a8b06d 100644 --- a/src/openvic-simulation/Modifier.hpp +++ b/src/openvic-simulation/Modifier.hpp @@ -105,12 +105,14 @@ namespace OpenVic { IdentifierRegistry modifiers; /* effect_validator takes in ModifierEffect const& */ - NodeTools::key_value_callback_t _modifier_effect_callback(ModifierValue& modifier, NodeTools::key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const; + NodeTools::key_value_callback_t _modifier_effect_callback(ModifierValue& modifier, + NodeTools::key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const; public: ModifierManager(); - bool add_modifier_effect(std::string_view identifier, bool province_good, ModifierEffect::format_t format = ModifierEffect::format_t::PERCENTAGE_DECIMAL); + bool add_modifier_effect(std::string_view identifier, bool province_good, + ModifierEffect::format_t format = ModifierEffect::format_t::PERCENTAGE_DECIMAL); IDENTIFIER_REGISTRY_ACCESSORS(modifier_effect) bool add_modifier(std::string_view identifier, ModifierValue&& values, Modifier::icon_t icon); @@ -118,30 +120,57 @@ namespace OpenVic { bool setup_modifier_effects(); - NodeTools::node_callback_t expect_validated_modifier_value_and_default(NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const; - NodeTools::node_callback_t expect_validated_modifier_value(NodeTools::callback_t modifier_callback, ModifierEffectValidator auto effect_validator) const; - - NodeTools::node_callback_t expect_modifier_value_and_default(NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback) const; - NodeTools::node_callback_t expect_modifier_value(NodeTools::callback_t modifier_callback) const; - - NodeTools::node_callback_t expect_whitelisted_modifier_value_and_default(NodeTools::callback_t modifier_callback, string_set_t const& whitelist, NodeTools::key_value_callback_t default_callback) const; - NodeTools::node_callback_t expect_whitelisted_modifier_value(NodeTools::callback_t modifier_callback, string_set_t const& whitelist) const; - - NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default(NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, NodeTools::key_map_t&& key_map) const; - NodeTools::node_callback_t expect_modifier_value_and_key_map(NodeTools::callback_t modifier_callback, NodeTools::key_map_t&& key_map) const; + NodeTools::node_callback_t expect_validated_modifier_value_and_default( + NodeTools::callback_t modifier_callback, + NodeTools::key_value_callback_t default_callback, + ModifierEffectValidator auto effect_validator) const; + NodeTools::node_callback_t expect_validated_modifier_value( + NodeTools::callback_t modifier_callback, + ModifierEffectValidator auto effect_validator) const; + + NodeTools::node_callback_t expect_modifier_value_and_default( + NodeTools::callback_t modifier_callback, + NodeTools::key_value_callback_t default_callback) const; + NodeTools::node_callback_t expect_modifier_value( + NodeTools::callback_t modifier_callback) const; + + NodeTools::node_callback_t expect_whitelisted_modifier_value_and_default( + NodeTools::callback_t modifier_callback, + string_set_t const& whitelist, + NodeTools::key_value_callback_t default_callback) const; + NodeTools::node_callback_t expect_whitelisted_modifier_value( + NodeTools::callback_t modifier_callback, + string_set_t const& whitelist) const; + + NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default( + NodeTools::callback_t modifier_callback, + NodeTools::key_value_callback_t default_callback, + NodeTools::key_map_t&& key_map) const; + NodeTools::node_callback_t expect_modifier_value_and_key_map( + NodeTools::callback_t modifier_callback, + NodeTools::key_map_t&& key_map) const; template - NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default(NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, NodeTools::key_map_t&& key_map, Args... args) const { + NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default( + NodeTools::callback_t modifier_callback, + NodeTools::key_value_callback_t default_callback, + NodeTools::key_map_t&& key_map, + Args... args) const { NodeTools::add_key_map_entries(key_map, args...); return expect_modifier_value_and_key_map_and_default(modifier_callback, default_callback, std::move(key_map)); } template - NodeTools::node_callback_t expect_modifier_value_and_keys_and_default(NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, Args... args) const { + NodeTools::node_callback_t expect_modifier_value_and_keys_and_default( + NodeTools::callback_t modifier_callback, + NodeTools::key_value_callback_t default_callback, + Args... args) const { return expect_modifier_value_and_key_map_and_default(modifier_callback, default_callback, {}, args...); } template - NodeTools::node_callback_t expect_modifier_value_and_keys(NodeTools::callback_t modifier_callback, Args... args) const { + NodeTools::node_callback_t expect_modifier_value_and_keys( + NodeTools::callback_t modifier_callback, + Args... args) const { return expect_modifier_value_and_key_map_and_default(modifier_callback, NodeTools::key_value_invalid_callback, {}, args...); } }; diff --git a/src/openvic-simulation/country/Country.cpp b/src/openvic-simulation/country/Country.cpp index ed8c3cb..d666411 100644 --- a/src/openvic-simulation/country/Country.cpp +++ b/src/openvic-simulation/country/Country.cpp @@ -122,10 +122,12 @@ bool CountryManager::add_country( return false; } - return countries.add_item({ identifier, color, graphical_culture, std::move(parties), std::move(unit_names), dynamic_tag, std::move(alternative_colours) }); + return countries.add_item({ identifier, color, graphical_culture, std::move(parties), + std::move(unit_names), dynamic_tag, std::move(alternative_colours) }); } -bool CountryManager::load_country_data_file(GameManager& game_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root) { +bool CountryManager::load_country_data_file(GameManager& game_manager, + std::string_view name, bool is_dynamic, ast::NodeCPtr root) { colour_t color; const GraphicalCultureType* graphical_culture; std::vector country_parties; @@ -135,7 +137,8 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, std::stri bool ret = expect_dictionary_keys_and_default( [&game_manager, &alternative_colours, &name](std::string_view key, ast::NodeCPtr value) -> bool { const GovernmentType* colour_gov_type; - bool ret = game_manager.get_politics_manager().get_government_type_manager().expect_government_type_str(assign_variable_callback_pointer(colour_gov_type))(key); + bool ret = game_manager.get_politics_manager().get_government_type_manager() + .expect_government_type_str(assign_variable_callback_pointer(colour_gov_type))(key); if (!ret) return false; @@ -147,14 +150,18 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, std::stri return alternative_colours.emplace(std::move(colour_gov_type), std::move(alternative_colour)).second; }, "color", ONE_EXACTLY, expect_colour(assign_variable_callback(color)), - "graphical_culture", ONE_EXACTLY, expect_identifier_or_string([&game_manager, &graphical_culture, &name](std::string_view value) -> bool { - graphical_culture = game_manager.get_pop_manager().get_culture_manager().get_graphical_culture_type_by_identifier(value); - if (graphical_culture == nullptr) { - Logger::error("When loading country ", name, ", specified graphical culture ", value, " is invalid!\nCheck that CultureManager has loaded before CountryManager."); - } + "graphical_culture", ONE_EXACTLY, expect_identifier_or_string( + [&game_manager, &graphical_culture, &name](std::string_view value) -> bool { + graphical_culture = game_manager.get_pop_manager().get_culture_manager() + .get_graphical_culture_type_by_identifier(value); + if (graphical_culture == nullptr) { + Logger::error("When loading country ", name, ", specified graphical culture ", value, + " is invalid!\nCheck that CultureManager has loaded before CountryManager."); + } - return graphical_culture != nullptr; - }), + return graphical_culture != nullptr; + } + ), "party", ZERO_OR_MORE, [&game_manager, &country_parties, &name](ast::NodeCPtr value) -> bool { std::string_view party_name; Date start_date, end_date; @@ -180,7 +187,8 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, std::stri "name", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(party_name)), "start_date", ONE_EXACTLY, expect_date(assign_variable_callback(start_date)), "end_date", ONE_EXACTLY, expect_date(assign_variable_callback(end_date)), - "ideology", ONE_EXACTLY, expect_identifier_or_string(game_manager.get_politics_manager().get_ideology_manager().expect_ideology_str(assign_variable_callback_pointer(ideology))) + "ideology", ONE_EXACTLY, expect_identifier_or_string(game_manager.get_politics_manager() + .get_ideology_manager().expect_ideology_str(assign_variable_callback_pointer(ideology))) )(value); country_parties.push_back({ party_name, start_date, end_date, *ideology, std::move(policies) }); @@ -203,6 +211,7 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, std::stri }) )(root); - ret &= add_country(name, color, *graphical_culture, std::move(country_parties), std::move(unit_names), is_dynamic, std::move(alternative_colours)); + ret &= add_country(name, color, *graphical_culture, std::move(country_parties), + std::move(unit_names), is_dynamic, std::move(alternative_colours)); return ret; } diff --git a/src/openvic-simulation/dataloader/Dataloader.cpp b/src/openvic-simulation/dataloader/Dataloader.cpp index ad35056..7a904ed 100644 --- a/src/openvic-simulation/dataloader/Dataloader.cpp +++ b/src/openvic-simulation/dataloader/Dataloader.cpp @@ -51,16 +51,18 @@ concept is_filename = std::same_as || std::convertible static bool filename_equals(const is_filename auto& lhs, const is_filename auto& rhs) { auto left = [&lhs] { - if constexpr (std::same_as, std::filesystem::path>) + if constexpr (std::same_as, std::filesystem::path>) { return lhs.filename().string(); - else + } else { return lhs; + } }(); auto right = [&rhs] { - if constexpr (std::same_as, std::filesystem::path>) + if constexpr (std::same_as, std::filesystem::path>) { return rhs.filename().string(); - else + } else { return rhs; + } }(); return path_equals(left, right); } @@ -79,17 +81,20 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { // Don't waste time trying to search for Victoria 2 when supplied a valid looking Victoria 2 game directory if (filename_equals(Victoria_2_folder, hint_path)) { - if (fs::is_regular_file(hint_path / v2_game_exe, error_code)) + if (fs::is_regular_file(hint_path / v2_game_exe, error_code)) { return hint_path; + } } const bool hint_path_was_empty = hint_path.empty(); if (hint_path_was_empty) { #if defined(_WIN32) - static const fs::path registry_path = Windows::ReadRegValue(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); + static const fs::path registry_path = Windows::ReadRegValue(HKEY_LOCAL_MACHINE, + "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); - if (!registry_path.empty()) + if (!registry_path.empty()) { return registry_path; + } #pragma warning(push) #pragma warning(disable : 4996) @@ -104,14 +109,14 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { } } #pragma warning(pop) -// Cannot support Android -// Only FreeBSD currently unofficially supports emulating Linux + // Cannot support Android + // Only FreeBSD currently unofficially supports emulating Linux #elif (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__) static const fs::path home = std::getenv("HOME"); hint_path = home / ".steam" / "steam"; - if (fs::is_symlink(hint_path, error_code)) + if (fs::is_symlink(hint_path, error_code)) { hint_path = fs::read_symlink(hint_path, error_code); - else if (!fs::is_directory(hint_path, error_code)) { + } else if (!fs::is_directory(hint_path, error_code)) { hint_path = home / ".local" / "share" / "Steam"; if (!fs::is_directory(hint_path, error_code)) { #ifdef __FreeBSD__ @@ -122,7 +127,7 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { return ""; } } -// Support only Mac, cannot support iOS + // Support only Mac, cannot support iOS #elif (defined(__APPLE__) && defined(__MACH__)) && TARGET_OS_MAC == 1 static const fs::path home = std::getenv("HOME"); hint_path = home / "Library" / "Application Support" / "Steam"; @@ -130,18 +135,21 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { Logger::warning("Could not find path for Steam installation on Mac."); return ""; } -// All platforms that reach this point do not seem to even have unofficial Steam support + // All platforms that reach this point do not seem to even have unofficial Steam support #else Logger::warning("Could not find path for Steam installation on unsupported platform."); #endif } // Could not determine Steam install on platform - if (hint_path.empty()) return ""; + if (hint_path.empty()) { + return ""; + } // Supplied path was useless, ignore hint_path - if (!hint_path_was_empty && !fs::exists(hint_path, error_code)) + if (!hint_path_was_empty && !fs::exists(hint_path, error_code)) { return _search_for_game_path(); + } // Steam Library's directory that will contain Victoria 2 fs::path vic2_steam_lib_directory; @@ -184,8 +192,9 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { parser.load_from_file(current_path); if (!parser.parse()) { // Could not find or load libraryfolders.vdf, report error as warning - if (!buffer.empty()) + if (!buffer.empty()) { Logger::warning _(buffer); + } return ""; } std::optional current_node = *(parser.get_key_values()); @@ -305,8 +314,9 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { } // Hail Mary check ignoring the hint_path - if (!hint_path_was_empty) + if (!hint_path_was_empty) { return _search_for_game_path(); + } Logger::warning("Could not find Victoria 2 game path, this requires manually supplying one."); return ""; // The supplied path fits literally none of the criteria @@ -314,8 +324,9 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { fs::path Dataloader::search_for_game_path(fs::path hint_path) { auto it = _cached_paths.find(hint_path); - if (it != _cached_paths.end()) + if (it != _cached_paths.end()) { return it->second; + } return _cached_paths[hint_path] = _search_for_game_path(hint_path); } @@ -360,7 +371,9 @@ fs::path Dataloader::lookup_file(fs::path const& path) const { static bool contains_file_with_name(Dataloader::path_vector_t const& paths, fs::path const& name) { for (fs::path const& path : paths) { - if (path.filename() == name) return true; + if (path.filename() == name) { + return true; + } } return false; } @@ -384,7 +397,8 @@ Dataloader::path_vector_t Dataloader::lookup_files_in_dir(fs::path const& path, return ret; } -bool Dataloader::apply_to_files_in_dir(fs::path const& path, fs::path const& extension, callback_t callback) const { +bool Dataloader::apply_to_files_in_dir(fs::path const& path, fs::path const& extension, + callback_t callback) const { bool ret = true; for (fs::path const& file : lookup_files_in_dir(path, extension)) { if (!callback(file)) { @@ -458,18 +472,27 @@ csv::Windows1252Parser Dataloader::parse_csv(fs::path const& path) { return _run_ovdl_parser(path); } -bool Dataloader::_load_pop_types(PopManager& pop_manager, UnitManager const& unit_manager, GoodManager const& good_manager, fs::path const& pop_type_directory) const { - const bool ret = apply_to_files_in_dir(pop_type_directory, ".txt", [&pop_manager, &unit_manager, &good_manager](fs::path const& file) -> bool { - return pop_manager.load_pop_type_file(file.stem().string(), unit_manager, good_manager, parse_defines(file).get_file_node()); - }); +bool Dataloader::_load_pop_types( + PopManager& pop_manager, UnitManager const& unit_manager, GoodManager const& good_manager +) const { + static const fs::path pop_type_directory = "poptypes"; + const bool ret = apply_to_files_in_dir(pop_type_directory, ".txt", + [&pop_manager, &unit_manager, &good_manager](fs::path const& file) -> bool { + return pop_manager.load_pop_type_file(file.stem().string(), unit_manager, + good_manager, parse_defines(file).get_file_node()); + } + ); pop_manager.lock_pop_types(); return ret; } -bool Dataloader::_load_units(UnitManager& unit_manager, GoodManager const& good_manager, fs::path const& units_directory) const { - const bool ret = apply_to_files_in_dir(units_directory, ".txt", [&unit_manager, &good_manager](fs::path const& file) -> bool { - return unit_manager.load_unit_file(good_manager, parse_defines(file).get_file_node()); - }); +bool Dataloader::_load_units(UnitManager& unit_manager, GoodManager const& good_manager) const { + static const fs::path units_directory = "units"; + const bool ret = apply_to_files_in_dir(units_directory, ".txt", + [&unit_manager, &good_manager](fs::path const& file) -> bool { + return unit_manager.load_unit_file(good_manager, parse_defines(file).get_file_node()); + } + ); unit_manager.lock_units(); return ret; } @@ -478,11 +501,13 @@ bool Dataloader::_load_oobs(GameManager& game_manager) const { static const fs::path oob_directory = "history/units"; /* used for countries with no defined initial OOB */ - game_manager.get_military_manager().get_deployment_manager().add_deployment("NULL", std::vector(), std::vector(), std::vector()); + game_manager.get_military_manager().get_deployment_manager().add_deployment( + "NULL", std::vector(), std::vector(), std::vector()); bool ret = apply_to_files_in_dir(oob_directory, ".txt", [&game_manager](fs::path const& file) -> bool { if (file.filename() == "v2dd2.txt") return true; /* dev diary just stuck in there for no reason whatsoever */ - return game_manager.get_military_manager().get_deployment_manager().load_oob_file(game_manager, file.filename().string(), parse_defines(file).get_file_node()); + return game_manager.get_military_manager().get_deployment_manager().load_oob_file(game_manager, + file.filename().string(), parse_defines(file).get_file_node()); }); /* we also load OOBs in top level subdirectories, for other start dates etc */ @@ -492,7 +517,9 @@ bool Dataloader::_load_oobs(GameManager& game_manager) const { for (fs::directory_entry const& entry : fs::directory_iterator { path, ec }) { if (entry.is_directory()) { ret &= apply_to_files_in_dir(entry, ".txt", [&entry, &game_manager](fs::path const& file) -> bool { - return game_manager.get_military_manager().get_deployment_manager().load_oob_file(game_manager, (entry.path().filename() / file.filename()).string(), parse_defines(file).get_file_node()); + return game_manager.get_military_manager().get_deployment_manager().load_oob_file( + game_manager, (entry.path().filename() / file.filename()).string(), + parse_defines(file).get_file_node()); }); } } @@ -519,7 +546,8 @@ bool Dataloader::_load_countries(GameManager& game_manager) const { return false; } - return game_manager.get_country_manager().load_country_data_file(game_manager, key, is_dynamic, parse_defines(lookup_file(countries_file.parent_path() / data_path)).get_file_node()); + return game_manager.get_country_manager().load_country_data_file(game_manager, key, is_dynamic, + parse_defines(lookup_file(countries_file.parent_path() / data_path)).get_file_node()); } )(parse_defines(lookup_file(countries_file)).get_file_node()); game_manager.get_country_manager().lock_countries(); @@ -530,18 +558,21 @@ bool Dataloader::_load_countries(GameManager& game_manager) const { bool Dataloader::_load_history(GameManager& game_manager) const { static const fs::path country_history_directory = "history/countries"; static const fs::path province_history_directory = "history/provinces"; - + /* Country History */ - bool ret = apply_to_files_in_dir(country_history_directory, ".txt", [this, &game_manager](fs::path const& file) -> bool { - std::string tag = file.filename().string().substr(0, 3); + bool ret = apply_to_files_in_dir(country_history_directory, ".txt", + [this, &game_manager](fs::path const& file) -> bool { + std::string tag = file.filename().string().substr(0, 3); - if (!game_manager.get_country_manager().has_country_identifier(tag)) { - Logger::error("Error loading history for country ", tag, ": tag not defined!"); - return false; + if (!game_manager.get_country_manager().has_country_identifier(tag)) { + Logger::error("Error loading history for country ", tag, ": tag not defined!"); + return false; + } + + return game_manager.get_history_manager().get_country_manager().load_country_history_file( + game_manager, tag, parse_defines(lookup_file(file)).get_file_node()); } - - return game_manager.get_history_manager().get_country_manager().load_country_history_file(game_manager, tag, parse_defines(lookup_file(file)).get_file_node()); - }); + ); game_manager.get_history_manager().get_country_manager().lock_country_histories(); /* Province History */ @@ -559,7 +590,8 @@ bool Dataloader::_load_history(GameManager& game_manager) const { return false; } - return game_manager.get_history_manager().get_province_manager().load_province_history_file(game_manager, province_id, parse_defines(lookup_file(file)).get_file_node()); + return game_manager.get_history_manager().get_province_manager().load_province_history_file( + game_manager, province_id, parse_defines(lookup_file(file)).get_file_node()); }); } } @@ -569,7 +601,8 @@ bool Dataloader::_load_history(GameManager& game_manager) const { return ret; } -bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_directory) const { +bool Dataloader::_load_map_dir(GameManager& game_manager) const { + static const fs::path map_directory = "map"; Map& map = game_manager.get_map(); static const fs::path defaults_filename = "default.map"; @@ -610,19 +643,19 @@ bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_di bool ret = expect_dictionary_keys( "max_provinces", ONE_EXACTLY, - expect_uint( - std::bind(&Map::set_max_provinces, &map, std::placeholders::_1) - ), + expect_uint( + std::bind(&Map::set_max_provinces, &map, std::placeholders::_1) + ), "sea_starts", ONE_EXACTLY, - expect_list_reserve_length( - water_province_identifiers, - expect_identifier( - [&water_province_identifiers](std::string_view identifier) -> bool { - water_province_identifiers.push_back(identifier); - return true; - } - ) - ), + expect_list_reserve_length( + water_province_identifiers, + expect_identifier( + [&water_province_identifiers](std::string_view identifier) -> bool { + water_province_identifiers.push_back(identifier); + return true; + } + ) + ), #define MAP_PATH_DICT_ENTRY(X) \ #X, ONE_EXACTLY, expect_string(assign_variable_callback(X)), @@ -631,8 +664,7 @@ bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_di #undef APPLY_TO_MAP_PATHS - "border_heights", - ZERO_OR_ONE, success_callback, + "border_heights", ZERO_OR_ONE, success_callback, "terrain_sheet_heights", ZERO_OR_ONE, success_callback, "tree", ZERO_OR_ONE, success_callback, "border_cutoff", ZERO_OR_ONE, success_callback @@ -643,22 +675,22 @@ bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_di } if (!map.load_province_definitions( - parse_csv(lookup_file(map_directory / definitions)).get_lines() - )) { + parse_csv(lookup_file(map_directory / definitions)).get_lines() + )) { Logger::error("Failed to load province definitions file!"); ret = false; } if (!map.load_province_positions( - game_manager.get_economy_manager().get_building_manager(), parse_defines(lookup_file(map_directory / positions)).get_file_node() - )) { + game_manager.get_economy_manager().get_building_manager(), parse_defines(lookup_file(map_directory / positions)).get_file_node() + )) { Logger::error("Failed to load province positions file!"); ret = false; } if (!map.load_region_file( - parse_defines(lookup_file(map_directory / region)).get_file_node() - )) { + parse_defines(lookup_file(map_directory / region)).get_file_node() + )) { Logger::error("Failed to load region file!"); ret = false; } @@ -669,24 +701,24 @@ bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_di } if (!map.get_terrain_type_manager().load_terrain_types( - game_manager.get_modifier_manager(), - parse_defines(lookup_file(map_directory / terrain_definition)).get_file_node() - )) { + game_manager.get_modifier_manager(), + parse_defines(lookup_file(map_directory / terrain_definition)).get_file_node() + )) { Logger::error("Failed to load terrain types!"); ret = false; } if (!map.load_map_images( - lookup_file(map_directory / provinces), - lookup_file(map_directory / terrain), false - )) { + lookup_file(map_directory / provinces), + lookup_file(map_directory / terrain), false + )) { Logger::error("Failed to load map images!"); ret = false; } if (!map.generate_and_load_province_adjacencies( - parse_csv(lookup_file(map_directory / adjacencies)).get_lines() - )) { + parse_csv(lookup_file(map_directory / adjacencies)).get_lines() + )) { Logger::error("Failed to generate and load province adjacencies!"); ret = false; } @@ -695,10 +727,6 @@ bool Dataloader::_load_map_dir(GameManager& game_manager, fs::path const& map_di } bool Dataloader::load_defines(GameManager& game_manager) const { - static const fs::path map_directory = "map"; - static const fs::path pop_type_directory = "poptypes"; - static const fs::path units_directory = "units"; - static const fs::path defines_file = "common/defines.lua"; static const fs::path buildings_file = "common/buildings.txt"; static const fs::path bookmark_file = "common/bookmarks.txt"; @@ -724,82 +752,84 @@ bool Dataloader::load_defines(GameManager& game_manager) const { ret = false; } if (!game_manager.get_economy_manager().get_good_manager().load_goods_file( - parse_defines(lookup_file(goods_file)).get_file_node() - )) { + parse_defines(lookup_file(goods_file)).get_file_node() + )) { Logger::error("Failed to load goods!"); ret = false; } - if (!_load_units(game_manager.get_military_manager().get_unit_manager(), game_manager.get_economy_manager().get_good_manager(), units_directory)) { + if (!_load_units(game_manager.get_military_manager().get_unit_manager(), + game_manager.get_economy_manager().get_good_manager() + )) { Logger::error("Failed to load units!"); ret = false; } - if (!_load_pop_types(game_manager.get_pop_manager(), game_manager.get_military_manager().get_unit_manager(), game_manager.get_economy_manager().get_good_manager(), pop_type_directory)) { + if (!_load_pop_types(game_manager.get_pop_manager(), game_manager.get_military_manager().get_unit_manager(), + game_manager.get_economy_manager().get_good_manager() + )) { Logger::error("Failed to load pop types!"); ret = false; } if (!game_manager.get_pop_manager().get_culture_manager().load_graphical_culture_type_file( - parse_defines(lookup_file(graphical_culture_type_file)).get_file_node() - )) { + parse_defines(lookup_file(graphical_culture_type_file)).get_file_node() + )) { Logger::error("Failed to load graphical culture types!"); ret = false; } if (!game_manager.get_pop_manager().get_culture_manager().load_culture_file( - parse_defines(lookup_file(culture_file)).get_file_node() - )) { + parse_defines(lookup_file(culture_file)).get_file_node() + )) { Logger::error("Failed to load cultures!"); ret = false; } if (!game_manager.get_pop_manager().get_religion_manager().load_religion_file( - parse_defines(lookup_file(religion_file)).get_file_node() - )) { + parse_defines(lookup_file(religion_file)).get_file_node() + )) { Logger::error("Failed to load religions!"); ret = false; } if (!game_manager.get_politics_manager().get_ideology_manager().load_ideology_file( - parse_defines(lookup_file(ideology_file)).get_file_node() - )) { + parse_defines(lookup_file(ideology_file)).get_file_node() + )) { Logger::error("Failed to load ideologies!"); ret = false; } if (!game_manager.get_politics_manager().load_government_types_file( - parse_defines(lookup_file(governments_file)).get_file_node() - )) { + parse_defines(lookup_file(governments_file)).get_file_node() + )) { Logger::error("Failed to load government types!"); ret = false; } if (!game_manager.get_politics_manager().get_issue_manager().load_issues_file( - parse_defines(lookup_file(issues_file)).get_file_node() - )) { + parse_defines(lookup_file(issues_file)).get_file_node() + )) { Logger::error("Failed to load issues!"); ret = false; } if (!game_manager.get_politics_manager().get_national_value_manager().load_national_values_file( - game_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() - )) { + game_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() + )) { Logger::error("Failed to load national values!"); ret = false; } - if (!game_manager.get_economy_manager().load_production_types_file( - game_manager.get_pop_manager(), - parse_defines(lookup_file(production_types_file)).get_file_node() - )) { + if (!game_manager.get_economy_manager().load_production_types_file(game_manager.get_pop_manager(), + parse_defines(lookup_file(production_types_file)).get_file_node() + )) { Logger::error("Failed to load production types!"); ret = false; } - if (!game_manager.get_economy_manager().load_buildings_file( - game_manager.get_modifier_manager(), - parse_defines(lookup_file(buildings_file)).get_file_node() - )) { + if (!game_manager.get_economy_manager().load_buildings_file(game_manager.get_modifier_manager(), + parse_defines(lookup_file(buildings_file)).get_file_node() + )) { Logger::error("Failed to load buildings!"); ret = false; } - if (!_load_map_dir(game_manager, map_directory)) { + if (!_load_map_dir(game_manager)) { Logger::error("Failed to load map!"); ret = false; } if (!game_manager.get_military_manager().get_leader_trait_manager().load_leader_traits_file( - game_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() - )) { + game_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() + )) { Logger::error("Failed to load leader traits!"); ret = false; } diff --git a/src/openvic-simulation/dataloader/Dataloader.hpp b/src/openvic-simulation/dataloader/Dataloader.hpp index 4a8b111..1a8e9ab 100644 --- a/src/openvic-simulation/dataloader/Dataloader.hpp +++ b/src/openvic-simulation/dataloader/Dataloader.hpp @@ -23,9 +23,11 @@ namespace OpenVic { private: path_vector_t roots; - bool _load_pop_types(PopManager& pop_manager, UnitManager const& unit_manager, GoodManager const& good_manager, fs::path const& pop_type_directory) const; - bool _load_units(UnitManager& unit_manager, GoodManager const& good_manager, fs::path const& units_directory) const; - bool _load_map_dir(GameManager& game_manager, fs::path const& map_directory) const; + bool _load_pop_types( + PopManager& pop_manager, UnitManager const& unit_manager, GoodManager const& good_manager + ) const; + bool _load_units(UnitManager& unit_manager, GoodManager const& good_manager) const; + bool _load_map_dir(GameManager& game_manager) const; bool _load_oobs(GameManager& game_manager) const; bool _load_countries(GameManager& game_manager) const; bool _load_history(GameManager& game_manager) const; @@ -43,15 +45,18 @@ namespace OpenVic { /// Supports being supplied: /// 1. A valid Victoria 2 game directory (Victoria 2 directory that contains a v2game.exe file) /// 2. An Empty path: assumes a common Steam install structure per platform. - /// 2b. If Windows, returns "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Paradox Interactive\Victoria 2" "path" registry value + /// 2b. If Windows, returns "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Paradox Interactive\Victoria 2" + /// "path" registry value /// 2c. If registry value returns an empty string, performs Steam checks below /// 3. A path to a root Steam install. (eg: C:\Program Files(x86)\Steam, ~/.steam/steam) - /// 4. A path to a root Steam steamapps directory. (eg: C:\Program Files(x86)\Steam\steamapps, ~/.steam/steam/steamapps) + /// 4. A path to a root Steam steamapps directory. (eg: C:\Program Files(x86)\Steam\steamapps, + /// ~/.steam/steam/steamapps) /// 5. A path to the root Steam libraryfolders.vdf, commonly in the root Steam steamapps directory. /// 6. A path to the Steam library directory that contains Victoria 2. /// 7. A path to a Steam library's steamapps directory that contains Victoria 2. /// 8. A path to a Steam library's steamapps/common directory that contains Victoria 2. - /// 9. If any of these checks don't resolve to a valid Victoria 2 game directory when supplied a non-empty hint_path, performs empty path behavior. + /// 9. If any of these checks don't resolve to a valid Victoria 2 game directory when supplied + /// a non-empty hint_path, performs empty path behavior. /// @return fs::path The root directory of a valid Victoria 2 install, or an empty path. /// static fs::path search_for_game_path(fs::path hint_path = {}); @@ -64,7 +69,9 @@ namespace OpenVic { */ fs::path lookup_file(fs::path const& path) const; path_vector_t lookup_files_in_dir(fs::path const& path, fs::path const& extension) const; - bool apply_to_files_in_dir(fs::path const& path, fs::path const& extension, NodeTools::callback_t callback) const; + bool apply_to_files_in_dir( + fs::path const& path, fs::path const& extension, NodeTools::callback_t callback + ) const; bool load_defines(GameManager& game_manager) const; bool load_pop_history(GameManager& game_manager, fs::path const& path) const; @@ -91,7 +98,9 @@ namespace OpenVic { /* Args: key, locale, localisation */ using localisation_callback_t = NodeTools::callback_t; - bool load_localisation_files(localisation_callback_t callback, fs::path const& localisation_dir = "localisation") const; + bool load_localisation_files( + localisation_callback_t callback, fs::path const& localisation_dir = "localisation" + ) const; private: struct fshash { diff --git a/src/openvic-simulation/dataloader/Dataloader_Windows.hpp b/src/openvic-simulation/dataloader/Dataloader_Windows.hpp index f4abbb6..6b6fce3 100644 --- a/src/openvic-simulation/dataloader/Dataloader_Windows.hpp +++ b/src/openvic-simulation/dataloader/Dataloader_Windows.hpp @@ -11,7 +11,9 @@ namespace OpenVic::Windows { inline std::wstring convert(std::string_view as) { // deal with trivial case of empty string - if (as.empty()) return std::wstring(); + if (as.empty()) { + return std::wstring(); + } // determine required length of new string size_t length = ::MultiByteToWideChar(CP_UTF8, 0, as.data(), (int)as.length(), 0, 0); @@ -28,7 +30,9 @@ namespace OpenVic::Windows { inline std::string convert(std::wstring_view as) { // deal with trivial case of empty string - if (as.empty()) return std::string(); + if (as.empty()) { + return std::string(); + } // determine required length of new string size_t length = ::WideCharToMultiByte(CP_UTF8, 0, as.data(), (int)as.length(), 0, 0, NULL, NULL); @@ -51,7 +55,10 @@ namespace OpenVic::Windows { template concept has_data = requires(T t) { - { t.data() } -> std::convertible_to; + { + t.data() + } + -> std::convertible_to; }; class RegistryKey { @@ -61,7 +68,9 @@ namespace OpenVic::Windows { } template - RegistryKey(HKEY parent_key_handle, std::basic_string_view child_key_name, std::basic_string_view value_name) { + RegistryKey(HKEY parent_key_handle, + std::basic_string_view child_key_name, + std::basic_string_view value_name) { open_key(parent_key_handle, child_key_name); query_key(value_name); } @@ -80,29 +89,32 @@ namespace OpenVic::Windows { template LSTATUS open_key(HKEY parent_key_handle, std::basic_string_view key_path) { - if (is_open()) + if (is_open()) { close_key(); - if constexpr (std::is_same_v) + } + if constexpr (std::is_same_v) { return RegOpenKeyExW(parent_key_handle, convert(key_path).data(), REG_NONE, KEY_READ, &_key_handle); - else + } else { return RegOpenKeyExW(parent_key_handle, key_path.data(), REG_NONE, KEY_READ, &_key_handle); + } } bool is_predefined() const { return (_key_handle == HKEY_CURRENT_USER) || - (_key_handle == HKEY_LOCAL_MACHINE) || - (_key_handle == HKEY_CLASSES_ROOT) || - (_key_handle == HKEY_CURRENT_CONFIG) || - (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || - (_key_handle == HKEY_PERFORMANCE_DATA) || - (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || - (_key_handle == HKEY_PERFORMANCE_TEXT) || - (_key_handle == HKEY_USERS); + (_key_handle == HKEY_LOCAL_MACHINE) || + (_key_handle == HKEY_CLASSES_ROOT) || + (_key_handle == HKEY_CURRENT_CONFIG) || + (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || + (_key_handle == HKEY_PERFORMANCE_DATA) || + (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || + (_key_handle == HKEY_PERFORMANCE_TEXT) || + (_key_handle == HKEY_USERS); } LSTATUS close_key() { - if (!is_open() || is_predefined()) + if (!is_open() || is_predefined()) { return ERROR_SUCCESS; + } auto result = RegCloseKey(_key_handle); _key_handle = nullptr; return result; @@ -131,8 +143,9 @@ namespace OpenVic::Windows { close_key(); std::size_t first_null = _value.find_first_of(L'\0'); - if (first_null != std::string::npos) + if (first_null != std::string::npos) { _value.resize(first_null); + } return result; } diff --git a/src/openvic-simulation/dataloader/NodeTools.cpp b/src/openvic-simulation/dataloader/NodeTools.cpp index 92080c4..69aebc9 100644 --- a/src/openvic-simulation/dataloader/NodeTools.cpp +++ b/src/openvic-simulation/dataloader/NodeTools.cpp @@ -53,7 +53,8 @@ node_callback_t NodeTools::expect_identifier_or_string(callback_t(callback, allow_empty)(*cast_node); } - Logger::error("Invalid node type ", node->get_type(), " when expecting ", ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static()); + Logger::error("Invalid node type ", node->get_type(), " when expecting ", + ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static()); } else { Logger::error("Null node when expecting ", ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static()); } @@ -123,18 +124,22 @@ node_callback_t NodeTools::expect_colour(callback_t callback) { return [callback](ast::NodeCPtr node) -> bool { colour_t col = NULL_COLOUR; uint32_t components = 0; - bool ret = expect_list_of_length(3, expect_fixed_point([&col, &components](fixed_point_t val) -> bool { - components++; - col <<= 8; - if (val < 0 || val > 255) { - Logger::error("Invalid colour component: ", val); - return false; - } else { - if (val <= 1) val *= 255; - col |= val.to_int32_t(); - return true; - } - }))(node); + bool ret = expect_list_of_length(3, expect_fixed_point( + [&col, &components](fixed_point_t val) -> bool { + components++; + col <<= 8; + if (val < 0 || val > 255) { + Logger::error("Invalid colour component: ", val); + return false; + } else { + if (val <= 1) { + val *= 255; + } + col |= val.to_int32_t(); + return true; + } + } + ))(node); ret &= callback(col << 8 * (3 - components)); return ret; }; @@ -230,7 +235,9 @@ node_callback_t NodeTools::expect_list_of_length(size_t length, node_callback_t if (size != length) { Logger::error("List length ", size, " does not match expected length ", length); ret = false; - if (length < size) return length; + if (length < size) { + return length; + } } return size; }, @@ -289,7 +296,8 @@ node_callback_t NodeTools::expect_dictionary(key_value_callback_t callback) { return expect_dictionary_and_length(default_length_callback, callback); } -bool NodeTools::add_key_map_entry(key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, node_callback_t callback) { +bool NodeTools::add_key_map_entry(key_map_t& key_map, std::string_view key, + dictionary_entry_t::expected_count_t expected_count, node_callback_t callback) { if (key_map.find(key) == key_map.end()) { key_map.emplace(key, dictionary_entry_t { expected_count, callback }); return true; @@ -336,7 +344,8 @@ bool NodeTools::check_key_map_counts(key_map_t& key_map) { return ret; } -node_callback_t NodeTools::expect_dictionary_key_map_and_length_and_default(key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback) { +node_callback_t NodeTools::expect_dictionary_key_map_and_length_and_default(key_map_t key_map, + length_callback_t length_callback, key_value_callback_t default_callback) { return [length_callback, default_callback, key_map = std::move(key_map)](ast::NodeCPtr node) mutable -> bool { bool ret = expect_dictionary_and_length( length_callback, dictionary_keys_callback(key_map, default_callback) @@ -355,7 +364,8 @@ node_callback_t NodeTools::expect_dictionary_key_map_and_default(key_map_t key_m } node_callback_t NodeTools::expect_dictionary_key_map(key_map_t key_map) { - return expect_dictionary_key_map_and_length_and_default(std::move(key_map), default_length_callback, key_value_invalid_callback); + return expect_dictionary_key_map_and_length_and_default(std::move(key_map), + default_length_callback, key_value_invalid_callback); } node_callback_t NodeTools::name_list_callback(callback_t&&> callback) { diff --git a/src/openvic-simulation/dataloader/NodeTools.hpp b/src/openvic-simulation/dataloader/NodeTools.hpp index 6469100..7ad5412 100644 --- a/src/openvic-simulation/dataloader/NodeTools.hpp +++ b/src/openvic-simulation/dataloader/NodeTools.hpp @@ -27,13 +27,19 @@ namespace OpenVic { namespace NodeTools { template - concept Functor = requires(Fn&& fn, Args&&... args) { - { std::invoke(std::forward(fn), std::forward(args)...) } -> std::same_as; + concept Functor = requires(Fn&& fn, Args&& ... args) { + { + std::invoke(std::forward(fn), std::forward(args)...) + } + -> std::same_as; }; template - concept FunctorConvertible = requires(Fn&& fn, Args&&... args) { - { std::invoke(std::forward(fn), std::forward(args)...) } -> std::convertible_to; + concept FunctorConvertible = requires(Fn&& fn, Args&& ... args) { + { + std::invoke(std::forward(fn), std::forward(args)...) + } + -> std::convertible_to; }; template @@ -52,10 +58,14 @@ namespace OpenVic { using callback_t = std::function; using node_callback_t = callback_t; - constexpr bool success_callback(ast::NodeCPtr) { return true; } + constexpr bool success_callback(ast::NodeCPtr) { + return true; + } using key_value_callback_t = callback_t; - constexpr bool key_value_success_callback(std::string_view, ast::NodeCPtr) { return true; } + constexpr bool key_value_success_callback(std::string_view, ast::NodeCPtr) { + return true; + } inline bool key_value_invalid_callback(std::string_view key, ast::NodeCPtr) { Logger::error("Invalid dictionary key: ", key); return false; @@ -109,7 +119,9 @@ namespace OpenVic { node_callback_t expect_assign(key_value_callback_t callback); using length_callback_t = std::function; - constexpr size_t default_length_callback(size_t size) { return size; }; + constexpr size_t default_length_callback(size_t size) { + return size; + }; node_callback_t expect_list_and_length(length_callback_t length_callback, node_callback_t callback); node_callback_t expect_list_of_length(size_t length, node_callback_t callback); @@ -147,33 +159,40 @@ namespace OpenVic { using enum dictionary_entry_t::expected_count_t; using key_map_t = string_map_t; - bool add_key_map_entry(key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, node_callback_t callback); + bool add_key_map_entry(key_map_t& key_map, std::string_view key, + dictionary_entry_t::expected_count_t expected_count, node_callback_t callback); bool remove_key_map_entry(key_map_t& key_map, std::string_view key); key_value_callback_t dictionary_keys_callback(key_map_t& key_map, key_value_callback_t default_callback); bool check_key_map_counts(key_map_t& key_map); - constexpr bool add_key_map_entries(key_map_t& key_map) { return true; } + constexpr bool add_key_map_entries(key_map_t& key_map) { + return true; + } template - bool add_key_map_entries(key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, NodeCallback auto callback, Args... args) { + bool add_key_map_entries(key_map_t& key_map, std::string_view key, + dictionary_entry_t::expected_count_t expected_count, NodeCallback auto callback, Args... args) { bool ret = add_key_map_entry(key_map, key, expected_count, callback); ret &= add_key_map_entries(key_map, args...); return ret; } - node_callback_t expect_dictionary_key_map_and_length_and_default(key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback); + node_callback_t expect_dictionary_key_map_and_length_and_default(key_map_t key_map, + length_callback_t length_callback, key_value_callback_t default_callback); node_callback_t expect_dictionary_key_map_and_length(key_map_t key_map, length_callback_t length_callback); node_callback_t expect_dictionary_key_map_and_default(key_map_t key_map, key_value_callback_t default_callback); node_callback_t expect_dictionary_key_map(key_map_t key_map); template - NodeCallback auto expect_dictionary_key_map_and_length_and_default(key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback, Args... args) { + NodeCallback auto expect_dictionary_key_map_and_length_and_default(key_map_t key_map, + length_callback_t length_callback, key_value_callback_t default_callback, Args... args) { // TODO - pass return value back up (part of big key_map_t rewrite?) add_key_map_entries(key_map, args...); return expect_dictionary_key_map_and_length_and_default(std::move(key_map), length_callback, default_callback); } template - NodeCallback auto expect_dictionary_keys_and_length_and_default(LengthCallback auto length_callback, KeyValueCallback auto default_callback, Args... args) { + NodeCallback auto expect_dictionary_keys_and_length_and_default(LengthCallback auto length_callback, + KeyValueCallback auto default_callback, Args... args) { return expect_dictionary_key_map_and_length_and_default({}, length_callback, default_callback, args...); } @@ -194,7 +213,10 @@ namespace OpenVic { template concept Reservable = requires(T& t) { - { t.size() } -> std::same_as; + { + t.size() + } + -> std::same_as; t.reserve(size_t {}); }; template diff --git a/src/openvic-simulation/economy/Building.cpp b/src/openvic-simulation/economy/Building.cpp index 4a99249..29eb50e 100644 --- a/src/openvic-simulation/economy/Building.cpp +++ b/src/openvic-simulation/economy/Building.cpp @@ -7,13 +7,13 @@ using namespace OpenVic::NodeTools; Building::Building(std::string_view identifier, BuildingType const& type, ARGS) : HasIdentifier { identifier }, type { type }, modifier { std::move(modifier) }, on_completion { on_completion }, - completion_size { completion_size }, max_level { max_level }, goods_cost { std::move(goods_cost) }, cost { cost }, - build_time { build_time }, visibility { visibility }, on_map { on_map }, default_enabled { default_enabled }, - production_type { production_type }, pop_build_factory { pop_build_factory }, strategic_factory { strategic_factory }, - advanced_factory { advanced_factory }, fort_level { fort_level }, naval_capacity { naval_capacity }, - colonial_points { std::move(colonial_points) }, in_province { in_province }, one_per_state { one_per_state }, - colonial_range { colonial_range }, infrastructure { infrastructure }, spawn_railway_track { spawn_railway_track }, - sail { sail }, steam { steam }, capital { capital }, port { port } {} + completion_size { completion_size }, max_level { max_level }, goods_cost { std::move(goods_cost) }, cost { cost }, + build_time { build_time }, visibility { visibility }, on_map { on_map }, default_enabled { default_enabled }, + production_type { production_type }, pop_build_factory { pop_build_factory }, strategic_factory { strategic_factory }, + advanced_factory { advanced_factory }, fort_level { fort_level }, naval_capacity { naval_capacity }, + colonial_points { std::move(colonial_points) }, in_province { in_province }, one_per_state { one_per_state }, + colonial_range { colonial_range }, infrastructure { infrastructure }, spawn_railway_track { spawn_railway_track }, + sail { sail }, steam { steam }, capital { capital }, port { port } {} BuildingType const& Building::get_type() const { return type; @@ -154,14 +154,15 @@ bool BuildingInstance::expand() { */ void BuildingInstance::update_state(Date const& today) { switch (expansion_state) { - case ExpansionState::Preparing: - start = today; - end = start + building.get_build_time(); - break; - case ExpansionState::Expanding: - expansion_progress = static_cast(today - start) / static_cast(end - start); - break; - default: expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; + case ExpansionState::Preparing: + start = today; + end = start + building.get_build_time(); + break; + case ExpansionState::Expanding: + expansion_progress = static_cast(today - start) / static_cast(end - start); + break; + default: + expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; } } @@ -198,13 +199,16 @@ bool BuildingManager::add_building(std::string_view identifier, BuildingType con } return buildings.add_item({ - identifier, *type, std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), cost, build_time, visibility, on_map, default_enabled, - production_type, pop_build_factory, strategic_factory, advanced_factory, fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, + identifier, *type, std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), + cost, build_time, visibility, on_map, default_enabled, production_type, pop_build_factory, strategic_factory, + advanced_factory, fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, colonial_range, infrastructure, spawn_railway_track, sail, steam, capital, port }); } -bool BuildingManager::load_buildings_file(GoodManager const& good_manager, ProductionTypeManager const& production_type_manager, ModifierManager const& modifier_manager, ast::NodeCPtr root) { +bool BuildingManager::load_buildings_file(GoodManager const& good_manager, + ProductionTypeManager const& production_type_manager, + ModifierManager const& modifier_manager, ast::NodeCPtr root) { bool ret = expect_dictionary_reserve_length(buildings, [this](std::string_view, ast::NodeCPtr value) -> bool { return expect_key("type", expect_identifier( std::bind(&BuildingManager::add_building_type, this, std::placeholders::_1) @@ -212,7 +216,8 @@ bool BuildingManager::load_buildings_file(GoodManager const& good_manager, Produ })(root); lock_building_types(); - ret &= expect_dictionary([this, &good_manager, &production_type_manager, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { + ret &= expect_dictionary([this, &good_manager, &production_type_manager, &modifier_manager]( + std::string_view key, ast::NodeCPtr value) -> bool { BuildingType const* type = nullptr; ProductionType const* production_type = nullptr; std::string_view on_completion; @@ -220,8 +225,10 @@ bool BuildingManager::load_buildings_file(GoodManager const& good_manager, Produ Building::level_t max_level = 0, fort_level = 0; Good::good_map_t goods_cost; Timespan build_time; - bool visibility = false, on_map = false, default_enabled = false, pop_build_factory = false, strategic_factory = false, advanced_factory = false; - bool in_province = false, one_per_state = false, spawn_railway_track = false, sail = false, steam = false, capital = false, port = false; + bool visibility = false, on_map = false, default_enabled = false, pop_build_factory = false; + bool strategic_factory = false, advanced_factory = false; + bool in_province = false, one_per_state = false, spawn_railway_track = false, sail = false, steam = false; + bool capital = false, port = false; uint64_t naval_capacity = 0; std::vector colonial_points; ModifierValue modifier; @@ -260,10 +267,10 @@ bool BuildingManager::load_buildings_file(GoodManager const& good_manager, Produ )(value); ret &= add_building( - key, type,std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), cost, build_time, - visibility, on_map, default_enabled, production_type, pop_build_factory, strategic_factory, advanced_factory, - fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, colonial_range, infrastructure, - spawn_railway_track, sail, steam, capital, port + key, type, std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), + cost, build_time, visibility, on_map, default_enabled, production_type, pop_build_factory, strategic_factory, + advanced_factory, fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, + colonial_range, infrastructure, spawn_railway_track, sail, steam, capital, port ); return ret; diff --git a/src/openvic-simulation/economy/Building.hpp b/src/openvic-simulation/economy/Building.hpp index b56c9a2..bbf97fb 100644 --- a/src/openvic-simulation/economy/Building.hpp +++ b/src/openvic-simulation/economy/Building.hpp @@ -166,7 +166,9 @@ namespace OpenVic { bool add_building(std::string_view identifier, BuildingType const* type, ARGS); IDENTIFIER_REGISTRY_ACCESSORS(building) - bool load_buildings_file(GoodManager const& good_manager, ProductionTypeManager const& production_type_manager, ModifierManager const& modifier_manager, ast::NodeCPtr root); + bool load_buildings_file(GoodManager const& good_manager, + ProductionTypeManager const& production_type_manager, + ModifierManager const& modifier_manager, ast::NodeCPtr root); bool generate_province_buildings(Province& province) const; }; diff --git a/src/openvic-simulation/economy/Good.cpp b/src/openvic-simulation/economy/Good.cpp index 0fd4618..60a85d0 100644 --- a/src/openvic-simulation/economy/Good.cpp +++ b/src/openvic-simulation/economy/Good.cpp @@ -84,12 +84,14 @@ bool GoodManager::add_good(std::string_view identifier, colour_t colour, GoodCat Logger::error("Invalid base price for ", identifier, ": ", base_price); return false; } - return goods.add_item({ identifier, colour, *category, base_price, available_from_start, tradeable, money, overseas_penalty }); + return goods.add_item({ identifier, colour, *category, base_price, + available_from_start, tradeable, money, overseas_penalty }); } void GoodManager::reset_to_defaults() { - for (Good& good : goods.get_items()) + for (Good& good : goods.get_items()) { good.reset_to_defaults(); + } } bool GoodManager::load_goods_file(ast::NodeCPtr root) { @@ -123,7 +125,8 @@ bool GoodManager::load_goods_file(ast::NodeCPtr root) { "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(money)), "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(overseas_penalty)) )(value); - ret &= add_good(key, colour, good_category, base_price, available_from_start, tradeable, money, overseas_penalty); + ret &= add_good(key, colour, good_category, base_price, + available_from_start, tradeable, money, overseas_penalty); return ret; } )(good_category_value); diff --git a/src/openvic-simulation/economy/ProductionType.cpp b/src/openvic-simulation/economy/ProductionType.cpp index f31ea59..6b7d757 100644 --- a/src/openvic-simulation/economy/ProductionType.cpp +++ b/src/openvic-simulation/economy/ProductionType.cpp @@ -5,8 +5,10 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -EmployedPop::EmployedPop(PopType const* pop_type, bool artisan, effect_t effect, fixed_point_t effect_multiplier, fixed_point_t amount) - : pop_type { pop_type }, artisan { artisan }, effect { effect }, effect_multiplier { effect_multiplier }, amount { amount } {} +EmployedPop::EmployedPop(PopType const* pop_type, bool artisan, effect_t effect, + fixed_point_t effect_multiplier, fixed_point_t amount) + : pop_type { pop_type }, artisan { artisan }, effect { effect }, + effect_multiplier { effect_multiplier }, amount { amount } {} PopType const* EmployedPop::get_pop_type() const { return pop_type; @@ -186,7 +188,8 @@ bool ProductionTypeManager::add_production_type(PRODUCTION_TYPE_ARGS, GoodManage "mine", ZERO_OR_ONE, expect_bool(assign_variable_callback(mine)) \ ) -bool ProductionTypeManager::load_production_types_file(GoodManager const& good_manager, PopManager const& pop_manager, ast::NodeCPtr root) { +bool ProductionTypeManager::load_production_types_file(GoodManager const& good_manager, + PopManager const& pop_manager, ast::NodeCPtr root) { size_t expected_types = 0; // pass 1: find and store template identifiers @@ -227,7 +230,8 @@ bool ProductionTypeManager::load_production_types_file(GoodManager const& good_m // pass 3: actually load production types production_types.reserve(production_types.size() + expected_types); ret &= expect_dictionary( - [this, &good_manager, &pop_manager, &template_target_map, &template_node_map](std::string_view key, ast::NodeCPtr node) -> bool { + [this, &good_manager, &pop_manager, &template_target_map, &template_node_map]( + std::string_view key, ast::NodeCPtr node) -> bool { if (template_node_map.contains(key)) return true; diff --git a/src/openvic-simulation/economy/ProductionType.hpp b/src/openvic-simulation/economy/ProductionType.hpp index 2deb461..d84be01 100644 --- a/src/openvic-simulation/economy/ProductionType.hpp +++ b/src/openvic-simulation/economy/ProductionType.hpp @@ -96,10 +96,10 @@ namespace OpenVic { private: IdentifierRegistry production_types; - NodeTools::node_callback_t _expect_employed_pop(GoodManager const& good_manager, PopManager const& pop_manager, - NodeTools::callback_t cb); - NodeTools::node_callback_t _expect_employed_pop_list(GoodManager const& good_manager, PopManager const& pop_manager, - NodeTools::callback_t&&> cb); + NodeTools::node_callback_t _expect_employed_pop(GoodManager const& good_manager, + PopManager const& pop_manager, NodeTools::callback_t cb); + NodeTools::node_callback_t _expect_employed_pop_list(GoodManager const& good_manager, + PopManager const& pop_manager, NodeTools::callback_t&&> cb); public: ProductionTypeManager(); diff --git a/src/openvic-simulation/history/Bookmark.hpp b/src/openvic-simulation/history/Bookmark.hpp index 63e1b3b..d4de34c 100644 --- a/src/openvic-simulation/history/Bookmark.hpp +++ b/src/openvic-simulation/history/Bookmark.hpp @@ -45,7 +45,8 @@ namespace OpenVic { public: BookmarkManager(); - bool add_bookmark(std::string_view name, std::string_view description, Date date, uint32_t initial_camera_x, uint32_t initial_camera_y); + bool add_bookmark(std::string_view name, std::string_view description, Date date, + uint32_t initial_camera_x, uint32_t initial_camera_y); IDENTIFIER_REGISTRY_ACCESSORS(bookmark); bool load_bookmark_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/history/CountryHistory.cpp b/src/openvic-simulation/history/CountryHistory.cpp index 5e91a85..9ed271b 100644 --- a/src/openvic-simulation/history/CountryHistory.cpp +++ b/src/openvic-simulation/history/CountryHistory.cpp @@ -20,7 +20,11 @@ CountryHistory::CountryHistory( fixed_point_t new_prestige, std::vector&& new_reforms, Deployment const* new_inital_oob -) : primary_culture { new_primary_culture }, accepted_cultures { std::move(new_accepted_cultures) }, religion { new_religion }, ruling_party { new_ruling_party }, last_election { new_last_election }, upper_house { std::move(new_upper_house) }, capital { new_capital }, government_type { new_government_type }, plurality { new_plurality }, national_value { new_national_value }, civilised { new_civilised }, prestige { new_prestige }, reforms { std::move(new_reforms) }, inital_oob { new_inital_oob } {} +) : primary_culture { new_primary_culture }, accepted_cultures { std::move(new_accepted_cultures) }, + religion { new_religion }, ruling_party { new_ruling_party }, last_election { new_last_election }, + upper_house { std::move(new_upper_house) }, capital { new_capital }, government_type { new_government_type }, + plurality { new_plurality }, national_value { new_national_value }, civilised { new_civilised }, + prestige { new_prestige }, reforms { std::move(new_reforms) }, inital_oob { new_inital_oob } {} Culture const* CountryHistory::get_primary_culture() const { return primary_culture; @@ -107,22 +111,50 @@ bool CountryHistoryManager::add_country_history_entry( /* combine duplicate histories, priority to current (defined later) */ auto& country_registry = country_histories[country]; const auto existing_entry = country_registry.find(date); - + if (existing_entry != country_registry.end()) { - if (primary_culture != nullptr) existing_entry->second.primary_culture = primary_culture; - if (updated_accepted_cultures) existing_entry->second.accepted_cultures = std::move(accepted_cultures); - if (religion != nullptr) existing_entry->second.religion = religion; - if (ruling_party != nullptr) existing_entry->second.ruling_party = ruling_party; - if (last_election != Date(0)) existing_entry->second.last_election = last_election; - if (updated_upper_house) existing_entry->second.upper_house = std::move(upper_house); - if (capital != nullptr) existing_entry->second.capital = capital; - if (government_type != nullptr) existing_entry->second.government_type = government_type; - if (plurality >= 0) existing_entry->second.plurality = plurality; - if (national_value != nullptr) existing_entry->second.national_value = national_value; - if (civilised) existing_entry->second.civilised = true; - if (prestige >= 0) existing_entry->second.prestige = prestige; - if (updated_reforms) existing_entry->second.reforms = std::move(reforms); - if (initial_oob != nullptr) existing_entry->second.inital_oob = initial_oob; + if (primary_culture != nullptr) { + existing_entry->second.primary_culture = primary_culture; + } + if (updated_accepted_cultures) { + existing_entry->second.accepted_cultures = std::move(accepted_cultures); + } + if (religion != nullptr) { + existing_entry->second.religion = religion; + } + if (ruling_party != nullptr) { + existing_entry->second.ruling_party = ruling_party; + } + if (last_election != Date(0)) { + existing_entry->second.last_election = last_election; + } + if (updated_upper_house) { + existing_entry->second.upper_house = std::move(upper_house); + } + if (capital != nullptr) { + existing_entry->second.capital = capital; + } + if (government_type != nullptr) { + existing_entry->second.government_type = government_type; + } + if (plurality >= 0) { + existing_entry->second.plurality = plurality; + } + if (national_value != nullptr) { + existing_entry->second.national_value = national_value; + } + if (civilised) { + existing_entry->second.civilised = true; + } + if (prestige >= 0) { + existing_entry->second.prestige = prestige; + } + if (updated_reforms) { + existing_entry->second.reforms = std::move(reforms); + } + if (initial_oob != nullptr) { + existing_entry->second.inital_oob = initial_oob; + } } else { country_registry.emplace(date, CountryHistory { primary_culture, @@ -147,7 +179,8 @@ bool CountryHistoryManager::add_country_history_entry( void CountryHistoryManager::lock_country_histories() { for (const auto& entry : country_histories) { if (entry.second.size() == 0) { - Logger::error("Attempted to lock country histories - country ", entry.first->get_identifier(), " has no history entries!"); + Logger::error("Attempted to lock country histories - country ", + entry.first->get_identifier(), " has no history entries!"); } } Logger::info("Locked country history registry after registering ", country_histories.size(), " items"); @@ -166,11 +199,17 @@ CountryHistory const* CountryHistoryManager::get_country_history(Country const* Logger::error("Attempted to access history of undefined country ", country->get_identifier()); return nullptr; } - + for (const auto& current : country_registry->second) { - if (current.first == entry) return ¤t.second; - if (current.first > entry) continue; - if (current.first > closest_entry && current.first < entry) closest_entry = current.first; + if (current.first == entry) { + return ¤t.second; + } + if (current.first > entry) { + continue; + } + if (current.first > closest_entry && current.first < entry) { + closest_entry = current.first; + } } auto entry_registry = country_registry->second.find(closest_entry); @@ -185,7 +224,8 @@ inline CountryHistory const* CountryHistoryManager::get_country_history(Country return get_country_history(country, entry->get_date()); } -inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game_manager, std::string_view name, Date const& date, ast::NodeCPtr root) { +inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game_manager, + std::string_view name, Date const& date, ast::NodeCPtr root) { Province const* capital = nullptr; Culture const* primary_culture = nullptr; Religion const* religion = nullptr; @@ -209,7 +249,8 @@ inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game Reform const* reform; - bool ret = game_manager.get_politics_manager().get_issue_manager().expect_reform_identifier(assign_variable_callback_pointer(reform))(value); + bool ret = game_manager.get_politics_manager().get_issue_manager() + .expect_reform_identifier(assign_variable_callback_pointer(reform))(value); if (std::find(reforms.begin(), reforms.end(), reform) != reforms.end()) { Logger::error("Redefinition of reform ", reform->get_identifier(), " in history of ", name); return false; @@ -221,24 +262,32 @@ inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game // TODO: technologies & inventions return true; }, - /* we have to use a lambda, assign_variable_callback_pointer apparently doesn't play nice with const & non-const accessors */ + /* we have to use a lambda, assign_variable_callback_pointer + * apparently doesn't play nice with const & non-const accessors */ "capital", ZERO_OR_ONE, game_manager.get_map().expect_province_identifier([&capital](Province const& province) -> bool { capital = &province; return true; }), - "primary_culture", ZERO_OR_ONE, game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier(assign_variable_callback_pointer(primary_culture)), - "culture", ZERO_OR_MORE, game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier([&game_manager, &accepted_cultures, &updated_accepted_cultures](Culture const& culture) -> bool { - updated_accepted_cultures = true; - accepted_cultures.push_back(&culture); - return true; - }), - "religion", ZERO_OR_ONE, game_manager.get_pop_manager().get_religion_manager().expect_religion_identifier(assign_variable_callback_pointer(religion)), - "government", ZERO_OR_ONE, game_manager.get_politics_manager().get_government_type_manager().expect_government_type_identifier(assign_variable_callback_pointer(government_type)), + "primary_culture", ZERO_OR_ONE, game_manager.get_pop_manager().get_culture_manager() + .expect_culture_identifier(assign_variable_callback_pointer(primary_culture)), + "culture", ZERO_OR_MORE, game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier( + [&game_manager, &accepted_cultures, &updated_accepted_cultures](Culture const & culture) -> bool { + updated_accepted_cultures = true; + accepted_cultures.push_back(&culture); + return true; + } + ), + "religion", ZERO_OR_ONE, game_manager.get_pop_manager().get_religion_manager() + .expect_religion_identifier(assign_variable_callback_pointer(religion)), + "government", ZERO_OR_ONE, game_manager.get_politics_manager().get_government_type_manager() + .expect_government_type_identifier(assign_variable_callback_pointer(government_type)), "plurality", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(plurality)), - "nationalvalue", ZERO_OR_ONE, game_manager.get_politics_manager().get_national_value_manager().expect_national_value_identifier(assign_variable_callback_pointer(national_value)), + "nationalvalue", ZERO_OR_ONE, game_manager.get_politics_manager().get_national_value_manager() + .expect_national_value_identifier(assign_variable_callback_pointer(national_value)), "civilized", ZERO_OR_ONE, expect_bool(assign_variable_callback(civilised)), "prestige", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(prestige)), - "ruling_party", ZERO_OR_ONE, expect_identifier([this, &game_manager, &ruling_party, &name, &date](std::string_view identifier) -> bool { + "ruling_party", ZERO_OR_ONE, expect_identifier([this, &game_manager, + &ruling_party, &name, &date](std::string_view identifier) -> bool { const std::vector* parties = &game_manager.get_country_manager().get_country_by_identifier(name)->get_parties(); for (auto& party : *parties) { if (party.get_name() == identifier) { @@ -246,8 +295,14 @@ inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game ruling_party = &party; return true; } else { - if (party.get_start_date() > date) Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid start date ", party.get_start_date(), " for bookmark: ", date.to_string()); - if (party.get_end_date() < date) Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid end date ", party.get_end_date(), " for bookmark: ", date.to_string()); + if (party.get_start_date() > date) { + Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid start date ", + party.get_start_date(), " for bookmark: ", date.to_string()); + } + if (party.get_end_date() < date) { + Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid end date ", + party.get_end_date(), " for bookmark: ", date.to_string()); + } ruling_party = &party; return true; } @@ -257,42 +312,52 @@ inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game return false; }), "last_election", ZERO_OR_ONE, expect_date(assign_variable_callback(last_election)), - "upper_house", ZERO_OR_ONE, game_manager.get_politics_manager().get_ideology_manager().expect_ideology_dictionary([&upper_house, &updated_upper_house](Ideology const& ideology, ast::NodeCPtr value) -> bool { - fixed_point_t popularity; + "upper_house", ZERO_OR_ONE, game_manager.get_politics_manager().get_ideology_manager().expect_ideology_dictionary( + [&upper_house, &updated_upper_house](Ideology const& ideology, ast::NodeCPtr value) -> bool { + fixed_point_t popularity; - updated_upper_house = true; - bool ret = expect_fixed_point(assign_variable_callback(popularity))(value); - upper_house.emplace(&ideology, popularity); - return ret; - }), + updated_upper_house = true; + bool ret = expect_fixed_point(assign_variable_callback(popularity))(value); + upper_house.emplace(&ideology, popularity); + return ret; + } + ), "oob", ZERO_OR_ONE, [&game_manager, &initial_oob](ast::NodeCPtr node) -> bool { std::string_view string; expect_string(assign_variable_callback(string))(node); if (string.starts_with('/')) { - if (game_manager.get_military_manager().get_deployment_manager().has_deployment_identifier(string.substr(1))) { - initial_oob = game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier(string.substr(1)); + if (game_manager.get_military_manager().get_deployment_manager() + .has_deployment_identifier(string.substr(1))) { + initial_oob = game_manager.get_military_manager().get_deployment_manager() + .get_deployment_by_identifier(string.substr(1)); return true; } } else { if (game_manager.get_military_manager().get_deployment_manager().has_deployment_identifier(string)) { - initial_oob = game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier(string); + initial_oob = game_manager.get_military_manager().get_deployment_manager() + .get_deployment_by_identifier(string); } } initial_oob = game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier("NULL"); return true; }, - "schools", ZERO_OR_ONE, success_callback, // TODO: technology school + "schools", ZERO_OR_ONE, success_callback, // TODO: technology school "foreign_investment", ZERO_OR_ONE, success_callback // TODO: foreign investment )(root); - ret &= add_country_history_entry(game_manager.get_country_manager().get_country_by_identifier(name), date, primary_culture, std::move(accepted_cultures), religion, ruling_party, last_election, std::move(upper_house), capital, government_type, plurality, national_value, civilised, prestige, std::move(reforms), initial_oob, updated_accepted_cultures, updated_upper_house, updated_reforms); + ret &= add_country_history_entry(game_manager.get_country_manager().get_country_by_identifier(name), date, + primary_culture, std::move(accepted_cultures), religion, ruling_party, last_election, std::move(upper_house), + capital, government_type, plurality, national_value, civilised, prestige, std::move(reforms), initial_oob, + updated_accepted_cultures, updated_upper_house, updated_reforms); return ret; } bool CountryHistoryManager::load_country_history_file(GameManager& game_manager, std::string_view name, ast::NodeCPtr root) { - if (game_manager.get_country_manager().get_country_by_identifier(name)->is_dynamic_tag()) return true; /* as far as I can tell dynamic countries are hardcoded, broken, and unused */ + if (game_manager.get_country_manager().get_country_by_identifier(name)->is_dynamic_tag()) { + return true; /* as far as I can tell dynamic countries are hardcoded, broken, and unused */ + } bool ret = _load_country_history_entry(game_manager, name, game_manager.get_define_manager().get_start_date(), root); @@ -304,10 +369,11 @@ bool CountryHistoryManager::load_country_history_file(GameManager& game_manager, Date const& end_date = game_manager.get_define_manager().get_end_date(); if (entry > end_date) { - Logger::error("History entry ", entry.to_string(), " of country ", name, " defined after defined end date ", end_date.to_string()); + Logger::error("History entry ", entry.to_string(), " of country ", name, + " defined after defined end date ", end_date.to_string()); return false; } - + return _load_country_history_entry(game_manager, name, entry, value); } )(root); diff --git a/src/openvic-simulation/history/ProvinceHistory.cpp b/src/openvic-simulation/history/ProvinceHistory.cpp index cc6c5b8..e5cc97b 100644 --- a/src/openvic-simulation/history/ProvinceHistory.cpp +++ b/src/openvic-simulation/history/ProvinceHistory.cpp @@ -1,323 +1,346 @@ #include "ProvinceHistory.hpp" -#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/dataloader/NodeTools.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; ProvinceHistory::ProvinceHistory( - Country const* new_owner, - Country const* new_controller, - uint8_t new_colonial, - bool new_slave, - std::vector&& new_cores, - Good const* new_rgo, - uint8_t new_life_rating, - TerrainType const* new_terrain_type, - std::map&& new_buildings, - std::map&& new_party_loyalties + Country const* new_owner, + Country const* new_controller, + uint8_t new_colonial, + bool new_slave, + std::vector&& new_cores, + Good const* new_rgo, + uint8_t new_life_rating, + TerrainType const* new_terrain_type, + std::map&& new_buildings, + std::map&& new_party_loyalties ) : owner { new_owner }, - controller { new_controller }, - colonial { new_colonial }, - slave { new_slave }, - cores { std::move(new_cores) }, - rgo { new_rgo }, - life_rating { new_life_rating }, - terrain_type { new_terrain_type }, - buildings { std::move(new_buildings) }, - party_loyalties { std::move(new_party_loyalties) } {} + controller { new_controller }, + colonial { new_colonial }, + slave { new_slave }, + cores { std::move(new_cores) }, + rgo { new_rgo }, + life_rating { new_life_rating }, + terrain_type { new_terrain_type }, + buildings { std::move(new_buildings) }, + party_loyalties { std::move(new_party_loyalties) } {} Country const* ProvinceHistory::get_owner() const { - return owner; + return owner; } Country const* ProvinceHistory::get_controller() const { - return controller; + return controller; } uint8_t ProvinceHistory::get_colony_status() const { - return colonial; + return colonial; } bool ProvinceHistory::is_slave() const { - return slave; + return slave; } -const std::vector& ProvinceHistory::get_cores() const { - return cores; +std::vector const& ProvinceHistory::get_cores() const { + return cores; } bool ProvinceHistory::is_core_of(Country const* country) const { - return std::find(cores.begin(), cores.end(), country) != cores.end(); + return std::find(cores.begin(), cores.end(), country) != cores.end(); } Good const* ProvinceHistory::get_rgo() const { - return rgo; + return rgo; } uint8_t ProvinceHistory::get_life_rating() const { - return life_rating; + return life_rating; } TerrainType const* ProvinceHistory::get_terrain_type() const { - return terrain_type; + return terrain_type; } -const std::map& ProvinceHistory::get_buildings() const { - return buildings; +std::map const& ProvinceHistory::get_buildings() const { + return buildings; } -const std::map& ProvinceHistory::get_party_loyalties() const { - return party_loyalties; +std::map const& ProvinceHistory::get_party_loyalties() const { + return party_loyalties; } bool ProvinceHistoryManager::add_province_history_entry( - Province const* province, - Date date, - Country const* owner, - Country const* controller, - uint8_t colonial, - bool slave, - std::vector&& cores, - std::vector&& remove_cores, - Good const* rgo, - uint8_t life_rating, - TerrainType const* terrain_type, - std::map&& buildings, - std::map&& party_loyalties, - std::bitset<5> updates + Province const* province, + Date date, + Country const* owner, + Country const* controller, + uint8_t colonial, + bool slave, + std::vector&& cores, + std::vector&& remove_cores, + Good const* rgo, + uint8_t life_rating, + TerrainType const* terrain_type, + std::map&& buildings, + std::map&& party_loyalties, + std::bitset<5> updates ) { - if (locked) { - Logger::error("Cannot add new history entry to province history registry: locked!"); - return false; - } - - /* combine duplicate histories, priority to current (defined later) */ - auto& province_registry = province_histories[province]; - const auto existing_entry = province_registry.find(date); - - if (existing_entry != province_registry.end()) { - if (owner != nullptr) existing_entry->second.owner = owner; - if (controller != nullptr) existing_entry->second.controller = controller; - if (rgo != nullptr) existing_entry->second.rgo = rgo; - if (terrain_type != nullptr) existing_entry->second.terrain_type = terrain_type; - if (updates[0]) existing_entry->second.colonial = colonial; - if (updates[1]) existing_entry->second.slave = slave; - if (updates[2]) existing_entry->second.life_rating = life_rating; - if (updates[3]) existing_entry->second.buildings = std::move(buildings); - if (updates[4]) existing_entry->second.party_loyalties = std::move(party_loyalties); - // province history cores are additive - existing_entry->second.cores.insert(existing_entry->second.cores.end(), cores.begin(), cores.end()); - for (const auto which : remove_cores) { - const auto core = std::find(cores.begin(), cores.end(), which); - if (core == cores.end()) { - Logger::error("In history of province ", province->get_identifier(), " tried to remove nonexistant core of country: ", which->get_identifier(), " at date ", date.to_string()); - return false; - } - existing_entry->second.cores.erase(core); - } - } else { - province_registry.emplace(date, ProvinceHistory { - owner, - controller, - colonial, - slave, - std::move(cores), - rgo, - life_rating, - terrain_type, - std::move(buildings), - std::move(party_loyalties) - }); - } - return true; + if (locked) { + Logger::error("Cannot add new history entry to province history registry: locked!"); + return false; + } + + /* combine duplicate histories, priority to current (defined later) */ + auto& province_registry = province_histories[province]; + const auto existing_entry = province_registry.find(date); + + if (existing_entry != province_registry.end()) { + if (owner != nullptr) existing_entry->second.owner = owner; + if (controller != nullptr) existing_entry->second.controller = controller; + if (rgo != nullptr) existing_entry->second.rgo = rgo; + if (terrain_type != nullptr) existing_entry->second.terrain_type = terrain_type; + if (updates[0]) existing_entry->second.colonial = colonial; + if (updates[1]) existing_entry->second.slave = slave; + if (updates[2]) existing_entry->second.life_rating = life_rating; + if (updates[3]) existing_entry->second.buildings = std::move(buildings); + if (updates[4]) existing_entry->second.party_loyalties = std::move(party_loyalties); + // province history cores are additive + existing_entry->second.cores.insert(existing_entry->second.cores.end(), cores.begin(), cores.end()); + for (const auto which : remove_cores) { + const auto core = std::find(cores.begin(), cores.end(), which); + if (core == cores.end()) { + Logger::error("In history of province ", province->get_identifier(), + " tried to remove nonexistant core of country: ", which->get_identifier(), " at date ", date.to_string()); + return false; + } + existing_entry->second.cores.erase(core); + } + } else { + province_registry.emplace(date, ProvinceHistory { + owner, + controller, + colonial, + slave, + std::move(cores), + rgo, + life_rating, + terrain_type, + std::move(buildings), + std::move(party_loyalties) + }); + } + return true; } void ProvinceHistoryManager::lock_province_histories() { - for (const auto& entry : province_histories) { - if (entry.second.size() == 0) { - Logger::error("Attempted to lock province histories - province ", entry.first->get_identifier(), " has no history entries!"); - } - } - Logger::info("Locked province history registry after registering ", province_histories.size(), " items"); - locked = true; + for (auto const& entry : province_histories) { + if (entry.second.size() == 0) { + Logger::error("Attempted to lock province histories - province ", entry.first->get_identifier(), + " has no history entries!"); + } + } + Logger::info("Locked province history registry after registering ", province_histories.size(), " items"); + locked = true; } bool ProvinceHistoryManager::is_locked() const { - return locked; + return locked; } ProvinceHistory const* ProvinceHistoryManager::get_province_history(Province const* province, Date entry) const { - Date closest_entry; - auto province_registry = province_histories.find(province); - - if (province_registry == province_histories.end()) { - Logger::error("Attempted to access history of undefined province ", province->get_identifier()); - return nullptr; - } - - for (const auto& current : province_registry->second) { - if (current.first == entry) return ¤t.second; - if (current.first > entry) continue; - if (current.first > closest_entry && current.first < entry) closest_entry = current.first; - } - - auto entry_registry = province_registry->second.find(closest_entry); - if (entry_registry != province_registry->second.end()) return &entry_registry->second; + Date closest_entry; + auto province_registry = province_histories.find(province); + + if (province_registry == province_histories.end()) { + Logger::error("Attempted to access history of undefined province ", province->get_identifier()); + return nullptr; + } + + for (auto const& current : province_registry->second) { + if (current.first == entry) { + return ¤t.second; + } + if (current.first > entry) { + continue; + } + if (current.first > closest_entry && current.first < entry) { + closest_entry = current.first; + } + } + + auto entry_registry = province_registry->second.find(closest_entry); + if (entry_registry != province_registry->second.end()) { + return &entry_registry->second; + } /* warned about lack of entries earlier, return nullptr */ return nullptr; } -inline ProvinceHistory const* ProvinceHistoryManager::get_province_history(Province const* province, Bookmark const* bookmark) const { - return get_province_history(province, bookmark->get_date()); +inline ProvinceHistory const* ProvinceHistoryManager::get_province_history( + Province const* province, Bookmark const* bookmark +) const { + return get_province_history(province, bookmark->get_date()); } -inline bool ProvinceHistoryManager::_load_province_history_entry(GameManager& game_manager, std::string_view province, Date const& date, ast::NodeCPtr root) { - Country const* owner = nullptr; - Country const* controller = nullptr; - std::vector cores; - std::vector remove_cores; - Good const* rgo; - uint8_t life_rating, colonial; - bool slave; - TerrainType const* terrain_type; - std::map buildings; - std::map party_loyalties; - - std::bitset<5> updates; - - bool ret = expect_dictionary_keys_and_default( - [&game_manager, &buildings, &updates](std::string_view key, ast::NodeCPtr value) -> bool { - // used for province buildings like forts or railroads - if (game_manager.get_economy_manager().get_building_manager().has_building_identifier(key)) { - Building const* building; - uint8_t level; - - bool ret = game_manager.get_economy_manager().get_building_manager().expect_building_str(assign_variable_callback_pointer(building))(key); - ret &= expect_uint(assign_variable_callback(level))(value); - - buildings.emplace(building, level); - updates[3] = true; - return ret; - } - - bool is_date; - Date().from_string(key, &is_date, true); - if (is_date) return true; - - return key_value_invalid_callback(key, value); - }, - "owner", ZERO_OR_ONE, game_manager.get_country_manager().expect_country_identifier(assign_variable_callback_pointer(owner)), - "controller", ZERO_OR_ONE, game_manager.get_country_manager().expect_country_identifier(assign_variable_callback_pointer(controller)), - "add_core", ZERO_OR_MORE, [&game_manager, &cores](ast::NodeCPtr node) -> bool { - Country const* core; - - bool ret = game_manager.get_country_manager().expect_country_identifier(assign_variable_callback_pointer(core))(node); - cores.push_back(core); - return ret; - }, - "remove_core", ZERO_OR_MORE, [&game_manager, &remove_cores](ast::NodeCPtr node) -> bool { - Country const* remove; - - bool ret = game_manager.get_country_manager().expect_country_identifier(assign_variable_callback_pointer(remove))(node); - remove_cores.push_back(remove); - return ret; - }, - "colonial", ZERO_OR_ONE, expect_uint([&colonial, &updates](uint8_t colony_level) -> bool { - colonial = colony_level; - updates[0] = true; - - return true; - }), - "colony", ZERO_OR_ONE, expect_uint([&colonial, &updates](uint8_t colony_level) -> bool { - colonial = colony_level; - updates[0] = true; - - return true; - }), - "is_slave", ZERO_OR_ONE, expect_bool([&slave, &updates](bool is_slave) -> bool { - if (is_slave) { - slave = true; - } else { - slave = false; - } - updates[1] = true; - - return true; - }), - "trade_goods", ZERO_OR_ONE, game_manager.get_economy_manager().get_good_manager().expect_good_identifier(assign_variable_callback_pointer(rgo)), - "life_rating", ZERO_OR_ONE, expect_uint([&life_rating, &updates](uint8_t rating) -> bool { - life_rating = rating; - updates[2] = true; - - return true; - }), - "terrain", ZERO_OR_ONE, game_manager.get_map().get_terrain_type_manager().expect_terrain_type_identifier(assign_variable_callback_pointer(terrain_type)), - "party_loyalty", ZERO_OR_MORE, [&game_manager, &party_loyalties, &updates](ast::NodeCPtr node) -> bool { - Ideology const* ideology; - uint8_t amount; // percent I do believe - - bool ret = expect_dictionary_keys( - "ideology", ONE_EXACTLY, game_manager.get_politics_manager().get_ideology_manager().expect_ideology_identifier(assign_variable_callback_pointer(ideology)), - "loyalty_value", ONE_EXACTLY, expect_uint(assign_variable_callback(amount)) - )(node); - party_loyalties.emplace(ideology, amount); - updates[4] = true; - return ret; - }, - "state_building", ZERO_OR_MORE, [&game_manager, &buildings, &updates](ast::NodeCPtr node) -> bool { - Building const* building; - uint8_t level; - - bool ret = expect_dictionary_keys( - "level", ONE_EXACTLY, expect_uint(assign_variable_callback(level)), - "building", ONE_EXACTLY, game_manager.get_economy_manager().get_building_manager().expect_building_identifier(assign_variable_callback_pointer(building)), - "upgrade", ZERO_OR_ONE, success_callback // doesn't appear to have an effect - )(node); - buildings.emplace(building, level); - updates[3] = true; - return ret; - } - )(root); - - ret &= add_province_history_entry( - game_manager.get_map().get_province_by_identifier(province), - date, - owner, - controller, - colonial, - slave, - std::move(cores), - std::move(remove_cores), - rgo, - life_rating, - terrain_type, - std::move(buildings), - std::move(party_loyalties), - updates - ); - return ret; +inline bool ProvinceHistoryManager::_load_province_history_entry( + GameManager& game_manager, std::string_view province, Date const& date, ast::NodeCPtr root +) { + Country const* owner = nullptr; + Country const* controller = nullptr; + std::vector cores; + std::vector remove_cores; + Good const* rgo; + uint8_t life_rating, colonial; + bool slave; + TerrainType const* terrain_type; + std::map buildings; + std::map party_loyalties; + std::bitset<5> updates; + + bool ret = expect_dictionary_keys_and_default( + [&game_manager, &buildings, &updates](std::string_view key, ast::NodeCPtr value) -> bool { + // used for province buildings like forts or railroads + if (game_manager.get_economy_manager().get_building_manager().has_building_identifier(key)) { + Building const* building; + uint8_t level; + + bool ret = game_manager.get_economy_manager().get_building_manager() + .expect_building_str(assign_variable_callback_pointer(building))(key); + ret &= expect_uint(assign_variable_callback(level))(value); + + buildings.emplace(building, level); + updates[3] = true; + return ret; + } + + bool is_date; + Date().from_string(key, &is_date, true); + if (is_date) return true; + + return key_value_invalid_callback(key, value); + }, + "owner", ZERO_OR_ONE, game_manager.get_country_manager() + .expect_country_identifier(assign_variable_callback_pointer(owner)), + "controller", ZERO_OR_ONE, game_manager.get_country_manager() + .expect_country_identifier(assign_variable_callback_pointer(controller)), + "add_core", ZERO_OR_MORE, [&game_manager, &cores](ast::NodeCPtr node) -> bool { + Country const* core; + + bool ret = game_manager.get_country_manager() + .expect_country_identifier(assign_variable_callback_pointer(core))(node); + cores.push_back(core); + return ret; + }, + "remove_core", ZERO_OR_MORE, [&game_manager, &remove_cores](ast::NodeCPtr node) -> bool { + Country const* remove; + + bool ret = game_manager.get_country_manager() + .expect_country_identifier(assign_variable_callback_pointer(remove))(node); + remove_cores.push_back(remove); + return ret; + }, + "colonial", ZERO_OR_ONE, expect_uint([&colonial, &updates](uint8_t colony_level) -> bool { + colonial = colony_level; + updates[0] = true; + + return true; + }), + "colony", ZERO_OR_ONE, expect_uint([&colonial, &updates](uint8_t colony_level) -> bool { + colonial = colony_level; + updates[0] = true; + + return true; + }), + "is_slave", ZERO_OR_ONE, expect_bool([&slave, &updates](bool is_slave) -> bool { + if (is_slave) { + slave = true; + } else { + slave = false; + } + updates[1] = true; + + return true; + }), + "trade_goods", ZERO_OR_ONE, game_manager.get_economy_manager().get_good_manager() + .expect_good_identifier(assign_variable_callback_pointer(rgo)), + "life_rating", ZERO_OR_ONE, expect_uint([&life_rating, &updates](uint8_t rating) -> bool { + life_rating = rating; + updates[2] = true; + + return true; + }), + "terrain", ZERO_OR_ONE, game_manager.get_map().get_terrain_type_manager() + .expect_terrain_type_identifier(assign_variable_callback_pointer(terrain_type)), + "party_loyalty", ZERO_OR_MORE, [&game_manager, &party_loyalties, &updates](ast::NodeCPtr node) -> bool { + Ideology const* ideology; + uint8_t amount; // percent I do believe + + bool ret = expect_dictionary_keys( + "ideology", ONE_EXACTLY, game_manager.get_politics_manager().get_ideology_manager() + .expect_ideology_identifier(assign_variable_callback_pointer(ideology)), + "loyalty_value", ONE_EXACTLY, expect_uint(assign_variable_callback(amount)) + )(node); + party_loyalties.emplace(ideology, amount); + updates[4] = true; + return ret; + }, + "state_building", ZERO_OR_MORE, [&game_manager, &buildings, &updates](ast::NodeCPtr node) -> bool { + Building const* building; + uint8_t level; + + bool ret = expect_dictionary_keys( + "level", ONE_EXACTLY, expect_uint(assign_variable_callback(level)), + "building", ONE_EXACTLY, game_manager.get_economy_manager().get_building_manager() + .expect_building_identifier(assign_variable_callback_pointer(building)), + "upgrade", ZERO_OR_ONE, success_callback // doesn't appear to have an effect + )(node); + buildings.emplace(building, level); + updates[3] = true; + return ret; + } + )(root); + + ret &= add_province_history_entry( + game_manager.get_map().get_province_by_identifier(province), + date, + owner, + controller, + colonial, + slave, + std::move(cores), + std::move(remove_cores), + rgo, + life_rating, + terrain_type, + std::move(buildings), + std::move(party_loyalties), + updates + ); + return ret; } bool ProvinceHistoryManager::load_province_history_file(GameManager& game_manager, std::string_view name, ast::NodeCPtr root) { - bool ret = _load_province_history_entry(game_manager, name, game_manager.get_define_manager().get_start_date(), root); - - ret &= expect_dictionary( - [this, &game_manager, &name](std::string_view key, ast::NodeCPtr value) -> bool { - bool is_date = false; - Date entry = Date().from_string(key, &is_date, true); - if (!is_date) return true; - - Date const& end_date = game_manager.get_define_manager().get_end_date(); - if (entry > end_date) { - Logger::error("History entry ", entry.to_string(), " of province ", name, " defined after defined end date ", end_date.to_string()); - return false; - } - - return _load_province_history_entry(game_manager, name, entry, value); - } - )(root); - - return ret; + bool ret = _load_province_history_entry(game_manager, name, game_manager.get_define_manager().get_start_date(), root); + + ret &= expect_dictionary( + [this, &game_manager, &name](std::string_view key, ast::NodeCPtr value) -> bool { + bool is_date = false; + Date entry = Date().from_string(key, &is_date, true); + if (!is_date) return true; + + Date const& end_date = game_manager.get_define_manager().get_end_date(); + if (entry > end_date) { + Logger::error("History entry ", entry.to_string(), " of province ", name, " defined after defined end date ", + end_date.to_string()); + return false; + } + + return _load_province_history_entry(game_manager, name, entry, value); + } + )(root); + + return ret; } diff --git a/src/openvic-simulation/history/ProvinceHistory.hpp b/src/openvic-simulation/history/ProvinceHistory.hpp index 0304b2a..d4e9615 100644 --- a/src/openvic-simulation/history/ProvinceHistory.hpp +++ b/src/openvic-simulation/history/ProvinceHistory.hpp @@ -1,96 +1,99 @@ #pragma once +#include #include #include -#include -#include "openvic-simulation/map/Province.hpp" -#include "openvic-simulation/map/TerrainType.hpp" #include "openvic-simulation/country/Country.hpp" -#include "openvic-simulation/economy/Good.hpp" #include "openvic-simulation/economy/Building.hpp" +#include "openvic-simulation/economy/Good.hpp" #include "openvic-simulation/history/Bookmark.hpp" +#include "openvic-simulation/map/Province.hpp" +#include "openvic-simulation/map/TerrainType.hpp" namespace OpenVic { - struct ProvinceHistoryManager; + struct ProvinceHistoryManager; + + struct ProvinceHistory { + friend struct ProvinceHistoryManager; - struct ProvinceHistory { - friend struct ProvinceHistoryManager; + private: + Country const* owner; + Country const* controller; + uint8_t colonial; + bool slave; + std::vector cores; // non-standard, maintains cores between entries + Good const* rgo; + uint8_t life_rating; + TerrainType const* terrain_type; + std::map buildings; + std::map party_loyalties; - private: - Country const* owner; - Country const* controller; - uint8_t colonial; - bool slave; - std::vector cores; // non-standard, maintains cores between entries - Good const* rgo; - uint8_t life_rating; - TerrainType const* terrain_type; - std::map buildings; - std::map party_loyalties; + ProvinceHistory( + Country const* new_owner, + Country const* new_controller, + uint8_t new_colonial, + bool new_slave, + std::vector&& new_cores, + Good const* new_rgo, + uint8_t new_life_rating, + TerrainType const* new_terrain_type, + std::map&& new_buildings, + std::map&& new_party_loyalties + ); - ProvinceHistory( - Country const* new_owner, - Country const* new_controller, - uint8_t new_colonial, - bool new_slave, - std::vector&& new_cores, - Good const* new_rgo, - uint8_t new_life_rating, - TerrainType const* new_terrain_type, - std::map&& new_buildings, - std::map&& new_party_loyalties - ); + public: + Country const* get_owner() const; + Country const* get_controller() const; + uint8_t get_colony_status() const; // 0 = state, 1 = protectorate, 2 = colony + bool is_slave() const; + std::vector const& get_cores() const; + bool is_core_of(Country const* country) const; + Good const* get_rgo() const; + uint8_t get_life_rating() const; + TerrainType const* get_terrain_type() const; + std::map const& get_buildings() const; + std::map const& get_party_loyalties() const; + }; - public: - Country const* get_owner() const; - Country const* get_controller() const; - uint8_t get_colony_status() const; // 0 = state, 1 = protectorate, 2 = colony - bool is_slave() const; - const std::vector& get_cores() const; - bool is_core_of(Country const* country) const; - Good const* get_rgo() const; - uint8_t get_life_rating() const; - TerrainType const* get_terrain_type() const; - const std::map& get_buildings() const; - const std::map& get_party_loyalties() const; - }; + struct ProvinceHistoryManager { + private: + std::map> province_histories; + bool locked = false; - struct ProvinceHistoryManager { - private: - std::map> province_histories; - bool locked = false; + inline bool _load_province_history_entry( + GameManager& game_manager, std::string_view province, Date const& date, ast::NodeCPtr root + ); - inline bool _load_province_history_entry(GameManager& game_manager, std::string_view province, Date const& date, ast::NodeCPtr root); - - public: - ProvinceHistoryManager() {} + public: + ProvinceHistoryManager() {} - bool add_province_history_entry( - Province const* province, - Date date, - Country const* owner, - Country const* controller, - uint8_t colonial, - bool slave, - std::vector&& cores, // additive to existing entries - std::vector&& remove_cores, // existing cores that need to be removed - Good const* rgo, - uint8_t life_rating, - TerrainType const* terrain_type, - std::map&& buildings, - std::map&& party_loyalties, - std::bitset<5> updates // bitmap of updated non-pointer values, top to bottom - ); + bool add_province_history_entry( + Province const* province, + Date date, + Country const* owner, + Country const* controller, + uint8_t colonial, + bool slave, + std::vector&& cores, // additive to existing entries + std::vector&& remove_cores, // existing cores that need to be removed + Good const* rgo, + uint8_t life_rating, + TerrainType const* terrain_type, + std::map&& buildings, + std::map&& party_loyalties, + std::bitset<5> updates // bitmap of updated non-pointer values, top to bottom + ); - void lock_province_histories(); - bool is_locked() const; + void lock_province_histories(); + bool is_locked() const; - /* Returns history of province at date, if date doesn't have an entry returns closest entry before date. Return can be nullptr if an error occurs. */ - ProvinceHistory const* get_province_history(Province const* province, Date entry) const; - /* Returns history of province at bookmark date. Return can be nullptr if an error occurs. */ - inline ProvinceHistory const* get_province_history(Province const* province, Bookmark const* bookmark) const; + /* Returns history of province at date, if date doesn't have an entry returns closest entry before date. + * Return can be nullptr if an error occurs. */ + ProvinceHistory const* get_province_history(Province const* province, Date entry) const; + /* Returns history of province at bookmark date. Return can be nullptr if an error occurs. */ + inline ProvinceHistory const* get_province_history(Province const* province, Bookmark const* bookmark) const; - bool load_province_history_file(GameManager& game_manager, std::string_view name, ast::NodeCPtr root); - }; + bool load_province_history_file(GameManager& game_manager, std::string_view name, ast::NodeCPtr root); + }; } // namespace OpenVic diff --git a/src/openvic-simulation/map/Map.cpp b/src/openvic-simulation/map/Map.cpp index 13d0933..f61c326 100644 --- a/src/openvic-simulation/map/Map.cpp +++ b/src/openvic-simulation/map/Map.cpp @@ -28,13 +28,15 @@ colour_t Mapmode::get_colour(Map const& map, Province const& province) const { return colour_func ? colour_func(map, province) : NULL_COLOUR; } -Map::Map() : provinces { "provinces" }, - regions { "regions" }, - mapmodes { "mapmodes" } {} +Map::Map() + : provinces { "provinces" }, + regions { "regions" }, + mapmodes { "mapmodes" } {} bool Map::add_province(std::string_view identifier, colour_t colour) { if (provinces.size() >= max_provinces) { - Logger::error("The map's province list is full - maximum number of provinces is ", max_provinces, " (this can be at most ", Province::MAX_INDEX, ")"); + Logger::error("The map's province list is full - maximum number of provinces is ", + max_provinces, " (this can be at most ", Province::MAX_INDEX, ")"); return false; } if (identifier.empty()) { @@ -48,7 +50,8 @@ bool Map::add_province(std::string_view identifier, colour_t colour) { Province new_province { identifier, colour, static_cast(provinces.size() + 1) }; const Province::index_t index = get_index_from_colour(colour); if (index != Province::NULL_INDEX) { - Logger::error("Duplicate province colours: ", get_province_by_index(index)->to_string(), " and ", new_province.to_string()); + Logger::error("Duplicate province colours: ", get_province_by_index(index)->to_string(), + " and ", new_province.to_string()); return false; } colour_index_map[new_province.get_colour()] = new_province.get_index(); @@ -145,22 +148,28 @@ Province const* Map::get_province_by_index(Province::index_t index) const { Province::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; + if (it != colour_index_map.end()) { + return it->second; + } return Province::NULL_INDEX; } Province::index_t Map::get_province_index_at(size_t x, size_t y) const { - if (x < width && y < height) return province_shape_image[x + y * width].index; + if (x < width && y < height) { + return province_shape_image[x + y * width].index; + } return Province::NULL_INDEX; } bool Map::set_max_provinces(Province::index_t new_max_provinces) { if (new_max_provinces <= Province::NULL_INDEX) { - Logger::error("Trying to set max province count to an invalid value ", new_max_provinces, " (must be greater than ", Province::NULL_INDEX, ")"); + Logger::error("Trying to set max province count to an invalid value ", + new_max_provinces, " (must be greater than ", Province::NULL_INDEX, ")"); return false; } if (!provinces.empty() || provinces.is_locked()) { - Logger::error("Trying to set max province count to ", new_max_provinces, " after provinces have already been added and/or 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; @@ -173,7 +182,8 @@ Province::index_t Map::get_max_provinces() const { void Map::set_selected_province(Province::index_t index) { if (index > get_province_count()) { - Logger::error("Trying to set selected province to an invalid index ", index, " (max index is ", get_province_count(), ")"); + Logger::error("Trying to set selected province to an invalid index ", index, + " (max index is ", get_province_count(), ")"); selected_province = Province::NULL_INDEX; } else { selected_province = index; @@ -234,8 +244,9 @@ bool Map::generate_mapmode_colours(Mapmode::index_t index, uint8_t* target) cons mapmode = &Mapmode::ERROR_MAPMODE; } // Skip past Province::NULL_INDEX - for (size_t i = 0; i < MAPMODE_COLOUR_SIZE; ++i) + for (size_t i = 0; i < MAPMODE_COLOUR_SIZE; ++i) { *target++ = 0; + } for (Province const& province : provinces.get_items()) { const colour_t colour = mapmode->get_colour(*this, province); *target++ = (colour >> 16) & FULL_COLOUR; @@ -278,15 +289,17 @@ bool Map::setup(BuildingManager const& building_manager, PopManager const& pop_m } void Map::update_state(Date const& today) { - for (Province& province : provinces.get_items()) + for (Province& province : provinces.get_items()) { province.update_state(today); + } update_highest_province_population(); update_total_map_population(); } void Map::tick(Date const& today) { - for (Province& province : provinces.get_items()) + for (Province& province : provinces.get_items()) { province.tick(today); + } } using namespace ovdl::csv; @@ -295,8 +308,12 @@ 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; + if (i == 0 && val.empty()) { + break; + } + if (val != standard_header[i]) { + return false; + } } return true; } @@ -306,7 +323,9 @@ static bool parse_province_colour(colour_t& colour, std::array const& lines) { { 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); + Logger::error("Non-standard province definition file header - make sure this is not a province definition: ", + header); } } if (lines.size() <= 1) { @@ -393,7 +413,8 @@ bool Map::load_region_file(ast::NodeCPtr root) { for (Province& province : provinces.get_items()) { const bool region_null = province.get_region() == nullptr; if (province.get_has_region() == region_null) { - Logger::error("Province has_region / region mismatch: has_region = ", province.get_has_region(), ", region = ", province.get_region()); + Logger::error("Province has_region / region mismatch: has_region = ", + province.get_has_region(), ", region = ", province.get_region()); province.has_region = !region_null; } } @@ -426,7 +447,8 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain } 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, ")"); + Logger::error("Invalid province BMP bits per pixel: ", province_bmp.get_bits_per_pixel(), + " (expected ", expected_province_bpp, ")"); return false; } @@ -437,12 +459,14 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain } 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, ")"); + 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()); + 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; } @@ -502,7 +526,8 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain terrain_type_pixels_list[province_shape_image[idx].index - 1][&mapping->get_type()]++; } - province_shape_image[idx].terrain = mapping->get_has_texture() && terrain < terrain_type_manager.get_terrain_texture_limit() ? terrain + 1 : 0; + province_shape_image[idx].terrain = mapping->get_has_texture() + && terrain < terrain_type_manager.get_terrain_texture_limit() ? terrain + 1 : 0; } else { province_shape_image[idx].terrain = 0; } @@ -516,7 +541,8 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain size_t missing = 0; for (size_t idx = 0; idx < province_checklist.size(); ++idx) { Province* province = provinces.get_item_by_index(idx); - province->_set_terrain_type(reinterpret_cast(get_largest_item(terrain_type_pixels_list[idx]).first)); + province->_set_terrain_type(reinterpret_cast( + get_largest_item(terrain_type_pixels_list[idx]).first)); province->on_map = province_checklist[idx]; if (!province->on_map) { if (detailed_errors) { @@ -551,8 +577,9 @@ bool Map::_generate_province_adjacencies() { Province* cur = get_province_by_index(province_shape_image[x + y * width].index); if (cur != nullptr) { changed |= generate_adjacency(cur, (x + 1) % width, y); - if (y + 1 < height) + if (y + 1 < height) { changed |= generate_adjacency(cur, x, y + 1); + } } } } diff --git a/src/openvic-simulation/map/Province.cpp b/src/openvic-simulation/map/Province.cpp index 45b3987..5a7625f 100644 --- a/src/openvic-simulation/map/Province.cpp +++ b/src/openvic-simulation/map/Province.cpp @@ -76,7 +76,9 @@ void Province::reset_buildings() { bool Province::expand_building(std::string_view building_type_identifier) { BuildingInstance* building = buildings.get_item_by_identifier(building_type_identifier); - if (building == nullptr) return false; + if (building == nullptr) { + return false; + } return building->expand(); } @@ -154,14 +156,16 @@ void Province::update_pops() { } void Province::update_state(Date const& today) { - for (BuildingInstance& building : buildings.get_items()) + for (BuildingInstance& building : buildings.get_items()) { building.update_state(today); + } update_pops(); } void Province::tick(Date const& today) { - for (BuildingInstance& building : buildings.get_items()) + for (BuildingInstance& building : buildings.get_items()) { building.tick(today); + } } Province::adjacency_t::adjacency_t(Province const* province, distance_t distance, flags_t flags) @@ -179,8 +183,9 @@ Province::flags_t Province::adjacency_t::get_flags() const { bool Province::is_adjacent_to(Province const* province) { for (adjacency_t adj : adjacencies) - if (adj.province == province) + if (adj.province == province) { return true; + } return false; } @@ -190,8 +195,9 @@ bool Province::add_adjacency(Province const* province, distance_t distance, flag return false; } - if (is_adjacent_to(province)) + if (is_adjacent_to(province)) { return false; + } adjacencies.push_back({ province, distance, flags }); return true; } @@ -201,5 +207,5 @@ std::vector const& Province::get_adjacencies() const { } void Province::_set_terrain_type(TerrainType const* type) { - terrain_type = type; + terrain_type = type; } diff --git a/src/openvic-simulation/map/Region.cpp b/src/openvic-simulation/map/Region.cpp index 477dc9e..ac232df 100644 --- a/src/openvic-simulation/map/Region.cpp +++ b/src/openvic-simulation/map/Region.cpp @@ -26,7 +26,9 @@ void ProvinceSet::lock(bool log) { Logger::error("Failed to lock province set - already locked!"); } else { locked = true; - if (log) Logger::info("Locked province set with ", size(), " provinces"); + if (log) { + Logger::info("Locked province set with ", size(), " provinces"); + } } } @@ -73,6 +75,8 @@ bool Region::get_meta() const { } colour_t Region::get_colour() const { - if (empty()) return FULL_COLOUR << 16; + if (empty()) { + return FULL_COLOUR << 16; + } return get_provinces().front()->get_colour(); } diff --git a/src/openvic-simulation/map/TerrainType.hpp b/src/openvic-simulation/map/TerrainType.hpp index edda0a9..19380fe 100644 --- a/src/openvic-simulation/map/TerrainType.hpp +++ b/src/openvic-simulation/map/TerrainType.hpp @@ -32,7 +32,8 @@ namespace OpenVic { const index_t priority; const bool has_texture; - TerrainTypeMapping(std::string_view new_identifier, TerrainType const& new_type, std::vector&& new_terrain_indicies, index_t new_priority, bool new_has_texture); + TerrainTypeMapping(std::string_view new_identifier, TerrainType const& new_type, + std::vector&& new_terrain_indicies, index_t new_priority, bool new_has_texture); public: TerrainTypeMapping(TerrainTypeMapping&&) = default; diff --git a/src/openvic-simulation/military/Deployment.cpp b/src/openvic-simulation/military/Deployment.cpp index d2637b1..441142d 100644 --- a/src/openvic-simulation/military/Deployment.cpp +++ b/src/openvic-simulation/military/Deployment.cpp @@ -5,8 +5,11 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Deployment::Deployment(std::string_view new_path, std::vector&& new_armies, std::vector&& new_navies, std::vector&& new_leaders) - : HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, leaders { std::move(new_leaders) } {} +Deployment::Deployment( + std::string_view new_path, std::vector&& new_armies, + std::vector&& new_navies, std::vector&& new_leaders +) : HasIdentifier { new_path }, armies { std::move(new_armies) }, + navies { std::move(new_navies) }, leaders { std::move(new_leaders) } {} const std::vector& Deployment::get_armies() const { return armies; @@ -22,7 +25,8 @@ const std::vector& Deployment::get_leaders() const { DeploymentManager::DeploymentManager() : deployments { "deployments" } {} -bool DeploymentManager::add_deployment(std::string_view path, std::vector&& armies, std::vector&& navies, std::vector&& leaders) { +bool DeploymentManager::add_deployment(std::string_view path, std::vector&& armies, + std::vector&& navies, std::vector&& leaders) { if (path.empty()) { Logger::error("Attemped to load order of battle with no path! Something is very wrong!"); return false; @@ -42,84 +46,97 @@ bool DeploymentManager::load_oob_file(GameManager& game_manager, std::string_vie bool ret = expect_dictionary_keys_and_default( key_value_success_callback, // TODO: load SOI information "leader", ZERO_OR_MORE, [&leaders, &game_manager](ast::NodeCPtr node) -> bool { - std::string_view name; - Unit::type_t type; - Date date; - LeaderTrait const* personality; - LeaderTrait const* background; - fixed_point_t prestige = 0; - - bool ret = expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), - "date", ONE_EXACTLY, expect_identifier_or_string(expect_date_str(assign_variable_callback(date))), - "type", ONE_EXACTLY, expect_identifier([&type](std::string_view leader_type) -> bool { - if (leader_type == "land") { - type = Unit::type_t::LAND; - } else { - type = Unit::type_t::NAVAL; - } - return true; - }), - "personality", ONE_EXACTLY, game_manager.get_military_manager().get_leader_trait_manager().expect_leader_trait_identifier(assign_variable_callback_pointer(personality)), - "background", ONE_EXACTLY, game_manager.get_military_manager().get_leader_trait_manager().expect_leader_trait_identifier(assign_variable_callback_pointer(background)), - "prestige", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(prestige)), - "picture", ZERO_OR_ONE, success_callback - )(node); - - if (!personality->is_personality_trait()) { - Logger::error("Leader ", name, " has personality ", personality->get_identifier(), " which is not a personality trait!"); - return false; - } - if (!background->is_background_trait()) { - Logger::error("Leader ", name, " has background ", background->get_identifier(), " which is not a background trait!"); - return false; - } - - leaders.push_back(Leader{ std::string(name), type, date, personality, background, prestige }); - return ret; }, + std::string_view name; + Unit::type_t type; + Date date; + LeaderTrait const* personality = nullptr; + LeaderTrait const* background = nullptr; + fixed_point_t prestige = 0; + + bool ret = expect_dictionary_keys( + "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), + "date", ONE_EXACTLY, expect_identifier_or_string(expect_date_str(assign_variable_callback(date))), + "type", ONE_EXACTLY, expect_identifier([&type](std::string_view leader_type) -> bool { + if (leader_type == "land") { + type = Unit::type_t::LAND; + } else { + type = Unit::type_t::NAVAL; + } + return true; + }), + "personality", ONE_EXACTLY, game_manager.get_military_manager().get_leader_trait_manager() + .expect_leader_trait_identifier(assign_variable_callback_pointer(personality)), + "background", ONE_EXACTLY, game_manager.get_military_manager().get_leader_trait_manager() + .expect_leader_trait_identifier(assign_variable_callback_pointer(background)), + "prestige", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(prestige)), + "picture", ZERO_OR_ONE, success_callback + )(node); + + if (!personality->is_personality_trait()) { + Logger::error("Leader ", name, " has personality ", personality->get_identifier(), + " which is not a personality trait!"); + return false; + } + if (!background->is_background_trait()) { + Logger::error("Leader ", name, " has background ", background->get_identifier(), + " which is not a background trait!"); + return false; + } + + leaders.push_back(Leader{ std::string(name), type, date, personality, background, prestige }); + return ret; + }, "army", ZERO_OR_MORE, [&armies, &game_manager](ast::NodeCPtr node) -> bool { - std::string_view name; - Province const* location; - std::vector regiments; - - bool ret = expect_dictionary_keys( - "leader", ZERO_OR_MORE, success_callback, /* another paradox gem, tested in game and they don't lead the army or even show up */ - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), - "location", ONE_EXACTLY, game_manager.get_map().expect_province_identifier(assign_variable_callback_pointer(location)), - "regiment", ONE_OR_MORE, [&game_manager, ®iments](ast::NodeCPtr node) -> bool { - Regiment regiment; - bool ret = expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback_string(regiment.name), false), - "type", ONE_EXACTLY, game_manager.get_military_manager().get_unit_manager().expect_unit_identifier(assign_variable_callback_pointer(regiment.type)), - "home", ONE_EXACTLY, game_manager.get_map().expect_province_identifier(assign_variable_callback_pointer(regiment.home)) - )(node); - regiments.push_back(regiment); - return ret; - } - )(node); - armies.push_back(Army{ std::string(name), location, std::move(regiments) }); - return ret; }, + std::string_view name; + Province const* location = nullptr; + std::vector regiments; + + bool ret = expect_dictionary_keys( + /* another paradox gem, tested in game and they don't lead the army or even show up */ + "leader", ZERO_OR_MORE, success_callback, + "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), + "location", ONE_EXACTLY, + game_manager.get_map().expect_province_identifier(assign_variable_callback_pointer(location)), + "regiment", ONE_OR_MORE, [&game_manager, ®iments](ast::NodeCPtr node) -> bool { + Regiment regiment; + bool ret = expect_dictionary_keys( + "name", ONE_EXACTLY, expect_string(assign_variable_callback_string(regiment.name), false), + "type", ONE_EXACTLY, game_manager.get_military_manager().get_unit_manager() + .expect_unit_identifier(assign_variable_callback_pointer(regiment.type)), + "home", ONE_EXACTLY, game_manager.get_map() + .expect_province_identifier(assign_variable_callback_pointer(regiment.home)) + )(node); + regiments.push_back(regiment); + return ret; + } + )(node); + armies.push_back(Army{ std::string(name), location, std::move(regiments) }); + return ret; + }, "navy", ZERO_OR_MORE, [&navies, &game_manager](ast::NodeCPtr node) -> bool { - std::string_view name; - Province const* location; - std::vector ships; - - bool ret = expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), - "location", ONE_EXACTLY, game_manager.get_map().expect_province_identifier(assign_variable_callback_pointer(location)), - "ship", ONE_OR_MORE, [&game_manager, &ships](ast::NodeCPtr node) -> bool { - Ship ship; - bool ret = expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback_string(ship.name), false), - "type", ONE_EXACTLY, game_manager.get_military_manager().get_unit_manager().expect_unit_identifier(assign_variable_callback_pointer(ship.type)) - )(node); - ships.push_back(ship); - return ret; - }, - "leader", ZERO_OR_MORE, success_callback - )(node); - navies.push_back(Navy{ std::string(name), location, std::move(ships) }); - return ret; } + std::string_view name; + Province const* location = nullptr; + std::vector ships; + + bool ret = expect_dictionary_keys( + "name", ONE_EXACTLY, expect_string(assign_variable_callback(name), false), + "location", ONE_EXACTLY, + game_manager.get_map().expect_province_identifier(assign_variable_callback_pointer(location)), + "ship", ONE_OR_MORE, [&game_manager, &ships](ast::NodeCPtr node) -> bool { + Ship ship; + bool ret = expect_dictionary_keys( + "name", ONE_EXACTLY, expect_string(assign_variable_callback_string(ship.name), false), + "type", ONE_EXACTLY, game_manager.get_military_manager().get_unit_manager() + .expect_unit_identifier(assign_variable_callback_pointer(ship.type)) + )(node); + ships.push_back(ship); + return ret; + }, + "leader", ZERO_OR_MORE, success_callback + )(node); + navies.push_back(Navy{ std::string(name), location, std::move(ships) }); + return ret; + } )(root); /* need to do this for platform compatibility of identifiers */ std::string identifier = std::string { path }; diff --git a/src/openvic-simulation/military/Deployment.hpp b/src/openvic-simulation/military/Deployment.hpp index 8ec0e49..9eb0a72 100644 --- a/src/openvic-simulation/military/Deployment.hpp +++ b/src/openvic-simulation/military/Deployment.hpp @@ -56,7 +56,8 @@ namespace OpenVic { const std::vector navies; const std::vector leaders; - Deployment(std::string_view new_path, std::vector&& new_armies, std::vector&& new_navies, std::vector&& new_leaders); + Deployment(std::string_view new_path, std::vector&& new_armies, + std::vector&& new_navies, std::vector&& new_leaders); public: const std::vector& get_armies() const; @@ -71,7 +72,8 @@ namespace OpenVic { public: DeploymentManager(); - bool add_deployment(std::string_view path, std::vector&& armies, std::vector&& navies, std::vector&& leaders); + bool add_deployment(std::string_view path, std::vector&& armies, + std::vector&& navies, std::vector&& leaders); IDENTIFIER_REGISTRY_ACCESSORS(deployment); bool load_oob_file(GameManager& game_manager, std::string_view path, ast::NodeCPtr root); diff --git a/src/openvic-simulation/military/LeaderTrait.cpp b/src/openvic-simulation/military/LeaderTrait.cpp index ed21c1f..81c6ccc 100644 --- a/src/openvic-simulation/military/LeaderTrait.cpp +++ b/src/openvic-simulation/military/LeaderTrait.cpp @@ -24,7 +24,8 @@ ModifierValue const& LeaderTrait::get_modifiers() const { LeaderTraitManager::LeaderTraitManager() : leader_traits { "leader trait" } {} -bool LeaderTraitManager::add_leader_trait(std::string_view identifier, LeaderTrait::trait_type_t type, ModifierValue&& modifiers) { +bool LeaderTraitManager::add_leader_trait(std::string_view identifier, + LeaderTrait::trait_type_t type, ModifierValue&& modifiers) { if (identifier.empty()) { Logger::error("Invalid leader trait identifier - empty!"); return false; diff --git a/src/openvic-simulation/military/Unit.cpp b/src/openvic-simulation/military/Unit.cpp index 294c77f..f079ee9 100644 --- a/src/openvic-simulation/military/Unit.cpp +++ b/src/openvic-simulation/military/Unit.cpp @@ -15,8 +15,9 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Unit::Unit(std::string_view identifier, type_t type, UNIT_PARAMS) - : HasIdentifier { identifier }, icon { icon }, type { type }, sprite { sprite }, active { active }, +Unit::Unit( + std::string_view identifier, type_t type, UNIT_PARAMS +) : HasIdentifier { identifier }, icon { icon }, type { type }, sprite { sprite }, active { active }, unit_type { unit_type }, floating_flag { floating_flag }, priority { priority }, max_strength { max_strength }, default_organisation { default_organisation }, maximum_speed { maximum_speed }, weighted_value { weighted_value }, move_sound { move_sound }, select_sound { select_sound }, build_time { build_time }, build_cost { std::move(build_cost) }, @@ -90,8 +91,9 @@ Good::good_map_t const& Unit::get_supply_cost() const { return supply_cost; } -LandUnit::LandUnit(std::string_view identifier, UNIT_PARAMS, LAND_PARAMS) - : Unit { identifier, type_t::LAND, UNIT_ARGS }, primary_culture { primary_culture }, +LandUnit::LandUnit( + std::string_view identifier, UNIT_PARAMS, LAND_PARAMS +) : Unit { identifier, type_t::LAND, UNIT_ARGS }, primary_culture { primary_culture }, sprite_override { sprite_override }, sprite_mount { sprite_mount }, sprite_mount_attach_node { sprite_mount_attach_node }, reconnaissance { reconnaissance }, attack { attack }, defence { defence }, discipline { discipline }, support { support }, maneuver { maneuver }, siege { siege } {} @@ -140,10 +142,11 @@ fixed_point_t LandUnit::get_siege() const { return siege; } -NavalUnit::NavalUnit(std::string_view identifier, UNIT_PARAMS, NAVY_PARAMS) - : Unit { identifier, type_t::NAVAL, UNIT_ARGS }, naval_icon { naval_icon }, sail { sail }, +NavalUnit::NavalUnit( + std::string_view identifier, UNIT_PARAMS, NAVY_PARAMS +) : Unit { identifier, type_t::NAVAL, UNIT_ARGS }, naval_icon { naval_icon }, sail { sail }, transport { transport }, capital { capital }, colonial_points { colonial_points }, - build_overseas { build_overseas }, min_port_level { min_port_level },limit_per_port { limit_per_port }, + build_overseas { build_overseas }, min_port_level { min_port_level }, limit_per_port { limit_per_port }, supply_consumption_score { supply_consumption_score }, hull { hull }, gun_power { gun_power }, fire_range { fire_range }, evasion { evasion }, torpedo_attack { torpedo_attack } {}; @@ -248,14 +251,16 @@ bool UnitManager::load_unit_file(GoodManager const& good_manager, ast::NodeCPtr bool active = true, floating_flag = false; uint32_t priority = 0; Timespan build_time; - fixed_point_t maximum_speed = 0, max_strength = 0, default_organisation = 0, weighted_value = 0, supply_consumption = 0; + fixed_point_t maximum_speed = 0, max_strength = 0, default_organisation = 0; + fixed_point_t weighted_value = 0, supply_consumption = 0; Good::good_map_t build_cost, supply_cost; using enum Unit::type_t; static const string_map_t type_map = { { "land", LAND }, { "naval", NAVAL } }; - bool ret = expect_key("type", expect_identifier(expect_mapped_string(type_map, assign_variable_callback(type))))(value); + bool ret = + expect_key("type", expect_identifier(expect_mapped_string(type_map, assign_variable_callback(type))))(value); if (!ret) { Logger::error("Failed to read type for unit: ", key); @@ -285,65 +290,63 @@ bool UnitManager::load_unit_file(GoodManager const& good_manager, ast::NodeCPtr ); switch (type) { - case LAND: - { - bool primary_culture = false; - std::string_view sprite_override, sprite_mount, sprite_mount_attach_node; - fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, siege = 0; - - ret &= add_key_map_entries(key_map, - "primary_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(primary_culture)), - "sprite_override", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_override)), - "sprite_mount", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_mount)), - "sprite_mount_attach_node", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_mount_attach_node)), - "reconnaissance", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reconnaissance)), - "attack", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(attack)), - "defence", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(defence)), - "discipline", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discipline)), - "support", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(support)), - "maneuver", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(maneuver)), - "siege", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(siege)) - ); - - ret &= expect_dictionary_key_map(key_map)(value); - - ret &= add_land_unit(key, UNIT_ARGS, LAND_ARGS); - - return ret; - } - break; - case NAVAL: - { - Unit::icon_t naval_icon = 0; - bool sail = false, transport = false, capital = false, build_overseas = false; - uint32_t min_port_level = 0; - int32_t limit_per_port = 0; - fixed_point_t fire_range = 0, evasion = 0, supply_consumption_score = 0, hull = 0, gun_power = 0, colonial_points = 0, torpedo_attack = 0; - - ret &= add_key_map_entries(key_map, - "naval_icon", ONE_EXACTLY, expect_uint(assign_variable_callback(naval_icon)), - "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(sail)), - "transport", ZERO_OR_ONE, expect_bool(assign_variable_callback(transport)), - "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(capital)), - "colonial_points", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(colonial_points)), - "can_build_overseas", ZERO_OR_ONE, expect_bool(assign_variable_callback(build_overseas)), - "min_port_level", ONE_EXACTLY, expect_uint(assign_variable_callback(min_port_level)), - "limit_per_port", ONE_EXACTLY, expect_int(assign_variable_callback(limit_per_port)), - "supply_consumption_score", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(supply_consumption_score)), - "hull", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(hull)), - "gun_power", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gun_power)), - "fire_range", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(fire_range)), - "evasion", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(evasion)), - "torpedo_attack", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(torpedo_attack)) - ); - - ret &= expect_dictionary_key_map(key_map)(value); - - ret &= add_naval_unit(key, UNIT_ARGS, NAVY_ARGS); - - return ret; - } - break; + case LAND: { + bool primary_culture = false; + std::string_view sprite_override, sprite_mount, sprite_mount_attach_node; + fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, siege = 0; + + ret &= add_key_map_entries(key_map, + "primary_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(primary_culture)), + "sprite_override", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_override)), + "sprite_mount", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_mount)), + "sprite_mount_attach_node", ZERO_OR_ONE, expect_identifier(assign_variable_callback(sprite_mount_attach_node)), + "reconnaissance", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reconnaissance)), + "attack", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(attack)), + "defence", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(defence)), + "discipline", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discipline)), + "support", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(support)), + "maneuver", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(maneuver)), + "siege", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(siege)) + ); + + ret &= expect_dictionary_key_map(key_map)(value); + + ret &= add_land_unit(key, UNIT_ARGS, LAND_ARGS); + + return ret; + } + case NAVAL: { + Unit::icon_t naval_icon = 0; + bool sail = false, transport = false, capital = false, build_overseas = false; + uint32_t min_port_level = 0; + int32_t limit_per_port = 0; + fixed_point_t fire_range = 0, evasion = 0, supply_consumption_score = 0, hull = 0; + fixed_point_t gun_power = 0, colonial_points = 0, torpedo_attack = 0; + + ret &= add_key_map_entries(key_map, + "naval_icon", ONE_EXACTLY, expect_uint(assign_variable_callback(naval_icon)), + "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(sail)), + "transport", ZERO_OR_ONE, expect_bool(assign_variable_callback(transport)), + "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(capital)), + "colonial_points", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(colonial_points)), + "can_build_overseas", ZERO_OR_ONE, expect_bool(assign_variable_callback(build_overseas)), + "min_port_level", ONE_EXACTLY, expect_uint(assign_variable_callback(min_port_level)), + "limit_per_port", ONE_EXACTLY, expect_int(assign_variable_callback(limit_per_port)), + "supply_consumption_score", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(supply_consumption_score)), + "hull", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(hull)), + "gun_power", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gun_power)), + "fire_range", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(fire_range)), + "evasion", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(evasion)), + "torpedo_attack", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(torpedo_attack)) + ); + + ret &= expect_dictionary_key_map(key_map)(value); + + ret &= add_naval_unit(key, UNIT_ARGS, NAVY_ARGS); + + return ret; + } default: Logger::error("Unknown unit type for ", key, ": ", static_cast(type)); return false; diff --git a/src/openvic-simulation/military/Unit.hpp b/src/openvic-simulation/military/Unit.hpp index ea28511..d1dcc8f 100644 --- a/src/openvic-simulation/military/Unit.hpp +++ b/src/openvic-simulation/military/Unit.hpp @@ -11,20 +11,20 @@ #define UNIT_PARAMS \ Unit::icon_t icon, std::string_view sprite, bool active, std::string_view unit_type, \ - bool floating_flag, uint32_t priority, fixed_point_t max_strength, fixed_point_t default_organisation, \ - fixed_point_t maximum_speed, fixed_point_t weighted_value, std::string_view move_sound, \ - std::string_view select_sound, Timespan build_time, Good::good_map_t &&build_cost, \ - fixed_point_t supply_consumption, Good::good_map_t &&supply_cost + bool floating_flag, uint32_t priority, fixed_point_t max_strength, fixed_point_t default_organisation, \ + fixed_point_t maximum_speed, fixed_point_t weighted_value, std::string_view move_sound, \ + std::string_view select_sound, Timespan build_time, Good::good_map_t &&build_cost, \ + fixed_point_t supply_consumption, Good::good_map_t &&supply_cost #define LAND_PARAMS \ bool primary_culture, std::string_view sprite_override, std::string_view sprite_mount, \ - std::string_view sprite_mount_attach_node, fixed_point_t reconnaissance, fixed_point_t attack, fixed_point_t defence, \ - fixed_point_t discipline, fixed_point_t support, fixed_point_t maneuver, fixed_point_t siege + std::string_view sprite_mount_attach_node, fixed_point_t reconnaissance, fixed_point_t attack, fixed_point_t defence, \ + fixed_point_t discipline, fixed_point_t support, fixed_point_t maneuver, fixed_point_t siege #define NAVY_PARAMS \ Unit::icon_t naval_icon, bool sail, bool transport, bool capital, fixed_point_t colonial_points, bool build_overseas, \ - uint32_t min_port_level, int32_t limit_per_port, fixed_point_t supply_consumption_score, fixed_point_t hull, \ - fixed_point_t gun_power, fixed_point_t fire_range, fixed_point_t evasion, fixed_point_t torpedo_attack + uint32_t min_port_level, int32_t limit_per_port, fixed_point_t supply_consumption_score, fixed_point_t hull, \ + fixed_point_t gun_power, fixed_point_t fire_range, fixed_point_t evasion, fixed_point_t torpedo_attack namespace OpenVic { struct Unit : HasIdentifier { diff --git a/src/openvic-simulation/misc/Define.cpp b/src/openvic-simulation/misc/Define.cpp index 509b0a5..3da1f4a 100644 --- a/src/openvic-simulation/misc/Define.cpp +++ b/src/openvic-simulation/misc/Define.cpp @@ -52,14 +52,17 @@ const Date& DefineManager::get_end_date() const { } bool DefineManager::add_date_define(std::string_view name, Date date) { - if (name != "start_date" && name != "end_date") return false; + if (name != "start_date" && name != "end_date") { + return false; + } bool ret = defines.add_item({ name, date.to_string(), Define::Type::None }); - if (name == "start_date") + if (name == "start_date") { start_date.reset(new Date(date)); - else if (name == "end_date") + } else if (name == "end_date") { end_date.reset(new Date(date)); + } return ret; } @@ -67,7 +70,8 @@ bool DefineManager::add_date_define(std::string_view name, Date date) { bool DefineManager::load_defines_file(ast::NodeCPtr root) { bool ret = expect_dictionary_keys( "defines", ONE_EXACTLY, expect_dictionary([this](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "country" || key == "economy" || key == "military" || key == "diplomacy" || key == "pops" || key == "ai" || key == "graphics") { + if (key == "country" || key == "economy" || key == "military" || key == "diplomacy" + || key == "pops" || key == "ai" || key == "graphics") { return expect_dictionary([this, &key](std::string_view inner_key, ast::NodeCPtr value) -> bool { std::string str_val; @@ -76,30 +80,30 @@ bool DefineManager::load_defines_file(ast::NodeCPtr root) { Define::Type type; switch (key[0]) { using enum Define::Type; - case 'c': // country - type = Country; - break; - case 'e': // economy - type = Economy; - break; - case 'm': // military - type = Military; - break; - case 'd': // diplomacy - type = Diplomacy; - break; - case 'p': // pops - type = Pops; - break; - case 'a': // ai - type = Ai; - break; - case 'g': // graphics - type = Graphics; - break; - default: - Logger::error("Unknown define type ", key, " found in defines!"); - return false; + case 'c': // country + type = Country; + break; + case 'e': // economy + type = Economy; + break; + case 'm': // military + type = Military; + break; + case 'd': // diplomacy + type = Diplomacy; + break; + case 'p': // pops + type = Pops; + break; + case 'a': // ai + type = Ai; + break; + case 'g': // graphics + type = Graphics; + break; + default: + Logger::error("Unknown define type ", key, " found in defines!"); + return false; } ret &= add_define(inner_key, std::move(str_val), type); diff --git a/src/openvic-simulation/politics/Government.cpp b/src/openvic-simulation/politics/Government.cpp index 927c773..97b1d68 100644 --- a/src/openvic-simulation/politics/Government.cpp +++ b/src/openvic-simulation/politics/Government.cpp @@ -5,8 +5,12 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -GovernmentType::GovernmentType(std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier) - : HasIdentifier { new_identifier }, ideologies { std::move(new_ideologies) }, elections { new_elections }, appoint_ruling_party { new_appoint_ruling_party }, term_duration { new_term_duration }, flag_type_identifier { new_flag_type_identifier } {} +GovernmentType::GovernmentType( + std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, + bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier +) : HasIdentifier { new_identifier }, ideologies { std::move(new_ideologies) }, elections { new_elections }, + appoint_ruling_party { new_appoint_ruling_party }, term_duration { new_term_duration }, + flag_type_identifier { new_flag_type_identifier } {} bool GovernmentType::is_ideology_compatible(Ideology const* ideology) const { return std::find(ideologies.begin(), ideologies.end(), ideology) != ideologies.end(); @@ -34,7 +38,8 @@ std::string_view GovernmentType::get_flag_type() const { GovernmentTypeManager::GovernmentTypeManager() : government_types { "government types" } {} -bool GovernmentTypeManager::add_government_type(std::string_view identifier, std::vector&& ideologies, bool elections, bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type) { +bool GovernmentTypeManager::add_government_type(std::string_view identifier, std::vector&& ideologies, + bool elections, bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type) { if (identifier.empty()) { Logger::error("Invalid government type identifier - empty!"); return false; diff --git a/src/openvic-simulation/politics/Government.hpp b/src/openvic-simulation/politics/Government.hpp index 8cdee48..455b822 100644 --- a/src/openvic-simulation/politics/Government.hpp +++ b/src/openvic-simulation/politics/Government.hpp @@ -14,7 +14,8 @@ namespace OpenVic { const Timespan term_duration; const std::string flag_type_identifier; - GovernmentType(std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier); + GovernmentType(std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, + bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier); public: GovernmentType(GovernmentType&&) = default; @@ -34,7 +35,8 @@ namespace OpenVic { public: GovernmentTypeManager(); - bool add_government_type(std::string_view identifier, std::vector&& ideologies, bool elections, bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type); + bool add_government_type(std::string_view identifier, std::vector&& ideologies, bool elections, + bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type); IDENTIFIER_REGISTRY_ACCESSORS(government_type) bool load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/Ideology.cpp b/src/openvic-simulation/politics/Ideology.cpp index 5b2c0ef..c52d8b1 100644 --- a/src/openvic-simulation/politics/Ideology.cpp +++ b/src/openvic-simulation/politics/Ideology.cpp @@ -5,9 +5,11 @@ using namespace OpenVic::NodeTools; IdeologyGroup::IdeologyGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} -Ideology::Ideology(std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, uncivilised { new_uncivilised }, - can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date } {} +Ideology::Ideology( + std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, + bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, + uncivilised { new_uncivilised }, can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date } {} IdeologyGroup const& Ideology::get_group() const { return group; @@ -36,7 +38,8 @@ bool IdeologyManager::add_ideology_group(std::string_view identifier) { return ideology_groups.add_item({ identifier }); } -bool IdeologyManager::add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, bool can_reduce_militancy, Date spawn_date) { +bool IdeologyManager::add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, + bool uncivilised, bool can_reduce_militancy, Date spawn_date) { if (identifier.empty()) { Logger::error("Invalid ideology identifier - empty!"); return false; diff --git a/src/openvic-simulation/politics/Ideology.hpp b/src/openvic-simulation/politics/Ideology.hpp index 557333e..3cd72f4 100644 --- a/src/openvic-simulation/politics/Ideology.hpp +++ b/src/openvic-simulation/politics/Ideology.hpp @@ -25,7 +25,8 @@ namespace OpenVic { //TODO - willingness to repeal/pass reforms (and its modifiers) - Ideology(std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date); + Ideology(std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, + bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date); public: Ideology(Ideology&&) = default; @@ -47,7 +48,8 @@ namespace OpenVic { bool add_ideology_group(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS(ideology_group) - bool add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, bool can_reduce_militancy, Date spawn_date); + bool add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, + bool uncivilised, bool can_reduce_militancy, Date spawn_date); IDENTIFIER_REGISTRY_ACCESSORS_CUSTOM_PLURAL(ideology, ideologies) bool load_ideology_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/Issue.cpp b/src/openvic-simulation/politics/Issue.cpp index 3f2fd10..4f05a99 100644 --- a/src/openvic-simulation/politics/Issue.cpp +++ b/src/openvic-simulation/politics/Issue.cpp @@ -46,7 +46,7 @@ size_t Reform::get_ordinal() const { } IssueManager::IssueManager() : issue_groups { "issue groups" }, issues { "issues" }, - reform_types { "reform types" }, reform_groups { "reform groups" }, reforms { "reforms" } {} + reform_types { "reform types" }, reform_groups { "reform groups" }, reforms { "reforms" } {} bool IssueManager::add_issue_group(std::string_view identifier) { if (identifier.empty()) { @@ -120,7 +120,8 @@ bool IssueManager::_load_issue(std::string_view identifier, IssueGroup const* gr return add_issue(identifier, group); } -bool IssueManager::_load_reform_group(size_t& expected_reforms, std::string_view identifier, ReformType const* type, ast::NodeCPtr node) { +bool IssueManager::_load_reform_group(size_t& expected_reforms, std::string_view identifier, + ReformType const* type, ast::NodeCPtr node) { bool ordered = false, administrative = false; bool ret = expect_dictionary_keys_and_default( increment_callback(expected_reforms), diff --git a/src/openvic-simulation/pop/Culture.cpp b/src/openvic-simulation/pop/Culture.cpp index 85c96a0..ebac344 100644 --- a/src/openvic-simulation/pop/Culture.cpp +++ b/src/openvic-simulation/pop/Culture.cpp @@ -57,7 +57,8 @@ bool CultureManager::add_graphical_culture_type(std::string_view identifier) { return graphical_culture_types.add_item({ identifier }); } -bool CultureManager::add_culture_group(std::string_view identifier, std::string_view leader, GraphicalCultureType const* graphical_culture_type, bool is_overseas) { +bool CultureManager::add_culture_group(std::string_view identifier, std::string_view leader, + GraphicalCultureType const* graphical_culture_type, bool is_overseas) { if (!graphical_culture_types.is_locked()) { Logger::error("Cannot register culture groups until graphical culture types are locked!"); return false; @@ -77,7 +78,8 @@ bool CultureManager::add_culture_group(std::string_view identifier, std::string_ return culture_groups.add_item({ identifier, leader, *graphical_culture_type, is_overseas }); } -bool CultureManager::add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, std::vector&& first_names, std::vector&& last_names) { +bool CultureManager::add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, + std::vector&& first_names, std::vector&& last_names) { if (!culture_groups.is_locked()) { Logger::error("Cannot register cultures until culture groups are locked!"); return false; @@ -119,7 +121,8 @@ bool CultureManager::_load_culture_group(size_t& total_expected_cultures, bool ret = expect_dictionary_keys_and_default( increment_callback(total_expected_cultures), "leader", ONE_EXACTLY, expect_identifier(assign_variable_callback(leader)), - "unit", ZERO_OR_ONE, expect_graphical_culture_type_identifier(assign_variable_callback_pointer(unit_graphical_culture_type)), + "unit", ZERO_OR_ONE, + expect_graphical_culture_type_identifier(assign_variable_callback_pointer(unit_graphical_culture_type)), "union", ZERO_OR_ONE, success_callback, "is_overseas", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_overseas)) )(culture_group_node); @@ -171,7 +174,8 @@ bool CultureManager::load_culture_file(ast::NodeCPtr root) { } static const std::string default_unit_graphical_culture_type_identifier = "Generic"; - GraphicalCultureType const* const default_unit_graphical_culture_type = get_graphical_culture_type_by_identifier(default_unit_graphical_culture_type_identifier); + GraphicalCultureType const* const default_unit_graphical_culture_type = + get_graphical_culture_type_by_identifier(default_unit_graphical_culture_type_identifier); if (default_unit_graphical_culture_type == nullptr) { Logger::error("Failed to find default unit graphical culture type: ", default_unit_graphical_culture_type_identifier); } @@ -179,7 +183,8 @@ bool CultureManager::load_culture_file(ast::NodeCPtr root) { size_t total_expected_cultures = 0; bool ret = expect_dictionary_reserve_length( culture_groups, - [this, default_unit_graphical_culture_type, &total_expected_cultures](std::string_view key, ast::NodeCPtr value) -> bool { + [this, default_unit_graphical_culture_type, &total_expected_cultures]( + std::string_view key, ast::NodeCPtr value) -> bool { return _load_culture_group(total_expected_cultures, default_unit_graphical_culture_type, key, value); } )(root); diff --git a/src/openvic-simulation/pop/Culture.hpp b/src/openvic-simulation/pop/Culture.hpp index 688733e..ca70c16 100644 --- a/src/openvic-simulation/pop/Culture.hpp +++ b/src/openvic-simulation/pop/Culture.hpp @@ -26,7 +26,8 @@ namespace OpenVic { // TODO - union tag - CultureGroup(std::string_view new_identifier, std::string_view new_leader, GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas); + CultureGroup(std::string_view new_identifier, std::string_view new_leader, + GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas); public: CultureGroup(CultureGroup&&) = default; @@ -45,7 +46,8 @@ namespace OpenVic { // TODO - radicalism, primary tag - Culture(std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, std::vector&& new_first_names, std::vector&& new_last_names); + Culture(std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, + std::vector&& new_first_names, std::vector&& new_last_names); public: Culture(Culture&&) = default; @@ -71,10 +73,12 @@ namespace OpenVic { bool add_graphical_culture_type(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS(graphical_culture_type) - bool add_culture_group(std::string_view identifier, std::string_view leader, GraphicalCultureType const* new_graphical_culture_type, bool is_overseas); + bool add_culture_group(std::string_view identifier, std::string_view leader, + GraphicalCultureType const* new_graphical_culture_type, bool is_overseas); IDENTIFIER_REGISTRY_ACCESSORS(culture_group) - bool add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, std::vector&& first_names, std::vector&& last_names); + bool add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, + std::vector&& first_names, std::vector&& last_names); IDENTIFIER_REGISTRY_ACCESSORS(culture) bool load_graphical_culture_type_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/pop/Pop.cpp b/src/openvic-simulation/pop/Pop.cpp index 5286393..761e5ff 100644 --- a/src/openvic-simulation/pop/Pop.cpp +++ b/src/openvic-simulation/pop/Pop.cpp @@ -147,15 +147,17 @@ bool PopManager::add_pop_type(std::string_view identifier, colour_t colour, PopT Logger::error("Invalid pop type merge max size for ", identifier, ": ", merge_max_size); return false; } - return pop_types.add_item({ identifier, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), - std::move(luxury_needs), std::move(rebel_units), max_size, merge_max_size, state_capital_only, demote_migrant, - is_artisan, is_slave }); + return pop_types.add_item({ + identifier, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), std::move(luxury_needs), + std::move(rebel_units), max_size, merge_max_size, state_capital_only, demote_migrant, is_artisan, is_slave + }); } /* REQUIREMENTS: * POP-3, POP-4, POP-5, POP-6, POP-7, POP-8, POP-9, POP-10, POP-11, POP-12, POP-13, POP-14 */ -bool PopManager::load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, GoodManager const& good_manager, ast::NodeCPtr root) { +bool PopManager::load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, + GoodManager const& good_manager, ast::NodeCPtr root) { static const string_map_t strata_map = { { "poor", PopType::strata_t::POOR }, { "middle", PopType::strata_t::MIDDLE }, @@ -209,13 +211,15 @@ bool PopManager::load_pop_type_file(std::string_view filestem, UnitManager const "unemployment", ZERO_OR_ONE, success_callback )(root); - ret &= add_pop_type(filestem, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), - std::move(luxury_needs), std::move(rebel_units), max_size, merge_max_size, state_capital_only, demote_migrant, - is_artisan, is_slave); + ret &= add_pop_type( + filestem, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), std::move(luxury_needs), + std::move(rebel_units), max_size, merge_max_size, state_capital_only, demote_migrant, is_artisan, is_slave + ); return ret; } -bool PopManager::load_pop_into_province(Province& province, std::string_view pop_type_identifier, ast::NodeCPtr pop_node) const { +bool PopManager::load_pop_into_province(Province& province, std::string_view pop_type_identifier, + ast::NodeCPtr pop_node) const { PopType const* type = get_pop_type_by_identifier(pop_type_identifier); Culture const* culture = nullptr; Religion const* religion = nullptr; @@ -231,7 +235,8 @@ bool PopManager::load_pop_into_province(Province& province, std::string_view pop if (type != nullptr && culture != nullptr && religion != nullptr && size > 0) { ret &= province.add_pop({ *type, *culture, *religion, size }); } else { - Logger::warning("Some pop arguments are invalid: province = ", province, ", type = ", type, ", culture = ", culture, ", religion = ", religion, ", size = ", size); + Logger::warning("Some pop arguments are invalid: province = ", province, ", type = ", type, + ", culture = ", culture, ", religion = ", religion, ", size = ", size); } return ret; } diff --git a/src/openvic-simulation/pop/Pop.hpp b/src/openvic-simulation/pop/Pop.hpp index 7261831..cba9f3c 100644 --- a/src/openvic-simulation/pop/Pop.hpp +++ b/src/openvic-simulation/pop/Pop.hpp @@ -108,7 +108,8 @@ namespace OpenVic { bool state_capital_only, bool demote_migrant, bool is_artisan, bool is_slave); IDENTIFIER_REGISTRY_ACCESSORS(pop_type) - bool load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, GoodManager const& good_manager, ast::NodeCPtr root); + bool load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, + GoodManager const& good_manager, ast::NodeCPtr root); bool load_pop_into_province(Province& province, std::string_view pop_type_identifier, ast::NodeCPtr pop_node) const; }; } diff --git a/src/openvic-simulation/pop/Religion.cpp b/src/openvic-simulation/pop/Religion.cpp index 1152ae5..a685fca 100644 --- a/src/openvic-simulation/pop/Religion.cpp +++ b/src/openvic-simulation/pop/Religion.cpp @@ -40,7 +40,8 @@ bool ReligionManager::add_religion_group(std::string_view identifier) { return religion_groups.add_item({ identifier }); } -bool ReligionManager::add_religion(std::string_view identifier, colour_t colour, ReligionGroup const* group, Religion::icon_t icon, bool pagan) { +bool ReligionManager::add_religion(std::string_view identifier, colour_t colour, + ReligionGroup const* group, Religion::icon_t icon, bool pagan) { if (!religion_groups.is_locked()) { Logger::error("Cannot register religions until religion groups are locked!"); return false; diff --git a/src/openvic-simulation/testing/Requirement.cpp b/src/openvic-simulation/testing/Requirement.cpp index d99153a..be4138d 100644 --- a/src/openvic-simulation/testing/Requirement.cpp +++ b/src/openvic-simulation/testing/Requirement.cpp @@ -3,22 +3,48 @@ using namespace OpenVic; // Getters -std::string Requirement::get_id() { return id; } -std::string Requirement::get_text() { return text; } -std::string Requirement::get_acceptance_criteria() { return acceptance_criteria; } -bool Requirement::get_pass() { return pass; } -bool Requirement::get_tested() { return tested; } -std::string Requirement::get_target_value() { return target_value; } -std::string Requirement::get_actual_value() { return actual_value; } +std::string Requirement::get_id() { + return id; +} +std::string Requirement::get_text() { + return text; +} +std::string Requirement::get_acceptance_criteria() { + return acceptance_criteria; +} +bool Requirement::get_pass() { + return pass; +} +bool Requirement::get_tested() { + return tested; +} +std::string Requirement::get_target_value() { + return target_value; +} +std::string Requirement::get_actual_value() { + return actual_value; +} // Setters -void Requirement::set_id(std::string in_id) { id = in_id; } -void Requirement::set_text(std::string in_text) { text = in_text; } -void Requirement::set_acceptance_criteria(std::string in_acceptance_criteria) { acceptance_criteria = in_acceptance_criteria; } +void Requirement::set_id(std::string in_id) { + id = in_id; +} +void Requirement::set_text(std::string in_text) { + text = in_text; +} +void Requirement::set_acceptance_criteria(std::string in_acceptance_criteria) { + acceptance_criteria = in_acceptance_criteria; +} void Requirement::set_pass(bool in_pass) { pass = in_pass; set_tested(true); // Ever setting a pass condition implies it has been tested } -void Requirement::set_tested(bool in_tested) { tested = in_tested; } -void Requirement::set_target_value(std::string in_target_value) { target_value = in_target_value; } -void Requirement::set_actual_value(std::string in_actual_value) { actual_value = in_actual_value; } +void Requirement::set_tested(bool in_tested) { + tested = in_tested; +} +void Requirement::set_target_value(std::string in_target_value) { + target_value = in_target_value; +} +void Requirement::set_actual_value(std::string in_actual_value) { + actual_value = in_actual_value; +} diff --git a/src/openvic-simulation/testing/TestScript.cpp b/src/openvic-simulation/testing/TestScript.cpp index 0a9ce6f..d08f34c 100644 --- a/src/openvic-simulation/testing/TestScript.cpp +++ b/src/openvic-simulation/testing/TestScript.cpp @@ -3,49 +3,77 @@ using namespace OpenVic; // Getters -std::vector TestScript::get_requirements() { return requirements; } -Requirement* TestScript::get_requirement_at_index(int index) { return requirements[index]; } +std::vector TestScript::get_requirements() { + return requirements; +} +Requirement* TestScript::get_requirement_at_index(int index) { + return requirements[index]; +} Requirement* TestScript::get_requirement_by_id(std::string id) { for (auto req : requirements) { - if (req->get_id() == id) return req; + if (req->get_id() == id) { + return req; + } } return new Requirement("NULL", "NULL", "NULL"); // edge case of failing to find } std::vector TestScript::get_passed_requirements() { std::vector passed_requirements = std::vector(); for (auto req : requirements) { - if (req->get_pass()) passed_requirements.push_back(req); + if (req->get_pass()) { + passed_requirements.push_back(req); + } } return passed_requirements; } std::vector TestScript::get_failed_requirements() { std::vector failed_requirements = std::vector(); for (auto req : requirements) { - if (!req->get_pass() && req->get_tested()) failed_requirements.push_back(req); + if (!req->get_pass() && req->get_tested()) { + failed_requirements.push_back(req); + } } return failed_requirements; } std::vector TestScript::get_untested_requirements() { std::vector untested_requirements = std::vector(); - for (auto req : requirements) { - if (!req->get_tested()) untested_requirements.push_back(req); + for (auto req : requirements) { + if (!req->get_tested()) { + untested_requirements.push_back(req); + } } return untested_requirements; } -GameManager* TestScript::get_game_manager() { return game_manager; } -std::string TestScript::get_script_name() { return script_name; } +GameManager* TestScript::get_game_manager() { + return game_manager; +} +std::string TestScript::get_script_name() { + return script_name; +} // Setters -void TestScript::set_requirements(std::vector in_requirements) { requirements = in_requirements; } -void TestScript::add_requirement(Requirement* req) { requirements.push_back(req); } -void TestScript::set_game_manager(GameManager* in_game_manager) { game_manager = in_game_manager; } -void TestScript::set_script_name(std::string in_script_name) { script_name = in_script_name; } +void TestScript::set_requirements(std::vector in_requirements) { + requirements = in_requirements; +} +void TestScript::add_requirement(Requirement* req) { + requirements.push_back(req); +} +void TestScript::set_game_manager(GameManager* in_game_manager) { + game_manager = in_game_manager; +} +void TestScript::set_script_name(std::string in_script_name) { + script_name = in_script_name; +} // Methods -void TestScript::pass_or_fail_req_with_actual_and_target_values(std::string req_name, std::string target_value, std::string actual_value) { +void TestScript::pass_or_fail_req_with_actual_and_target_values(std::string req_name, std::string target_value, + std::string actual_value) { Requirement* req = get_requirement_by_id(req_name); req->set_target_value(target_value); req->set_actual_value(actual_value); - if (target_value == actual_value) req->set_pass(true); - else req->set_pass(false); + if (target_value == actual_value) { + req->set_pass(true); + } else { + req->set_pass(false); + } } diff --git a/src/openvic-simulation/testing/Testing.cpp b/src/openvic-simulation/testing/Testing.cpp index 42df80c..883c4f6 100644 --- a/src/openvic-simulation/testing/Testing.cpp +++ b/src/openvic-simulation/testing/Testing.cpp @@ -54,7 +54,7 @@ void Testing::report_results() { report_result("Failed Requirements", test_results, failed_reqs); report_result("Untested Requirements", test_results, untested_reqs); - test_results << std::endl<< std::endl; + test_results << std::endl << std::endl; } test_results.close(); } @@ -65,6 +65,8 @@ void Testing::report_result(std::string req_title, std::ofstream& outfile, std:: for (auto req : reqs) { outfile << req->get_id() << " "; } - if (reqs.size() < 1) outfile << "None"; + if (reqs.size() < 1) { + outfile << "None"; + } outfile << std::endl << std::endl; } diff --git a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp index 4a16c31..c79e602 100644 --- a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp @@ -12,84 +12,84 @@ namespace OpenVic { void add_requirements() { Requirement* FS_44 = new Requirement("FS_44", - "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename Canned Food.png", - "The icon for the Canned Food good has been loaded into the program"); + "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename Canned Food.png", + "The icon for the Canned Food good has been loaded into the program"); add_requirement(FS_44); Requirement* FS_48 = new Requirement("FS_48", - "The icon for the Coal good shall be loaded from the R/art/economy/goods folder with the filename Coal.png", - "The icon for the Coal good has been loaded into the program"); + "The icon for the Coal good shall be loaded from the R/art/economy/goods folder with the filename Coal.png", + "The icon for the Coal good has been loaded into the program"); add_requirement(FS_48); Requirement* FS_61 = new Requirement("FS_61", - "The icon for the Grain good shall be loaded from the R/art/economy/goods folder with the filename Grain.png", - "The icon for the Grain good has been loaded into the program"); + "The icon for the Grain good shall be loaded from the R/art/economy/goods folder with the filename Grain.png", + "The icon for the Grain good has been loaded into the program"); add_requirement(FS_61); Requirement* FS_62 = new Requirement("FS_62", - "The icon for the Iron good shall be loaded from the R/art/economy/goods folder with the filename Iron.png", - "The icon for the Iron good has been loaded into the program"); + "The icon for the Iron good shall be loaded from the R/art/economy/goods folder with the filename Iron.png", + "The icon for the Iron good has been loaded into the program"); add_requirement(FS_62); Requirement* FS_63 = new Requirement("FS_63", - "The icon for the Liquor good shall be loaded from the R/art/economy/goods folder with the filename Liquor.png", - "The icon for the Liquor good has been loaded into the program"); + "The icon for the Liquor good shall be loaded from the R/art/economy/goods folder with the filename Liquor.png", + "The icon for the Liquor good has been loaded into the program"); add_requirement(FS_63); Requirement* FS_67 = new Requirement("FS_67", - "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename Machine Parts.png", - "The icon for the Machine Parts good has been loaded into the program"); + "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename Machine Parts.png", + "The icon for the Machine Parts good has been loaded into the program"); add_requirement(FS_67); Requirement* FS_86 = new Requirement("FS_86", - "The icon for the Wool good shall be loaded from the R/art/economy/goods folder with the filename Wool.png", - "The icon for the Wool good has been loaded into the program"); + "The icon for the Wool good shall be loaded from the R/art/economy/goods folder with the filename Wool.png", + "The icon for the Wool good has been loaded into the program"); add_requirement(FS_86); Requirement* FS_2 = new Requirement("FS_2", - "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", - "User data is saved to the correct place"); + "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", + "User data is saved to the correct place"); add_requirement(FS_2); Requirement* FS_20 = new Requirement("FS_20", - "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", - "User data is saved to the correct place"); + "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", + "User data is saved to the correct place"); add_requirement(FS_20); Requirement* FS_21 = new Requirement("FS_21", - "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", - "User data is saved to the correct place"); + "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", + "User data is saved to the correct place"); add_requirement(FS_21); Requirement* FS_22 = new Requirement("FS_22", - "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", - "User data is saved to the correct place"); + "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", + "User data is saved to the correct place"); add_requirement(FS_22); Requirement* FS_24 = new Requirement("FS_24", - "All .csv files in the locale folder shall contain translation keys and translations", - "No errant files in locale directory"); + "All .csv files in the locale folder shall contain translation keys and translations", + "No errant files in locale directory"); add_requirement(FS_24); Requirement* FS_17 = new Requirement("FS_17", - "List of available locales are loaded from R/localisation/ directory", - "Locales loaded correctly"); + "List of available locales are loaded from R/localisation/ directory", + "Locales loaded correctly"); add_requirement(FS_17); Requirement* FS_333 = new Requirement("FS_333", - "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", - "The unique colours of 'R/map/provinces.bmp' define provinces"); + "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", + "The unique colours of 'R/map/provinces.bmp' define provinces"); add_requirement(FS_333); Requirement* FS_335 = new Requirement("FS_335", - "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", - "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID"); + "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", + "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID"); add_requirement(FS_335); Requirement* FS_334 = new Requirement("FS_334", - "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", - "'R/map/default.map' contains a list of province IDs which are used to define water provinces"); + "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", + "'R/map/default.map' contains a list of province IDs which are used to define water provinces"); add_requirement(FS_334); Requirement* FS_338 = new Requirement("FS_338", - "The image for the minimap background shall be loaded from the R/art/ui folder with the filename minimap.png", - "The image for the minimap background has been loaded into the program"); + "The image for the minimap background shall be loaded from the R/art/ui folder with the filename minimap.png", + "The image for the minimap background has been loaded into the program"); add_requirement(FS_338); Requirement* FS_343 = new Requirement("FS_343", - "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", - "The textures making up the cosmetic terrain map have been loaded into the program"); + "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", + "The textures making up the cosmetic terrain map have been loaded into the program"); add_requirement(FS_343); Requirement* FS_341 = new Requirement("FS_341", - "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", - "'R/map/region.txt' defines state areas with lists of province IDs"); + "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", + "'R/map/region.txt' defines state areas with lists of province IDs"); add_requirement(FS_341); Requirement* SND_10 = new Requirement("SND_10", - "SFX shall be refered to by their filename, without the extension", - "Sound effects are identified by their filename without extension"); + "SFX shall be refered to by their filename, without the extension", + "Sound effects are identified by their filename without extension"); add_requirement(SND_10); } diff --git a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp index d1a857f..5e1f317 100644 --- a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp @@ -12,196 +12,196 @@ namespace OpenVic { void add_requirements() { Requirement* ECON_123 = new Requirement("ECON_123", - "The base price for Aeroplanes shall be 110", - "The base price of 110 for Aeroplanes can be seen in program output data"); + "The base price for Aeroplanes shall be 110", + "The base price of 110 for Aeroplanes can be seen in program output data"); add_requirement(ECON_123); Requirement* ECON_124 = new Requirement("ECON_124", - "The base price for Ammunition shall be 17.5", - "The base price of 17.5 for Ammunition can be seen in program output data"); + "The base price for Ammunition shall be 17.5", + "The base price of 17.5 for Ammunition can be seen in program output data"); add_requirement(ECON_124); Requirement* ECON_125 = new Requirement("ECON_125", - "The base price for Artillery shall be 60", - "The base price of 60 for Artillery can be seen in program output data"); + "The base price for Artillery shall be 60", + "The base price of 60 for Artillery can be seen in program output data"); add_requirement(ECON_125); Requirement* ECON_126 = new Requirement("ECON_126", - "The base price for Automobiles shall be 70", - "The base price of 70 for Automobiles can be seen in program output data"); + "The base price for Automobiles shall be 70", + "The base price of 70 for Automobiles can be seen in program output data"); add_requirement(ECON_126); Requirement* ECON_127 = new Requirement("ECON_127", - "The base price for Canned Food shall be 16", - "The base price of 16 for Canned Food can be seen in program output data"); + "The base price for Canned Food shall be 16", + "The base price of 16 for Canned Food can be seen in program output data"); add_requirement(ECON_127); Requirement* ECON_128 = new Requirement("ECON_128", - "The base price for Cattle shall be 2", - "The base price of 2 for Cattle can be seen in program output data"); + "The base price for Cattle shall be 2", + "The base price of 2 for Cattle can be seen in program output data"); add_requirement(ECON_128); Requirement* ECON_129 = new Requirement("ECON_129", - "The base price for Cement shall be 16", - "The base price of 16 for Cement can be seen in program output data"); + "The base price for Cement shall be 16", + "The base price of 16 for Cement can be seen in program output data"); add_requirement(ECON_129); Requirement* ECON_130 = new Requirement("ECON_130", - "The base price for Clipper Convoys shall be 42", - "The base price of 42 for Clipper Convoys can be seen in program output data"); + "The base price for Clipper Convoys shall be 42", + "The base price of 42 for Clipper Convoys can be seen in program output data"); add_requirement(ECON_130); Requirement* ECON_131 = new Requirement("ECON_131", - "The base price for Coal shall be 2.3", - "The base price of 2.3 for Coal can be seen in program output data"); + "The base price for Coal shall be 2.3", + "The base price of 2.3 for Coal can be seen in program output data"); add_requirement(ECON_131); Requirement* ECON_132 = new Requirement("ECON_132", - "The base price for Coffee shall be 2.1", - "The base price of 2.1 for Coffee can be seen in program output data"); + "The base price for Coffee shall be 2.1", + "The base price of 2.1 for Coffee can be seen in program output data"); add_requirement(ECON_132); Requirement* ECON_133 = new Requirement("ECON_133", - "The base price for Cotton shall be 2", - "The base price of 2 for Cotton can be seen in program output data"); + "The base price for Cotton shall be 2", + "The base price of 2 for Cotton can be seen in program output data"); add_requirement(ECON_133); Requirement* ECON_134 = new Requirement("ECON_134", - "The base price for Dye shall be 12", - "The base price of 12 for Dye can be seen in program output data"); + "The base price for Dye shall be 12", + "The base price of 12 for Dye can be seen in program output data"); add_requirement(ECON_134); Requirement* ECON_135 = new Requirement("ECON_135", - "The base price for Electric Gear shall be 16", - "The base price of 16 for Electric Gear can be seen in program output data"); + "The base price for Electric Gear shall be 16", + "The base price of 16 for Electric Gear can be seen in program output data"); add_requirement(ECON_135); Requirement* ECON_136 = new Requirement("ECON_136", - "The base price for Explosives shall be 20", - "The base price of 20 for Explosives can be seen in program output data"); + "The base price for Explosives shall be 20", + "The base price of 20 for Explosives can be seen in program output data"); add_requirement(ECON_136); Requirement* ECON_137 = new Requirement("ECON_137", - "The base price for Fabric shall be 1.8", - "The base price of 1.8 for Fabric can be seen in program output data"); + "The base price for Fabric shall be 1.8", + "The base price of 1.8 for Fabric can be seen in program output data"); add_requirement(ECON_137); Requirement* ECON_138 = new Requirement("ECON_138", - "The base price for Fertilizer shall be 10", - "The base price of 10 for Fertilizer can be seen in program output data"); + "The base price for Fertilizer shall be 10", + "The base price of 10 for Fertilizer can be seen in program output data"); add_requirement(ECON_138); Requirement* ECON_139 = new Requirement("ECON_139", - "The base price for Fish shall be 1.5", - "The base price of 1.5 for Fish can be seen in program output data"); + "The base price for Fish shall be 1.5", + "The base price of 1.5 for Fish can be seen in program output data"); add_requirement(ECON_139); Requirement* ECON_140 = new Requirement("ECON_140", - "The base price for Fruit shall be 1.8", - "The base price of 1.8 for Fruit can be seen in program output data"); + "The base price for Fruit shall be 1.8", + "The base price of 1.8 for Fruit can be seen in program output data"); add_requirement(ECON_140); Requirement* ECON_141 = new Requirement("ECON_141", - "The base price for Fuel shall be 25", - "The base price of 25 for Fuel can be seen in program output data"); + "The base price for Fuel shall be 25", + "The base price of 25 for Fuel can be seen in program output data"); add_requirement(ECON_141); Requirement* ECON_142 = new Requirement("ECON_142", - "The base price for Furniture shall be 4.9", - "The base price of 4.9 for Furniture can be seen in program output data"); + "The base price for Furniture shall be 4.9", + "The base price of 4.9 for Furniture can be seen in program output data"); add_requirement(ECON_142); Requirement* ECON_234 = new Requirement("ECON_234", - "The base price for Glass shall be 2.9", - "The base price of 2.9 for Glass can be seen in program output data"); + "The base price for Glass shall be 2.9", + "The base price of 2.9 for Glass can be seen in program output data"); add_requirement(ECON_234); Requirement* ECON_235 = new Requirement("ECON_235", - "The base price for Grain shall be 2.2", - "The base price of 2.2 for Grain can be seen in program output data"); + "The base price for Grain shall be 2.2", + "The base price of 2.2 for Grain can be seen in program output data"); add_requirement(ECON_235); Requirement* ECON_236 = new Requirement("ECON_236", - "The base price for Iron shall be 3.5", - "The base price of 3.5 for Iron can be seen in program output data"); + "The base price for Iron shall be 3.5", + "The base price of 3.5 for Iron can be seen in program output data"); add_requirement(ECON_236); Requirement* ECON_237 = new Requirement("ECON_237", - "The base price for Liquor shall be 6.4", - "The base price of 6.4 for Liquor can be seen in program output data"); + "The base price for Liquor shall be 6.4", + "The base price of 6.4 for Liquor can be seen in program output data"); add_requirement(ECON_237); Requirement* ECON_238 = new Requirement("ECON_238", - "The base price for Lumber shall be 1", - "The base price of 1 for Lumber can be seen in program output data"); + "The base price for Lumber shall be 1", + "The base price of 1 for Lumber can be seen in program output data"); add_requirement(ECON_238); Requirement* ECON_239 = new Requirement("ECON_239", - "The base price for Luxury Clothes shall be 65", - "The base price of 65 for Luxury Clothes can be seen in program output data"); + "The base price for Luxury Clothes shall be 65", + "The base price of 65 for Luxury Clothes can be seen in program output data"); add_requirement(ECON_239); Requirement* ECON_240 = new Requirement("ECON_240", - "The base price for Luxury Furniture shall be 59", - "The base price of 59 for Luxury Furniture can be seen in program output data"); + "The base price for Luxury Furniture shall be 59", + "The base price of 59 for Luxury Furniture can be seen in program output data"); add_requirement(ECON_240); Requirement* ECON_241 = new Requirement("ECON_241", - "The base price for Machine Parts shall be 36.5", - "The base price of 36.5 for Machine Parts can be seen in program output data"); + "The base price for Machine Parts shall be 36.5", + "The base price of 36.5 for Machine Parts can be seen in program output data"); add_requirement(ECON_241); Requirement* ECON_242 = new Requirement("ECON_242", - "The base price for Oil shall be 12", - "The base price of 12 for Oil can be seen in program output data"); + "The base price for Oil shall be 12", + "The base price of 12 for Oil can be seen in program output data"); add_requirement(ECON_242); Requirement* ECON_243 = new Requirement("ECON_243", - "The base price for Opium shall be 3.2", - "The base price of 3.2 for Opium can be seen in program output data"); + "The base price for Opium shall be 3.2", + "The base price of 3.2 for Opium can be seen in program output data"); add_requirement(ECON_243); Requirement* ECON_244 = new Requirement("ECON_244", - "The base price for Paper shall be 3.4", - "The base price of 3.4 for Paper can be seen in program output data"); + "The base price for Paper shall be 3.4", + "The base price of 3.4 for Paper can be seen in program output data"); add_requirement(ECON_244); Requirement* ECON_245 = new Requirement("ECON_245", - "The base price for Precious Metal shall be 8", - "The base price of 8 for Precious Metal can be seen in program output data"); + "The base price for Precious Metal shall be 8", + "The base price of 8 for Precious Metal can be seen in program output data"); add_requirement(ECON_245); Requirement* ECON_246 = new Requirement("ECON_246", - "The base price for Radios shall be 16", - "The base price of 16 for Radios can be seen in program output data"); + "The base price for Radios shall be 16", + "The base price of 16 for Radios can be seen in program output data"); add_requirement(ECON_246); Requirement* ECON_247 = new Requirement("ECON_247", - "The base price for Regular Clothes shall be 5.8", - "The base price of 5.8 for Regular Clothes can be seen in program output data"); + "The base price for Regular Clothes shall be 5.8", + "The base price of 5.8 for Regular Clothes can be seen in program output data"); add_requirement(ECON_247); Requirement* ECON_248 = new Requirement("ECON_248", - "The base price for Rubber shall be 7", - "The base price of 7 for Rubber can be seen in program output data"); + "The base price for Rubber shall be 7", + "The base price of 7 for Rubber can be seen in program output data"); add_requirement(ECON_248); Requirement* ECON_249 = new Requirement("ECON_249", - "The base price for Silk shall be 10", - "The base price of 10 for Silk can be seen in program output data"); + "The base price for Silk shall be 10", + "The base price of 10 for Silk can be seen in program output data"); add_requirement(ECON_249); Requirement* ECON_250 = new Requirement("ECON_250", - "The base price for Small Arms shall be 37", - "The base price of 37 for Small Arms can be seen in program output data"); + "The base price for Small Arms shall be 37", + "The base price of 37 for Small Arms can be seen in program output data"); add_requirement(ECON_250); Requirement* ECON_251 = new Requirement("ECON_251", - "The base price for Steamer Convoys shall be 65", - "The base price of 65 for Steamer Convoys can be seen in program output data"); + "The base price for Steamer Convoys shall be 65", + "The base price of 65 for Steamer Convoys can be seen in program output data"); add_requirement(ECON_251); Requirement* ECON_252 = new Requirement("ECON_252", - "The base price for Steel shall be 4.7", - "The base price of 4.7 for Steel can be seen in program output data"); + "The base price for Steel shall be 4.7", + "The base price of 4.7 for Steel can be seen in program output data"); add_requirement(ECON_252); Requirement* ECON_253 = new Requirement("ECON_253", - "The base price for Sulphur shall be 6", - "The base price of 6 for Sulphur can be seen in program output data"); + "The base price for Sulphur shall be 6", + "The base price of 6 for Sulphur can be seen in program output data"); add_requirement(ECON_253); Requirement* ECON_254 = new Requirement("ECON_254", - "The base price for Tanks shall be 98", - "The base price of 98 for Tanks can be seen in program output data"); + "The base price for Tanks shall be 98", + "The base price of 98 for Tanks can be seen in program output data"); add_requirement(ECON_254); Requirement* ECON_255 = new Requirement("ECON_255", - "The base price for Tea shall be 2.6", - "The base price of 2.6 for Tea can be seen in program output data"); + "The base price for Tea shall be 2.6", + "The base price of 2.6 for Tea can be seen in program output data"); add_requirement(ECON_255); Requirement* ECON_256 = new Requirement("ECON_256", - "The base price for Telephones shall be 16", - "The base price of 16 for Telephones can be seen in program output data"); + "The base price for Telephones shall be 16", + "The base price of 16 for Telephones can be seen in program output data"); add_requirement(ECON_256); Requirement* ECON_257 = new Requirement("ECON_257", - "The base price for Timber shall be 0.9", - "The base price of 0.9 for Timber can be seen in program output data"); + "The base price for Timber shall be 0.9", + "The base price of 0.9 for Timber can be seen in program output data"); add_requirement(ECON_257); Requirement* ECON_258 = new Requirement("ECON_258", - "The base price for Tobacco shall be 1.1", - "The base price of 1.1 for Tobacco can be seen in program output data"); + "The base price for Tobacco shall be 1.1", + "The base price of 1.1 for Tobacco can be seen in program output data"); add_requirement(ECON_258); Requirement* ECON_259 = new Requirement("ECON_259", - "The base price for Tropical Wood shall be 5.4", - "The base price of 5.4 for Tropical Wood can be seen in program output data"); + "The base price for Tropical Wood shall be 5.4", + "The base price of 5.4 for Tropical Wood can be seen in program output data"); add_requirement(ECON_259); Requirement* ECON_260 = new Requirement("ECON_260", - "The base price for Wine shall be 9.7", - "The base price of 9.7 for Wine can be seen in program output data"); + "The base price for Wine shall be 9.7", + "The base price of 9.7 for Wine can be seen in program output data"); add_requirement(ECON_260); Requirement* ECON_261 = new Requirement("ECON_261", - "The base price for Wool shall be 0.7", - "The base price of 0.7 for Wool can be seen in program output data"); + "The base price for Wool shall be 0.7", + "The base price of 0.7 for Wool can be seen in program output data"); add_requirement(ECON_261); } @@ -505,9 +505,11 @@ namespace OpenVic { void check_base_price(std::string identifier, std::string target_value, std::string req_name) { // Get string of base_price from goods manager - fixed_point_t base_price_fp = get_game_manager()->get_economy_manager().get_good_manager().get_good_by_identifier(identifier)->get_base_price(); + fixed_point_t base_price_fp = get_game_manager()->get_economy_manager().get_good_manager() + .get_good_by_identifier(identifier)->get_base_price(); std::stringstream ss; - ss << std::fixed << std::setprecision(1) << base_price_fp.to_double(); // Use a single digit floating point of the value + // Use a single digit floating point of the value + ss << std::fixed << std::setprecision(1) << base_price_fp.to_double(); std::string base_price = ss.str(); // Perform req checks diff --git a/src/openvic-simulation/types/Colour.hpp b/src/openvic-simulation/types/Colour.hpp index 15c574f..e516d5b 100644 --- a/src/openvic-simulation/types/Colour.hpp +++ b/src/openvic-simulation/types/Colour.hpp @@ -15,8 +15,8 @@ namespace OpenVic { * When colour_t is used in a purely graphical context, NULL_COLOUR * should be allowed. */ - static constexpr colour_t NULL_COLOUR = 0, FULL_COLOUR = 0xFF, - MAX_COLOUR_RGB = 0xFFFFFF, MAX_COLOUR_ARGB = 0xFFFFFFFF; + static constexpr colour_t NULL_COLOUR = 0, FULL_COLOUR = 0xFF; + static constexpr colour_t MAX_COLOUR_RGB = 0xFFFFFF, MAX_COLOUR_ARGB = 0xFFFFFFFF; constexpr colour_t float_to_colour_byte(float f, float min = 0.0f, float max = 1.0f) { return static_cast(std::clamp(min + f * (max - min), min, max) * 255.0f); diff --git a/src/openvic-simulation/types/Date.cpp b/src/openvic-simulation/types/Date.cpp index 6e21dfc..68d0941 100644 --- a/src/openvic-simulation/types/Date.cpp +++ b/src/openvic-simulation/types/Date.cpp @@ -12,20 +12,40 @@ using namespace OpenVic; Timespan::Timespan(day_t value) : days { value } {} -bool Timespan::operator<(Timespan other) const { return days < other.days; }; -bool Timespan::operator>(Timespan other) const { return days > other.days; }; -bool Timespan::operator<=(Timespan other) const { return days <= other.days; }; -bool Timespan::operator>=(Timespan other) const { return days >= other.days; }; -bool Timespan::operator==(Timespan other) const { return days == other.days; }; -bool Timespan::operator!=(Timespan other) const { return days != other.days; }; +bool Timespan::operator<(Timespan other) const { + return days < other.days; +}; +bool Timespan::operator>(Timespan other) const { + return days > other.days; +}; +bool Timespan::operator<=(Timespan other) const { + return days <= other.days; +}; +bool Timespan::operator>=(Timespan other) const { + return days >= other.days; +}; +bool Timespan::operator==(Timespan other) const { + return days == other.days; +}; +bool Timespan::operator!=(Timespan other) const { + return days != other.days; +}; -Timespan Timespan::operator+(Timespan other) const { return days + other.days; } +Timespan Timespan::operator+(Timespan other) const { + return days + other.days; +} -Timespan Timespan::operator-(Timespan other) const { return days - other.days; } +Timespan Timespan::operator-(Timespan other) const { + return days - other.days; +} -Timespan Timespan::operator*(day_t factor) const { return days * factor; } +Timespan Timespan::operator*(day_t factor) const { + return days * factor; +} -Timespan Timespan::operator/(day_t factor) const { return days / factor; } +Timespan Timespan::operator/(day_t factor) const { + return days / factor; +} Timespan& Timespan::operator+=(Timespan other) { days += other.days; @@ -65,16 +85,16 @@ Timespan::operator std::string() const { } Timespan Timespan::fromYears(day_t num) { - return num * Date::DAYS_IN_YEAR; + return num * Date::DAYS_IN_YEAR; } Timespan Timespan::fromMonths(day_t num) { - return (num / Date::MONTHS_IN_YEAR) * Date::DAYS_IN_YEAR + - Date::DAYS_UP_TO_MONTH[num % Date::MONTHS_IN_YEAR]; + return (num / Date::MONTHS_IN_YEAR) * Date::DAYS_IN_YEAR + + Date::DAYS_UP_TO_MONTH[num % Date::MONTHS_IN_YEAR]; } Timespan Timespan::fromDays(day_t num) { - return num; + return num; } std::ostream& OpenVic::operator<<(std::ostream& out, Timespan const& timespan) { @@ -132,16 +152,32 @@ Date::day_t Date::getDay() const { return (static_cast(timespan) % DAYS_IN_YEAR) - DAYS_UP_TO_MONTH[getMonth() - 1] + 1; } -bool Date::operator<(Date other) const { return timespan < other.timespan; }; -bool Date::operator>(Date other) const { return timespan > other.timespan; }; -bool Date::operator<=(Date other) const { return timespan <= other.timespan; }; -bool Date::operator>=(Date other) const { return timespan >= other.timespan; }; -bool Date::operator==(Date other) const { return timespan == other.timespan; }; -bool Date::operator!=(Date other) const { return timespan != other.timespan; }; +bool Date::operator<(Date other) const { + return timespan < other.timespan; +}; +bool Date::operator>(Date other) const { + return timespan > other.timespan; +}; +bool Date::operator<=(Date other) const { + return timespan <= other.timespan; +}; +bool Date::operator>=(Date other) const { + return timespan >= other.timespan; +}; +bool Date::operator==(Date other) const { + return timespan == other.timespan; +}; +bool Date::operator!=(Date other) const { + return timespan != other.timespan; +}; -Date Date::operator+(Timespan other) const { return timespan + other; } +Date Date::operator+(Timespan other) const { + return timespan + other; +} -Timespan Date::operator-(Date other) const { return timespan - other.timespan; } +Timespan Date::operator-(Date other) const { + return timespan - other.timespan; +} Date& Date::operator+=(Timespan other) { timespan += other; @@ -175,20 +211,28 @@ Date::operator std::string() const { } std::ostream& OpenVic::operator<<(std::ostream& out, Date const& date) { - return out << static_cast(date.getYear()) << Date::SEPARATOR_CHARACTER << static_cast(date.getMonth()) << Date::SEPARATOR_CHARACTER << static_cast(date.getDay()); + return out << static_cast(date.getYear()) << Date::SEPARATOR_CHARACTER + << static_cast(date.getMonth()) << Date::SEPARATOR_CHARACTER << static_cast(date.getDay()); } // Parsed from string of the form YYYY.MM.DD Date Date::from_string(char const* const str, char const* const end, bool* successful, bool quiet) { - if (successful != nullptr) *successful = true; + if (successful != nullptr) { + *successful = true; + } year_t year = 0; month_t month = 1; day_t day = 1; if (str == nullptr || end <= str) { - if (!quiet) Logger::error("Invalid string start/end pointers: ", static_cast(str), " - ", static_cast(end)); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Invalid string start/end pointers: ", static_cast(str), + " - ", static_cast(end)); + } + if (successful != nullptr) { + *successful = false; + } return { year, month, day }; } @@ -196,16 +240,25 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe while (std::isdigit(*year_end) && ++year_end < end); if (year_end <= str) { - if (!quiet) Logger::error("Failed to find year digits in date: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to find year digits in date: ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } return { year, month, day }; } bool sub_successful = false; uint64_t val = StringUtils::string_to_uint64(str, year_end, &sub_successful, 10); if (!sub_successful || val > std::numeric_limits::max()) { - if (!quiet) Logger::error("Failed to read year: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to read year: ", std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } return { year, month, day }; } year = val; @@ -217,14 +270,24 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe while (std::isdigit(*month_end) && ++month_end < end); } if (month_start >= month_end) { - if (!quiet) Logger::error("Failed to find month digits in date: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to find month digits in date: ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } else { sub_successful = false; val = StringUtils::string_to_uint64(month_start, month_end, &sub_successful, 10); if (!sub_successful || val < 1 || val > MONTHS_IN_YEAR) { - if (!quiet) Logger::error("Failed to read month: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to read month: ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } else { month = val; if (month_end < end) { @@ -235,32 +298,60 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe while (std::isdigit(*day_end) && ++day_end < end); } if (day_start >= day_end) { - if (!quiet) Logger::error("Failed to find day digits in date: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to find day digits in date: ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } else { sub_successful = false; val = StringUtils::string_to_uint64(day_start, day_end, &sub_successful); if (!sub_successful || val < 1 || val > DAYS_IN_MONTH[month - 1]) { - if (!quiet) Logger::error("Failed to read day: ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Failed to read day: ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } else { day = val; if (day_end < end) { - if (!quiet) Logger::error("Unexpected string \"", std::string_view { day_end, static_cast(end - day_end) }, "\" at the end of date ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error( + "Unexpected string \"", + std::string_view { day_end, static_cast(end - day_end) }, + "\" at the end of date ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } } } } else { - if (!quiet) Logger::error("Unexpected character \"", *month_end, "\" in month of date ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Unexpected character \"", *month_end, "\" in month of date ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } } } } } else { - if (!quiet) Logger::error("Unexpected character \"", *year_end, "\" in year of date ", std::string_view { str, static_cast(end - str) }); - if (successful != nullptr) *successful = false; + if (!quiet) { + Logger::error("Unexpected character \"", *year_end, "\" in year of date ", + std::string_view { str, static_cast(end - str) }); + } + if (successful != nullptr) { + *successful = false; + } } } return { year, month, day }; diff --git a/src/openvic-simulation/types/IdentifierRegistry.cpp b/src/openvic-simulation/types/IdentifierRegistry.cpp index f92750b..1bc3747 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.cpp +++ b/src/openvic-simulation/types/IdentifierRegistry.cpp @@ -25,7 +25,9 @@ HasColour::HasColour(colour_t const new_colour, bool can_be_null, bool can_have_ assert((can_be_null || colour != NULL_COLOUR) && colour <= (!can_have_alpha ? MAX_COLOUR_RGB : MAX_COLOUR_ARGB)); } -colour_t HasColour::get_colour() const { return colour; } +colour_t HasColour::get_colour() const { + return colour; +} std::string HasColour::colour_to_hex_string() const { return OpenVic::colour_to_hex_string(colour); diff --git a/src/openvic-simulation/types/IdentifierRegistry.hpp b/src/openvic-simulation/types/IdentifierRegistry.hpp index f53d78b..0c5c5ab 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.hpp +++ b/src/openvic-simulation/types/IdentifierRegistry.hpp @@ -45,10 +45,8 @@ namespace OpenVic { #define HASID_PROPERTY(NAME) \ const NAME; \ -\ public: \ auto get_##NAME() const->decltype(get_property(NAME)) { return get_property(NAME); } \ -\ private: }; @@ -80,7 +78,8 @@ private: */ class HasIdentifierAndColour : public HasIdentifier, public HasColour { protected: - HasIdentifierAndColour(std::string_view new_identifier, const colour_t new_colour, bool can_be_null, bool can_have_alpha); + HasIdentifierAndColour(std::string_view new_identifier, const colour_t new_colour, + bool can_be_null, bool can_have_alpha); public: HasIdentifierAndColour(HasIdentifierAndColour const&) = delete; @@ -97,9 +96,8 @@ private: constexpr auto pred = [](typename decimal_map_t::value_type a, typename decimal_map_t::value_type b) -> bool { return a.second < b.second; }; - const typename decimal_map_t::const_iterator result = std::max_element( - map.begin(), map.end(), pred - ); + const typename decimal_map_t::const_iterator result = + std::max_element(map.begin(), map.end(), pred); if (result != map.end()) { return *result; } else { @@ -111,11 +109,13 @@ private: /* Callbacks for trying to add duplicate keys via UniqueKeyRegistry::add_item */ static bool duplicate_fail_callback(std::string_view registry_name, std::string_view duplicate_identifier) { - Logger::error("Failure adding item to the ", registry_name, " registry - an item with the identifier \"", duplicate_identifier, "\" already exists!"); + Logger::error("Failure adding item to the ", registry_name, " registry - an item with the identifier \"", + duplicate_identifier, "\" already exists!"); return false; } static bool duplicate_warning_callback(std::string_view registry_name, std::string_view duplicate_identifier) { - Logger::warning("Warning adding item to the ", registry_name, " registry - an item with the identifier \"", duplicate_identifier, "\" already exists!"); + Logger::warning("Warning adding item to the ", registry_name, " registry - an item with the identifier \"", + duplicate_identifier, "\" already exists!"); return true; } static bool duplicate_ignore_callback(std::string_view registry_name, std::string_view duplicate_identifier) { @@ -141,14 +141,16 @@ private: using value_type = _Type; using storage_type = _Storage; - UniqueKeyRegistry(std::string_view new_name, bool new_log_lock = true, _GetIdentifier new_GetIdentifier = {}, _GetPointer new_GetPointer = {}) + UniqueKeyRegistry(std::string_view new_name, bool new_log_lock = true, + _GetIdentifier new_GetIdentifier = {}, _GetPointer new_GetPointer = {}) : name { new_name }, log_lock { new_log_lock }, GetIdentifier { new_GetIdentifier }, GetPointer { new_GetPointer } {} std::string_view get_name() const { return name; } - bool add_item(storage_type&& item, NodeTools::callback_t duplicate_callback = duplicate_fail_callback) { + bool add_item(storage_type&& item, + NodeTools::callback_t duplicate_callback = duplicate_fail_callback) { if (locked) { Logger::error("Cannot add item to the ", name, " registry - locked!"); return false; @@ -156,7 +158,9 @@ private: const std::string_view new_identifier = GetIdentifier(GetPointer(item)); if (duplicate_callback && duplicate_callback.target() == duplicate_ignore_callback) { - if (has_identifier(new_identifier)) return true; + if (has_identifier(new_identifier)) { + return true; + } } else { value_type const* old_item = get_item_by_identifier(new_identifier); if (old_item != nullptr) { @@ -173,7 +177,9 @@ private: Logger::error("Failed to lock ", name, " registry - already locked!"); } else { locked = true; - if (log_lock) Logger::info("Locked ", name, " registry after registering ", size(), " items"); + if (log_lock) { + Logger::info("Locked ", name, " registry after registering ", size(), " items"); + } } } @@ -256,7 +262,8 @@ private: return identifiers; } - NodeTools::node_callback_t expect_item_decimal_map(NodeTools::callback_t&&> callback) const { + NodeTools::node_callback_t expect_item_decimal_map( + NodeTools::callback_t&&> callback) const { return [this, callback](ast::NodeCPtr node) -> bool { decimal_map_t map; bool ret = expect_item_dictionary([&map](value_type const& key, ast::NodeCPtr value) -> bool { diff --git a/src/openvic-simulation/types/Vector.cpp b/src/openvic-simulation/types/Vector.cpp index 10d2dd2..5065084 100644 --- a/src/openvic-simulation/types/Vector.cpp +++ b/src/openvic-simulation/types/Vector.cpp @@ -8,7 +8,6 @@ constexpr vec2_t::vec2_t(T new_val) : x { new_val }, y { new_val } {} template constexpr vec2_t::vec2_t(T new_x, T new_y) : x { new_x }, y { new_y } {} - template constexpr vec2_t vec2_t::abs() const { return { }; diff --git a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp index 649d3f6..16e400f 100644 --- a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp +++ b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp @@ -253,7 +253,9 @@ namespace OpenVic { } val += err; } - if (val.is_negative()) stream << "-"; + if (val.is_negative()) { + stream << "-"; + } val = val.abs(); stream << val.to_int64_t() << "."; val = val.get_frac(); @@ -283,7 +285,9 @@ namespace OpenVic { // Deterministic static constexpr fixed_point_t parse(char const* str, char const* const end, bool* successful = nullptr) { - if (successful != nullptr) *successful = false; + if (successful != nullptr) { + *successful = false; + } if (str == nullptr || str >= end) { return _0(); @@ -294,7 +298,9 @@ namespace OpenVic { if (*str == '-') { negative = true; ++str; - if (str == end) return _0(); + if (str == end) { + return _0(); + } } char const* dot_pointer = str; @@ -306,20 +312,26 @@ namespace OpenVic { } fixed_point_t result = _0(); - if (successful != nullptr) *successful = true; + if (successful != nullptr) { + *successful = true; + } if (dot_pointer != str) { // Non-empty integer part bool int_successful = false; result += parse_integer(str, dot_pointer, &int_successful); - if (!int_successful && successful != nullptr) *successful = false; + if (!int_successful && successful != nullptr) { + *successful = false; + } } if (dot_pointer + 1 < end) { // Non-empty fractional part bool frac_successful = false; result += parse_fraction(dot_pointer + 1, end, &frac_successful); - if (!frac_successful && successful != nullptr) *successful = false; + if (!frac_successful && successful != nullptr) { + *successful = false; + } } return negative ? -result : result; @@ -599,7 +611,9 @@ namespace OpenVic { static constexpr fixed_point_t parse_fraction(char const* str, char const* end, bool* successful) { char const* const read_end = str + PRECISION; - if (read_end < end) end = read_end; + if (read_end < end) { + end = read_end; + } uint64_t parsed_value = StringUtils::string_to_uint64(str, end, successful, 10); while (end++ < read_end) { parsed_value *= 10; diff --git a/src/openvic-simulation/utility/BMP.cpp b/src/openvic-simulation/utility/BMP.cpp index 2fa9417..cdd8ead 100644 --- a/src/openvic-simulation/utility/BMP.cpp +++ b/src/openvic-simulation/utility/BMP.cpp @@ -91,14 +91,16 @@ bool BMP::read_header() { #define STR(x) #x static const std::set BITS_PER_PIXEL { VALID_BITS_PER_PIXEL }; if (!BITS_PER_PIXEL.contains(header.bits_per_pixel)) { - Logger::error("Invalid BMP bits per pixel: ", header.bits_per_pixel, " (must be one of " STR(VALID_BITS_PER_PIXEL) ")"); + Logger::error("Invalid BMP bits per pixel: ", header.bits_per_pixel, + " (must be one of " STR(VALID_BITS_PER_PIXEL) ")"); header_validated = false; } #undef VALID_BITS_PER_PIXEL #undef STR static constexpr uint16_t PALETTE_BITS_PER_PIXEL_LIMIT = 8; if (header.num_colours != 0 && header.bits_per_pixel > PALETTE_BITS_PER_PIXEL_LIMIT) { - Logger::error("Invalid BMP palette size: ", header.num_colours, " (should be 0 as bits per pixel is ", header.bits_per_pixel, " > 8)"); + Logger::error("Invalid BMP palette size: ", header.num_colours, + " (should be 0 as bits per pixel is ", header.bits_per_pixel, " > 8)"); header_validated = false; } // TODO - validate important_colours diff --git a/src/openvic-simulation/utility/Logger.cpp b/src/openvic-simulation/utility/Logger.cpp index 68c43dd..5e25c98 100644 --- a/src/openvic-simulation/utility/Logger.cpp +++ b/src/openvic-simulation/utility/Logger.cpp @@ -5,18 +5,30 @@ using namespace OpenVic; void Logger::set_logger_funcs() { - Logger::set_info_func([](std::string&& str) { std::cout << str; }); - Logger::set_warning_func([](std::string&& str) { std::cerr << str; }); - Logger::set_error_func([](std::string&& str) { std::cerr << str; }); + Logger::set_info_func([](std::string&& str) { + std::cout << str; + }); + Logger::set_warning_func([](std::string&& str) { + std::cerr << str; + }); + Logger::set_error_func([](std::string&& str) { + std::cerr << str; + }); } char const* Logger::get_filename(char const* filepath, char const* default_path) { - if (filepath == nullptr) return default_path; + if (filepath == nullptr) { + return default_path; + } char const* last_slash = filepath; while (*filepath != '\0') { - if (*filepath == '\\' || *filepath == '/') last_slash = filepath + 1; + if (*filepath == '\\' || *filepath == '/') { + last_slash = filepath + 1; + } filepath++; } - if (*last_slash == '\0') return default_path; + if (*last_slash == '\0') { + return default_path; + } return last_slash; } diff --git a/src/openvic-simulation/utility/Logger.hpp b/src/openvic-simulation/utility/Logger.hpp index d60e59e..b2395ac 100644 --- a/src/openvic-simulation/utility/Logger.hpp +++ b/src/openvic-simulation/utility/Logger.hpp @@ -20,15 +20,23 @@ namespace OpenVic { int _line; std::string _function; - public: source_location(std::string f, int l, std::string n) : _file(f), _line(l), _function(n) {} - static source_location current(std::string f = __builtin_FILE(), int l = __builtin_LINE(), std::string n = __builtin_FUNCTION()) { + + public: + static source_location current(std::string f = __builtin_FILE(), int l = __builtin_LINE(), + std::string n = __builtin_FUNCTION()) { return source_location(f, l, n); } - inline char const* file_name() const { return _file.c_str(); } - inline int line() const { return _line; } - inline char const* function_name() const { return _function.c_str(); } + inline char const* file_name() const { + return _file.c_str(); + } + inline int line() const { + return _line; + } + inline char const* function_name() const { + return _function.c_str(); + } }; #endif @@ -57,8 +65,10 @@ namespace OpenVic { log(log_channel_t& log_channel, Ts&&... ts, source_location const& location) { std::stringstream stream; stream << "\n" << get_filename(location.file_name()) << "(" - //<< location.line() << ") `" << location.function_name() << "`: "; - << location.line() << "): "; + /* Function name removed to reduce clutter. It is already included + * in Godot's print functions, so this was repeating it. */ + //<< location.line() << ") `" << location.function_name() << "`: "; + << location.line() << "): "; ((stream << std::forward(ts)), ...); stream << std::endl; log_channel.queue.push(stream.str()); diff --git a/src/openvic-simulation/utility/StringUtils.hpp b/src/openvic-simulation/utility/StringUtils.hpp index 5784208..d968bf6 100644 --- a/src/openvic-simulation/utility/StringUtils.hpp +++ b/src/openvic-simulation/utility/StringUtils.hpp @@ -12,11 +12,14 @@ namespace OpenVic::StringUtils { * or not conversion was successful. It can be nullptr if this information is not needed. */ constexpr uint64_t string_to_uint64(char const* str, const char* const end, bool* successful = nullptr, int base = 10) { - if (successful != nullptr) *successful = false; + if (successful != nullptr) { + *successful = false; + } // Base value should be between 2 and 36. If it's not, return 0 as an invalid case. - if (str == nullptr || end <= str || base < 0 || base == 1 || base > 36) + if (str == nullptr || end <= str || base < 0 || base == 1 || base > 36) { return 0; + } // The result of the conversion will be stored in this variable. uint64_t result = 0; @@ -26,8 +29,10 @@ namespace OpenVic::StringUtils { if (*str == '0') { if (str + 1 != end && (str[1] == 'x' || str[1] == 'X')) { base = 16; // Hexadecimal. - str += 2; // Skip '0x' or '0X' - if (str == end) return 0; + str += 2; // Skip '0x' or '0X' + if (str == end) { + return 0; + } } else { base = 8; // Octal. } @@ -38,7 +43,9 @@ namespace OpenVic::StringUtils { // If base is 16 and string starts with '0x' or '0X', skip these characters. if (*str == '0' && str + 1 != end && (str[1] == 'x' || str[1] == 'X')) { str += 2; - if (str == end) return 0; + if (str == end) { + return 0; + } } } @@ -76,7 +83,9 @@ namespace OpenVic::StringUtils { // If successful is not null and the entire string was parsed, // set *successful to true (if not it is already false). - if (successful != nullptr && str == end) *successful = true; + if (successful != nullptr && str == end) { + *successful = true; + } return result; } @@ -90,29 +99,38 @@ namespace OpenVic::StringUtils { } constexpr int64_t string_to_int64(char const* str, const char* const end, bool* successful = nullptr, int base = 10) { - if (successful != nullptr) *successful = false; + if (successful != nullptr) { + *successful = false; + } - if (str == nullptr || end <= str) return 0; + if (str == nullptr || end <= str) { + return 0; + } // This flag will be set if the number is negative. bool is_negative = false; // Check if there is a sign character. if (*str == '+' || *str == '-') { - if (*str == '-') + if (*str == '-') { is_negative = true; + } ++str; - if (str == end) return 0; + if (str == end) { + return 0; + } } const uint64_t result = string_to_uint64(str, end, successful, base); if (!is_negative) { - if (result >= std::numeric_limits::max()) + if (result >= std::numeric_limits::max()) { return std::numeric_limits::max(); + } return result; } else { - if (result > std::numeric_limits::max()) + if (result > std::numeric_limits::max()) { return std::numeric_limits::min(); + } return -result; } } -- cgit v1.2.3-56-ga3b1 From 1b5e43fa7750cc4025d32f18390593cbce3ba842 Mon Sep 17 00:00:00 2001 From: hop311 Date: Sun, 29 Oct 2023 14:11:10 +0000 Subject: Clang-format formatting (with manual cleanup) --- .clang-format | 38 ++- clang-format.sh | 6 + src/headless/main.cpp | 4 +- src/openvic-simulation/GameAdvancementHook.cpp | 17 +- src/openvic-simulation/GameAdvancementHook.hpp | 10 +- src/openvic-simulation/GameManager.cpp | 16 +- src/openvic-simulation/Modifier.cpp | 70 +++-- src/openvic-simulation/Modifier.hpp | 76 ++--- src/openvic-simulation/country/Country.cpp | 76 ++--- src/openvic-simulation/country/Country.hpp | 23 +- src/openvic-simulation/dataloader/Dataloader.cpp | 124 ++++---- src/openvic-simulation/dataloader/Dataloader.hpp | 6 +- .../dataloader/Dataloader_Windows.hpp | 37 +-- src/openvic-simulation/dataloader/NodeTools.cpp | 141 ++++----- src/openvic-simulation/dataloader/NodeTools.hpp | 67 ++-- src/openvic-simulation/economy/Building.cpp | 150 ++++----- src/openvic-simulation/economy/Building.hpp | 55 ++-- src/openvic-simulation/economy/EconomyManager.hpp | 1 + src/openvic-simulation/economy/Good.cpp | 76 +++-- src/openvic-simulation/economy/Good.hpp | 12 +- src/openvic-simulation/economy/ProductionType.cpp | 49 +-- src/openvic-simulation/economy/ProductionType.hpp | 29 +- src/openvic-simulation/history/Bookmark.cpp | 66 ++-- src/openvic-simulation/history/Bookmark.hpp | 15 +- src/openvic-simulation/history/CountryHistory.cpp | 270 ++++++++-------- src/openvic-simulation/history/CountryHistory.hpp | 50 +-- src/openvic-simulation/history/ProvinceHistory.cpp | 132 ++++---- src/openvic-simulation/history/ProvinceHistory.hpp | 26 +- src/openvic-simulation/map/Map.cpp | 119 ++++---- src/openvic-simulation/map/Province.cpp | 13 +- src/openvic-simulation/map/TerrainType.cpp | 30 +- src/openvic-simulation/map/TerrainType.hpp | 12 +- src/openvic-simulation/military/Deployment.cpp | 12 +- src/openvic-simulation/military/Deployment.hpp | 11 +- src/openvic-simulation/military/LeaderTrait.cpp | 8 +- src/openvic-simulation/military/LeaderTrait.hpp | 16 +- .../military/MilitaryManager.hpp | 2 +- src/openvic-simulation/military/Unit.cpp | 50 ++- src/openvic-simulation/military/Unit.hpp | 16 +- src/openvic-simulation/misc/Define.cpp | 19 +- src/openvic-simulation/misc/Define.hpp | 19 +- src/openvic-simulation/politics/Government.cpp | 46 ++- src/openvic-simulation/politics/Government.hpp | 12 +- src/openvic-simulation/politics/Ideology.cpp | 73 +++-- src/openvic-simulation/politics/Ideology.hpp | 16 +- src/openvic-simulation/politics/Issue.cpp | 33 +- src/openvic-simulation/politics/Issue.hpp | 37 +-- src/openvic-simulation/pop/Culture.cpp | 78 +++-- src/openvic-simulation/pop/Culture.hpp | 30 +- src/openvic-simulation/pop/Pop.cpp | 67 ++-- src/openvic-simulation/pop/Pop.hpp | 23 +- src/openvic-simulation/pop/Religion.cpp | 56 ++-- src/openvic-simulation/pop/Religion.hpp | 9 +- src/openvic-simulation/testing/Requirement.cpp | 2 +- src/openvic-simulation/testing/Requirement.hpp | 3 +- src/openvic-simulation/testing/TestScript.cpp | 7 +- src/openvic-simulation/testing/TestScript.hpp | 10 +- src/openvic-simulation/testing/Testing.cpp | 6 +- src/openvic-simulation/testing/Testing.hpp | 17 +- .../testing/test_scripts/A_001_file_tests.cpp | 150 +++++---- .../testing/test_scripts/A_002_economy_tests.cpp | 340 ++++++++++++--------- .../test_scripts/A_003_military_unit_tests.cpp | 10 +- .../test_scripts/A_004_networking_tests.cpp | 10 +- .../testing/test_scripts/A_005_nation_tests.cpp | 10 +- .../testing/test_scripts/A_006_politics_tests.cpp | 10 +- src/openvic-simulation/types/Date.cpp | 70 +++-- .../types/IdentifierRegistry.cpp | 10 +- .../types/IdentifierRegistry.hpp | 92 ++++-- src/openvic-simulation/types/Vector.cpp | 2 +- .../types/fixed_point/FixedPoint.hpp | 2 +- src/openvic-simulation/utility/BMP.cpp | 19 +- .../utility/ConstexprIntToStr.hpp | 6 +- src/openvic-simulation/utility/Logger.hpp | 9 +- 73 files changed, 1643 insertions(+), 1591 deletions(-) create mode 100644 clang-format.sh diff --git a/.clang-format b/.clang-format index d1aab5d..0712ea6 100644 --- a/.clang-format +++ b/.clang-format @@ -5,7 +5,9 @@ Standard: c++20 UseTab: Always TabWidth: 4 IndentWidth: 4 -ColumnLimit: 0 +ColumnLimit: 128 +PointerAlignment: Left +DerivePointerAlignment: false SpacesInSquareBrackets: false SpacesInParentheses: false SpacesInCStyleCastParentheses: false @@ -14,6 +16,7 @@ SpacesInConditionalStatement: false SpacesInAngles: false SpaceInEmptyParentheses: false SpaceInEmptyBlock: false +SpacesInParens: Never SpaceBeforeSquareBrackets: false SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeParens: ControlStatements @@ -23,13 +26,14 @@ SpaceBeforeCpp11BracedList: true SpaceBeforeAssignmentOperators: true SpaceAfterTemplateKeyword: false SpaceAfterLogicalNot: false -PointerAlignment: Left PackConstructorInitializers: BinPack NamespaceIndentation: All -LambdaBodyIndentation: Signature +#LambdaBodyIndentation: Signature IndentExternBlock: Indent -IndentCaseLabels: true +IndentCaseBlocks: false +IndentCaseLabels: false IndentAccessModifiers: false +IndentRequiresClause: false IncludeBlocks: Regroup FixNamespaceComments: false EmptyLineBeforeAccessModifier: LogicalBlock @@ -38,17 +42,35 @@ CompactNamespaces: false BreakConstructorInitializers: BeforeColon BreakBeforeBraces: Attach AlwaysBreakTemplateDeclarations: Yes -AllowShortLambdasOnASingleLine: All -AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AlwaysBreakAfterReturnType: None +PenaltyReturnTypeOnItsOwnLine: 10 +BreakBeforeConceptDeclarations: Always +AllowShortLambdasOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: Never AllowShortEnumsOnASingleLine: true AllowShortCaseLabelsOnASingleLine: true -AlignTrailingComments: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCompoundRequirementOnASingleLine: true +AllowShortFunctionsOnASingleLine: Empty +AllowShortLoopsOnASingleLine: false +AlignTrailingComments: + Kind: Never + OverEmptyLines: 0 AlignEscapedNewlines: DontAlign AlignAfterOpenBracket: BlockIndent +AlignOperands: DontAlign +AlignConsecutiveShortCaseStatements: + Enabled: true + AcrossEmptyLines: true + AcrossComments: true + AlignCaseColons: false BinPackArguments: true BinPackParameters: true -IndentRequiresClause: false AccessModifierOffset: -4 +InsertNewlineAtEOF: true +InsertBraces: true +MaxEmptyLinesToKeep: 2 +RequiresClausePosition: OwnLine IncludeCategories: - Regex: <[[:alnum:]_]+> Priority: 1 diff --git a/clang-format.sh b/clang-format.sh new file mode 100644 index 0000000..3af256e --- /dev/null +++ b/clang-format.sh @@ -0,0 +1,6 @@ +#/usr/bin/env bash + +echo "\n\nFormatting openvic-simulation with clang-format:\n" +find ./src/ -iname *.hpp -o -iname *.cpp | xargs clang-format --verbose -i + +exit 0 diff --git a/src/headless/main.cpp b/src/headless/main.cpp index 04bfc7b..36a1329 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -2,8 +2,8 @@ #include #include -#include #include +#include using namespace OpenVic; @@ -112,7 +112,7 @@ int main(int argc, char const* argv[]) { } else if (strcmp(arg, "-t") == 0) { run_tests = true; } else if (strcmp(arg, "-b") == 0) { - if (!_read("-b", "base directory", std::identity{})) { + if (!_read("-b", "base directory", std::identity {})) { return -1; } } else if (strcmp(arg, "-s") == 0) { diff --git a/src/openvic-simulation/GameAdvancementHook.cpp b/src/openvic-simulation/GameAdvancementHook.cpp index d48a1c2..4a6449c 100644 --- a/src/openvic-simulation/GameAdvancementHook.cpp +++ b/src/openvic-simulation/GameAdvancementHook.cpp @@ -3,19 +3,14 @@ using namespace OpenVic; const std::vector GameAdvancementHook::GAME_SPEEDS = { - std::chrono::milliseconds { 4000 }, - std::chrono::milliseconds { 3000 }, - std::chrono::milliseconds { 2000 }, - std::chrono::milliseconds { 1000 }, - std::chrono::milliseconds { 100 }, - std::chrono::milliseconds { 1 } + std::chrono::milliseconds { 4000 }, std::chrono::milliseconds { 3000 }, std::chrono::milliseconds { 2000 }, + std::chrono::milliseconds { 1000 }, std::chrono::milliseconds { 100 }, std::chrono::milliseconds { 1 } }; -GameAdvancementHook::GameAdvancementHook(AdvancementFunction tickFunction, - RefreshFunction updateFunction, bool startPaused, speed_t startingSpeed) - : triggerFunction { tickFunction }, - refreshFunction { updateFunction }, - isPaused { startPaused } { +GameAdvancementHook::GameAdvancementHook( + AdvancementFunction tickFunction, RefreshFunction updateFunction, bool startPaused, speed_t startingSpeed +) + : triggerFunction { tickFunction }, refreshFunction { updateFunction }, isPaused { startPaused } { lastPolledTime = std::chrono::high_resolution_clock::now(); setSimulationSpeed(startingSpeed); } diff --git a/src/openvic-simulation/GameAdvancementHook.hpp b/src/openvic-simulation/GameAdvancementHook.hpp index 9d19948..2a27ff9 100644 --- a/src/openvic-simulation/GameAdvancementHook.hpp +++ b/src/openvic-simulation/GameAdvancementHook.hpp @@ -20,7 +20,8 @@ namespace OpenVic { using time_point_t = std::chrono::time_point; time_point_t lastPolledTime; - // A function pointer that advances the simulation, intended to be a capturing lambda or something similar. May need to be reworked later + // A function pointer that advances the simulation, intended to be a capturing + // lambda or something similar. May need to be reworked later AdvancementFunction triggerFunction; RefreshFunction refreshFunction; speed_t currentSpeed; @@ -28,8 +29,9 @@ namespace OpenVic { public: bool isPaused; - GameAdvancementHook(AdvancementFunction tickFunction, RefreshFunction updateFunction, - bool startPaused = true, speed_t startingSpeed = 0); + GameAdvancementHook( + AdvancementFunction tickFunction, RefreshFunction updateFunction, bool startPaused = true, speed_t startingSpeed = 0 + ); void setSimulationSpeed(speed_t speed); speed_t getSimulationSpeed() const; @@ -42,4 +44,4 @@ namespace OpenVic { void conditionallyAdvanceGame(); void reset(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/GameManager.cpp b/src/openvic-simulation/GameManager.cpp index c1710f6..261dea5 100644 --- a/src/openvic-simulation/GameManager.cpp +++ b/src/openvic-simulation/GameManager.cpp @@ -4,13 +4,12 @@ using namespace OpenVic; GameManager::GameManager(state_updated_func_t state_updated_callback) : clock { - [this]() { - tick(); - }, - [this]() { - update_state(); - } -}, state_updated { state_updated_callback } {} + [this]() { + tick(); + }, + [this]() { + update_state(); + } }, state_updated { state_updated_callback } {} void GameManager::set_needs_update() { needs_update = true; @@ -56,8 +55,7 @@ bool GameManager::expand_building(Province::index_t province_index, std::string_ set_needs_update(); Province* province = map.get_province_by_index(province_index); if (province == nullptr) { - Logger::error("Invalid province index ", province_index, - " while trying to expand building ", building_type_identifier); + Logger::error("Invalid province index ", province_index, " while trying to expand building ", building_type_identifier); return false; } return province->expand_building(building_type_identifier); diff --git a/src/openvic-simulation/Modifier.cpp b/src/openvic-simulation/Modifier.cpp index 32f68f7..a42cc66 100644 --- a/src/openvic-simulation/Modifier.cpp +++ b/src/openvic-simulation/Modifier.cpp @@ -89,7 +89,8 @@ Modifier::icon_t Modifier::get_icon() const { return icon; } -ModifierInstance::ModifierInstance(Modifier const& modifier, Date expiry_date) : modifier { modifier }, expiry_date { expiry_date } {} +ModifierInstance::ModifierInstance(Modifier const& modifier, Date expiry_date) + : modifier { modifier }, expiry_date { expiry_date } {} Modifier const& ModifierInstance::get_modifier() const { return modifier; @@ -99,8 +100,7 @@ Date const& ModifierInstance::get_expiry_date() const { return expiry_date; } -ModifierManager::ModifierManager() - : modifier_effects { "modifier effects" }, modifiers { "modifiers" } {} +ModifierManager::ModifierManager() : modifier_effects { "modifier effects" }, modifiers { "modifiers" } {} bool ModifierManager::add_modifier_effect(std::string_view identifier, bool positive_good, ModifierEffect::format_t format) { if (identifier.empty()) { @@ -150,7 +150,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= add_modifier_effect("influence_modifier", true); ret &= add_modifier_effect("issue_change_speed", true); ret &= add_modifier_effect("land_organisation", true); - ret &= add_modifier_effect("land_unit_start_experience", true); // weird, land_unit_start_experience = 15 would give a 15% boost + // weird, land_unit_start_experience = 15 would give a 15% boost + ret &= add_modifier_effect("land_unit_start_experience", true); ret &= add_modifier_effect("leadership_modifier", true); ret &= add_modifier_effect("loan_interest", false); ret &= add_modifier_effect("max_loan_modifier", true); @@ -261,8 +262,7 @@ bool ModifierManager::setup_modifier_effects() { } key_value_callback_t ModifierManager::_modifier_effect_callback( - ModifierValue& modifier, key_value_callback_t default_callback, - ModifierEffectValidator auto effect_validator + ModifierValue& modifier, key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator ) const { return [this, &modifier, default_callback, effect_validator](std::string_view key, ast::NodeCPtr value) -> bool { @@ -270,9 +270,7 @@ key_value_callback_t ModifierManager::_modifier_effect_callback( if (effect != nullptr) { if (effect_validator(*effect)) { if (modifier.values.find(effect) == modifier.values.end()) { - return expect_fixed_point( - assign_variable_callback(modifier.values[effect]) - )(value); + return expect_fixed_point(assign_variable_callback(modifier.values[effect]))(value); } else { Logger::error("Duplicate modifier effect: ", key); return false; @@ -286,8 +284,10 @@ key_value_callback_t ModifierManager::_modifier_effect_callback( }; } -node_callback_t ModifierManager::expect_validated_modifier_value_and_default(callback_t modifier_callback, - key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const { +node_callback_t ModifierManager::expect_validated_modifier_value_and_default( + callback_t modifier_callback, key_value_callback_t default_callback, + ModifierEffectValidator auto effect_validator +) const { return [this, modifier_callback, default_callback, effect_validator](ast::NodeCPtr root) -> bool { ModifierValue modifier; bool ret = expect_dictionary(_modifier_effect_callback(modifier, default_callback, effect_validator))(root); @@ -295,47 +295,57 @@ node_callback_t ModifierManager::expect_validated_modifier_value_and_default(cal return ret; }; } -node_callback_t ModifierManager::expect_validated_modifier_value(callback_t modifier_callback, - ModifierEffectValidator auto effect_validator) const { +node_callback_t ModifierManager::expect_validated_modifier_value( + callback_t modifier_callback, ModifierEffectValidator auto effect_validator +) const { return expect_validated_modifier_value_and_default(modifier_callback, key_value_invalid_callback, effect_validator); } -node_callback_t ModifierManager::expect_modifier_value_and_default(callback_t modifier_callback, - key_value_callback_t default_callback) const { - return expect_validated_modifier_value_and_default(modifier_callback, default_callback, - [](ModifierEffect const&) -> bool { return true; }); +node_callback_t ModifierManager::expect_modifier_value_and_default( + callback_t modifier_callback, key_value_callback_t default_callback +) const { + return expect_validated_modifier_value_and_default(modifier_callback, default_callback, [](ModifierEffect const&) -> bool { + return true; + }); } node_callback_t ModifierManager::expect_modifier_value(callback_t modifier_callback) const { return expect_modifier_value_and_default(modifier_callback, key_value_invalid_callback); } -node_callback_t ModifierManager::expect_whitelisted_modifier_value_and_default(callback_t modifier_callback, - string_set_t const& whitelist, key_value_callback_t default_callback) const { - return expect_validated_modifier_value_and_default(modifier_callback, - default_callback, [&whitelist](ModifierEffect const& effect) -> bool { - return whitelist.contains(effect.get_identifier()); - }); +node_callback_t ModifierManager::expect_whitelisted_modifier_value_and_default( + callback_t modifier_callback, string_set_t const& whitelist, key_value_callback_t default_callback +) const { + return expect_validated_modifier_value_and_default( + modifier_callback, default_callback, + [&whitelist](ModifierEffect const& effect) -> bool { + return whitelist.contains(effect.get_identifier()); + } + ); } -node_callback_t ModifierManager::expect_whitelisted_modifier_value(callback_t modifier_callback, - string_set_t const& whitelist) const { +node_callback_t ModifierManager::expect_whitelisted_modifier_value( + callback_t modifier_callback, string_set_t const& whitelist +) const { return expect_whitelisted_modifier_value_and_default(modifier_callback, whitelist, key_value_invalid_callback); } -node_callback_t ModifierManager::expect_modifier_value_and_key_map_and_default(callback_t modifier_callback, - key_value_callback_t default_callback, key_map_t&& key_map) const { +node_callback_t ModifierManager::expect_modifier_value_and_key_map_and_default( + callback_t modifier_callback, key_value_callback_t default_callback, key_map_t&& key_map +) const { return [this, modifier_callback, key_map = std::move(key_map)](ast::NodeCPtr node) mutable -> bool { bool ret = expect_modifier_value_and_default( - modifier_callback, dictionary_keys_callback(key_map, key_value_invalid_callback) + modifier_callback, + dictionary_keys_callback(key_map, key_value_invalid_callback) )(node); ret &= check_key_map_counts(key_map); return ret; }; } -node_callback_t ModifierManager::expect_modifier_value_and_key_map(callback_t modifier_callback, - key_map_t&& key_map) const { +node_callback_t ModifierManager::expect_modifier_value_and_key_map( + callback_t modifier_callback, key_map_t&& key_map +) const { return expect_modifier_value_and_key_map_and_default(modifier_callback, key_value_invalid_callback, std::move(key_map)); } diff --git a/src/openvic-simulation/Modifier.hpp b/src/openvic-simulation/Modifier.hpp index 3a8b06d..2a98782 100644 --- a/src/openvic-simulation/Modifier.hpp +++ b/src/openvic-simulation/Modifier.hpp @@ -8,11 +8,7 @@ namespace OpenVic { struct ModifierEffect : HasIdentifier { friend struct ModifierManager; - enum class format_t { - RAW_DECIMAL, - PERCENTAGE_DECIMAL, - INT - }; + enum class format_t { RAW_DECIMAL, PERCENTAGE_DECIMAL, INT }; private: /* If true, positive values will be green and negative values will be red. @@ -105,14 +101,18 @@ namespace OpenVic { IdentifierRegistry modifiers; /* effect_validator takes in ModifierEffect const& */ - NodeTools::key_value_callback_t _modifier_effect_callback(ModifierValue& modifier, - NodeTools::key_value_callback_t default_callback, ModifierEffectValidator auto effect_validator) const; + NodeTools::key_value_callback_t _modifier_effect_callback( + ModifierValue& modifier, NodeTools::key_value_callback_t default_callback, + ModifierEffectValidator auto effect_validator + ) const; public: ModifierManager(); - bool add_modifier_effect(std::string_view identifier, bool province_good, - ModifierEffect::format_t format = ModifierEffect::format_t::PERCENTAGE_DECIMAL); + bool add_modifier_effect( + std::string_view identifier, bool province_good, + ModifierEffect::format_t format = ModifierEffect::format_t::PERCENTAGE_DECIMAL + ); IDENTIFIER_REGISTRY_ACCESSORS(modifier_effect) bool add_modifier(std::string_view identifier, ModifierValue&& values, Modifier::icon_t icon); @@ -121,57 +121,57 @@ namespace OpenVic { bool setup_modifier_effects(); NodeTools::node_callback_t expect_validated_modifier_value_and_default( - NodeTools::callback_t modifier_callback, - NodeTools::key_value_callback_t default_callback, - ModifierEffectValidator auto effect_validator) const; + NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, + ModifierEffectValidator auto effect_validator + ) const; NodeTools::node_callback_t expect_validated_modifier_value( - NodeTools::callback_t modifier_callback, - ModifierEffectValidator auto effect_validator) const; + NodeTools::callback_t modifier_callback, ModifierEffectValidator auto effect_validator + ) const; NodeTools::node_callback_t expect_modifier_value_and_default( - NodeTools::callback_t modifier_callback, - NodeTools::key_value_callback_t default_callback) const; - NodeTools::node_callback_t expect_modifier_value( - NodeTools::callback_t modifier_callback) const; + NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback + ) const; + NodeTools::node_callback_t expect_modifier_value(NodeTools::callback_t modifier_callback) const; NodeTools::node_callback_t expect_whitelisted_modifier_value_and_default( - NodeTools::callback_t modifier_callback, - string_set_t const& whitelist, - NodeTools::key_value_callback_t default_callback) const; + NodeTools::callback_t modifier_callback, string_set_t const& whitelist, + NodeTools::key_value_callback_t default_callback + ) const; NodeTools::node_callback_t expect_whitelisted_modifier_value( - NodeTools::callback_t modifier_callback, - string_set_t const& whitelist) const; + NodeTools::callback_t modifier_callback, string_set_t const& whitelist + ) const; NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default( - NodeTools::callback_t modifier_callback, - NodeTools::key_value_callback_t default_callback, - NodeTools::key_map_t&& key_map) const; + NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, + NodeTools::key_map_t&& key_map + ) const; NodeTools::node_callback_t expect_modifier_value_and_key_map( - NodeTools::callback_t modifier_callback, - NodeTools::key_map_t&& key_map) const; + NodeTools::callback_t modifier_callback, NodeTools::key_map_t&& key_map + ) const; template NodeTools::node_callback_t expect_modifier_value_and_key_map_and_default( - NodeTools::callback_t modifier_callback, - NodeTools::key_value_callback_t default_callback, - NodeTools::key_map_t&& key_map, - Args... args) const { + NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, + NodeTools::key_map_t&& key_map, Args... args + ) const { NodeTools::add_key_map_entries(key_map, args...); return expect_modifier_value_and_key_map_and_default(modifier_callback, default_callback, std::move(key_map)); } template NodeTools::node_callback_t expect_modifier_value_and_keys_and_default( - NodeTools::callback_t modifier_callback, - NodeTools::key_value_callback_t default_callback, - Args... args) const { + NodeTools::callback_t modifier_callback, NodeTools::key_value_callback_t default_callback, + Args... args + ) const { return expect_modifier_value_and_key_map_and_default(modifier_callback, default_callback, {}, args...); } template NodeTools::node_callback_t expect_modifier_value_and_keys( - NodeTools::callback_t modifier_callback, - Args... args) const { - return expect_modifier_value_and_key_map_and_default(modifier_callback, NodeTools::key_value_invalid_callback, {}, args...); + NodeTools::callback_t modifier_callback, Args... args + ) const { + return expect_modifier_value_and_key_map_and_default( + modifier_callback, NodeTools::key_value_invalid_callback, {}, args... + ); } }; } diff --git a/src/openvic-simulation/country/Country.cpp b/src/openvic-simulation/country/Country.cpp index d666411..fc867d3 100644 --- a/src/openvic-simulation/country/Country.cpp +++ b/src/openvic-simulation/country/Country.cpp @@ -42,17 +42,10 @@ const std::vector& CountryParty::get_policies() const { } CountryParty::CountryParty( - std::string_view new_name, - Date new_start_date, - Date new_end_date, - const Ideology& new_ideology, + std::string_view new_name, Date new_start_date, Date new_end_date, const Ideology& new_ideology, std::vector&& new_policies -) : name { new_name }, - start_date { new_start_date }, - end_date { new_end_date }, - ideology { new_ideology }, - policies { std::move(new_policies) } { -} +) : name { new_name }, start_date { new_start_date }, end_date { new_end_date }, ideology { new_ideology }, + policies { std::move(new_policies) } {} std::string_view UnitNames::get_identifier() const { return identifier; @@ -62,12 +55,8 @@ const std::vector& UnitNames::get_names() const { return names; } -UnitNames::UnitNames( - std::string_view new_identifier, - std::vector&& new_names -) : identifier { new_identifier }, - names { std::move(new_names) } { -} +UnitNames::UnitNames(std::string_view new_identifier, std::vector&& new_names) + : identifier { new_identifier }, names { std::move(new_names) } {} const GraphicalCultureType& Country::get_graphical_culture() const { return graphical_culture; @@ -90,44 +79,33 @@ const bool Country::is_dynamic_tag() const { } Country::Country( - std::string_view new_identifier, - colour_t new_color, - const GraphicalCultureType& new_graphical_culture, - std::vector&& new_parties, - std::vector&& new_unit_names, - bool new_dynamic_tag, + std::string_view new_identifier, colour_t new_color, const GraphicalCultureType& new_graphical_culture, + std::vector&& new_parties, std::vector&& new_unit_names, bool new_dynamic_tag, std::map&& new_alternative_colours -) : HasIdentifierAndColour(new_identifier, new_color, false, false), - graphical_culture { new_graphical_culture }, - parties { std::move(new_parties) }, - unit_names { std::move(new_unit_names) }, - dynamic_tag { new_dynamic_tag }, - alternative_colours { std::move(new_alternative_colours) } { -} +) : HasIdentifierAndColour(new_identifier, new_color, false, false), graphical_culture { new_graphical_culture }, + parties { std::move(new_parties) }, unit_names { std::move(new_unit_names) }, dynamic_tag { new_dynamic_tag }, + alternative_colours { std::move(new_alternative_colours) } {} -CountryManager::CountryManager() - : countries { "countries" } { -} +CountryManager::CountryManager() : countries { "countries" } {} bool CountryManager::add_country( - std::string_view identifier, - colour_t color, - const GraphicalCultureType& graphical_culture, - std::vector&& parties, - std::vector&& unit_names, - bool dynamic_tag, + std::string_view identifier, colour_t color, const GraphicalCultureType& graphical_culture, + std::vector&& parties, std::vector&& unit_names, bool dynamic_tag, std::map&& alternative_colours ) { if (identifier.empty()) { return false; } - return countries.add_item({ identifier, color, graphical_culture, std::move(parties), - std::move(unit_names), dynamic_tag, std::move(alternative_colours) }); + return countries.add_item({ + identifier, color, graphical_culture, std::move(parties), std::move(unit_names), + dynamic_tag, std::move(alternative_colours) + }); } -bool CountryManager::load_country_data_file(GameManager& game_manager, - std::string_view name, bool is_dynamic, ast::NodeCPtr root) { +bool CountryManager::load_country_data_file( + GameManager& game_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root +) { colour_t color; const GraphicalCultureType* graphical_culture; std::vector country_parties; @@ -140,12 +118,16 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, bool ret = game_manager.get_politics_manager().get_government_type_manager() .expect_government_type_str(assign_variable_callback_pointer(colour_gov_type))(key); - if (!ret) return false; + if (!ret) { + return false; + } colour_t alternative_colour; ret &= expect_colour(assign_variable_callback(alternative_colour))(value); - if (!ret) return false; + if (!ret) { + return false; + } return alternative_colours.emplace(std::move(colour_gov_type), std::move(alternative_colour)).second; }, @@ -211,7 +193,9 @@ bool CountryManager::load_country_data_file(GameManager& game_manager, }) )(root); - ret &= add_country(name, color, *graphical_culture, std::move(country_parties), - std::move(unit_names), is_dynamic, std::move(alternative_colours)); + ret &= add_country( + name, color, *graphical_culture, std::move(country_parties), std::move(unit_names), is_dynamic, + std::move(alternative_colours) + ); return ret; } diff --git a/src/openvic-simulation/country/Country.hpp b/src/openvic-simulation/country/Country.hpp index 8077698..66ce2e6 100644 --- a/src/openvic-simulation/country/Country.hpp +++ b/src/openvic-simulation/country/Country.hpp @@ -37,10 +37,7 @@ namespace OpenVic { const std::vector policies; CountryParty( - std::string_view new_name, - Date new_start_date, - Date new_end_date, - const Ideology& new_ideology, + std::string_view new_name, Date new_start_date, Date new_end_date, const Ideology& new_ideology, std::vector&& new_policies ); @@ -77,12 +74,8 @@ namespace OpenVic { const std::map alternative_colours; Country( - std::string_view new_identifier, - colour_t new_color, - const GraphicalCultureType& new_graphical_culture, - std::vector&& new_parties, - std::vector&& new_unit_names, - const bool new_dynamic_tag, + std::string_view new_identifier, colour_t new_color, const GraphicalCultureType& new_graphical_culture, + std::vector&& new_parties, std::vector&& new_unit_names, const bool new_dynamic_tag, std::map&& new_alternative_colours ); @@ -102,16 +95,12 @@ namespace OpenVic { CountryManager(); bool add_country( - std::string_view identifier, - colour_t color, - const GraphicalCultureType& graphical_culture, - std::vector&& parties, - std::vector&& unit_names, - bool dynamic_tag, + std::string_view identifier, colour_t color, const GraphicalCultureType& graphical_culture, + std::vector&& parties, std::vector&& unit_names, bool dynamic_tag, std::map&& alternative_colours ); IDENTIFIER_REGISTRY_ACCESSORS_CUSTOM_PLURAL(country, countries); bool load_country_data_file(GameManager& game_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/dataloader/Dataloader.cpp b/src/openvic-simulation/dataloader/Dataloader.cpp index 7a904ed..5301aa1 100644 --- a/src/openvic-simulation/dataloader/Dataloader.cpp +++ b/src/openvic-simulation/dataloader/Dataloader.cpp @@ -89,8 +89,8 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { const bool hint_path_was_empty = hint_path.empty(); if (hint_path_was_empty) { #if defined(_WIN32) - static const fs::path registry_path = Windows::ReadRegValue(HKEY_LOCAL_MACHINE, - "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); + static const fs::path registry_path = + Windows::ReadRegValue(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); if (!registry_path.empty()) { return registry_path; @@ -171,7 +171,8 @@ static fs::path _search_for_game_path(fs::path hint_path = {}) { bool vic2_install_confirmed = false; // if current_path is not a regular file, this is a non-default Steam Library, skip this parser evaluation - if (fs::is_regular_file(current_path, error_code) && (is_libraryfolders_vdf || filename_equals(libraryfolders, current_path))) { + if (fs::is_regular_file(current_path, error_code) && + (is_libraryfolders_vdf || filename_equals(libraryfolders, current_path))) { lexy_vdf::Parser parser; std::string buffer; @@ -397,8 +398,8 @@ Dataloader::path_vector_t Dataloader::lookup_files_in_dir(fs::path const& path, return ret; } -bool Dataloader::apply_to_files_in_dir(fs::path const& path, fs::path const& extension, - callback_t callback) const { +bool Dataloader::apply_to_files_in_dir(fs::path const& path, fs::path const& extension, callback_t callback) + const { bool ret = true; for (fs::path const& file : lookup_files_in_dir(path, extension)) { if (!callback(file)) { @@ -478,8 +479,9 @@ bool Dataloader::_load_pop_types( static const fs::path pop_type_directory = "poptypes"; const bool ret = apply_to_files_in_dir(pop_type_directory, ".txt", [&pop_manager, &unit_manager, &good_manager](fs::path const& file) -> bool { - return pop_manager.load_pop_type_file(file.stem().string(), unit_manager, - good_manager, parse_defines(file).get_file_node()); + return pop_manager.load_pop_type_file( + file.stem().string(), unit_manager, good_manager, parse_defines(file).get_file_node() + ); } ); pop_manager.lock_pop_types(); @@ -491,8 +493,7 @@ bool Dataloader::_load_units(UnitManager& unit_manager, GoodManager const& good_ const bool ret = apply_to_files_in_dir(units_directory, ".txt", [&unit_manager, &good_manager](fs::path const& file) -> bool { return unit_manager.load_unit_file(good_manager, parse_defines(file).get_file_node()); - } - ); + }); unit_manager.lock_units(); return ret; } @@ -502,12 +503,16 @@ bool Dataloader::_load_oobs(GameManager& game_manager) const { /* used for countries with no defined initial OOB */ game_manager.get_military_manager().get_deployment_manager().add_deployment( - "NULL", std::vector(), std::vector(), std::vector()); + "NULL", std::vector(), std::vector(), std::vector() + ); bool ret = apply_to_files_in_dir(oob_directory, ".txt", [&game_manager](fs::path const& file) -> bool { - if (file.filename() == "v2dd2.txt") return true; /* dev diary just stuck in there for no reason whatsoever */ - return game_manager.get_military_manager().get_deployment_manager().load_oob_file(game_manager, - file.filename().string(), parse_defines(file).get_file_node()); + if (file.filename() == "v2dd2.txt") { + return true; /* dev diary just stuck in there for no reason whatsoever */ + } + return game_manager.get_military_manager().get_deployment_manager().load_oob_file( + game_manager, file.filename().string(), parse_defines(file).get_file_node() + ); }); /* we also load OOBs in top level subdirectories, for other start dates etc */ @@ -518,8 +523,8 @@ bool Dataloader::_load_oobs(GameManager& game_manager) const { if (entry.is_directory()) { ret &= apply_to_files_in_dir(entry, ".txt", [&entry, &game_manager](fs::path const& file) -> bool { return game_manager.get_military_manager().get_deployment_manager().load_oob_file( - game_manager, (entry.path().filename() / file.filename()).string(), - parse_defines(file).get_file_node()); + game_manager, (entry.path().filename() / file.filename()).string(), parse_defines(file).get_file_node() + ); }); } } @@ -534,22 +539,21 @@ bool Dataloader::_load_countries(GameManager& game_manager) const { bool is_dynamic = false; - bool ret = expect_dictionary( - [this, &game_manager, &is_dynamic](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "dynamic_tags") { - return expect_bool(assign_variable_callback(is_dynamic))(value); - } - - std::string_view data_path; + bool ret = expect_dictionary([this, &game_manager, &is_dynamic](std::string_view key, ast::NodeCPtr value) -> bool { + if (key == "dynamic_tags") { + return expect_bool(assign_variable_callback(is_dynamic))(value); + } - if (!expect_string(assign_variable_callback(data_path))(value)) { - return false; - } + std::string_view data_path; - return game_manager.get_country_manager().load_country_data_file(game_manager, key, is_dynamic, - parse_defines(lookup_file(countries_file.parent_path() / data_path)).get_file_node()); + if (!expect_string(assign_variable_callback(data_path))(value)) { + return false; } - )(parse_defines(lookup_file(countries_file)).get_file_node()); + + return game_manager.get_country_manager().load_country_data_file( + game_manager, key, is_dynamic, parse_defines(lookup_file(countries_file.parent_path() / data_path)).get_file_node() + ); + })(parse_defines(lookup_file(countries_file)).get_file_node()); game_manager.get_country_manager().lock_countries(); return ret; @@ -560,19 +564,18 @@ bool Dataloader::_load_history(GameManager& game_manager) const { static const fs::path province_history_directory = "history/provinces"; /* Country History */ - bool ret = apply_to_files_in_dir(country_history_directory, ".txt", - [this, &game_manager](fs::path const& file) -> bool { - std::string tag = file.filename().string().substr(0, 3); - - if (!game_manager.get_country_manager().has_country_identifier(tag)) { - Logger::error("Error loading history for country ", tag, ": tag not defined!"); - return false; - } + bool ret = apply_to_files_in_dir(country_history_directory, ".txt", [this, &game_manager](fs::path const& file) -> bool { + std::string tag = file.filename().string().substr(0, 3); - return game_manager.get_history_manager().get_country_manager().load_country_history_file( - game_manager, tag, parse_defines(lookup_file(file)).get_file_node()); + if (!game_manager.get_country_manager().has_country_identifier(tag)) { + Logger::error("Error loading history for country ", tag, ": tag not defined!"); + return false; } - ); + + return game_manager.get_history_manager().get_country_manager().load_country_history_file( + game_manager, tag, parse_defines(lookup_file(file)).get_file_node() + ); + }); game_manager.get_history_manager().get_country_manager().lock_country_histories(); /* Province History */ @@ -591,7 +594,8 @@ bool Dataloader::_load_history(GameManager& game_manager) const { } return game_manager.get_history_manager().get_province_manager().load_province_history_file( - game_manager, province_id, parse_defines(lookup_file(file)).get_file_node()); + game_manager, province_id, parse_defines(lookup_file(file)).get_file_node() + ); }); } } @@ -657,8 +661,7 @@ bool Dataloader::_load_map_dir(GameManager& game_manager) const { ) ), -#define MAP_PATH_DICT_ENTRY(X) \ - #X, ONE_EXACTLY, expect_string(assign_variable_callback(X)), +#define MAP_PATH_DICT_ENTRY(X) #X, ONE_EXACTLY, expect_string(assign_variable_callback(X)), APPLY_TO_MAP_PATHS(MAP_PATH_DICT_ENTRY) #undef MAP_PATH_DICT_ENTRY @@ -674,23 +677,20 @@ bool Dataloader::_load_map_dir(GameManager& game_manager) const { Logger::error("Failed to load map default file!"); } - if (!map.load_province_definitions( - parse_csv(lookup_file(map_directory / definitions)).get_lines() - )) { + if (!map.load_province_definitions(parse_csv(lookup_file(map_directory / definitions)).get_lines())) { Logger::error("Failed to load province definitions file!"); ret = false; } if (!map.load_province_positions( - game_manager.get_economy_manager().get_building_manager(), parse_defines(lookup_file(map_directory / positions)).get_file_node() + game_manager.get_economy_manager().get_building_manager(), + parse_defines(lookup_file(map_directory / positions)).get_file_node() )) { Logger::error("Failed to load province positions file!"); ret = false; } - if (!map.load_region_file( - parse_defines(lookup_file(map_directory / region)).get_file_node() - )) { + if (!map.load_region_file(parse_defines(lookup_file(map_directory / region)).get_file_node())) { Logger::error("Failed to load region file!"); ret = false; } @@ -701,24 +701,18 @@ bool Dataloader::_load_map_dir(GameManager& game_manager) const { } if (!map.get_terrain_type_manager().load_terrain_types( - game_manager.get_modifier_manager(), - parse_defines(lookup_file(map_directory / terrain_definition)).get_file_node() + game_manager.get_modifier_manager(), parse_defines(lookup_file(map_directory / terrain_definition)).get_file_node() )) { Logger::error("Failed to load terrain types!"); ret = false; } - if (!map.load_map_images( - lookup_file(map_directory / provinces), - lookup_file(map_directory / terrain), false - )) { + if (!map.load_map_images(lookup_file(map_directory / provinces), lookup_file(map_directory / terrain), false)) { Logger::error("Failed to load map images!"); ret = false; } - if (!map.generate_and_load_province_adjacencies( - parse_csv(lookup_file(map_directory / adjacencies)).get_lines() - )) { + if (!map.generate_and_load_province_adjacencies(parse_csv(lookup_file(map_directory / adjacencies)).get_lines())) { Logger::error("Failed to generate and load province adjacencies!"); ret = false; } @@ -757,13 +751,14 @@ bool Dataloader::load_defines(GameManager& game_manager) const { Logger::error("Failed to load goods!"); ret = false; } - if (!_load_units(game_manager.get_military_manager().get_unit_manager(), - game_manager.get_economy_manager().get_good_manager() + if (!_load_units( + game_manager.get_military_manager().get_unit_manager(), game_manager.get_economy_manager().get_good_manager() )) { Logger::error("Failed to load units!"); ret = false; } - if (!_load_pop_types(game_manager.get_pop_manager(), game_manager.get_military_manager().get_unit_manager(), + if (!_load_pop_types( + game_manager.get_pop_manager(), game_manager.get_military_manager().get_unit_manager(), game_manager.get_economy_manager().get_good_manager() )) { Logger::error("Failed to load pop types!"); @@ -855,11 +850,10 @@ bool Dataloader::load_defines(GameManager& game_manager) const { bool Dataloader::load_pop_history(GameManager& game_manager, fs::path const& path) const { return apply_to_files_in_dir(path, ".txt", [&game_manager](fs::path const& file) -> bool { - return game_manager.get_map().expect_province_dictionary( - [&game_manager](Province& province, ast::NodeCPtr value) -> bool { + return game_manager.get_map() + .expect_province_dictionary([&game_manager](Province& province, ast::NodeCPtr value) -> bool { return province.load_pop_list(game_manager.get_pop_manager(), value); - } - )(parse_defines(file).get_file_node()); + })(parse_defines(file).get_file_node()); }); } diff --git a/src/openvic-simulation/dataloader/Dataloader.hpp b/src/openvic-simulation/dataloader/Dataloader.hpp index 1a8e9ab..0bf3086 100644 --- a/src/openvic-simulation/dataloader/Dataloader.hpp +++ b/src/openvic-simulation/dataloader/Dataloader.hpp @@ -92,9 +92,9 @@ namespace OpenVic { Finnish, _LocaleCount }; - static constexpr char const* locale_names[_LocaleCount] = { - "en_GB", "fr_FR", "de_DE", "pl_PL", "es_ES", "it_IT", "sv_SE", "cs_CZ", "hu_HU", "nl_NL", "pt_PT", "ru_RU", "fi_FI" - }; + static constexpr char const* locale_names[_LocaleCount] = { "en_GB", "fr_FR", "de_DE", "pl_PL", "es_ES", + "it_IT", "sv_SE", "cs_CZ", "hu_HU", "nl_NL", + "pt_PT", "ru_RU", "fi_FI" }; /* Args: key, locale, localisation */ using localisation_callback_t = NodeTools::callback_t; diff --git a/src/openvic-simulation/dataloader/Dataloader_Windows.hpp b/src/openvic-simulation/dataloader/Dataloader_Windows.hpp index 6b6fce3..37991b6 100644 --- a/src/openvic-simulation/dataloader/Dataloader_Windows.hpp +++ b/src/openvic-simulation/dataloader/Dataloader_Windows.hpp @@ -55,22 +55,17 @@ namespace OpenVic::Windows { template concept has_data = requires(T t) { - { - t.data() - } - -> std::convertible_to; + { t.data() } -> std::convertible_to; }; class RegistryKey { public: - RegistryKey(HKEY key_handle) - : _key_handle(key_handle) { - } + RegistryKey(HKEY key_handle) : _key_handle(key_handle) {} template - RegistryKey(HKEY parent_key_handle, - std::basic_string_view child_key_name, - std::basic_string_view value_name) { + RegistryKey( + HKEY parent_key_handle, std::basic_string_view child_key_name, std::basic_string_view value_name + ) { open_key(parent_key_handle, child_key_name); query_key(value_name); } @@ -100,14 +95,10 @@ namespace OpenVic::Windows { } bool is_predefined() const { - return (_key_handle == HKEY_CURRENT_USER) || - (_key_handle == HKEY_LOCAL_MACHINE) || - (_key_handle == HKEY_CLASSES_ROOT) || - (_key_handle == HKEY_CURRENT_CONFIG) || - (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || - (_key_handle == HKEY_PERFORMANCE_DATA) || - (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || - (_key_handle == HKEY_PERFORMANCE_TEXT) || + return (_key_handle == HKEY_CURRENT_USER) || (_key_handle == HKEY_LOCAL_MACHINE) || + (_key_handle == HKEY_CLASSES_ROOT) || (_key_handle == HKEY_CURRENT_CONFIG) || + (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (_key_handle == HKEY_PERFORMANCE_DATA) || + (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || (_key_handle == HKEY_PERFORMANCE_TEXT) || (_key_handle == HKEY_USERS); } @@ -139,7 +130,9 @@ namespace OpenVic::Windows { return result; } _value = std::wstring(data_size / sizeof(wchar_t), L'\0'); - result = RegQueryValueExW(_key_handle, wide_value.data(), NULL, NULL, reinterpret_cast(_value.data()), &data_size); + result = RegQueryValueExW( + _key_handle, wide_value.data(), NULL, NULL, reinterpret_cast(_value.data()), &data_size + ); close_key(); std::size_t first_null = _value.find_first_of(L'\0'); @@ -156,7 +149,9 @@ namespace OpenVic::Windows { }; template - std::basic_string ReadRegValue(HKEY root, std::basic_string_view key, std::basic_string_view name) { + std::basic_string ReadRegValue( + HKEY root, std::basic_string_view key, std::basic_string_view name + ) { RegistryKey registry_key(root, key, name); if constexpr (std::is_same_v) { return convert(registry_key.value()); @@ -172,4 +167,4 @@ namespace OpenVic::Windows { return ReadRegValue(root, key_sv, name_sv); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/dataloader/NodeTools.cpp b/src/openvic-simulation/dataloader/NodeTools.cpp index 69aebc9..2f93bc2 100644 --- a/src/openvic-simulation/dataloader/NodeTools.cpp +++ b/src/openvic-simulation/dataloader/NodeTools.cpp @@ -53,55 +53,51 @@ node_callback_t NodeTools::expect_identifier_or_string(callback_t(callback, allow_empty)(*cast_node); } - Logger::error("Invalid node type ", node->get_type(), " when expecting ", - ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static()); + Logger::error( + "Invalid node type ", node->get_type(), " when expecting ", ast::IdentifierNode::get_type_static(), " or ", + ast::StringNode::get_type_static() + ); } else { - Logger::error("Null node when expecting ", ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static()); + Logger::error( + "Null node when expecting ", ast::IdentifierNode::get_type_static(), " or ", ast::StringNode::get_type_static() + ); } return false; }; } node_callback_t NodeTools::expect_bool(callback_t callback) { - static const string_map_t bool_map = { - { "yes", true }, { "no", false } - }; + static const string_map_t bool_map = { { "yes", true }, { "no", false } }; return expect_identifier(expect_mapped_string(bool_map, callback)); } node_callback_t NodeTools::expect_int_bool(callback_t callback) { - static const string_map_t bool_map = { - { "1", true }, { "0", false } - }; + static const string_map_t bool_map = { { "1", true }, { "0", false } }; return expect_identifier(expect_mapped_string(bool_map, callback)); } node_callback_t NodeTools::expect_int64(callback_t callback) { - return expect_identifier( - [callback](std::string_view identifier) -> bool { - bool successful = false; - const int64_t val = StringUtils::string_to_int64(identifier, &successful, 10); - if (successful) { - return callback(val); - } - Logger::error("Invalid int identifier text: ", identifier); - return false; + return expect_identifier([callback](std::string_view identifier) -> bool { + bool successful = false; + const int64_t val = StringUtils::string_to_int64(identifier, &successful, 10); + if (successful) { + return callback(val); } - ); + Logger::error("Invalid int identifier text: ", identifier); + return false; + }); } node_callback_t NodeTools::expect_uint64(callback_t callback) { - return expect_identifier( - [callback](std::string_view identifier) -> bool { - bool successful = false; - const uint64_t val = StringUtils::string_to_uint64(identifier, &successful, 10); - if (successful) { - return callback(val); - } - Logger::error("Invalid uint identifier text: ", identifier); - return false; + return expect_identifier([callback](std::string_view identifier) -> bool { + bool successful = false; + const uint64_t val = StringUtils::string_to_uint64(identifier, &successful, 10); + if (successful) { + return callback(val); } - ); + Logger::error("Invalid uint identifier text: ", identifier); + return false; + }); } callback_t NodeTools::expect_fixed_point_str(callback_t callback) { @@ -201,30 +197,26 @@ node_callback_t NodeTools::expect_fvec2(callback_t callback) { } node_callback_t NodeTools::expect_assign(key_value_callback_t callback) { - return _expect_type( - [callback](ast::AssignNode const& assign_node) -> bool { - return callback(assign_node._name, assign_node._initializer.get()); - } - ); + return _expect_type([callback](ast::AssignNode const& assign_node) -> bool { + return callback(assign_node._name, assign_node._initializer.get()); + }); } node_callback_t NodeTools::expect_list_and_length(length_callback_t length_callback, node_callback_t callback) { - return _expect_type( - [length_callback, callback](ast::AbstractListNode const& list_node) -> bool { - std::vector const& list = list_node._statements; - bool ret = true; - size_t size = length_callback(list.size()); - if (size > list.size()) { - Logger::error("Trying to read more values than the list contains: ", size, " > ", list.size()); - size = list.size(); - ret = false; - } - std::for_each(list.begin(), list.begin() + size, [callback, &ret](ast::NodeUPtr const& sub_node) -> void { - ret &= callback(sub_node.get()); - }); - return ret; + return _expect_type([length_callback, callback](ast::AbstractListNode const& list_node) -> bool { + std::vector const& list = list_node._statements; + bool ret = true; + size_t size = length_callback(list.size()); + if (size > list.size()) { + Logger::error("Trying to read more values than the list contains: ", size, " > ", list.size()); + size = list.size(); + ret = false; } - ); + std::for_each(list.begin(), list.begin() + size, [callback, &ret](ast::NodeUPtr const& sub_node) -> void { + ret &= callback(sub_node.get()); + }); + return ret; + }); } node_callback_t NodeTools::expect_list_of_length(size_t length, node_callback_t callback) { @@ -266,26 +258,24 @@ node_callback_t NodeTools::expect_length(callback_t callback) { } node_callback_t NodeTools::expect_key(std::string_view key, node_callback_t callback, bool* key_found) { - return _expect_type( - [key, callback, key_found](ast::AbstractListNode const& list_node) -> bool { - std::vector const& list = list_node._statements; - for (ast::NodeUPtr const& sub_node : list_node._statements) { - ast::AssignNode const* assign_node = sub_node->cast_to(); - if (assign_node != nullptr && assign_node->_name == key) { - if (key_found != nullptr) { - *key_found = true; - } - return callback(&*assign_node->_initializer); + return _expect_type([key, callback, key_found](ast::AbstractListNode const& list_node) -> bool { + std::vector const& list = list_node._statements; + for (ast::NodeUPtr const& sub_node : list_node._statements) { + ast::AssignNode const* assign_node = sub_node->cast_to(); + if (assign_node != nullptr && assign_node->_name == key) { + if (key_found != nullptr) { + *key_found = true; } + return callback(&*assign_node->_initializer); } - if (key_found != nullptr) { - *key_found = false; - } else { - Logger::error("Failed to find expected key: ", key); - } - return false; } - ); + if (key_found != nullptr) { + *key_found = false; + } else { + Logger::error("Failed to find expected key: ", key); + } + return false; + }); } node_callback_t NodeTools::expect_dictionary_and_length(length_callback_t length_callback, key_value_callback_t callback) { @@ -296,8 +286,9 @@ node_callback_t NodeTools::expect_dictionary(key_value_callback_t callback) { return expect_dictionary_and_length(default_length_callback, callback); } -bool NodeTools::add_key_map_entry(key_map_t& key_map, std::string_view key, - dictionary_entry_t::expected_count_t expected_count, node_callback_t callback) { +bool NodeTools::add_key_map_entry( + key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, node_callback_t callback +) { if (key_map.find(key) == key_map.end()) { key_map.emplace(key, dictionary_entry_t { expected_count, callback }); return true; @@ -344,12 +335,11 @@ bool NodeTools::check_key_map_counts(key_map_t& key_map) { return ret; } -node_callback_t NodeTools::expect_dictionary_key_map_and_length_and_default(key_map_t key_map, - length_callback_t length_callback, key_value_callback_t default_callback) { +node_callback_t NodeTools::expect_dictionary_key_map_and_length_and_default( + key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback +) { return [length_callback, default_callback, key_map = std::move(key_map)](ast::NodeCPtr node) mutable -> bool { - bool ret = expect_dictionary_and_length( - length_callback, dictionary_keys_callback(key_map, default_callback) - )(node); + bool ret = expect_dictionary_and_length(length_callback, dictionary_keys_callback(key_map, default_callback))(node); ret &= check_key_map_counts(key_map); return ret; }; @@ -364,8 +354,9 @@ node_callback_t NodeTools::expect_dictionary_key_map_and_default(key_map_t key_m } node_callback_t NodeTools::expect_dictionary_key_map(key_map_t key_map) { - return expect_dictionary_key_map_and_length_and_default(std::move(key_map), - default_length_callback, key_value_invalid_callback); + return expect_dictionary_key_map_and_length_and_default( + std::move(key_map), default_length_callback, key_value_invalid_callback + ); } node_callback_t NodeTools::name_list_callback(callback_t&&> callback) { diff --git a/src/openvic-simulation/dataloader/NodeTools.hpp b/src/openvic-simulation/dataloader/NodeTools.hpp index 7ad5412..798976f 100644 --- a/src/openvic-simulation/dataloader/NodeTools.hpp +++ b/src/openvic-simulation/dataloader/NodeTools.hpp @@ -27,19 +27,13 @@ namespace OpenVic { namespace NodeTools { template - concept Functor = requires(Fn&& fn, Args&& ... args) { - { - std::invoke(std::forward(fn), std::forward(args)...) - } - -> std::same_as; + concept Functor = requires(Fn&& fn, Args&&... args) { + { std::invoke(std::forward(fn), std::forward(args)...) } -> std::same_as; }; template - concept FunctorConvertible = requires(Fn&& fn, Args&& ... args) { - { - std::invoke(std::forward(fn), std::forward(args)...) - } - -> std::convertible_to; + concept FunctorConvertible = requires(Fn&& fn, Args&&... args) { + { std::invoke(std::forward(fn), std::forward(args)...) } -> std::convertible_to; }; template @@ -88,7 +82,10 @@ namespace OpenVic { val <= static_cast(std::numeric_limits::max())) { return callback(val); } - Logger::error("Invalid int: ", val, " (valid range: [", static_cast(std::numeric_limits::lowest()), ", ", static_cast(std::numeric_limits::max()), "])"); + Logger::error( + "Invalid int: ", val, " (valid range: [", static_cast(std::numeric_limits::lowest()), ", ", + static_cast(std::numeric_limits::max()), "])" + ); return false; }); } @@ -99,7 +96,9 @@ namespace OpenVic { if (val <= static_cast(std::numeric_limits::max())) { return callback(val); } - Logger::error("Invalid uint: ", val, " (valid range: [0, ", static_cast(std::numeric_limits::max()), "])"); + Logger::error( + "Invalid uint: ", val, " (valid range: [0, ", static_cast(std::numeric_limits::max()), "])" + ); return false; }); } @@ -159,8 +158,10 @@ namespace OpenVic { using enum dictionary_entry_t::expected_count_t; using key_map_t = string_map_t; - bool add_key_map_entry(key_map_t& key_map, std::string_view key, - dictionary_entry_t::expected_count_t expected_count, node_callback_t callback); + bool add_key_map_entry( + key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, + node_callback_t callback + ); bool remove_key_map_entry(key_map_t& key_map, std::string_view key); key_value_callback_t dictionary_keys_callback(key_map_t& key_map, key_value_callback_t default_callback); bool check_key_map_counts(key_map_t& key_map); @@ -169,30 +170,35 @@ namespace OpenVic { return true; } template - bool add_key_map_entries(key_map_t& key_map, std::string_view key, - dictionary_entry_t::expected_count_t expected_count, NodeCallback auto callback, Args... args) { + bool add_key_map_entries( + key_map_t& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, + NodeCallback auto callback, Args... args + ) { bool ret = add_key_map_entry(key_map, key, expected_count, callback); ret &= add_key_map_entries(key_map, args...); return ret; } - node_callback_t expect_dictionary_key_map_and_length_and_default(key_map_t key_map, - length_callback_t length_callback, key_value_callback_t default_callback); + node_callback_t expect_dictionary_key_map_and_length_and_default( + key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback + ); node_callback_t expect_dictionary_key_map_and_length(key_map_t key_map, length_callback_t length_callback); node_callback_t expect_dictionary_key_map_and_default(key_map_t key_map, key_value_callback_t default_callback); node_callback_t expect_dictionary_key_map(key_map_t key_map); template - NodeCallback auto expect_dictionary_key_map_and_length_and_default(key_map_t key_map, - length_callback_t length_callback, key_value_callback_t default_callback, Args... args) { + NodeCallback auto expect_dictionary_key_map_and_length_and_default( + key_map_t key_map, length_callback_t length_callback, key_value_callback_t default_callback, Args... args + ) { // TODO - pass return value back up (part of big key_map_t rewrite?) add_key_map_entries(key_map, args...); return expect_dictionary_key_map_and_length_and_default(std::move(key_map), length_callback, default_callback); } template - NodeCallback auto expect_dictionary_keys_and_length_and_default(LengthCallback auto length_callback, - KeyValueCallback auto default_callback, Args... args) { + NodeCallback auto expect_dictionary_keys_and_length_and_default( + LengthCallback auto length_callback, KeyValueCallback auto default_callback, Args... args + ) { return expect_dictionary_key_map_and_length_and_default({}, length_callback, default_callback, args...); } @@ -208,15 +214,14 @@ namespace OpenVic { template NodeCallback auto expect_dictionary_keys(Args... args) { - return expect_dictionary_key_map_and_length_and_default({}, default_length_callback, key_value_invalid_callback, args...); + return expect_dictionary_key_map_and_length_and_default( + {}, default_length_callback, key_value_invalid_callback, args... + ); } template concept Reservable = requires(T& t) { - { - t.size() - } - -> std::same_as; + { t.size() } -> std::same_as; t.reserve(size_t {}); }; template @@ -288,9 +293,7 @@ namespace OpenVic { } template - requires requires(T& t) { - t += T {}; - } + requires requires(T& t) { t += T {}; } Callback auto add_variable_callback(T& var) { return [&var](T val) -> bool { var += val; @@ -299,9 +302,7 @@ namespace OpenVic { } template - requires requires(T& t) { - t++; - } + requires requires(T& t) { t++; } KeyValueCallback auto increment_callback(T& var) { return [&var](std::string_view, ast::NodeCPtr) -> bool { var++; diff --git a/src/openvic-simulation/economy/Building.cpp b/src/openvic-simulation/economy/Building.cpp index 29eb50e..a79741b 100644 --- a/src/openvic-simulation/economy/Building.cpp +++ b/src/openvic-simulation/economy/Building.cpp @@ -5,15 +5,16 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Building::Building(std::string_view identifier, BuildingType const& type, ARGS) - : HasIdentifier { identifier }, type { type }, modifier { std::move(modifier) }, on_completion { on_completion }, - completion_size { completion_size }, max_level { max_level }, goods_cost { std::move(goods_cost) }, cost { cost }, - build_time { build_time }, visibility { visibility }, on_map { on_map }, default_enabled { default_enabled }, - production_type { production_type }, pop_build_factory { pop_build_factory }, strategic_factory { strategic_factory }, - advanced_factory { advanced_factory }, fort_level { fort_level }, naval_capacity { naval_capacity }, - colonial_points { std::move(colonial_points) }, in_province { in_province }, one_per_state { one_per_state }, - colonial_range { colonial_range }, infrastructure { infrastructure }, spawn_railway_track { spawn_railway_track }, - sail { sail }, steam { steam }, capital { capital }, port { port } {} +Building::Building( + std::string_view identifier, BuildingType const& type, ARGS +) : HasIdentifier { identifier }, type { type }, modifier { std::move(modifier) }, on_completion { on_completion }, + completion_size { completion_size }, max_level { max_level }, goods_cost { std::move(goods_cost) }, cost { cost }, + build_time { build_time }, visibility { visibility }, on_map { on_map }, default_enabled { default_enabled }, + production_type { production_type }, pop_build_factory { pop_build_factory }, strategic_factory { strategic_factory }, + advanced_factory { advanced_factory }, fort_level { fort_level }, naval_capacity { naval_capacity }, + colonial_points { std::move(colonial_points) }, in_province { in_province }, one_per_state { one_per_state }, + colonial_range { colonial_range }, infrastructure { infrastructure }, spawn_railway_track { spawn_railway_track }, + sail { sail }, steam { steam }, capital { capital }, port { port } {} BuildingType const& Building::get_type() const { return type; @@ -161,8 +162,7 @@ void BuildingInstance::update_state(Date const& today) { case ExpansionState::Expanding: expansion_progress = static_cast(today - start) / static_cast(end - start); break; - default: - expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; + default: expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; } } @@ -206,9 +206,10 @@ bool BuildingManager::add_building(std::string_view identifier, BuildingType con }); } -bool BuildingManager::load_buildings_file(GoodManager const& good_manager, - ProductionTypeManager const& production_type_manager, - ModifierManager const& modifier_manager, ast::NodeCPtr root) { +bool BuildingManager::load_buildings_file( + GoodManager const& good_manager, ProductionTypeManager const& production_type_manager, + ModifierManager const& modifier_manager, ast::NodeCPtr root +) { bool ret = expect_dictionary_reserve_length(buildings, [this](std::string_view, ast::NodeCPtr value) -> bool { return expect_key("type", expect_identifier( std::bind(&BuildingManager::add_building_type, this, std::placeholders::_1) @@ -216,65 +217,68 @@ bool BuildingManager::load_buildings_file(GoodManager const& good_manager, })(root); lock_building_types(); - ret &= expect_dictionary([this, &good_manager, &production_type_manager, &modifier_manager]( - std::string_view key, ast::NodeCPtr value) -> bool { - BuildingType const* type = nullptr; - ProductionType const* production_type = nullptr; - std::string_view on_completion; - fixed_point_t completion_size = 0, cost = 0, infrastructure = 0, colonial_range = 0; - Building::level_t max_level = 0, fort_level = 0; - Good::good_map_t goods_cost; - Timespan build_time; - bool visibility = false, on_map = false, default_enabled = false, pop_build_factory = false; - bool strategic_factory = false, advanced_factory = false; - bool in_province = false, one_per_state = false, spawn_railway_track = false, sail = false, steam = false; - bool capital = false, port = false; - uint64_t naval_capacity = 0; - std::vector colonial_points; - ModifierValue modifier; - - bool ret = modifier_manager.expect_modifier_value_and_keys(move_variable_callback(modifier), - "type", ONE_EXACTLY, expect_building_type_identifier(assign_variable_callback_pointer(type)), - "on_completion", ZERO_OR_ONE, expect_identifier(assign_variable_callback(on_completion)), - "completion_size", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(completion_size)), - "max_level", ONE_EXACTLY, expect_uint(assign_variable_callback(max_level)), - "goods_cost", ONE_EXACTLY, good_manager.expect_good_decimal_map(move_variable_callback(goods_cost)), - "cost", ZERO_OR_MORE, expect_fixed_point(assign_variable_callback(cost)), - "time", ONE_EXACTLY, expect_days(assign_variable_callback(build_time)), - "visibility", ONE_EXACTLY, expect_bool(assign_variable_callback(visibility)), - "onmap", ONE_EXACTLY, expect_bool(assign_variable_callback(on_map)), - "default_enabled", ZERO_OR_ONE, expect_bool(assign_variable_callback(default_enabled)), - "production_type", ZERO_OR_ONE, production_type_manager.expect_production_type_identifier( - assign_variable_callback_pointer(production_type)), - "pop_build_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(pop_build_factory)), - "strategic_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(strategic_factory)), - "advanced_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(advanced_factory)), - "fort_level", ZERO_OR_ONE, expect_uint(assign_variable_callback(fort_level)), - "naval_capacity", ZERO_OR_ONE, expect_uint(assign_variable_callback(naval_capacity)), - "colonial_points", ZERO_OR_ONE, expect_list(expect_fixed_point([&colonial_points](fixed_point_t points) -> bool { - colonial_points.push_back(points); - return true; - })), - "province", ZERO_OR_ONE, expect_bool(assign_variable_callback(in_province)), - "one_per_state", ZERO_OR_ONE, expect_bool(assign_variable_callback(one_per_state)), - "colonial_range", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(colonial_range)), - "infrastructure", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(infrastructure)), - "spawn_railway_track", ZERO_OR_ONE, expect_bool(assign_variable_callback(spawn_railway_track)), - "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(sail)), - "steam", ZERO_OR_ONE, expect_bool(assign_variable_callback(steam)), - "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(capital)), - "port", ZERO_OR_ONE, expect_bool(assign_variable_callback(port)) - )(value); - - ret &= add_building( - key, type, std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), - cost, build_time, visibility, on_map, default_enabled, production_type, pop_build_factory, strategic_factory, - advanced_factory, fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, - colonial_range, infrastructure, spawn_railway_track, sail, steam, capital, port - ); - - return ret; - })(root); + ret &= expect_dictionary( + [this, &good_manager, &production_type_manager, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { + BuildingType const* type = nullptr; + ProductionType const* production_type = nullptr; + std::string_view on_completion; + fixed_point_t completion_size = 0, cost = 0, infrastructure = 0, colonial_range = 0; + Building::level_t max_level = 0, fort_level = 0; + Good::good_map_t goods_cost; + Timespan build_time; + bool visibility = false, on_map = false, default_enabled = false, pop_build_factory = false; + bool strategic_factory = false, advanced_factory = false; + bool in_province = false, one_per_state = false, spawn_railway_track = false, sail = false, steam = false; + bool capital = false, port = false; + uint64_t naval_capacity = 0; + std::vector colonial_points; + ModifierValue modifier; + + bool ret = modifier_manager.expect_modifier_value_and_keys(move_variable_callback(modifier), + "type", ONE_EXACTLY, expect_building_type_identifier(assign_variable_callback_pointer(type)), + "on_completion", ZERO_OR_ONE, expect_identifier(assign_variable_callback(on_completion)), + "completion_size", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(completion_size)), + "max_level", ONE_EXACTLY, expect_uint(assign_variable_callback(max_level)), + "goods_cost", ONE_EXACTLY, good_manager.expect_good_decimal_map(move_variable_callback(goods_cost)), + "cost", ZERO_OR_MORE, expect_fixed_point(assign_variable_callback(cost)), + "time", ONE_EXACTLY, expect_days(assign_variable_callback(build_time)), + "visibility", ONE_EXACTLY, expect_bool(assign_variable_callback(visibility)), + "onmap", ONE_EXACTLY, expect_bool(assign_variable_callback(on_map)), + "default_enabled", ZERO_OR_ONE, expect_bool(assign_variable_callback(default_enabled)), + "production_type", ZERO_OR_ONE, production_type_manager.expect_production_type_identifier( + assign_variable_callback_pointer(production_type)), + "pop_build_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(pop_build_factory)), + "strategic_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(strategic_factory)), + "advanced_factory", ZERO_OR_ONE, expect_bool(assign_variable_callback(advanced_factory)), + "fort_level", ZERO_OR_ONE, expect_uint(assign_variable_callback(fort_level)), + "naval_capacity", ZERO_OR_ONE, expect_uint(assign_variable_callback(naval_capacity)), + "colonial_points", ZERO_OR_ONE, expect_list(expect_fixed_point( + [&colonial_points](fixed_point_t points) -> bool { + colonial_points.push_back(points); + return true; + } + )), + "province", ZERO_OR_ONE, expect_bool(assign_variable_callback(in_province)), + "one_per_state", ZERO_OR_ONE, expect_bool(assign_variable_callback(one_per_state)), + "colonial_range", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(colonial_range)), + "infrastructure", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(infrastructure)), + "spawn_railway_track", ZERO_OR_ONE, expect_bool(assign_variable_callback(spawn_railway_track)), + "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(sail)), + "steam", ZERO_OR_ONE, expect_bool(assign_variable_callback(steam)), + "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(capital)), + "port", ZERO_OR_ONE, expect_bool(assign_variable_callback(port)) + )(value); + + ret &= add_building( + key, type, std::move(modifier), on_completion, completion_size, max_level, std::move(goods_cost), cost, + build_time, visibility, on_map, default_enabled, production_type, pop_build_factory, strategic_factory, + advanced_factory, fort_level, naval_capacity, std::move(colonial_points), in_province, one_per_state, + colonial_range, infrastructure, spawn_railway_track, sail, steam, capital, port + ); + + return ret; + } + )(root); lock_buildings(); return ret; diff --git a/src/openvic-simulation/economy/Building.hpp b/src/openvic-simulation/economy/Building.hpp index bbf97fb..89b6db8 100644 --- a/src/openvic-simulation/economy/Building.hpp +++ b/src/openvic-simulation/economy/Building.hpp @@ -1,19 +1,19 @@ #pragma once -#include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/IdentifierRegistry.hpp" +#include "openvic-simulation/Modifier.hpp" #include "openvic-simulation/economy/Good.hpp" #include "openvic-simulation/economy/ProductionType.hpp" -#include "openvic-simulation/Modifier.hpp" +#include "openvic-simulation/types/Date.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #define ARGS \ ModifierValue&& modifier, std::string_view on_completion, fixed_point_t completion_size, level_t max_level, \ - Good::good_map_t&& goods_cost, fixed_point_t cost, Timespan build_time, bool visibility, bool on_map, bool default_enabled, \ - ProductionType const* production_type, bool pop_build_factory, bool strategic_factory, bool advanced_factory, level_t fort_level, \ - uint64_t naval_capacity, std::vector&& colonial_points, bool in_province, bool one_per_state, fixed_point_t colonial_range, \ - fixed_point_t infrastructure, bool spawn_railway_track, bool sail, bool steam, \ - bool capital, bool port + Good::good_map_t&& goods_cost, fixed_point_t cost, Timespan build_time, bool visibility, bool on_map, \ + bool default_enabled, ProductionType const* production_type, bool pop_build_factory, bool strategic_factory, \ + bool advanced_factory, level_t fort_level, uint64_t naval_capacity, std::vector&& colonial_points, \ + bool in_province, bool one_per_state, fixed_point_t colonial_range, fixed_point_t infrastructure, \ + bool spawn_railway_track, bool sail, bool steam, bool capital, bool port namespace OpenVic { @@ -33,14 +33,14 @@ namespace OpenVic { private: BuildingType const& type; const ModifierValue modifier; - const std::string on_completion; //probably sound played on completion + const std::string on_completion; // probably sound played on completion const fixed_point_t completion_size; const level_t max_level; const Good::good_map_t goods_cost; const fixed_point_t cost; - const Timespan build_time; //time + const Timespan build_time; // time const bool visibility; - const bool on_map; //onmap + const bool on_map; // onmap const bool default_enabled; ProductionType const* production_type; @@ -48,21 +48,21 @@ namespace OpenVic { const bool strategic_factory; const bool advanced_factory; - const level_t fort_level; //probably the step-per-level + const level_t fort_level; // probably the step-per-level const uint64_t naval_capacity; const std::vector colonial_points; - const bool in_province; //province + const bool in_province; // province const bool one_per_state; const fixed_point_t colonial_range; const fixed_point_t infrastructure; const bool spawn_railway_track; - const bool sail; //only in clipper shipyard - const bool steam; //only in steamer shipyard - const bool capital; //only in naval base - const bool port; //only in naval base + const bool sail; // only in clipper shipyard + const bool steam; // only in steamer shipyard + const bool capital; // only in naval base + const bool port; // only in naval base Building(std::string_view identifier, BuildingType const& type, ARGS); @@ -108,14 +108,9 @@ namespace OpenVic { BuildingType(BuildingType&&) = default; }; - enum class ExpansionState { - CannotExpand, - CanExpand, - Preparing, - Expanding - }; + enum class ExpansionState { CannotExpand, CanExpand, Preparing, Expanding }; - struct BuildingInstance : HasIdentifier { //used in the actual game + struct BuildingInstance : HasIdentifier { // used in the actual game friend struct BuildingManager; using level_t = Building::level_t; @@ -145,13 +140,12 @@ namespace OpenVic { bool expand(); void update_state(Date const& today); void tick(Date const& today); - }; struct Province; struct BuildingManager { - using level_t = Building::level_t; //this is getting ridiculous + using level_t = Building::level_t; // this is getting ridiculous private: IdentifierRegistry building_types; @@ -166,9 +160,10 @@ namespace OpenVic { bool add_building(std::string_view identifier, BuildingType const* type, ARGS); IDENTIFIER_REGISTRY_ACCESSORS(building) - bool load_buildings_file(GoodManager const& good_manager, - ProductionTypeManager const& production_type_manager, - ModifierManager const& modifier_manager, ast::NodeCPtr root); + bool load_buildings_file( + GoodManager const& good_manager, ProductionTypeManager const& production_type_manager, + ModifierManager const& modifier_manager, ast::NodeCPtr root + ); bool generate_province_buildings(Province& province) const; }; diff --git a/src/openvic-simulation/economy/EconomyManager.hpp b/src/openvic-simulation/economy/EconomyManager.hpp index 05dfc91..b7d45c9 100644 --- a/src/openvic-simulation/economy/EconomyManager.hpp +++ b/src/openvic-simulation/economy/EconomyManager.hpp @@ -10,6 +10,7 @@ namespace OpenVic { BuildingManager building_manager; GoodManager good_manager; ProductionTypeManager production_type_manager; + public: REF_GETTERS(building_manager) REF_GETTERS(good_manager) diff --git a/src/openvic-simulation/economy/Good.cpp b/src/openvic-simulation/economy/Good.cpp index 60a85d0..11230d2 100644 --- a/src/openvic-simulation/economy/Good.cpp +++ b/src/openvic-simulation/economy/Good.cpp @@ -7,15 +7,12 @@ using namespace OpenVic::NodeTools; GoodCategory::GoodCategory(std::string_view new_identifier) : HasIdentifier { new_identifier } {} -Good::Good(std::string_view new_identifier, colour_t new_colour, GoodCategory const& new_category, price_t new_base_price, - bool new_available_from_start, bool new_tradeable, bool new_money, bool new_overseas_penalty) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, - category { new_category }, - base_price { new_base_price }, - available_from_start { new_available_from_start }, - tradeable { new_tradeable }, - money { new_money }, - overseas_penalty { new_overseas_penalty } { +Good::Good( + std::string_view new_identifier, colour_t new_colour, GoodCategory const& new_category, price_t new_base_price, + bool new_available_from_start, bool new_tradeable, bool new_money, bool new_overseas_penalty +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, category { new_category }, + base_price { new_base_price }, available_from_start { new_available_from_start }, tradeable { new_tradeable }, + money { new_money }, overseas_penalty { new_overseas_penalty } { assert(base_price > NULL_PRICE); } @@ -66,8 +63,10 @@ bool GoodManager::add_good_category(std::string_view identifier) { return good_categories.add_item({ identifier }); } -bool GoodManager::add_good(std::string_view identifier, colour_t colour, GoodCategory const* category, - Good::price_t base_price, bool available_from_start, bool tradeable, bool money, bool overseas_penalty) { +bool GoodManager::add_good( + std::string_view identifier, colour_t colour, GoodCategory const* category, Good::price_t base_price, + bool available_from_start, bool tradeable, bool money, bool overseas_penalty +) { if (identifier.empty()) { Logger::error("Invalid good identifier - empty!"); return false; @@ -84,8 +83,10 @@ bool GoodManager::add_good(std::string_view identifier, colour_t colour, GoodCat Logger::error("Invalid base price for ", identifier, ": ", base_price); return false; } - return goods.add_item({ identifier, colour, *category, base_price, - available_from_start, tradeable, money, overseas_penalty }); + return goods.add_item({ + identifier, colour, *category, base_price, available_from_start, + tradeable, money, overseas_penalty + }); } void GoodManager::reset_to_defaults() { @@ -106,32 +107,29 @@ bool GoodManager::load_goods_file(ast::NodeCPtr root) { )(root); lock_good_categories(); goods.reserve(goods.size() + total_expected_goods); - ret &= expect_dictionary( - [this](std::string_view good_category_key, ast::NodeCPtr good_category_value) -> bool { - GoodCategory const* good_category = get_good_category_by_identifier(good_category_key); - - return expect_dictionary( - [this, good_category](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = NULL_COLOUR; - Good::price_t base_price; - bool available_from_start = true, tradeable = true; - bool money = false, overseas_penalty = false; - - bool ret = expect_dictionary_keys( - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_price)), - "available_from_start", ZERO_OR_ONE, expect_bool(assign_variable_callback(available_from_start)), - "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(tradeable)), - "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(money)), - "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(overseas_penalty)) - )(value); - ret &= add_good(key, colour, good_category, base_price, - available_from_start, tradeable, money, overseas_penalty); - return ret; - } - )(good_category_value); - } - )(root); + ret &= expect_dictionary([this](std::string_view good_category_key, ast::NodeCPtr good_category_value) -> bool { + GoodCategory const* good_category = get_good_category_by_identifier(good_category_key); + + return expect_dictionary([this, good_category](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = NULL_COLOUR; + Good::price_t base_price; + bool available_from_start = true, tradeable = true; + bool money = false, overseas_penalty = false; + + bool ret = expect_dictionary_keys( + "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), + "cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_price)), + "available_from_start", ZERO_OR_ONE, expect_bool(assign_variable_callback(available_from_start)), + "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(tradeable)), + "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(money)), + "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(overseas_penalty)) + )(value); + ret &= add_good( + key, colour, good_category, base_price, available_from_start, tradeable, money, overseas_penalty + ); + return ret; + })(good_category_value); + })(root); lock_goods(); return ret; } diff --git a/src/openvic-simulation/economy/Good.hpp b/src/openvic-simulation/economy/Good.hpp index 2a850fa..ae2d6a9 100644 --- a/src/openvic-simulation/economy/Good.hpp +++ b/src/openvic-simulation/economy/Good.hpp @@ -42,8 +42,10 @@ namespace OpenVic { const bool available_from_start, tradeable, money, overseas_penalty; bool available; - Good(std::string_view new_identifier, colour_t new_colour, GoodCategory const& new_category, price_t new_base_price, - bool new_available_from_start, bool new_tradeable, bool new_money, bool new_overseas_penalty); + Good( + std::string_view new_identifier, colour_t new_colour, GoodCategory const& new_category, price_t new_base_price, + bool new_available_from_start, bool new_tradeable, bool new_money, bool new_overseas_penalty + ); public: Good(Good&&) = default; @@ -70,8 +72,10 @@ namespace OpenVic { bool add_good_category(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS_CUSTOM_PLURAL(good_category, good_categories) - bool add_good(std::string_view identifier, colour_t colour, GoodCategory const* category, Good::price_t base_price, - bool available_from_start, bool tradeable, bool money, bool overseas_penalty); + bool add_good( + std::string_view identifier, colour_t colour, GoodCategory const* category, Good::price_t base_price, + bool available_from_start, bool tradeable, bool money, bool overseas_penalty + ); IDENTIFIER_REGISTRY_ACCESSORS(good) void reset_to_defaults(); diff --git a/src/openvic-simulation/economy/ProductionType.cpp b/src/openvic-simulation/economy/ProductionType.cpp index 6b7d757..1c65c4d 100644 --- a/src/openvic-simulation/economy/ProductionType.cpp +++ b/src/openvic-simulation/economy/ProductionType.cpp @@ -5,10 +5,10 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -EmployedPop::EmployedPop(PopType const* pop_type, bool artisan, effect_t effect, - fixed_point_t effect_multiplier, fixed_point_t amount) - : pop_type { pop_type }, artisan { artisan }, effect { effect }, - effect_multiplier { effect_multiplier }, amount { amount } {} +EmployedPop::EmployedPop( + PopType const* pop_type, bool artisan, effect_t effect, fixed_point_t effect_multiplier, fixed_point_t amount +) : pop_type { pop_type }, artisan { artisan }, effect { effect }, effect_multiplier { effect_multiplier }, + amount { amount } {} PopType const* EmployedPop::get_pop_type() const { return pop_type; @@ -30,9 +30,11 @@ fixed_point_t EmployedPop::get_amount() const { return amount; } -ProductionType::ProductionType(PRODUCTION_TYPE_ARGS) : HasIdentifier { identifier }, owner { owner }, employees { employees }, - type { type }, workforce { workforce }, input_goods { std::move(input_goods) }, output_goods { output_goods }, - value { value }, bonuses { std::move(bonuses) }, efficiency { std::move(efficiency) }, coastal { coastal }, farm { farm }, mine { mine } {} +ProductionType::ProductionType( + PRODUCTION_TYPE_ARGS +) : HasIdentifier { identifier }, owner { owner }, employees { employees }, type { type }, workforce { workforce }, + input_goods { std::move(input_goods) }, output_goods { output_goods }, value { value }, bonuses { std::move(bonuses) }, + efficiency { std::move(efficiency) }, coastal { coastal }, farm { farm }, mine { mine } {} EmployedPop const& ProductionType::get_owner() const { return owner; @@ -84,8 +86,9 @@ bool ProductionType::is_mine() const { ProductionTypeManager::ProductionTypeManager() : production_types { "production types" } {} -node_callback_t ProductionTypeManager::_expect_employed_pop(GoodManager const& good_manager, PopManager const& pop_manager, - callback_t cb) { +node_callback_t ProductionTypeManager::_expect_employed_pop( + GoodManager const& good_manager, PopManager const& pop_manager, callback_t cb +) { return [this, &good_manager, &pop_manager, cb](ast::NodeCPtr node) -> bool { std::string_view pop_type; @@ -119,8 +122,9 @@ node_callback_t ProductionTypeManager::_expect_employed_pop(GoodManager const& g }; } -node_callback_t ProductionTypeManager::_expect_employed_pop_list(GoodManager const& good_manager, PopManager const& pop_manager, - callback_t&&> cb) { +node_callback_t ProductionTypeManager::_expect_employed_pop_list( + GoodManager const& good_manager, PopManager const& pop_manager, callback_t&&> cb +) { return [this, &good_manager, &pop_manager, cb](ast::NodeCPtr node) -> bool { std::vector employed_pops; @@ -135,7 +139,8 @@ node_callback_t ProductionTypeManager::_expect_employed_pop_list(GoodManager con } #define POPTYPE_CHECK(employed_pop) \ - if ((employed_pop.pop_type == nullptr && !employed_pop.artisan) || (employed_pop.pop_type != nullptr && employed_pop.artisan)) { \ + if ((employed_pop.pop_type == nullptr && !employed_pop.artisan) || \ + (employed_pop.pop_type != nullptr && employed_pop.artisan)) { \ Logger::error("Invalid pop type parsed for owner of production type ", identifier, "!"); \ return false; \ } @@ -173,7 +178,8 @@ bool ProductionTypeManager::add_production_type(PRODUCTION_TYPE_ARGS, GoodManage }); } -#define PARSE_NODE expect_dictionary_keys_and_default( \ +#define PARSE_NODE \ + expect_dictionary_keys_and_default( \ key_value_success_callback, \ "owner", ZERO_OR_ONE, _expect_employed_pop(good_manager, pop_manager, move_variable_callback(owner)), \ "employees", ZERO_OR_ONE, _expect_employed_pop_list(good_manager, pop_manager, move_variable_callback(employees)), \ @@ -188,8 +194,9 @@ bool ProductionTypeManager::add_production_type(PRODUCTION_TYPE_ARGS, GoodManage "mine", ZERO_OR_ONE, expect_bool(assign_variable_callback(mine)) \ ) -bool ProductionTypeManager::load_production_types_file(GoodManager const& good_manager, - PopManager const& pop_manager, ast::NodeCPtr root) { +bool ProductionTypeManager::load_production_types_file( + GoodManager const& good_manager, PopManager const& pop_manager, ast::NodeCPtr root +) { size_t expected_types = 0; // pass 1: find and store template identifiers @@ -201,7 +208,8 @@ bool ProductionTypeManager::load_production_types_file(GoodManager const& good_m std::string_view template_id = ""; bool found_template = false; - const bool ret = expect_key("template", expect_identifier(assign_variable_callback(template_id)), &found_template)(value); + const bool ret = + expect_key("template", expect_identifier(assign_variable_callback(template_id)), &found_template)(value); if (found_template) { if (ret) { templates.emplace(template_id); @@ -232,8 +240,9 @@ bool ProductionTypeManager::load_production_types_file(GoodManager const& good_m ret &= expect_dictionary( [this, &good_manager, &pop_manager, &template_target_map, &template_node_map]( std::string_view key, ast::NodeCPtr node) -> bool { - if (template_node_map.contains(key)) + if (template_node_map.contains(key)) { return true; + } EmployedPop owner; std::vector employees; @@ -264,8 +273,8 @@ bool ProductionTypeManager::load_production_types_file(GoodManager const& good_m ret &= PARSE_NODE(node); ret &= add_production_type( - key, owner, employees, type, workforce, std::move(input_goods), output_goods, value, - std::move(bonuses), std::move(efficiency), coastal, farm, mine, good_manager + key, owner, employees, type, workforce, std::move(input_goods), output_goods, value, std::move(bonuses), + std::move(efficiency), coastal, farm, mine, good_manager ); return ret; } @@ -274,4 +283,4 @@ bool ProductionTypeManager::load_production_types_file(GoodManager const& good_m production_types.lock(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/ProductionType.hpp b/src/openvic-simulation/economy/ProductionType.hpp index d84be01..802580b 100644 --- a/src/openvic-simulation/economy/ProductionType.hpp +++ b/src/openvic-simulation/economy/ProductionType.hpp @@ -16,11 +16,7 @@ namespace OpenVic { struct EmployedPop { friend struct ProductionTypeManager; - enum struct effect_t { - INPUT, - OUTPUT, - THROUGHPUT - }; + enum struct effect_t { INPUT, OUTPUT, THROUGHPUT }; private: PopType const* pop_type; // poptype @@ -29,7 +25,9 @@ namespace OpenVic { fixed_point_t effect_multiplier; fixed_point_t amount; - EmployedPop(PopType const* pop_type, bool artisan, effect_t effect, fixed_point_t effect_multiplier, fixed_point_t amount); + EmployedPop( + PopType const* pop_type, bool artisan, effect_t effect, fixed_point_t effect_multiplier, fixed_point_t amount + ); public: EmployedPop() = default; @@ -52,11 +50,7 @@ namespace OpenVic { private: const EmployedPop owner; const std::vector employees; - const enum struct type_t { - FACTORY, - RGO, - ARTISAN - } type; + const enum struct type_t { FACTORY, RGO, ARTISAN } type; const Pop::pop_size_t workforce; const Good::good_map_t input_goods; @@ -96,10 +90,13 @@ namespace OpenVic { private: IdentifierRegistry production_types; - NodeTools::node_callback_t _expect_employed_pop(GoodManager const& good_manager, - PopManager const& pop_manager, NodeTools::callback_t cb); - NodeTools::node_callback_t _expect_employed_pop_list(GoodManager const& good_manager, - PopManager const& pop_manager, NodeTools::callback_t&&> cb); + NodeTools::node_callback_t _expect_employed_pop( + GoodManager const& good_manager, PopManager const& pop_manager, NodeTools::callback_t cb + ); + NodeTools::node_callback_t _expect_employed_pop_list( + GoodManager const& good_manager, PopManager const& pop_manager, + NodeTools::callback_t&&> cb + ); public: ProductionTypeManager(); @@ -109,4 +106,4 @@ namespace OpenVic { bool load_production_types_file(GoodManager const& good_manager, PopManager const& pop_manager, ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/Bookmark.cpp b/src/openvic-simulation/history/Bookmark.cpp index 1786821..edfa064 100644 --- a/src/openvic-simulation/history/Bookmark.cpp +++ b/src/openvic-simulation/history/Bookmark.cpp @@ -12,20 +12,10 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Bookmark::Bookmark( - size_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, - uint32_t new_initial_camera_x, + size_t new_index, std::string_view new_name, std::string_view new_description, Date new_date, uint32_t new_initial_camera_x, uint32_t new_initial_camera_y -) - : HasIdentifier { std::to_string(new_index) }, - name { new_name }, - description { new_description }, - date { new_date }, - initial_camera_x { new_initial_camera_x }, - initial_camera_y { new_initial_camera_y } { -} +) : HasIdentifier { std::to_string(new_index) }, name { new_name }, description { new_description }, date { new_date }, + initial_camera_x { new_initial_camera_x }, initial_camera_y { new_initial_camera_y } {} std::string_view Bookmark::get_name() const { return name; @@ -50,40 +40,34 @@ uint32_t Bookmark::get_initial_camera_y() const { BookmarkManager::BookmarkManager() : bookmarks { "bookmarks" } {} bool BookmarkManager::add_bookmark( - std::string_view name, - std::string_view description, - Date date, - uint32_t initial_camera_x, - uint32_t initial_camera_y + std::string_view name, std::string_view description, Date date, uint32_t initial_camera_x, uint32_t initial_camera_y ) { return bookmarks.add_item({ bookmarks.size(), name, description, date, initial_camera_x, initial_camera_y }); } bool BookmarkManager::load_bookmark_file(ast::NodeCPtr root) { - bool ret = expect_dictionary( - [this](std::string_view key, ast::NodeCPtr value) -> bool { - if (key != "bookmark") { - Logger::error("Invalid bookmark declaration ", key); - return false; - } - - std::string_view name, description; - Date date; - uint32_t initial_camera_x, initial_camera_y; - - bool ret = expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), - "desc", ONE_EXACTLY, expect_string(assign_variable_callback(description)), - "date", ONE_EXACTLY, expect_date(assign_variable_callback(date)), - "cameraX", ONE_EXACTLY, expect_uint(assign_variable_callback(initial_camera_x)), - "cameraY", ONE_EXACTLY, expect_uint(assign_variable_callback(initial_camera_y)) - )(value); - - ret &= add_bookmark(name, description, date, initial_camera_x, initial_camera_y); - return ret; + const bool ret = expect_dictionary([this](std::string_view key, ast::NodeCPtr value) -> bool { + if (key != "bookmark") { + Logger::error("Invalid bookmark declaration ", key); + return false; } - )(root); + + std::string_view name, description; + Date date; + uint32_t initial_camera_x, initial_camera_y; + + bool ret = expect_dictionary_keys( + "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), + "desc", ONE_EXACTLY, expect_string(assign_variable_callback(description)), + "date", ONE_EXACTLY, expect_date(assign_variable_callback(date)), + "cameraX", ONE_EXACTLY, expect_uint(assign_variable_callback(initial_camera_x)), + "cameraY", ONE_EXACTLY, expect_uint(assign_variable_callback(initial_camera_y)) + )(value); + + ret &= add_bookmark(name, description, date, initial_camera_x, initial_camera_y); + return ret; + })(root); lock_bookmarks(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/Bookmark.hpp b/src/openvic-simulation/history/Bookmark.hpp index d4de34c..8f0075f 100644 --- a/src/openvic-simulation/history/Bookmark.hpp +++ b/src/openvic-simulation/history/Bookmark.hpp @@ -20,12 +20,8 @@ namespace OpenVic { const uint32_t initial_camera_y; Bookmark( - size_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, - uint32_t new_initial_camera_x, - uint32_t new_initial_camera_y + size_t new_index, std::string_view new_name, std::string_view new_description, Date new_date, + uint32_t new_initial_camera_x, uint32_t new_initial_camera_y ); public: @@ -45,10 +41,11 @@ namespace OpenVic { public: BookmarkManager(); - bool add_bookmark(std::string_view name, std::string_view description, Date date, - uint32_t initial_camera_x, uint32_t initial_camera_y); + bool add_bookmark( + std::string_view name, std::string_view description, Date date, uint32_t initial_camera_x, uint32_t initial_camera_y + ); IDENTIFIER_REGISTRY_ACCESSORS(bookmark); bool load_bookmark_file(ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/CountryHistory.cpp b/src/openvic-simulation/history/CountryHistory.cpp index 9ed271b..2dfc171 100644 --- a/src/openvic-simulation/history/CountryHistory.cpp +++ b/src/openvic-simulation/history/CountryHistory.cpp @@ -6,20 +6,11 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; CountryHistory::CountryHistory( - Culture const* new_primary_culture, - std::vector&& new_accepted_cultures, - Religion const* new_religion, - CountryParty const* new_ruling_party, - Date new_last_election, - std::map&& new_upper_house, - Province const* new_capital, - GovernmentType const* new_government_type, - fixed_point_t new_plurality, - NationalValue const* new_national_value, - bool new_civilised, - fixed_point_t new_prestige, - std::vector&& new_reforms, - Deployment const* new_inital_oob + Culture const* new_primary_culture, std::vector&& new_accepted_cultures, Religion const* new_religion, + CountryParty const* new_ruling_party, Date new_last_election, std::map&& new_upper_house, + Province const* new_capital, GovernmentType const* new_government_type, fixed_point_t new_plurality, + NationalValue const* new_national_value, bool new_civilised, fixed_point_t new_prestige, + std::vector&& new_reforms, Deployment const* new_inital_oob ) : primary_culture { new_primary_culture }, accepted_cultures { std::move(new_accepted_cultures) }, religion { new_religion }, ruling_party { new_ruling_party }, last_election { new_last_election }, upper_house { std::move(new_upper_house) }, capital { new_capital }, government_type { new_government_type }, @@ -83,25 +74,12 @@ Deployment const* CountryHistory::get_inital_oob() const { } bool CountryHistoryManager::add_country_history_entry( - Country const* country, - Date date, - Culture const* primary_culture, - std::vector&& accepted_cultures, - Religion const* religion, - CountryParty const* ruling_party, - Date last_election, - std::map&& upper_house, - Province const* capital, - GovernmentType const* government_type, - fixed_point_t plurality, - NationalValue const* national_value, - bool civilised, - fixed_point_t prestige, - std::vector&& reforms, - Deployment const* initial_oob, - bool updated_accepted_cultures, - bool updated_upper_house, - bool updated_reforms + Country const* country, Date date, Culture const* primary_culture, std::vector&& accepted_cultures, + Religion const* religion, CountryParty const* ruling_party, Date last_election, + std::map&& upper_house, Province const* capital, GovernmentType const* government_type, + fixed_point_t plurality, NationalValue const* national_value, bool civilised, fixed_point_t prestige, + std::vector&& reforms, Deployment const* initial_oob, bool updated_accepted_cultures, + bool updated_upper_house, bool updated_reforms ) { if (locked) { Logger::error("Cannot add new history entry to country history registry: locked!"); @@ -156,22 +134,13 @@ bool CountryHistoryManager::add_country_history_entry( existing_entry->second.inital_oob = initial_oob; } } else { - country_registry.emplace(date, CountryHistory { - primary_culture, - std::move(accepted_cultures), - religion, - ruling_party, - last_election, - std::move(upper_house), - capital, - government_type, - plurality, - national_value, - civilised, - prestige, - std::move(reforms), - initial_oob - }); + country_registry.emplace( date, + CountryHistory { + primary_culture, std::move(accepted_cultures), religion, ruling_party, last_election, + std::move(upper_house), capital, government_type, plurality, national_value, civilised, + prestige, std::move(reforms), initial_oob + } + ); } return true; } @@ -179,8 +148,9 @@ bool CountryHistoryManager::add_country_history_entry( void CountryHistoryManager::lock_country_histories() { for (const auto& entry : country_histories) { if (entry.second.size() == 0) { - Logger::error("Attempted to lock country histories - country ", - entry.first->get_identifier(), " has no history entries!"); + Logger::error( + "Attempted to lock country histories - country ", entry.first->get_identifier(), " has no history entries!" + ); } } Logger::info("Locked country history registry after registering ", country_histories.size(), " items"); @@ -224,8 +194,9 @@ inline CountryHistory const* CountryHistoryManager::get_country_history(Country return get_country_history(country, entry->get_date()); } -inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game_manager, - std::string_view name, Date const& date, ast::NodeCPtr root) { +inline bool CountryHistoryManager::_load_country_history_entry( + GameManager& game_manager, std::string_view name, Date const& date, ast::NodeCPtr root +) { Province const* capital = nullptr; Culture const* primary_culture = nullptr; Religion const* religion = nullptr; @@ -264,93 +235,112 @@ inline bool CountryHistoryManager::_load_country_history_entry(GameManager& game }, /* we have to use a lambda, assign_variable_callback_pointer * apparently doesn't play nice with const & non-const accessors */ - "capital", ZERO_OR_ONE, game_manager.get_map().expect_province_identifier([&capital](Province const& province) -> bool { - capital = &province; - return true; - }), - "primary_culture", ZERO_OR_ONE, game_manager.get_pop_manager().get_culture_manager() - .expect_culture_identifier(assign_variable_callback_pointer(primary_culture)), - "culture", ZERO_OR_MORE, game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier( - [&game_manager, &accepted_cultures, &updated_accepted_cultures](Culture const & culture) -> bool { - updated_accepted_cultures = true; - accepted_cultures.push_back(&culture); + "capital", ZERO_OR_ONE, + game_manager.get_map().expect_province_identifier([&capital](Province const& province) -> bool { + capital = &province; return true; - } - ), - "religion", ZERO_OR_ONE, game_manager.get_pop_manager().get_religion_manager() - .expect_religion_identifier(assign_variable_callback_pointer(religion)), - "government", ZERO_OR_ONE, game_manager.get_politics_manager().get_government_type_manager() - .expect_government_type_identifier(assign_variable_callback_pointer(government_type)), + }), + "primary_culture", ZERO_OR_ONE, + game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier( + assign_variable_callback_pointer(primary_culture) + ), + "culture", ZERO_OR_MORE, + game_manager.get_pop_manager().get_culture_manager().expect_culture_identifier( + [&game_manager, &accepted_cultures, &updated_accepted_cultures](Culture const& culture) -> bool { + updated_accepted_cultures = true; + accepted_cultures.push_back(&culture); + return true; + } + ), + "religion", ZERO_OR_ONE, + game_manager.get_pop_manager().get_religion_manager().expect_religion_identifier( + assign_variable_callback_pointer(religion) + ), + "government", ZERO_OR_ONE, + game_manager.get_politics_manager().get_government_type_manager().expect_government_type_identifier( + assign_variable_callback_pointer(government_type) + ), "plurality", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(plurality)), - "nationalvalue", ZERO_OR_ONE, game_manager.get_politics_manager().get_national_value_manager() - .expect_national_value_identifier(assign_variable_callback_pointer(national_value)), + "nationalvalue", ZERO_OR_ONE, + game_manager.get_politics_manager().get_national_value_manager().expect_national_value_identifier( + assign_variable_callback_pointer(national_value) + ), "civilized", ZERO_OR_ONE, expect_bool(assign_variable_callback(civilised)), "prestige", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(prestige)), - "ruling_party", ZERO_OR_ONE, expect_identifier([this, &game_manager, - &ruling_party, &name, &date](std::string_view identifier) -> bool { - const std::vector* parties = &game_manager.get_country_manager().get_country_by_identifier(name)->get_parties(); - for (auto& party : *parties) { - if (party.get_name() == identifier) { - if (party.get_start_date() <= date && date <= party.get_end_date()) { - ruling_party = &party; - return true; - } else { - if (party.get_start_date() > date) { - Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid start date ", - party.get_start_date(), " for bookmark: ", date.to_string()); - } - if (party.get_end_date() < date) { - Logger::warning("Ruling party ", identifier, " of country ", name, " has invalid end date ", - party.get_end_date(), " for bookmark: ", date.to_string()); + "ruling_party", ZERO_OR_ONE, + expect_identifier([this, &game_manager, &ruling_party, &name, &date](std::string_view identifier) -> bool { + const std::vector* parties = + &game_manager.get_country_manager().get_country_by_identifier(name)->get_parties(); + for (auto& party : *parties) { + if (party.get_name() == identifier) { + if (party.get_start_date() <= date && date <= party.get_end_date()) { + ruling_party = &party; + return true; + } else { + if (party.get_start_date() > date) { + Logger::warning( + "Ruling party ", identifier, " of country ", name, " has invalid start date ", + party.get_start_date(), " for bookmark: ", date.to_string() + ); + } + if (party.get_end_date() < date) { + Logger::warning( + "Ruling party ", identifier, " of country ", name, " has invalid end date ", + party.get_end_date(), " for bookmark: ", date.to_string() + ); + } + ruling_party = &party; + return true; } - ruling_party = &party; - return true; } } - } - Logger::error("Ruling party ", identifier, " of country ", name, " is not defined!"); - return false; - }), + Logger::error("Ruling party ", identifier, " of country ", name, " is not defined!"); + return false; + }), "last_election", ZERO_OR_ONE, expect_date(assign_variable_callback(last_election)), - "upper_house", ZERO_OR_ONE, game_manager.get_politics_manager().get_ideology_manager().expect_ideology_dictionary( - [&upper_house, &updated_upper_house](Ideology const& ideology, ast::NodeCPtr value) -> bool { - fixed_point_t popularity; - - updated_upper_house = true; - bool ret = expect_fixed_point(assign_variable_callback(popularity))(value); - upper_house.emplace(&ideology, popularity); - return ret; - } - ), - "oob", ZERO_OR_ONE, [&game_manager, &initial_oob](ast::NodeCPtr node) -> bool { - std::string_view string; - expect_string(assign_variable_callback(string))(node); - - if (string.starts_with('/')) { - if (game_manager.get_military_manager().get_deployment_manager() - .has_deployment_identifier(string.substr(1))) { - initial_oob = game_manager.get_military_manager().get_deployment_manager() - .get_deployment_by_identifier(string.substr(1)); - return true; + "upper_house", ZERO_OR_ONE, + game_manager.get_politics_manager().get_ideology_manager().expect_ideology_dictionary( + [&upper_house, &updated_upper_house](Ideology const& ideology, ast::NodeCPtr value) -> bool { + fixed_point_t popularity; + + updated_upper_house = true; + bool ret = expect_fixed_point(assign_variable_callback(popularity))(value); + upper_house.emplace(&ideology, popularity); + return ret; } - } else { - if (game_manager.get_military_manager().get_deployment_manager().has_deployment_identifier(string)) { - initial_oob = game_manager.get_military_manager().get_deployment_manager() - .get_deployment_by_identifier(string); + ), + "oob", ZERO_OR_ONE, + [&game_manager, &initial_oob](ast::NodeCPtr node) -> bool { + std::string_view string; + expect_string(assign_variable_callback(string))(node); + + if (string.starts_with('/')) { + if (game_manager.get_military_manager().get_deployment_manager() + .has_deployment_identifier(string.substr(1))) { + initial_oob = game_manager.get_military_manager().get_deployment_manager() + .get_deployment_by_identifier(string.substr(1)); + return true; + } + } else { + if (game_manager.get_military_manager().get_deployment_manager().has_deployment_identifier(string)) { + initial_oob = + game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier(string); + } } - } - initial_oob = game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier("NULL"); - return true; - }, + initial_oob = + game_manager.get_military_manager().get_deployment_manager().get_deployment_by_identifier("NULL"); + return true; + }, "schools", ZERO_OR_ONE, success_callback, // TODO: technology school "foreign_investment", ZERO_OR_ONE, success_callback // TODO: foreign investment )(root); - ret &= add_country_history_entry(game_manager.get_country_manager().get_country_by_identifier(name), date, - primary_culture, std::move(accepted_cultures), religion, ruling_party, last_election, std::move(upper_house), - capital, government_type, plurality, national_value, civilised, prestige, std::move(reforms), initial_oob, - updated_accepted_cultures, updated_upper_house, updated_reforms); + ret &= add_country_history_entry( + game_manager.get_country_manager().get_country_by_identifier(name), date, primary_culture, std::move(accepted_cultures), + religion, ruling_party, last_election, std::move(upper_house), capital, government_type, plurality, national_value, + civilised, prestige, std::move(reforms), initial_oob, updated_accepted_cultures, updated_upper_house, updated_reforms + ); return ret; } @@ -361,22 +351,24 @@ bool CountryHistoryManager::load_country_history_file(GameManager& game_manager, bool ret = _load_country_history_entry(game_manager, name, game_manager.get_define_manager().get_start_date(), root); - ret &= expect_dictionary( - [this, &game_manager, &name](std::string_view key, ast::NodeCPtr value) -> bool { - bool is_date = false; - Date entry = Date().from_string(key, &is_date, true); - if (!is_date) return true; - - Date const& end_date = game_manager.get_define_manager().get_end_date(); - if (entry > end_date) { - Logger::error("History entry ", entry.to_string(), " of country ", name, - " defined after defined end date ", end_date.to_string()); - return false; - } + ret &= expect_dictionary([this, &game_manager, &name](std::string_view key, ast::NodeCPtr value) -> bool { + bool is_date = false; + Date entry = Date().from_string(key, &is_date, true); + if (!is_date) { + return true; + } - return _load_country_history_entry(game_manager, name, entry, value); + Date const& end_date = game_manager.get_define_manager().get_end_date(); + if (entry > end_date) { + Logger::error( + "History entry ", entry.to_string(), " of country ", name, " defined after defined end date ", + end_date.to_string() + ); + return false; } - )(root); + + return _load_country_history_entry(game_manager, name, entry, value); + })(root); return ret; } diff --git a/src/openvic-simulation/history/CountryHistory.hpp b/src/openvic-simulation/history/CountryHistory.hpp index 56d04c6..52d99df 100644 --- a/src/openvic-simulation/history/CountryHistory.hpp +++ b/src/openvic-simulation/history/CountryHistory.hpp @@ -41,19 +41,11 @@ namespace OpenVic { // TODO: starting foreign investment CountryHistory( - Culture const* new_primary_culture, - std::vector&& new_accepted_cultures, - Religion const* new_religion, - CountryParty const* new_ruling_party, - Date new_last_election, - std::map&& new_upper_house, - Province const* new_capital, - GovernmentType const* new_government_type, - fixed_point_t new_plurality, - NationalValue const* new_national_value, - bool new_civilised, - fixed_point_t new_prestige, - std::vector&& new_reforms, + Culture const* new_primary_culture, std::vector&& new_accepted_cultures, + Religion const* new_religion, CountryParty const* new_ruling_party, Date new_last_election, + std::map&& new_upper_house, Province const* new_capital, + GovernmentType const* new_government_type, fixed_point_t new_plurality, NationalValue const* new_national_value, + bool new_civilised, fixed_point_t new_prestige, std::vector&& new_reforms, Deployment const* new_inital_oob ); @@ -79,37 +71,27 @@ namespace OpenVic { std::map> country_histories; bool locked = false; - inline bool _load_country_history_entry(GameManager& game_manager, std::string_view name, Date const& date, ast::NodeCPtr root); + inline bool _load_country_history_entry( + GameManager& game_manager, std::string_view name, Date const& date, ast::NodeCPtr root + ); public: CountryHistoryManager() {} bool add_country_history_entry( - Country const* country, - Date date, - Culture const* primary_culture, - std::vector&& accepted_cultures, - Religion const* religion, - CountryParty const* ruling_party, - Date last_election, - std::map&& upper_house, - Province const* capital, - GovernmentType const* government_type, - fixed_point_t plurality, - NationalValue const* national_value, - bool civilised, - fixed_point_t prestige, - std::vector&& reforms, - Deployment const* initial_oob, - bool updated_accepted_cultures, - bool updated_upper_house, - bool updated_reforms + Country const* country, Date date, Culture const* primary_culture, std::vector&& accepted_cultures, + Religion const* religion, CountryParty const* ruling_party, Date last_election, + std::map&& upper_house, Province const* capital, + GovernmentType const* government_type, fixed_point_t plurality, NationalValue const* national_value, bool civilised, + fixed_point_t prestige, std::vector&& reforms, Deployment const* initial_oob, + bool updated_accepted_cultures, bool updated_upper_house, bool updated_reforms ); void lock_country_histories(); bool is_locked() const; - /* Returns history of country at date, if date doesn't have an entry returns closest entry before date. Return can be nullptr if an error occurs. */ + /* Returns history of country at date, if date doesn't have an entry returns + * closest entry before date. Return can be nullptr if an error occurs. */ CountryHistory const* get_country_history(Country const* country, Date entry) const; /* Returns history of country at bookmark date. Return can be nullptr if an error occurs. */ inline CountryHistory const* get_country_history(Country const* country, Bookmark const* entry) const; diff --git a/src/openvic-simulation/history/ProvinceHistory.cpp b/src/openvic-simulation/history/ProvinceHistory.cpp index e5cc97b..4057bfa 100644 --- a/src/openvic-simulation/history/ProvinceHistory.cpp +++ b/src/openvic-simulation/history/ProvinceHistory.cpp @@ -7,26 +7,12 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; ProvinceHistory::ProvinceHistory( - Country const* new_owner, - Country const* new_controller, - uint8_t new_colonial, - bool new_slave, - std::vector&& new_cores, - Good const* new_rgo, - uint8_t new_life_rating, - TerrainType const* new_terrain_type, - std::map&& new_buildings, - std::map&& new_party_loyalties -) : owner { new_owner }, - controller { new_controller }, - colonial { new_colonial }, - slave { new_slave }, - cores { std::move(new_cores) }, - rgo { new_rgo }, - life_rating { new_life_rating }, - terrain_type { new_terrain_type }, - buildings { std::move(new_buildings) }, - party_loyalties { std::move(new_party_loyalties) } {} + Country const* new_owner, Country const* new_controller, uint8_t new_colonial, bool new_slave, + std::vector&& new_cores, Good const* new_rgo, uint8_t new_life_rating, TerrainType const* new_terrain_type, + std::map&& new_buildings, std::map&& new_party_loyalties +) : owner { new_owner }, controller { new_controller }, colonial { new_colonial }, slave { new_slave }, + cores { std::move(new_cores) }, rgo { new_rgo }, life_rating { new_life_rating }, terrain_type { new_terrain_type }, + buildings { std::move(new_buildings) }, party_loyalties { std::move(new_party_loyalties) } {} Country const* ProvinceHistory::get_owner() const { return owner; @@ -73,20 +59,10 @@ std::map const& ProvinceHistory::get_party_loyalties() } bool ProvinceHistoryManager::add_province_history_entry( - Province const* province, - Date date, - Country const* owner, - Country const* controller, - uint8_t colonial, - bool slave, - std::vector&& cores, - std::vector&& remove_cores, - Good const* rgo, - uint8_t life_rating, - TerrainType const* terrain_type, - std::map&& buildings, - std::map&& party_loyalties, - std::bitset<5> updates + Province const* province, Date date, Country const* owner, Country const* controller, uint8_t colonial, bool slave, + std::vector&& cores, std::vector&& remove_cores, Good const* rgo, uint8_t life_rating, + TerrainType const* terrain_type, std::map&& buildings, + std::map&& party_loyalties, std::bitset<5> updates ) { if (locked) { Logger::error("Cannot add new history entry to province history registry: locked!"); @@ -98,37 +74,49 @@ bool ProvinceHistoryManager::add_province_history_entry( const auto existing_entry = province_registry.find(date); if (existing_entry != province_registry.end()) { - if (owner != nullptr) existing_entry->second.owner = owner; - if (controller != nullptr) existing_entry->second.controller = controller; - if (rgo != nullptr) existing_entry->second.rgo = rgo; - if (terrain_type != nullptr) existing_entry->second.terrain_type = terrain_type; - if (updates[0]) existing_entry->second.colonial = colonial; - if (updates[1]) existing_entry->second.slave = slave; - if (updates[2]) existing_entry->second.life_rating = life_rating; - if (updates[3]) existing_entry->second.buildings = std::move(buildings); - if (updates[4]) existing_entry->second.party_loyalties = std::move(party_loyalties); + if (owner != nullptr) { + existing_entry->second.owner = owner; + } + if (controller != nullptr) { + existing_entry->second.controller = controller; + } + if (rgo != nullptr) { + existing_entry->second.rgo = rgo; + } + if (terrain_type != nullptr) { + existing_entry->second.terrain_type = terrain_type; + } + if (updates[0]) { + existing_entry->second.colonial = colonial; + } + if (updates[1]) { + existing_entry->second.slave = slave; + } + if (updates[2]) { + existing_entry->second.life_rating = life_rating; + } + if (updates[3]) { + existing_entry->second.buildings = std::move(buildings); + } + if (updates[4]) { + existing_entry->second.party_loyalties = std::move(party_loyalties); + } // province history cores are additive existing_entry->second.cores.insert(existing_entry->second.cores.end(), cores.begin(), cores.end()); for (const auto which : remove_cores) { const auto core = std::find(cores.begin(), cores.end(), which); if (core == cores.end()) { - Logger::error("In history of province ", province->get_identifier(), - " tried to remove nonexistant core of country: ", which->get_identifier(), " at date ", date.to_string()); + Logger::error( + "In history of province ", province->get_identifier(), " tried to remove nonexistant core of country: ", + which->get_identifier(), " at date ", date.to_string() + ); return false; } existing_entry->second.cores.erase(core); } } else { province_registry.emplace(date, ProvinceHistory { - owner, - controller, - colonial, - slave, - std::move(cores), - rgo, - life_rating, - terrain_type, - std::move(buildings), + owner, controller, colonial, slave, std::move(cores), rgo, life_rating, terrain_type, std::move(buildings), std::move(party_loyalties) }); } @@ -138,8 +126,9 @@ bool ProvinceHistoryManager::add_province_history_entry( void ProvinceHistoryManager::lock_province_histories() { for (auto const& entry : province_histories) { if (entry.second.size() == 0) { - Logger::error("Attempted to lock province histories - province ", entry.first->get_identifier(), - " has no history entries!"); + Logger::error( + "Attempted to lock province histories - province ", entry.first->get_identifier(), " has no history entries!" + ); } } Logger::info("Locked province history registry after registering ", province_histories.size(), " items"); @@ -218,7 +207,9 @@ inline bool ProvinceHistoryManager::_load_province_history_entry( bool is_date; Date().from_string(key, &is_date, true); - if (is_date) return true; + if (is_date) { + return true; + } return key_value_invalid_callback(key, value); }, @@ -304,20 +295,9 @@ inline bool ProvinceHistoryManager::_load_province_history_entry( )(root); ret &= add_province_history_entry( - game_manager.get_map().get_province_by_identifier(province), - date, - owner, - controller, - colonial, - slave, - std::move(cores), - std::move(remove_cores), - rgo, - life_rating, - terrain_type, - std::move(buildings), - std::move(party_loyalties), - updates + game_manager.get_map().get_province_by_identifier(province), date, owner, controller, colonial, slave, + std::move(cores), std::move(remove_cores), rgo, life_rating, terrain_type, std::move(buildings), + std::move(party_loyalties), updates ); return ret; } @@ -329,12 +309,16 @@ bool ProvinceHistoryManager::load_province_history_file(GameManager& game_manage [this, &game_manager, &name](std::string_view key, ast::NodeCPtr value) -> bool { bool is_date = false; Date entry = Date().from_string(key, &is_date, true); - if (!is_date) return true; + if (!is_date) { + return true; + } Date const& end_date = game_manager.get_define_manager().get_end_date(); if (entry > end_date) { - Logger::error("History entry ", entry.to_string(), " of province ", name, " defined after defined end date ", - end_date.to_string()); + Logger::error( + "History entry ", entry.to_string(), " of province ", name, " defined after defined end date ", + end_date.to_string() + ); return false; } diff --git a/src/openvic-simulation/history/ProvinceHistory.hpp b/src/openvic-simulation/history/ProvinceHistory.hpp index d4e9615..00ce212 100644 --- a/src/openvic-simulation/history/ProvinceHistory.hpp +++ b/src/openvic-simulation/history/ProvinceHistory.hpp @@ -30,15 +30,9 @@ namespace OpenVic { std::map party_loyalties; ProvinceHistory( - Country const* new_owner, - Country const* new_controller, - uint8_t new_colonial, - bool new_slave, - std::vector&& new_cores, - Good const* new_rgo, - uint8_t new_life_rating, - TerrainType const* new_terrain_type, - std::map&& new_buildings, + Country const* new_owner, Country const* new_controller, uint8_t new_colonial, bool new_slave, + std::vector&& new_cores, Good const* new_rgo, uint8_t new_life_rating, + TerrainType const* new_terrain_type, std::map&& new_buildings, std::map&& new_party_loyalties ); @@ -69,19 +63,11 @@ namespace OpenVic { ProvinceHistoryManager() {} bool add_province_history_entry( - Province const* province, - Date date, - Country const* owner, - Country const* controller, - uint8_t colonial, - bool slave, + Province const* province, Date date, Country const* owner, Country const* controller, uint8_t colonial, bool slave, std::vector&& cores, // additive to existing entries std::vector&& remove_cores, // existing cores that need to be removed - Good const* rgo, - uint8_t life_rating, - TerrainType const* terrain_type, - std::map&& buildings, - std::map&& party_loyalties, + Good const* rgo, uint8_t life_rating, TerrainType const* terrain_type, + std::map&& buildings, std::map&& party_loyalties, std::bitset<5> updates // bitmap of updated non-pointer values, top to bottom ); diff --git a/src/openvic-simulation/map/Map.cpp b/src/openvic-simulation/map/Map.cpp index f61c326..4df17bf 100644 --- a/src/openvic-simulation/map/Map.cpp +++ b/src/openvic-simulation/map/Map.cpp @@ -10,15 +10,15 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Mapmode::Mapmode(std::string_view new_identifier, index_t new_index, colour_func_t new_colour_func) - : HasIdentifier { new_identifier }, - index { new_index }, - colour_func { new_colour_func } { +Mapmode::Mapmode( + std::string_view new_identifier, index_t new_index, colour_func_t new_colour_func +) : HasIdentifier { new_identifier }, index { new_index }, colour_func { new_colour_func } { assert(colour_func != nullptr); } -const Mapmode Mapmode::ERROR_MAPMODE { "mapmode_error", 0, - [](Map const& map, Province const& province) -> colour_t { return 0xFFFF0000; } }; +const Mapmode Mapmode::ERROR_MAPMODE { + "mapmode_error", 0, [](Map const& map, Province const& province) -> colour_t { return 0xFFFF0000; } +}; Mapmode::index_t Mapmode::get_index() const { return index; @@ -28,15 +28,14 @@ colour_t Mapmode::get_colour(Map const& map, Province const& province) const { return colour_func ? colour_func(map, province) : NULL_COLOUR; } -Map::Map() - : provinces { "provinces" }, - regions { "regions" }, - mapmodes { "mapmodes" } {} +Map::Map() : provinces { "provinces" }, regions { "regions" }, mapmodes { "mapmodes" } {} bool Map::add_province(std::string_view identifier, colour_t colour) { if (provinces.size() >= max_provinces) { - Logger::error("The map's province list is full - maximum number of provinces is ", - max_provinces, " (this can be at most ", Province::MAX_INDEX, ")"); + Logger::error( + "The map's province list is full - maximum number of provinces is ", max_provinces, " (this can be at most ", + Province::MAX_INDEX, ")" + ); return false; } if (identifier.empty()) { @@ -50,8 +49,9 @@ bool Map::add_province(std::string_view identifier, colour_t colour) { Province new_province { identifier, colour, static_cast(provinces.size() + 1) }; const Province::index_t index = get_index_from_colour(colour); if (index != Province::NULL_INDEX) { - Logger::error("Duplicate province colours: ", get_province_by_index(index)->to_string(), - " and ", new_province.to_string()); + Logger::error( + "Duplicate province colours: ", get_province_by_index(index)->to_string(), " and ", new_province.to_string() + ); return false; } colour_index_map[new_province.get_colour()] = new_province.get_index(); @@ -163,13 +163,16 @@ Province::index_t Map::get_province_index_at(size_t x, size_t y) const { bool Map::set_max_provinces(Province::index_t new_max_provinces) { if (new_max_provinces <= Province::NULL_INDEX) { - Logger::error("Trying to set max province count to an invalid value ", - new_max_provinces, " (must be greater than ", Province::NULL_INDEX, ")"); + Logger::error( + "Trying to set max province count to an invalid value ", new_max_provinces, " (must be greater than ", + Province::NULL_INDEX, ")" + ); return false; } if (!provinces.empty() || provinces.is_locked()) { - Logger::error("Trying to set max province count to ", new_max_provinces, - " after provinces have already been added and/or 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; @@ -182,8 +185,9 @@ Province::index_t Map::get_max_provinces() const { void Map::set_selected_province(Province::index_t index) { if (index > get_province_count()) { - Logger::error("Trying to set selected province to an invalid index ", index, - " (max index is ", get_province_count(), ")"); + Logger::error( + "Trying to set selected province to an invalid index ", index, " (max index is ", get_province_count(), ")" + ); selected_province = Province::NULL_INDEX; } else { selected_province = index; @@ -345,8 +349,9 @@ bool Map::load_province_definitions(std::vector const& lines) { { 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); + Logger::error( + "Non-standard province definition file header - make sure this is not a province definition: ", header + ); } } if (lines.size() <= 1) { @@ -355,36 +360,29 @@ bool Map::load_province_definitions(std::vector const& lines) { } provinces.reserve(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 = NULL_COLOUR; - 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(identifier, colour); + 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 = NULL_COLOUR; + 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(identifier, colour); } - ); + }); lock_provinces(); return ret; } bool Map::load_province_positions(BuildingManager const& building_manager, ast::NodeCPtr root) { - return expect_province_dictionary( - [&building_manager](Province& province, ast::NodeCPtr node) -> bool { - return province.load_positions(building_manager, node); - } - )(root); + return expect_province_dictionary([&building_manager](Province& province, ast::NodeCPtr node) -> bool { + return province.load_positions(building_manager, node); + })(root); } bool Map::load_region_file(ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - regions, + const bool ret = expect_dictionary_reserve_length(regions, [this](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { std::vector province_identifiers; bool ret = expect_list_reserve_length( @@ -413,8 +411,10 @@ bool Map::load_region_file(ast::NodeCPtr root) { for (Province& province : provinces.get_items()) { const bool region_null = province.get_region() == nullptr; if (province.get_has_region() == region_null) { - Logger::error("Province has_region / region mismatch: has_region = ", - province.get_has_region(), ", region = ", province.get_region()); + Logger::error( + "Province has_region / region mismatch: has_region = ", province.get_has_region(), + ", region = ", province.get_region() + ); province.has_region = !region_null; } } @@ -447,8 +447,10 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain } 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, ")"); + Logger::error( + "Invalid province BMP bits per pixel: ", province_bmp.get_bits_per_pixel(), " (expected ", expected_province_bpp, + ")" + ); return false; } @@ -459,14 +461,17 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain } 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, ")"); + 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()); + 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; } @@ -512,8 +517,9 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain if (unrecognised_province_colours.find(province_colour) == unrecognised_province_colours.end()) { unrecognised_province_colours.insert(province_colour); if (detailed_errors) { - Logger::warning("Unrecognised province colour ", colour_to_hex_string(province_colour), - " at (", x, ", ", y, ")"); + Logger::warning( + "Unrecognised province colour ", colour_to_hex_string(province_colour), " at (", x, ", ", y, ")" + ); } } province_shape_image[idx].index = Province::NULL_INDEX; @@ -526,8 +532,8 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain terrain_type_pixels_list[province_shape_image[idx].index - 1][&mapping->get_type()]++; } - province_shape_image[idx].terrain = mapping->get_has_texture() - && terrain < terrain_type_manager.get_terrain_texture_limit() ? terrain + 1 : 0; + province_shape_image[idx].terrain = + mapping->get_has_texture() && terrain < terrain_type_manager.get_terrain_texture_limit() ? terrain + 1 : 0; } else { province_shape_image[idx].terrain = 0; } @@ -541,8 +547,9 @@ bool Map::load_map_images(fs::path const& province_path, fs::path const& terrain size_t missing = 0; for (size_t idx = 0; idx < province_checklist.size(); ++idx) { Province* province = provinces.get_item_by_index(idx); - province->_set_terrain_type(reinterpret_cast( - get_largest_item(terrain_type_pixels_list[idx]).first)); + province->_set_terrain_type( + reinterpret_cast(get_largest_item(terrain_type_pixels_list[idx]).first) + ); province->on_map = province_checklist[idx]; if (!province->on_map) { if (detailed_errors) { diff --git a/src/openvic-simulation/map/Province.cpp b/src/openvic-simulation/map/Province.cpp index 5a7625f..225d4c0 100644 --- a/src/openvic-simulation/map/Province.cpp +++ b/src/openvic-simulation/map/Province.cpp @@ -3,9 +3,10 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Province::Province(std::string_view new_identifier, colour_t new_colour, index_t new_index) - : HasIdentifierAndColour { new_identifier, new_colour, false, false }, - index { new_index }, buildings { "buildings", false } { +Province::Province( + std::string_view new_identifier, colour_t new_colour, index_t new_index +) : HasIdentifierAndColour { new_identifier, new_colour, false, false }, index { new_index }, + buildings { "buildings", false } { assert(index != NULL_INDEX); } @@ -93,8 +94,7 @@ std::string Province::to_string() const { } bool Province::load_pop_list(PopManager const& pop_manager, ast::NodeCPtr root) { - return expect_dictionary_reserve_length( - pops, + return expect_dictionary_reserve_length(pops, [this, &pop_manager](std::string_view pop_type_identifier, ast::NodeCPtr pop_node) -> bool { return pop_manager.load_pop_into_province(*this, pop_type_identifier, pop_node); } @@ -182,10 +182,11 @@ Province::flags_t Province::adjacency_t::get_flags() const { } bool Province::is_adjacent_to(Province const* province) { - for (adjacency_t adj : adjacencies) + for (adjacency_t adj : adjacencies) { if (adj.province == province) { return true; } + } return false; } diff --git a/src/openvic-simulation/map/TerrainType.cpp b/src/openvic-simulation/map/TerrainType.cpp index db910ce..1753246 100644 --- a/src/openvic-simulation/map/TerrainType.cpp +++ b/src/openvic-simulation/map/TerrainType.cpp @@ -5,8 +5,10 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -TerrainType::TerrainType(std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_modifier, bool new_is_water) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, modifier { std::move(new_modifier) }, is_water { new_is_water } {} +TerrainType::TerrainType( + std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_modifier, bool new_is_water +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, modifier { std::move(new_modifier) }, + is_water { new_is_water } {} ModifierValue const& TerrainType::get_modifier() const { return modifier; @@ -16,10 +18,11 @@ bool TerrainType::get_is_water() const { return is_water; } -TerrainTypeMapping::TerrainTypeMapping(std::string_view new_identifier, TerrainType const& new_type, - std::vector&& new_terrain_indicies, index_t new_priority, bool new_has_texture) - : HasIdentifier { new_identifier }, type { new_type }, terrain_indicies { std::move(new_terrain_indicies) }, - priority { new_priority }, has_texture { new_has_texture } {} +TerrainTypeMapping::TerrainTypeMapping( + std::string_view new_identifier, TerrainType const& new_type, std::vector&& new_terrain_indicies, + index_t new_priority, bool new_has_texture +) : HasIdentifier { new_identifier }, type { new_type }, terrain_indicies { std::move(new_terrain_indicies) }, + priority { new_priority }, has_texture { new_has_texture } {} TerrainType const& TerrainTypeMapping::get_type() const { return type; @@ -37,7 +40,8 @@ bool TerrainTypeMapping::get_has_texture() const { return has_texture; } -TerrainTypeManager::TerrainTypeManager() : terrain_types { "terrain types" }, terrain_type_mappings { "terrain type mappings" } {} +TerrainTypeManager::TerrainTypeManager() + : terrain_types { "terrain types" }, terrain_type_mappings { "terrain type mappings" } {} bool TerrainTypeManager::add_terrain_type(std::string_view identifier, colour_t colour, ModifierValue&& values, bool is_water) { if (identifier.empty()) { @@ -51,8 +55,10 @@ bool TerrainTypeManager::add_terrain_type(std::string_view identifier, colour_t return terrain_types.add_item({ identifier, colour, std::move(values), is_water }); } -bool TerrainTypeManager::add_terrain_type_mapping(std::string_view identifier, TerrainType const* type, - std::vector&& terrain_indicies, TerrainTypeMapping::index_t priority, bool has_texture) { +bool TerrainTypeManager::add_terrain_type_mapping( + std::string_view identifier, TerrainType const* type, std::vector&& terrain_indicies, + TerrainTypeMapping::index_t priority, bool has_texture +) { if (!terrain_types_are_locked()) { Logger::error("Cannot register terrain type mappings until terrain types are locked!"); return false; @@ -71,8 +77,10 @@ bool TerrainTypeManager::add_terrain_type_mapping(std::string_view identifier, T if (it == terrain_type_mappings_map.end()) { terrain_type_mappings_map.emplace(idx, terrain_type_mappings.size()); } else { - Logger::error("Terrain index ", static_cast(idx), " cannot map to ", identifier, - " as it already maps to ", terrain_type_mappings.get_item_by_index(it->second)); + Logger::error( + "Terrain index ", static_cast(idx), " cannot map to ", identifier, " as it already maps to ", + terrain_type_mappings.get_item_by_index(it->second) + ); ret = false; } } diff --git a/src/openvic-simulation/map/TerrainType.hpp b/src/openvic-simulation/map/TerrainType.hpp index 19380fe..656c938 100644 --- a/src/openvic-simulation/map/TerrainType.hpp +++ b/src/openvic-simulation/map/TerrainType.hpp @@ -32,8 +32,10 @@ namespace OpenVic { const index_t priority; const bool has_texture; - TerrainTypeMapping(std::string_view new_identifier, TerrainType const& new_type, - std::vector&& new_terrain_indicies, index_t new_priority, bool new_has_texture); + TerrainTypeMapping( + std::string_view new_identifier, TerrainType const& new_type, std::vector&& new_terrain_indicies, + index_t new_priority, bool new_has_texture + ); public: TerrainTypeMapping(TerrainTypeMapping&&) = default; @@ -62,8 +64,10 @@ namespace OpenVic { bool add_terrain_type(std::string_view identifier, colour_t colour, ModifierValue&& values, bool is_water); IDENTIFIER_REGISTRY_ACCESSORS(terrain_type) - bool add_terrain_type_mapping(std::string_view identifier, TerrainType const* type, - std::vector&& terrain_indicies, TerrainTypeMapping::index_t priority, bool has_texture); + bool add_terrain_type_mapping( + std::string_view identifier, TerrainType const* type, std::vector&& terrain_indicies, + TerrainTypeMapping::index_t priority, bool has_texture + ); IDENTIFIER_REGISTRY_ACCESSORS(terrain_type_mapping) TerrainTypeMapping const* get_terrain_type_mapping_for(TerrainTypeMapping::index_t idx) const; diff --git a/src/openvic-simulation/military/Deployment.cpp b/src/openvic-simulation/military/Deployment.cpp index 441142d..5b3aa77 100644 --- a/src/openvic-simulation/military/Deployment.cpp +++ b/src/openvic-simulation/military/Deployment.cpp @@ -6,10 +6,9 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Deployment::Deployment( - std::string_view new_path, std::vector&& new_armies, - std::vector&& new_navies, std::vector&& new_leaders -) : HasIdentifier { new_path }, armies { std::move(new_armies) }, - navies { std::move(new_navies) }, leaders { std::move(new_leaders) } {} + std::string_view new_path, std::vector&& new_armies, std::vector&& new_navies, std::vector&& new_leaders +) : HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, + leaders { std::move(new_leaders) } {} const std::vector& Deployment::get_armies() const { return armies; @@ -25,8 +24,9 @@ const std::vector& Deployment::get_leaders() const { DeploymentManager::DeploymentManager() : deployments { "deployments" } {} -bool DeploymentManager::add_deployment(std::string_view path, std::vector&& armies, - std::vector&& navies, std::vector&& leaders) { +bool DeploymentManager::add_deployment( + std::string_view path, std::vector&& armies, std::vector&& navies, std::vector&& leaders +) { if (path.empty()) { Logger::error("Attemped to load order of battle with no path! Something is very wrong!"); return false; diff --git a/src/openvic-simulation/military/Deployment.hpp b/src/openvic-simulation/military/Deployment.hpp index 9eb0a72..34cf82a 100644 --- a/src/openvic-simulation/military/Deployment.hpp +++ b/src/openvic-simulation/military/Deployment.hpp @@ -56,8 +56,10 @@ namespace OpenVic { const std::vector navies; const std::vector leaders; - Deployment(std::string_view new_path, std::vector&& new_armies, - std::vector&& new_navies, std::vector&& new_leaders); + Deployment( + std::string_view new_path, std::vector&& new_armies, std::vector&& new_navies, + std::vector&& new_leaders + ); public: const std::vector& get_armies() const; @@ -72,8 +74,9 @@ namespace OpenVic { public: DeploymentManager(); - bool add_deployment(std::string_view path, std::vector&& armies, - std::vector&& navies, std::vector&& leaders); + bool add_deployment( + std::string_view path, std::vector&& armies, std::vector&& navies, std::vector&& leaders + ); IDENTIFIER_REGISTRY_ACCESSORS(deployment); bool load_oob_file(GameManager& game_manager, std::string_view path, ast::NodeCPtr root); diff --git a/src/openvic-simulation/military/LeaderTrait.cpp b/src/openvic-simulation/military/LeaderTrait.cpp index 81c6ccc..df87e4e 100644 --- a/src/openvic-simulation/military/LeaderTrait.cpp +++ b/src/openvic-simulation/military/LeaderTrait.cpp @@ -24,8 +24,9 @@ ModifierValue const& LeaderTrait::get_modifiers() const { LeaderTraitManager::LeaderTraitManager() : leader_traits { "leader trait" } {} -bool LeaderTraitManager::add_leader_trait(std::string_view identifier, - LeaderTrait::trait_type_t type, ModifierValue&& modifiers) { +bool LeaderTraitManager::add_leader_trait( + std::string_view identifier, LeaderTrait::trait_type_t type, ModifierValue&& modifiers +) { if (identifier.empty()) { Logger::error("Invalid leader trait identifier - empty!"); return false; @@ -39,7 +40,8 @@ bool LeaderTraitManager::load_leader_traits_file(ModifierManager const& modifier const auto trait_callback = [this, &modifier_manager](LeaderTrait::trait_type_t type) -> key_value_callback_t { return [this, &modifier_manager, type](std::string_view trait_identifier, ast::NodeCPtr value) -> bool { ModifierValue modifiers; - bool ret = modifier_manager.expect_whitelisted_modifier_value(move_variable_callback(modifiers), allowed_modifiers)(value); + bool ret = + modifier_manager.expect_whitelisted_modifier_value(move_variable_callback(modifiers), allowed_modifiers)(value); ret &= add_leader_trait(trait_identifier, type, std::move(modifiers)); return ret; }; diff --git a/src/openvic-simulation/military/LeaderTrait.hpp b/src/openvic-simulation/military/LeaderTrait.hpp index d885057..e61a1fc 100644 --- a/src/openvic-simulation/military/LeaderTrait.hpp +++ b/src/openvic-simulation/military/LeaderTrait.hpp @@ -14,13 +14,9 @@ namespace OpenVic { struct LeaderTrait : HasIdentifier { friend struct LeaderTraitManager; - enum class trait_type_t { - PERSONALITY, - BACKGROUND - }; + enum class trait_type_t { PERSONALITY, BACKGROUND }; private: - const trait_type_t type; /* * Allowed modifiers for leaders: @@ -51,15 +47,7 @@ namespace OpenVic { private: IdentifierRegistry leader_traits; inline static const string_set_t allowed_modifiers = { - "attack", - "defence", - "morale", - "organisation", - "reconnaissance", - "speed", - "attrition", - "experience", - "reliability" + "attack", "defence", "morale", "organisation", "reconnaissance", "speed", "attrition", "experience", "reliability" }; public: diff --git a/src/openvic-simulation/military/MilitaryManager.hpp b/src/openvic-simulation/military/MilitaryManager.hpp index 57ba8d1..0e7e1b1 100644 --- a/src/openvic-simulation/military/MilitaryManager.hpp +++ b/src/openvic-simulation/military/MilitaryManager.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/military/LeaderTrait.hpp" #include "openvic-simulation/military/Deployment.hpp" +#include "openvic-simulation/military/LeaderTrait.hpp" #include "openvic-simulation/military/Unit.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/military/Unit.cpp b/src/openvic-simulation/military/Unit.cpp index f079ee9..1b5f2d2 100644 --- a/src/openvic-simulation/military/Unit.cpp +++ b/src/openvic-simulation/military/Unit.cpp @@ -2,23 +2,24 @@ #define UNIT_ARGS \ icon, sprite, active, unit_type, floating_flag, priority, max_strength, default_organisation, maximum_speed, \ - weighted_value, move_sound, select_sound, build_time, std::move(build_cost), supply_consumption, std::move(supply_cost) + weighted_value, move_sound, select_sound, build_time, std::move(build_cost), supply_consumption, \ + std::move(supply_cost) #define LAND_ARGS \ - primary_culture, sprite_override, sprite_mount, sprite_mount_attach_node, \ - reconnaissance, attack, defence, discipline, support, maneuver, siege + primary_culture, sprite_override, sprite_mount, sprite_mount_attach_node, reconnaissance, attack, defence, discipline, \ + support, maneuver, siege #define NAVY_ARGS \ - naval_icon, sail, transport, capital, colonial_points, build_overseas, min_port_level, \ - limit_per_port, supply_consumption_score, hull, gun_power, fire_range, evasion, torpedo_attack + naval_icon, sail, transport, capital, colonial_points, build_overseas, min_port_level, limit_per_port, \ + supply_consumption_score, hull, gun_power, fire_range, evasion, torpedo_attack using namespace OpenVic; using namespace OpenVic::NodeTools; Unit::Unit( std::string_view identifier, type_t type, UNIT_PARAMS -) : HasIdentifier { identifier }, icon { icon }, type { type }, sprite { sprite }, active { active }, - unit_type { unit_type }, floating_flag { floating_flag }, priority { priority }, max_strength { max_strength }, +) : HasIdentifier { identifier }, icon { icon }, type { type }, sprite { sprite }, active { active }, unit_type { unit_type }, + floating_flag { floating_flag }, priority { priority }, max_strength { max_strength }, default_organisation { default_organisation }, maximum_speed { maximum_speed }, weighted_value { weighted_value }, move_sound { move_sound }, select_sound { select_sound }, build_time { build_time }, build_cost { std::move(build_cost) }, supply_consumption { supply_consumption }, supply_cost { std::move(supply_cost) } {} @@ -93,10 +94,10 @@ Good::good_map_t const& Unit::get_supply_cost() const { LandUnit::LandUnit( std::string_view identifier, UNIT_PARAMS, LAND_PARAMS -) : Unit { identifier, type_t::LAND, UNIT_ARGS }, primary_culture { primary_culture }, - sprite_override { sprite_override }, sprite_mount { sprite_mount }, sprite_mount_attach_node { sprite_mount_attach_node }, - reconnaissance { reconnaissance }, attack { attack }, defence { defence }, discipline { discipline }, support { support }, - maneuver { maneuver }, siege { siege } {} +) : Unit { identifier, type_t::LAND, UNIT_ARGS }, primary_culture { primary_culture }, sprite_override { sprite_override }, + sprite_mount { sprite_mount }, sprite_mount_attach_node { sprite_mount_attach_node }, reconnaissance { reconnaissance }, + attack { attack }, defence { defence }, discipline { discipline }, support { support }, maneuver { maneuver }, + siege { siege } {} bool LandUnit::get_primary_culture() const { return primary_culture; @@ -144,11 +145,11 @@ fixed_point_t LandUnit::get_siege() const { NavalUnit::NavalUnit( std::string_view identifier, UNIT_PARAMS, NAVY_PARAMS -) : Unit { identifier, type_t::NAVAL, UNIT_ARGS }, naval_icon { naval_icon }, sail { sail }, - transport { transport }, capital { capital }, colonial_points { colonial_points }, - build_overseas { build_overseas }, min_port_level { min_port_level }, limit_per_port { limit_per_port }, - supply_consumption_score { supply_consumption_score }, hull { hull }, gun_power { gun_power }, - fire_range { fire_range }, evasion { evasion }, torpedo_attack { torpedo_attack } {}; +) : Unit { identifier, type_t::NAVAL, UNIT_ARGS }, naval_icon { naval_icon }, sail { sail }, transport { transport }, + capital { capital }, colonial_points { colonial_points }, build_overseas { build_overseas }, + min_port_level { min_port_level }, limit_per_port { limit_per_port }, + supply_consumption_score { supply_consumption_score }, hull { hull }, gun_power { gun_power }, fire_range { fire_range }, + evasion { evasion }, torpedo_attack { torpedo_attack } {}; NavalUnit::icon_t NavalUnit::get_naval_icon() const { return naval_icon; @@ -220,7 +221,7 @@ bool UnitManager::_check_shared_parameters(std::string_view identifier, UNIT_PAR return false; } - //TODO check that icon and sprite exist + // TODO check that icon and sprite exist return true; } @@ -238,7 +239,7 @@ bool UnitManager::add_naval_unit(std::string_view identifier, UNIT_PARAMS, NAVY_ return false; } - //TODO: check that icon and sounds exist + // TODO: check that icon and sounds exist return units.add_item(NavalUnit { identifier, UNIT_ARGS, NAVY_ARGS }); } @@ -256,11 +257,8 @@ bool UnitManager::load_unit_file(GoodManager const& good_manager, ast::NodeCPtr Good::good_map_t build_cost, supply_cost; using enum Unit::type_t; - static const string_map_t type_map = { - { "land", LAND }, { "naval", NAVAL } - }; - bool ret = - expect_key("type", expect_identifier(expect_mapped_string(type_map, assign_variable_callback(type))))(value); + static const string_map_t type_map = { { "land", LAND }, { "naval", NAVAL } }; + bool ret = expect_key("type", expect_identifier(expect_mapped_string(type_map, assign_variable_callback(type))))(value); if (!ret) { Logger::error("Failed to read type for unit: ", key); @@ -268,7 +266,7 @@ bool UnitManager::load_unit_file(GoodManager const& good_manager, ast::NodeCPtr } key_map_t key_map; - //shared + // shared ret &= add_key_map_entries(key_map, "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), "type", ONE_EXACTLY, success_callback, @@ -347,9 +345,7 @@ bool UnitManager::load_unit_file(GoodManager const& good_manager, ast::NodeCPtr return ret; } - default: - Logger::error("Unknown unit type for ", key, ": ", static_cast(type)); - return false; + default: Logger::error("Unknown unit type for ", key, ": ", static_cast(type)); return false; } })(root); } diff --git a/src/openvic-simulation/military/Unit.hpp b/src/openvic-simulation/military/Unit.hpp index d1dcc8f..acfc8b8 100644 --- a/src/openvic-simulation/military/Unit.hpp +++ b/src/openvic-simulation/military/Unit.hpp @@ -10,11 +10,10 @@ #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #define UNIT_PARAMS \ - Unit::icon_t icon, std::string_view sprite, bool active, std::string_view unit_type, \ - bool floating_flag, uint32_t priority, fixed_point_t max_strength, fixed_point_t default_organisation, \ - fixed_point_t maximum_speed, fixed_point_t weighted_value, std::string_view move_sound, \ - std::string_view select_sound, Timespan build_time, Good::good_map_t &&build_cost, \ - fixed_point_t supply_consumption, Good::good_map_t &&supply_cost + Unit::icon_t icon, std::string_view sprite, bool active, std::string_view unit_type, bool floating_flag, \ + uint32_t priority, fixed_point_t max_strength, fixed_point_t default_organisation, fixed_point_t maximum_speed, \ + fixed_point_t weighted_value, std::string_view move_sound, std::string_view select_sound, Timespan build_time, \ + Good::good_map_t&& build_cost, fixed_point_t supply_consumption, Good::good_map_t&& supply_cost #define LAND_PARAMS \ bool primary_culture, std::string_view sprite_override, std::string_view sprite_mount, \ @@ -30,10 +29,7 @@ namespace OpenVic { struct Unit : HasIdentifier { using icon_t = uint32_t; - enum struct type_t { - LAND, - NAVAL - }; + enum struct type_t { LAND, NAVAL }; private: const type_t type; @@ -175,4 +171,4 @@ namespace OpenVic { bool load_unit_file(GoodManager const& good_manager, ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/misc/Define.cpp b/src/openvic-simulation/misc/Define.cpp index 3da1f4a..5e6a3cb 100644 --- a/src/openvic-simulation/misc/Define.cpp +++ b/src/openvic-simulation/misc/Define.cpp @@ -15,14 +15,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Define::Define( - std::string_view new_identifier, - std::string&& new_value, - Type new_type -) : HasIdentifier { new_identifier }, - value { std::move(new_value) }, - type { new_type } { -} +Define::Define(std::string_view new_identifier, std::string&& new_value, Type new_type) + : HasIdentifier { new_identifier }, value { std::move(new_value) }, type { new_type } {} fixed_point_t Define::get_value_as_fp() const { return fixed_point_t::parse(value); @@ -36,8 +30,7 @@ uint64_t Define::get_value_as_uint() const { return std::strtoull(value.data(), nullptr, 10); } -DefineManager::DefineManager() : defines { "defines" } { -} +DefineManager::DefineManager() : defines { "defines" } {} bool DefineManager::add_define(std::string_view name, std::string&& value, Define::Type type) { return defines.add_item({ name, std::move(value), type }, duplicate_warning_callback); @@ -70,8 +63,8 @@ bool DefineManager::add_date_define(std::string_view name, Date date) { bool DefineManager::load_defines_file(ast::NodeCPtr root) { bool ret = expect_dictionary_keys( "defines", ONE_EXACTLY, expect_dictionary([this](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "country" || key == "economy" || key == "military" || key == "diplomacy" - || key == "pops" || key == "ai" || key == "graphics") { + if (key == "country" || key == "economy" || key == "military" || key == "diplomacy" || + key == "pops" || key == "ai" || key == "graphics") { return expect_dictionary([this, &key](std::string_view inner_key, ast::NodeCPtr value) -> bool { std::string str_val; @@ -122,4 +115,4 @@ bool DefineManager::load_defines_file(ast::NodeCPtr root) { )(root); lock_defines(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/misc/Define.hpp b/src/openvic-simulation/misc/Define.hpp index 9b768b7..0db9716 100644 --- a/src/openvic-simulation/misc/Define.hpp +++ b/src/openvic-simulation/misc/Define.hpp @@ -12,26 +12,13 @@ namespace OpenVic { struct Define : HasIdentifier { friend struct DefineManager; - enum class Type : unsigned char { - None, - Country, - Economy, - Military, - Diplomacy, - Pops, - Ai, - Graphics - }; + enum class Type : unsigned char { None, Country, Economy, Military, Diplomacy, Pops, Ai, Graphics }; private: std::string HASID_PROPERTY(value); Type HASID_PROPERTY(type); - Define( - std::string_view new_identifier, - std::string&& new_value, - Type new_type - ); + Define(std::string_view new_identifier, std::string&& new_value, Type new_type); public: Define(Define&&) = default; @@ -60,4 +47,4 @@ namespace OpenVic { bool load_defines_file(ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Government.cpp b/src/openvic-simulation/politics/Government.cpp index 97b1d68..823284a 100644 --- a/src/openvic-simulation/politics/Government.cpp +++ b/src/openvic-simulation/politics/Government.cpp @@ -38,8 +38,10 @@ std::string_view GovernmentType::get_flag_type() const { GovernmentTypeManager::GovernmentTypeManager() : government_types { "government types" } {} -bool GovernmentTypeManager::add_government_type(std::string_view identifier, std::vector&& ideologies, - bool elections, bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type) { +bool GovernmentTypeManager::add_government_type( + std::string_view identifier, std::vector&& ideologies, bool elections, bool appoint_ruling_party, + Timespan term_duration, std::string_view flag_type +) { if (identifier.empty()) { Logger::error("Invalid government type identifier - empty!"); return false; @@ -55,13 +57,14 @@ bool GovernmentTypeManager::add_government_type(std::string_view identifier, std return false; } - return government_types.add_item({ identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, flag_type }); + return government_types.add_item({ + identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, flag_type + }); } /* REQUIREMENTS: FS-525, SIM-27 */ bool GovernmentTypeManager::load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root) { - bool ret = expect_dictionary_reserve_length( - government_types, + bool ret = expect_dictionary_reserve_length(government_types, [this, &ideology_manager](std::string_view government_type_identifier, ast::NodeCPtr government_type_value) -> bool { std::vector ideologies; bool elections = false, appoint_ruling_party = false; @@ -79,14 +82,18 @@ bool GovernmentTypeManager::load_government_types_file(IdeologyManager const& id ideologies.reserve(total_expected_ideologies); ret &= expect_dictionary( - [this, &ideology_manager, &ideologies, government_type_identifier](std::string_view key, ast::NodeCPtr value) -> bool { - static const string_set_t reserved_keys = { - "election", "duration", "appoint_ruling_party", "flagType" - }; - if (reserved_keys.find(key) != reserved_keys.end()) return true; + [this, &ideology_manager, &ideologies, government_type_identifier]( + std::string_view key, ast::NodeCPtr value) -> bool { + static const string_set_t reserved_keys = { "election", "duration", "appoint_ruling_party", "flagType" }; + if (reserved_keys.find(key) != reserved_keys.end()) { + return true; + } Ideology const* ideology = ideology_manager.get_ideology_by_identifier(key); if (ideology == nullptr) { - Logger::error("When loading government type ", government_type_identifier, ", specified ideology ", key, " is invalid!"); + Logger::error( + "When loading government type ", government_type_identifier, ", specified ideology ", key, + " is invalid!" + ); return false; } return expect_bool([&ideologies, ideology, government_type_identifier](bool val) -> bool { @@ -95,20 +102,29 @@ bool GovernmentTypeManager::load_government_types_file(IdeologyManager const& id ideologies.push_back(ideology); return true; } - Logger::error("Government type ", government_type_identifier, " marked as supporting ideology ", ideology->get_identifier()); + Logger::error( + "Government type ", government_type_identifier, " marked as supporting ideology ", + ideology->get_identifier() + ); return false; } - Logger::error("Government type ", government_type_identifier, " redundantly marked as not supporting ideology ", ideology->get_identifier(), " multiple times"); + Logger::error( + "Government type ", government_type_identifier, " redundantly marked as not supporting ideology ", + ideology->get_identifier(), " multiple times" + ); return false; })(value); } )(government_type_value); - ret &= add_government_type(government_type_identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, flag_type_identifier); + ret &= add_government_type( + government_type_identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, + flag_type_identifier + ); return ret; } )(root); lock_government_types(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Government.hpp b/src/openvic-simulation/politics/Government.hpp index 455b822..9fff111 100644 --- a/src/openvic-simulation/politics/Government.hpp +++ b/src/openvic-simulation/politics/Government.hpp @@ -14,8 +14,10 @@ namespace OpenVic { const Timespan term_duration; const std::string flag_type_identifier; - GovernmentType(std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, - bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier); + GovernmentType( + std::string_view new_identifier, std::vector&& new_ideologies, bool new_elections, + bool new_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier + ); public: GovernmentType(GovernmentType&&) = default; @@ -35,8 +37,10 @@ namespace OpenVic { public: GovernmentTypeManager(); - bool add_government_type(std::string_view identifier, std::vector&& ideologies, bool elections, - bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type); + bool add_government_type( + std::string_view identifier, std::vector&& ideologies, bool elections, bool appoint_ruling_party, + Timespan term_duration, std::string_view flag_type + ); IDENTIFIER_REGISTRY_ACCESSORS(government_type) bool load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/Ideology.cpp b/src/openvic-simulation/politics/Ideology.cpp index c52d8b1..acbd82f 100644 --- a/src/openvic-simulation/politics/Ideology.cpp +++ b/src/openvic-simulation/politics/Ideology.cpp @@ -6,10 +6,10 @@ using namespace OpenVic::NodeTools; IdeologyGroup::IdeologyGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} Ideology::Ideology( - std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, - bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date -) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, - uncivilised { new_uncivilised }, can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date } {} + std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, bool new_uncivilised, + bool new_can_reduce_militancy, Date new_spawn_date +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, uncivilised { new_uncivilised }, + can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date } {} IdeologyGroup const& Ideology::get_group() const { return group; @@ -38,8 +38,10 @@ bool IdeologyManager::add_ideology_group(std::string_view identifier) { return ideology_groups.add_item({ identifier }); } -bool IdeologyManager::add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, - bool uncivilised, bool can_reduce_militancy, Date spawn_date) { +bool IdeologyManager::add_ideology( + std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, bool can_reduce_militancy, + Date spawn_date +) { if (identifier.empty()) { Logger::error("Invalid ideology identifier - empty!"); return false; @@ -60,11 +62,10 @@ bool IdeologyManager::add_ideology(std::string_view identifier, colour_t colour, /* REQUIREMENTS: * POL-9, POL-10, POL-11, POL-12, POL-13, POL-14, POL-15 -*/ + */ bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { size_t expected_ideologies = 0; - bool ret = expect_dictionary_reserve_length( - ideology_groups, + bool ret = expect_dictionary_reserve_length(ideology_groups, [this, &expected_ideologies](std::string_view key, ast::NodeCPtr value) -> bool { bool ret = expect_length(add_variable_callback(expected_ideologies))(value); ret &= add_ideology_group(key); @@ -74,35 +75,31 @@ bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { lock_ideology_groups(); ideologies.reserve(ideologies.size() + expected_ideologies); - ret &= expect_dictionary( - [this](std::string_view ideology_group_key, ast::NodeCPtr ideology_group_value) -> bool { - IdeologyGroup const* ideology_group = get_ideology_group_by_identifier(ideology_group_key); - - return expect_dictionary( - [this, ideology_group](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = NULL_COLOUR; - bool uncivilised = true, can_reduce_militancy = false; - Date spawn_date; - - bool ret = expect_dictionary_keys( - "uncivilized", ZERO_OR_ONE, expect_bool(assign_variable_callback(uncivilised)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "date", ZERO_OR_ONE, expect_date(assign_variable_callback(spawn_date)), - "can_reduce_militancy", ZERO_OR_ONE, expect_bool(assign_variable_callback(can_reduce_militancy)), - "add_political_reform", ONE_EXACTLY, success_callback, - "remove_political_reform", ONE_EXACTLY, success_callback, - "add_social_reform", ONE_EXACTLY, success_callback, - "remove_social_reform", ONE_EXACTLY, success_callback, - "add_military_reform", ZERO_OR_ONE, success_callback, - "add_economic_reform", ZERO_OR_ONE, success_callback - )(value); - ret &= add_ideology(key, colour, ideology_group, uncivilised, can_reduce_militancy, spawn_date); - return ret; - } - )(ideology_group_value); - } - )(root); + ret &= expect_dictionary([this](std::string_view ideology_group_key, ast::NodeCPtr ideology_group_value) -> bool { + IdeologyGroup const* ideology_group = get_ideology_group_by_identifier(ideology_group_key); + + return expect_dictionary([this, ideology_group](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = NULL_COLOUR; + bool uncivilised = true, can_reduce_militancy = false; + Date spawn_date; + + bool ret = expect_dictionary_keys( + "uncivilized", ZERO_OR_ONE, expect_bool(assign_variable_callback(uncivilised)), + "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), + "date", ZERO_OR_ONE, expect_date(assign_variable_callback(spawn_date)), + "can_reduce_militancy", ZERO_OR_ONE, expect_bool(assign_variable_callback(can_reduce_militancy)), + "add_political_reform", ONE_EXACTLY, success_callback, + "remove_political_reform", ONE_EXACTLY, success_callback, + "add_social_reform", ONE_EXACTLY, success_callback, + "remove_social_reform", ONE_EXACTLY, success_callback, + "add_military_reform", ZERO_OR_ONE, success_callback, + "add_economic_reform", ZERO_OR_ONE, success_callback + )(value); + ret &= add_ideology(key, colour, ideology_group, uncivilised, can_reduce_militancy, spawn_date); + return ret; + })(ideology_group_value); + })(root); lock_ideologies(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Ideology.hpp b/src/openvic-simulation/politics/Ideology.hpp index 3cd72f4..046dbc9 100644 --- a/src/openvic-simulation/politics/Ideology.hpp +++ b/src/openvic-simulation/politics/Ideology.hpp @@ -23,10 +23,12 @@ namespace OpenVic { const bool uncivilised, can_reduce_militancy; const Date spawn_date; - //TODO - willingness to repeal/pass reforms (and its modifiers) + // TODO - willingness to repeal/pass reforms (and its modifiers) - Ideology(std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, - bool new_uncivilised, bool new_can_reduce_militancy, Date new_spawn_date); + Ideology( + std::string_view new_identifier, colour_t new_colour, IdeologyGroup const& new_group, bool new_uncivilised, + bool new_can_reduce_militancy, Date new_spawn_date + ); public: Ideology(Ideology&&) = default; @@ -48,10 +50,12 @@ namespace OpenVic { bool add_ideology_group(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS(ideology_group) - bool add_ideology(std::string_view identifier, colour_t colour, IdeologyGroup const* group, - bool uncivilised, bool can_reduce_militancy, Date spawn_date); + bool add_ideology( + std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, + bool can_reduce_militancy, Date spawn_date + ); IDENTIFIER_REGISTRY_ACCESSORS_CUSTOM_PLURAL(ideology, ideologies) bool load_ideology_file(ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Issue.cpp b/src/openvic-simulation/politics/Issue.cpp index 4f05a99..cc3c12b 100644 --- a/src/openvic-simulation/politics/Issue.cpp +++ b/src/openvic-simulation/politics/Issue.cpp @@ -5,8 +5,7 @@ using namespace OpenVic::NodeTools; IssueGroup::IssueGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} -Issue::Issue(std::string_view identifier, IssueGroup const& group) - : HasIdentifier { identifier }, group { group } {} +Issue::Issue(std::string_view identifier, IssueGroup const& group) : HasIdentifier { identifier }, group { group } {} IssueGroup const& Issue::get_group() const { return group; @@ -45,8 +44,9 @@ size_t Reform::get_ordinal() const { return ordinal; } -IssueManager::IssueManager() : issue_groups { "issue groups" }, issues { "issues" }, - reform_types { "reform types" }, reform_groups { "reform groups" }, reforms { "reforms" } {} +IssueManager::IssueManager() + : issue_groups { "issue groups" }, issues { "issues" }, reform_types { "reform types" }, reform_groups { "reform groups" }, + reforms { "reforms" } {} bool IssueManager::add_issue_group(std::string_view identifier) { if (identifier.empty()) { @@ -116,12 +116,13 @@ bool IssueManager::_load_issue_group(size_t& expected_issues, std::string_view i } bool IssueManager::_load_issue(std::string_view identifier, IssueGroup const* group, ast::NodeCPtr node) { - //TODO: policy modifiers, policy rule changes + // TODO: policy modifiers, policy rule changes return add_issue(identifier, group); } -bool IssueManager::_load_reform_group(size_t& expected_reforms, std::string_view identifier, - ReformType const* type, ast::NodeCPtr node) { +bool IssueManager::_load_reform_group( + size_t& expected_reforms, std::string_view identifier, ReformType const* type, ast::NodeCPtr node +) { bool ordered = false, administrative = false; bool ret = expect_dictionary_keys_and_default( increment_callback(expected_reforms), @@ -133,7 +134,7 @@ bool IssueManager::_load_reform_group(size_t& expected_reforms, std::string_view } bool IssueManager::_load_reform(size_t& ordinal, std::string_view identifier, ReformGroup const* group, ast::NodeCPtr node) { - //TODO: conditions to allow, policy modifiers, policy rule changes + // TODO: conditions to allow, policy modifiers, policy rule changes return add_reform(identifier, group, ordinal); } @@ -145,16 +146,18 @@ bool IssueManager::_load_reform(size_t& ordinal, std::string_view identifier, Re * POL-84, POL-85, POL-86, POL-87, POL-89, POL-90, POL-91, POL-92, POL-93, POL-95, POL-96, POL-97, POL-98, * POL-99, POL-101, POL-102, POL-103, POL-104, POL-105, POL-107, POL-108, POL-109, POL-110, POL-111, POL-113, * POL-113, POL-114, POL-115, POL-116 -*/ + */ bool IssueManager::load_issues_file(ast::NodeCPtr root) { size_t expected_issue_groups = 0; size_t expected_reform_groups = 0; bool ret = expect_dictionary_reserve_length(reform_types, [this, &expected_issue_groups, &expected_reform_groups](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "party_issues") + if (key == "party_issues") { return expect_length(add_variable_callback(expected_issue_groups))(value); - else return expect_length(add_variable_callback(expected_reform_groups))(value) & add_reform_type( - key, key == "economic_reforms" || "education_reforms" || "military_reforms"); + } else { + return expect_length(add_variable_callback(expected_reform_groups))(value) & + add_reform_type(key, key == "economic_reforms" || "education_reforms" || "military_reforms"); + } } )(root); lock_reform_types(); @@ -198,7 +201,9 @@ bool IssueManager::load_issues_file(ast::NodeCPtr root) { ReformGroup const* reform_group = get_reform_group_by_identifier(group_key); size_t ordinal = 0; return expect_dictionary([this, reform_group, &ordinal](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "next_step_only" || key == "administrative") return true; + if (key == "next_step_only" || key == "administrative") { + return true; + } bool ret = _load_reform(ordinal, key, reform_group, value); ordinal++; return ret; @@ -210,4 +215,4 @@ bool IssueManager::load_issues_file(ast::NodeCPtr root) { lock_reforms(); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Issue.hpp b/src/openvic-simulation/politics/Issue.hpp index 9d72334..84aa886 100644 --- a/src/openvic-simulation/politics/Issue.hpp +++ b/src/openvic-simulation/politics/Issue.hpp @@ -2,14 +2,14 @@ #include #include -#include "openvic-simulation/types/IdentifierRegistry.hpp" + #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-dataloader/v2script/AbstractSyntaxTree.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" namespace OpenVic { struct IssueManager; - //Issue group (i.e. trade_policy) + // Issue group (i.e. trade_policy) struct IssueGroup : HasIdentifier { friend struct IssueManager; @@ -20,14 +20,14 @@ namespace OpenVic { IssueGroup(IssueGroup&&) = default; }; - //Issue (i.e. protectionism) + // Issue (i.e. protectionism) struct Issue : HasIdentifier { friend struct IssueManager; private: IssueGroup const& group; - //TODO: policy modifiers, policy rule changes + // TODO: policy modifiers, policy rule changes protected: Issue(std::string_view identifier, IssueGroup const& group); @@ -37,13 +37,13 @@ namespace OpenVic { IssueGroup const& get_group() const; }; - //Reform type (i.e. political_issues) + // Reform type (i.e. political_issues) struct ReformType : HasIdentifier { friend struct IssueManager; private: - bool uncivilised; //whether this group is available to non-westernised countries - //in vanilla education, military and economic reforms are hardcoded to true and the rest to false + bool uncivilised; // whether this group is available to non-westernised countries + // in vanilla education, military and economic reforms are hardcoded to true and the rest to false ReformType(std::string_view new_identifier, bool uncivilised); @@ -51,13 +51,13 @@ namespace OpenVic { ReformType(ReformType&&) = default; }; - //Reform group (i.e. slavery) + // Reform group (i.e. slavery) struct ReformGroup : IssueGroup { friend struct IssueManager; private: ReformType const& type; - const bool ordered; //next_step_only + const bool ordered; // next_step_only const bool administrative; ReformGroup(std::string_view identifier, ReformType const& type, bool ordered, bool administrative); @@ -69,17 +69,17 @@ namespace OpenVic { bool is_administrative() const; }; - //Reform (i.e. yes_slavery) + // Reform (i.e. yes_slavery) struct Reform : Issue { friend struct IssueManager; private: - ReformGroup const& reform_group; //stores an already casted reference - const size_t ordinal; //assigned by the parser to allow policy sorting + ReformGroup const& reform_group; // stores an already casted reference + const size_t ordinal; // assigned by the parser to allow policy sorting Reform(std::string_view new_identifier, ReformGroup const& group, size_t ordinal); - //TODO: conditions to allow, + // TODO: conditions to allow, public: Reform(Reform&&) = default; @@ -88,7 +88,7 @@ namespace OpenVic { size_t get_ordinal() const; }; - //Issue manager - holds the registries + // Issue manager - holds the registries struct IssueManager { private: IdentifierRegistry issue_groups; @@ -99,8 +99,9 @@ namespace OpenVic { bool _load_issue_group(size_t& expected_issues, std::string_view identifier, ast::NodeCPtr node); bool _load_issue(std::string_view identifier, IssueGroup const* group, ast::NodeCPtr node); - bool _load_reform_group(size_t& expected_reforms, std::string_view identifier, ReformType const* type, - ast::NodeCPtr node); + bool _load_reform_group( + size_t& expected_reforms, std::string_view identifier, ReformType const* type, ast::NodeCPtr node + ); bool _load_reform(size_t& ordinal, std::string_view identifier, ReformGroup const* group, ast::NodeCPtr node); public: @@ -123,4 +124,4 @@ namespace OpenVic { bool load_issues_file(ast::NodeCPtr root); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/pop/Culture.cpp b/src/openvic-simulation/pop/Culture.cpp index ebac344..e386930 100644 --- a/src/openvic-simulation/pop/Culture.cpp +++ b/src/openvic-simulation/pop/Culture.cpp @@ -7,11 +7,11 @@ using namespace OpenVic::NodeTools; GraphicalCultureType::GraphicalCultureType(std::string_view new_identifier) : HasIdentifier { new_identifier } {} -CultureGroup::CultureGroup(std::string_view new_identifier, std::string_view new_leader, - GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas) - : HasIdentifier { new_identifier }, leader { new_leader }, - unit_graphical_culture_type { new_unit_graphical_culture_type }, - is_overseas { new_is_overseas } {} +CultureGroup::CultureGroup( + std::string_view new_identifier, std::string_view new_leader, GraphicalCultureType const& new_unit_graphical_culture_type, + bool new_is_overseas +) : HasIdentifier { new_identifier }, leader { new_leader }, unit_graphical_culture_type { new_unit_graphical_culture_type }, + is_overseas { new_is_overseas } {} std::string_view CultureGroup::get_leader() const { return leader; @@ -25,12 +25,11 @@ bool CultureGroup::get_is_overseas() const { return is_overseas; } -Culture::Culture(std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, - std::vector&& new_first_names, std::vector&& new_last_names) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, - group { new_group }, - first_names { std::move(new_first_names) }, - last_names { std::move(new_last_names) } {} +Culture::Culture( + std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, + std::vector&& new_first_names, std::vector&& new_last_names +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, + first_names { std::move(new_first_names) }, last_names { std::move(new_last_names) } {} CultureGroup const& Culture::get_group() const { return group; @@ -45,9 +44,7 @@ std::vector const& Culture::get_last_names() const { } CultureManager::CultureManager() - : graphical_culture_types { "graphical culture types" }, - culture_groups { "culture groups" }, - cultures { "cultures" } {} + : graphical_culture_types { "graphical culture types" }, culture_groups { "culture groups" }, cultures { "cultures" } {} bool CultureManager::add_graphical_culture_type(std::string_view identifier) { if (identifier.empty()) { @@ -57,8 +54,9 @@ bool CultureManager::add_graphical_culture_type(std::string_view identifier) { return graphical_culture_types.add_item({ identifier }); } -bool CultureManager::add_culture_group(std::string_view identifier, std::string_view leader, - GraphicalCultureType const* graphical_culture_type, bool is_overseas) { +bool CultureManager::add_culture_group( + std::string_view identifier, std::string_view leader, GraphicalCultureType const* graphical_culture_type, bool is_overseas +) { if (!graphical_culture_types.is_locked()) { Logger::error("Cannot register culture groups until graphical culture types are locked!"); return false; @@ -78,8 +76,10 @@ bool CultureManager::add_culture_group(std::string_view identifier, std::string_ return culture_groups.add_item({ identifier, leader, *graphical_culture_type, is_overseas }); } -bool CultureManager::add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, - std::vector&& first_names, std::vector&& last_names) { +bool CultureManager::add_culture( + std::string_view identifier, colour_t colour, CultureGroup const* group, std::vector&& first_names, + std::vector&& last_names +) { if (!culture_groups.is_locked()) { Logger::error("Cannot register cultures until culture groups are locked!"); return false; @@ -100,8 +100,7 @@ bool CultureManager::add_culture(std::string_view identifier, colour_t colour, C } bool CultureManager::load_graphical_culture_type_file(ast::NodeCPtr root) { - const bool ret = expect_list_reserve_length( - graphical_culture_types, + const bool ret = expect_list_reserve_length(graphical_culture_types, expect_identifier( std::bind(&CultureManager::add_graphical_culture_type, this, std::placeholders::_1) ) @@ -110,9 +109,10 @@ bool CultureManager::load_graphical_culture_type_file(ast::NodeCPtr root) { return ret; } -bool CultureManager::_load_culture_group(size_t& total_expected_cultures, - GraphicalCultureType const* default_unit_graphical_culture_type, - std::string_view culture_group_key, ast::NodeCPtr culture_group_node) { +bool CultureManager::_load_culture_group( + size_t& total_expected_cultures, GraphicalCultureType const* default_unit_graphical_culture_type, + std::string_view culture_group_key, ast::NodeCPtr culture_group_node +) { std::string_view leader; GraphicalCultureType const* unit_graphical_culture_type = default_unit_graphical_culture_type; @@ -130,8 +130,9 @@ bool CultureManager::_load_culture_group(size_t& total_expected_cultures, return ret; } -bool CultureManager::_load_culture(CultureGroup const* culture_group, - std::string_view culture_key, ast::NodeCPtr culture_node) { +bool CultureManager::_load_culture( + CultureGroup const* culture_group, std::string_view culture_key, ast::NodeCPtr culture_node +) { colour_t colour = NULL_COLOUR; std::vector first_names, last_names; @@ -181,8 +182,7 @@ bool CultureManager::load_culture_file(ast::NodeCPtr root) { } size_t total_expected_cultures = 0; - bool ret = expect_dictionary_reserve_length( - culture_groups, + bool ret = expect_dictionary_reserve_length(culture_groups, [this, default_unit_graphical_culture_type, &total_expected_cultures]( std::string_view key, ast::NodeCPtr value) -> bool { return _load_culture_group(total_expected_cultures, default_unit_graphical_culture_type, key, value); @@ -191,20 +191,16 @@ bool CultureManager::load_culture_file(ast::NodeCPtr root) { lock_culture_groups(); cultures.reserve(cultures.size() + total_expected_cultures); - ret &= expect_dictionary( - [this](std::string_view culture_group_key, ast::NodeCPtr culture_group_value) -> bool { - CultureGroup const* culture_group = get_culture_group_by_identifier(culture_group_key); - return expect_dictionary( - [this, culture_group](std::string_view key, ast::NodeCPtr value) -> bool { - static const string_set_t reserved_keys = { - "leader", "unit", "union", "is_overseas" - }; - if (reserved_keys.find(key) != reserved_keys.end()) return true; - return _load_culture(culture_group, key, value); - } - )(culture_group_value); - } - )(root); + ret &= expect_dictionary([this](std::string_view culture_group_key, ast::NodeCPtr culture_group_value) -> bool { + CultureGroup const* culture_group = get_culture_group_by_identifier(culture_group_key); + return expect_dictionary([this, culture_group](std::string_view key, ast::NodeCPtr value) -> bool { + static const string_set_t reserved_keys = { "leader", "unit", "union", "is_overseas" }; + if (reserved_keys.find(key) != reserved_keys.end()) { + return true; + } + return _load_culture(culture_group, key, value); + })(culture_group_value); + })(root); lock_cultures(); return ret; } diff --git a/src/openvic-simulation/pop/Culture.hpp b/src/openvic-simulation/pop/Culture.hpp index ca70c16..402af0c 100644 --- a/src/openvic-simulation/pop/Culture.hpp +++ b/src/openvic-simulation/pop/Culture.hpp @@ -26,8 +26,10 @@ namespace OpenVic { // TODO - union tag - CultureGroup(std::string_view new_identifier, std::string_view new_leader, - GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas); + CultureGroup( + std::string_view new_identifier, std::string_view new_leader, + GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas + ); public: CultureGroup(CultureGroup&&) = default; @@ -46,8 +48,10 @@ namespace OpenVic { // TODO - radicalism, primary tag - Culture(std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, - std::vector&& new_first_names, std::vector&& new_last_names); + Culture( + std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, + std::vector&& new_first_names, std::vector&& new_last_names + ); public: Culture(Culture&&) = default; @@ -63,8 +67,10 @@ namespace OpenVic { IdentifierRegistry culture_groups; IdentifierRegistry cultures; - bool _load_culture_group(size_t& total_expected_cultures, GraphicalCultureType const* default_unit_graphical_culture_type, - std::string_view culture_group_key, ast::NodeCPtr culture_group_node); + bool _load_culture_group( + size_t& total_expected_cultures, GraphicalCultureType const* default_unit_graphical_culture_type, + std::string_view culture_group_key, ast::NodeCPtr culture_group_node + ); bool _load_culture(CultureGroup const* culture_group, std::string_view culture_key, ast::NodeCPtr node); public: @@ -73,12 +79,16 @@ namespace OpenVic { bool add_graphical_culture_type(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS(graphical_culture_type) - bool add_culture_group(std::string_view identifier, std::string_view leader, - GraphicalCultureType const* new_graphical_culture_type, bool is_overseas); + bool add_culture_group( + std::string_view identifier, std::string_view leader, GraphicalCultureType const* new_graphical_culture_type, + bool is_overseas + ); IDENTIFIER_REGISTRY_ACCESSORS(culture_group) - bool add_culture(std::string_view identifier, colour_t colour, CultureGroup const* group, - std::vector&& first_names, std::vector&& last_names); + bool add_culture( + std::string_view identifier, colour_t colour, CultureGroup const* group, std::vector&& first_names, + std::vector&& last_names + ); IDENTIFIER_REGISTRY_ACCESSORS(culture) bool load_graphical_culture_type_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/pop/Pop.cpp b/src/openvic-simulation/pop/Pop.cpp index 761e5ff..f63a704 100644 --- a/src/openvic-simulation/pop/Pop.cpp +++ b/src/openvic-simulation/pop/Pop.cpp @@ -9,11 +9,9 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -Pop::Pop(PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size) - : type { new_type }, - culture { new_culture }, - religion { new_religion }, - size { new_size } { +Pop::Pop( + PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size +) : type { new_type }, culture { new_culture }, religion { new_religion }, size { new_size } { assert(size > 0); } @@ -49,25 +47,16 @@ Pop::pop_size_t Pop::get_pop_daily_change() const { return Pop::get_num_promoted() - (Pop::get_num_demoted() + Pop::get_num_migrated()); } -PopType::PopType(std::string_view new_identifier, colour_t new_colour, - strata_t new_strata, sprite_t new_sprite, - Good::good_map_t&& new_life_needs, Good::good_map_t&& new_everyday_needs, - Good::good_map_t&& new_luxury_needs, rebel_units_t&& new_rebel_units, - Pop::pop_size_t new_max_size, Pop::pop_size_t new_merge_max_size, - bool new_state_capital_only, bool new_demote_migrant, bool new_is_artisan, bool new_is_slave) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, - strata { new_strata }, - sprite { new_sprite }, - life_needs { std::move(new_life_needs) }, - everyday_needs { std::move(new_everyday_needs) }, - luxury_needs { std::move(new_luxury_needs) }, - rebel_units { std::move(new_rebel_units) }, - max_size { new_max_size }, - merge_max_size { new_merge_max_size }, - state_capital_only { new_state_capital_only }, - demote_migrant { new_demote_migrant }, - is_artisan { new_is_artisan }, - is_slave { new_is_slave } { +PopType::PopType( + std::string_view new_identifier, colour_t new_colour, strata_t new_strata, sprite_t new_sprite, + Good::good_map_t&& new_life_needs, Good::good_map_t&& new_everyday_needs, Good::good_map_t&& new_luxury_needs, + rebel_units_t&& new_rebel_units, Pop::pop_size_t new_max_size, Pop::pop_size_t new_merge_max_size, + bool new_state_capital_only, bool new_demote_migrant, bool new_is_artisan, bool new_is_slave +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, strata { new_strata }, sprite { new_sprite }, + life_needs { std::move(new_life_needs) }, everyday_needs { std::move(new_everyday_needs) }, + luxury_needs { std::move(new_luxury_needs) }, rebel_units { std::move(new_rebel_units) }, max_size { new_max_size }, + merge_max_size { new_merge_max_size }, state_capital_only { new_state_capital_only }, + demote_migrant { new_demote_migrant }, is_artisan { new_is_artisan }, is_slave { new_is_slave } { assert(sprite > 0); assert(max_size >= 0); assert(merge_max_size >= 0); @@ -123,10 +112,12 @@ bool PopType::get_is_slave() const { PopManager::PopManager() : pop_types { "pop types" } {} -bool PopManager::add_pop_type(std::string_view identifier, colour_t colour, PopType::strata_t strata, - PopType::sprite_t sprite, Good::good_map_t&& life_needs, Good::good_map_t&& everyday_needs, - Good::good_map_t&& luxury_needs, PopType::rebel_units_t&& rebel_units, Pop::pop_size_t max_size, - Pop::pop_size_t merge_max_size, bool state_capital_only, bool demote_migrant, bool is_artisan, bool is_slave) { +bool PopManager::add_pop_type( + std::string_view identifier, colour_t colour, PopType::strata_t strata, PopType::sprite_t sprite, + Good::good_map_t&& life_needs, Good::good_map_t&& everyday_needs, Good::good_map_t&& luxury_needs, + PopType::rebel_units_t&& rebel_units, Pop::pop_size_t max_size, Pop::pop_size_t merge_max_size, bool state_capital_only, + bool demote_migrant, bool is_artisan, bool is_slave +) { if (identifier.empty()) { Logger::error("Invalid pop type identifier - empty!"); return false; @@ -148,16 +139,18 @@ bool PopManager::add_pop_type(std::string_view identifier, colour_t colour, PopT return false; } return pop_types.add_item({ - identifier, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), std::move(luxury_needs), - std::move(rebel_units), max_size, merge_max_size, state_capital_only, demote_migrant, is_artisan, is_slave + identifier, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), + std::move(luxury_needs), std::move(rebel_units), max_size, merge_max_size, state_capital_only, + demote_migrant, is_artisan, is_slave }); } /* REQUIREMENTS: * POP-3, POP-4, POP-5, POP-6, POP-7, POP-8, POP-9, POP-10, POP-11, POP-12, POP-13, POP-14 */ -bool PopManager::load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, - GoodManager const& good_manager, ast::NodeCPtr root) { +bool PopManager::load_pop_type_file( + std::string_view filestem, UnitManager const& unit_manager, GoodManager const& good_manager, ast::NodeCPtr root +) { static const string_map_t strata_map = { { "poor", PopType::strata_t::POOR }, { "middle", PopType::strata_t::MIDDLE }, @@ -218,8 +211,8 @@ bool PopManager::load_pop_type_file(std::string_view filestem, UnitManager const return ret; } -bool PopManager::load_pop_into_province(Province& province, std::string_view pop_type_identifier, - ast::NodeCPtr pop_node) const { +bool PopManager::load_pop_into_province(Province& province, std::string_view pop_type_identifier, ast::NodeCPtr pop_node) + const { PopType const* type = get_pop_type_by_identifier(pop_type_identifier); Culture const* culture = nullptr; Religion const* religion = nullptr; @@ -235,8 +228,10 @@ bool PopManager::load_pop_into_province(Province& province, std::string_view pop if (type != nullptr && culture != nullptr && religion != nullptr && size > 0) { ret &= province.add_pop({ *type, *culture, *religion, size }); } else { - Logger::warning("Some pop arguments are invalid: province = ", province, ", type = ", type, - ", culture = ", culture, ", religion = ", religion, ", size = ", size); + Logger::warning( + "Some pop arguments are invalid: province = ", province, ", type = ", type, ", culture = ", culture, + ", religion = ", religion, ", size = ", size + ); } return ret; } diff --git a/src/openvic-simulation/pop/Pop.hpp b/src/openvic-simulation/pop/Pop.hpp index cba9f3c..4abb2a9 100644 --- a/src/openvic-simulation/pop/Pop.hpp +++ b/src/openvic-simulation/pop/Pop.hpp @@ -52,11 +52,7 @@ namespace OpenVic { using rebel_units_t = decimal_map_t; private: - const enum class strata_t { - POOR, - MIDDLE, - RICH - } strata; + const enum class strata_t { POOR, MIDDLE, RICH } strata; const sprite_t sprite; const Good::good_map_t life_needs, everyday_needs, luxury_needs; const rebel_units_t rebel_units; @@ -65,10 +61,12 @@ namespace OpenVic { // TODO - country and province migration targets, promote_to targets, ideologies and issues - PopType(std::string_view new_identifier, colour_t new_colour, strata_t new_strata, sprite_t new_sprite, + PopType( + std::string_view new_identifier, colour_t new_colour, strata_t new_strata, sprite_t new_sprite, Good::good_map_t&& new_life_needs, Good::good_map_t&& new_everyday_needs, Good::good_map_t&& new_luxury_needs, rebel_units_t&& new_rebel_units, Pop::pop_size_t new_max_size, Pop::pop_size_t new_merge_max_size, - bool new_state_capital_only, bool new_demote_migrant, bool new_is_artisan, bool new_is_slave); + bool new_state_capital_only, bool new_demote_migrant, bool new_is_artisan, bool new_is_slave + ); public: PopType(PopType&&) = default; @@ -102,14 +100,17 @@ namespace OpenVic { REF_GETTERS(culture_manager) REF_GETTERS(religion_manager) - bool add_pop_type(std::string_view identifier, colour_t new_colour, PopType::strata_t strata, PopType::sprite_t sprite, + bool add_pop_type( + std::string_view identifier, colour_t new_colour, PopType::strata_t strata, PopType::sprite_t sprite, Good::good_map_t&& life_needs, Good::good_map_t&& everyday_needs, Good::good_map_t&& luxury_needs, PopType::rebel_units_t&& rebel_units, Pop::pop_size_t max_size, Pop::pop_size_t merge_max_size, - bool state_capital_only, bool demote_migrant, bool is_artisan, bool is_slave); + bool state_capital_only, bool demote_migrant, bool is_artisan, bool is_slave + ); IDENTIFIER_REGISTRY_ACCESSORS(pop_type) - bool load_pop_type_file(std::string_view filestem, UnitManager const& unit_manager, - GoodManager const& good_manager, ast::NodeCPtr root); + bool load_pop_type_file( + std::string_view filestem, UnitManager const& unit_manager, GoodManager const& good_manager, ast::NodeCPtr root + ); bool load_pop_into_province(Province& province, std::string_view pop_type_identifier, ast::NodeCPtr pop_node) const; }; } diff --git a/src/openvic-simulation/pop/Religion.cpp b/src/openvic-simulation/pop/Religion.cpp index a685fca..489984d 100644 --- a/src/openvic-simulation/pop/Religion.cpp +++ b/src/openvic-simulation/pop/Religion.cpp @@ -7,12 +7,10 @@ using namespace OpenVic::NodeTools; ReligionGroup::ReligionGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} -Religion::Religion(std::string_view new_identifier, colour_t new_colour, - ReligionGroup const& new_group, icon_t new_icon, bool new_pagan) - : HasIdentifierAndColour { new_identifier, new_colour, true, false }, - group { new_group }, - icon { new_icon }, - pagan { new_pagan } { +Religion::Religion( + std::string_view new_identifier, colour_t new_colour, ReligionGroup const& new_group, icon_t new_icon, bool new_pagan +) : HasIdentifierAndColour { new_identifier, new_colour, true, false }, group { new_group }, icon { new_icon }, + pagan { new_pagan } { assert(icon > 0); } @@ -28,9 +26,7 @@ bool Religion::get_pagan() const { return pagan; } -ReligionManager::ReligionManager() - : religion_groups { "religion groups" }, - religions { "religions" } {} +ReligionManager::ReligionManager() : religion_groups { "religion groups" }, religions { "religions" } {} bool ReligionManager::add_religion_group(std::string_view identifier) { if (identifier.empty()) { @@ -40,8 +36,9 @@ bool ReligionManager::add_religion_group(std::string_view identifier) { return religion_groups.add_item({ identifier }); } -bool ReligionManager::add_religion(std::string_view identifier, colour_t colour, - ReligionGroup const* group, Religion::icon_t icon, bool pagan) { +bool ReligionManager::add_religion( + std::string_view identifier, colour_t colour, ReligionGroup const* group, Religion::icon_t icon, bool pagan +) { if (!religion_groups.is_locked()) { Logger::error("Cannot register religions until religion groups are locked!"); return false; @@ -71,8 +68,7 @@ bool ReligionManager::add_religion(std::string_view identifier, colour_t colour, */ bool ReligionManager::load_religion_file(ast::NodeCPtr root) { size_t total_expected_religions = 0; - bool ret = expect_dictionary_reserve_length( - religion_groups, + bool ret = expect_dictionary_reserve_length(religion_groups, [this, &total_expected_religions](std::string_view key, ast::NodeCPtr value) -> bool { bool ret = expect_length(add_variable_callback(total_expected_religions))(value); ret &= add_religion_group(key); @@ -81,27 +77,23 @@ bool ReligionManager::load_religion_file(ast::NodeCPtr root) { )(root); lock_religion_groups(); religions.reserve(religions.size() + total_expected_religions); - ret &= expect_dictionary( - [this](std::string_view religion_group_key, ast::NodeCPtr religion_group_value) -> bool { - ReligionGroup const* religion_group = get_religion_group_by_identifier(religion_group_key); + ret &= expect_dictionary([this](std::string_view religion_group_key, ast::NodeCPtr religion_group_value) -> bool { + ReligionGroup const* religion_group = get_religion_group_by_identifier(religion_group_key); - return expect_dictionary( - [this, religion_group](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = NULL_COLOUR; - Religion::icon_t icon = 0; - bool pagan = false; + return expect_dictionary([this, religion_group](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = NULL_COLOUR; + Religion::icon_t icon = 0; + bool pagan = false; - bool ret = expect_dictionary_keys( - "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "pagan", ZERO_OR_ONE, expect_bool(assign_variable_callback(pagan)) - )(value); - ret &= add_religion(key, colour, religion_group, icon, pagan); - return ret; - } - )(religion_group_value); - } - )(root); + bool ret = expect_dictionary_keys( + "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), + "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), + "pagan", ZERO_OR_ONE, expect_bool(assign_variable_callback(pagan)) + )(value); + ret &= add_religion(key, colour, religion_group, icon, pagan); + return ret; + })(religion_group_value); + })(root); lock_religions(); return ret; } diff --git a/src/openvic-simulation/pop/Religion.hpp b/src/openvic-simulation/pop/Religion.hpp index 6b17266..a47754d 100644 --- a/src/openvic-simulation/pop/Religion.hpp +++ b/src/openvic-simulation/pop/Religion.hpp @@ -27,7 +27,10 @@ namespace OpenVic { const icon_t icon; const bool pagan; - Religion(std::string_view new_identifier, colour_t new_colour, ReligionGroup const& new_group, icon_t new_icon, bool new_pagan); + Religion( + std::string_view new_identifier, colour_t new_colour, ReligionGroup const& new_group, icon_t new_icon, + bool new_pagan + ); public: Religion(Religion&&) = default; @@ -48,7 +51,9 @@ namespace OpenVic { bool add_religion_group(std::string_view identifier); IDENTIFIER_REGISTRY_ACCESSORS(religion_group) - bool add_religion(std::string_view identifier, colour_t colour, ReligionGroup const* group, Religion::icon_t icon, bool pagan); + bool add_religion( + std::string_view identifier, colour_t colour, ReligionGroup const* group, Religion::icon_t icon, bool pagan + ); IDENTIFIER_REGISTRY_ACCESSORS(religion) bool load_religion_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/testing/Requirement.cpp b/src/openvic-simulation/testing/Requirement.cpp index be4138d..99a29de 100644 --- a/src/openvic-simulation/testing/Requirement.cpp +++ b/src/openvic-simulation/testing/Requirement.cpp @@ -37,7 +37,7 @@ void Requirement::set_acceptance_criteria(std::string in_acceptance_criteria) { } void Requirement::set_pass(bool in_pass) { pass = in_pass; - set_tested(true); // Ever setting a pass condition implies it has been tested + set_tested(true); // Ever setting a pass condition implies it has been tested } void Requirement::set_tested(bool in_tested) { tested = in_tested; diff --git a/src/openvic-simulation/testing/Requirement.hpp b/src/openvic-simulation/testing/Requirement.hpp index caea5c6..20dad3d 100644 --- a/src/openvic-simulation/testing/Requirement.hpp +++ b/src/openvic-simulation/testing/Requirement.hpp @@ -9,7 +9,7 @@ namespace OpenVic { std::string id; std::string text; std::string acceptance_criteria; - bool pass = false; // Explicitly false to begin + bool pass = false; // Explicitly false to begin bool tested = false; // Initialised and used during script execution @@ -17,7 +17,6 @@ namespace OpenVic { std::string actual_value; public: - Requirement(std::string in_id, std::string in_text, std::string in_acceptance_criteria) { id = in_id; text = in_text; diff --git a/src/openvic-simulation/testing/TestScript.cpp b/src/openvic-simulation/testing/TestScript.cpp index d08f34c..a238fb5 100644 --- a/src/openvic-simulation/testing/TestScript.cpp +++ b/src/openvic-simulation/testing/TestScript.cpp @@ -15,7 +15,7 @@ Requirement* TestScript::get_requirement_by_id(std::string id) { return req; } } - return new Requirement("NULL", "NULL", "NULL"); // edge case of failing to find + return new Requirement("NULL", "NULL", "NULL"); // edge case of failing to find } std::vector TestScript::get_passed_requirements() { std::vector passed_requirements = std::vector(); @@ -66,8 +66,9 @@ void TestScript::set_script_name(std::string in_script_name) { } // Methods -void TestScript::pass_or_fail_req_with_actual_and_target_values(std::string req_name, std::string target_value, - std::string actual_value) { +void TestScript::pass_or_fail_req_with_actual_and_target_values( + std::string req_name, std::string target_value, std::string actual_value +) { Requirement* req = get_requirement_by_id(req_name); req->set_target_value(target_value); req->set_actual_value(actual_value); diff --git a/src/openvic-simulation/testing/TestScript.hpp b/src/openvic-simulation/testing/TestScript.hpp index c278323..bfc2e95 100644 --- a/src/openvic-simulation/testing/TestScript.hpp +++ b/src/openvic-simulation/testing/TestScript.hpp @@ -1,7 +1,8 @@ #pragma once -#include #include -#include + +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/Requirement.hpp" namespace OpenVic { @@ -12,7 +13,6 @@ namespace OpenVic { std::string script_name; public: - // expects an overriden method that performs arbitrary code execution // so that each script uniquely performs tests // for both requirement adding to script and to execute code @@ -36,6 +36,8 @@ namespace OpenVic { void set_script_name(std::string in_script_name); // Methods - void pass_or_fail_req_with_actual_and_target_values(std::string req_name, std::string target_value, std::string actual_value); + void pass_or_fail_req_with_actual_and_target_values( + std::string req_name, std::string target_value, std::string actual_value + ); }; } diff --git a/src/openvic-simulation/testing/Testing.cpp b/src/openvic-simulation/testing/Testing.cpp index 883c4f6..da9dccf 100644 --- a/src/openvic-simulation/testing/Testing.cpp +++ b/src/openvic-simulation/testing/Testing.cpp @@ -1,7 +1,9 @@ -#include -#include +#include "Testing.hpp" + #include +#include "openvic-simulation/testing/TestScript.hpp" + using namespace OpenVic; Testing::Testing(GameManager* game_manager) { diff --git a/src/openvic-simulation/testing/Testing.hpp b/src/openvic-simulation/testing/Testing.hpp index 670c95a..18ade0a 100644 --- a/src/openvic-simulation/testing/Testing.hpp +++ b/src/openvic-simulation/testing/Testing.hpp @@ -1,22 +1,21 @@ #pragma once -#include -#include #include #include -#include -#include -#include -#include -#include -#include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" +#include "openvic-simulation/testing/test_scripts/A_001_file_tests.cpp" +#include "openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp" +#include "openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp" +#include "openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp" +#include "openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp" +#include "openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp" namespace OpenVic { class Testing { public: - Testing(GameManager* game_manager); ~Testing(); diff --git a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp index c79e602..e24d44c 100644 --- a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_001_file_tests : public TestScript { @@ -11,92 +11,121 @@ namespace OpenVic { } void add_requirements() { - Requirement* FS_44 = new Requirement("FS_44", - "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename Canned Food.png", - "The icon for the Canned Food good has been loaded into the program"); + Requirement* FS_44 = new Requirement( + "FS_44", + "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename " + "Canned Food.png", + "The icon for the Canned Food good has been loaded into the program" + ); add_requirement(FS_44); - Requirement* FS_48 = new Requirement("FS_48", + Requirement* FS_48 = new Requirement( + "FS_48", "The icon for the Coal good shall be loaded from the R/art/economy/goods folder with the filename Coal.png", - "The icon for the Coal good has been loaded into the program"); + "The icon for the Coal good has been loaded into the program" + ); add_requirement(FS_48); - Requirement* FS_61 = new Requirement("FS_61", + Requirement* FS_61 = new Requirement( + "FS_61", "The icon for the Grain good shall be loaded from the R/art/economy/goods folder with the filename Grain.png", - "The icon for the Grain good has been loaded into the program"); + "The icon for the Grain good has been loaded into the program" + ); add_requirement(FS_61); - Requirement* FS_62 = new Requirement("FS_62", + Requirement* FS_62 = new Requirement( + "FS_62", "The icon for the Iron good shall be loaded from the R/art/economy/goods folder with the filename Iron.png", - "The icon for the Iron good has been loaded into the program"); + "The icon for the Iron good has been loaded into the program" + ); add_requirement(FS_62); - Requirement* FS_63 = new Requirement("FS_63", + Requirement* FS_63 = new Requirement( + "FS_63", "The icon for the Liquor good shall be loaded from the R/art/economy/goods folder with the filename Liquor.png", - "The icon for the Liquor good has been loaded into the program"); + "The icon for the Liquor good has been loaded into the program" + ); add_requirement(FS_63); - Requirement* FS_67 = new Requirement("FS_67", - "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename Machine Parts.png", - "The icon for the Machine Parts good has been loaded into the program"); + Requirement* FS_67 = new Requirement( + "FS_67", + "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename " + "Machine Parts.png", + "The icon for the Machine Parts good has been loaded into the program" + ); add_requirement(FS_67); - Requirement* FS_86 = new Requirement("FS_86", + Requirement* FS_86 = new Requirement( + "FS_86", "The icon for the Wool good shall be loaded from the R/art/economy/goods folder with the filename Wool.png", - "The icon for the Wool good has been loaded into the program"); + "The icon for the Wool good has been loaded into the program" + ); add_requirement(FS_86); - Requirement* FS_2 = new Requirement("FS_2", - "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", - "User data is saved to the correct place"); + Requirement* FS_2 = new Requirement( + "FS_2", "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", + "User data is saved to the correct place" + ); add_requirement(FS_2); - Requirement* FS_20 = new Requirement("FS_20", - "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", - "User data is saved to the correct place"); + Requirement* FS_20 = new Requirement( + "FS_20", "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", + "User data is saved to the correct place" + ); add_requirement(FS_20); - Requirement* FS_21 = new Requirement("FS_21", - "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", - "User data is saved to the correct place"); + Requirement* FS_21 = new Requirement( + "FS_21", "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", + "User data is saved to the correct place" + ); add_requirement(FS_21); - Requirement* FS_22 = new Requirement("FS_22", - "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", - "User data is saved to the correct place"); + Requirement* FS_22 = new Requirement( + "FS_22", "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", + "User data is saved to the correct place" + ); add_requirement(FS_22); - Requirement* FS_24 = new Requirement("FS_24", - "All .csv files in the locale folder shall contain translation keys and translations", - "No errant files in locale directory"); + Requirement* FS_24 = new Requirement( + "FS_24", "All .csv files in the locale folder shall contain translation keys and translations", + "No errant files in locale directory" + ); add_requirement(FS_24); - Requirement* FS_17 = new Requirement("FS_17", - "List of available locales are loaded from R/localisation/ directory", - "Locales loaded correctly"); + Requirement* FS_17 = new Requirement( + "FS_17", "List of available locales are loaded from R/localisation/ directory", "Locales loaded correctly" + ); add_requirement(FS_17); - Requirement* FS_333 = new Requirement("FS_333", - "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", - "The unique colours of 'R/map/provinces.bmp' define provinces"); + Requirement* FS_333 = new Requirement( + "FS_333", "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", + "The unique colours of 'R/map/provinces.bmp' define provinces" + ); add_requirement(FS_333); - Requirement* FS_335 = new Requirement("FS_335", - "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", - "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID"); + Requirement* FS_335 = new Requirement( + "FS_335", "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", + "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID" + ); add_requirement(FS_335); - Requirement* FS_334 = new Requirement("FS_334", - "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", - "'R/map/default.map' contains a list of province IDs which are used to define water provinces"); + Requirement* FS_334 = new Requirement( + "FS_334", "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", + "'R/map/default.map' contains a list of province IDs which are used to define water provinces" + ); add_requirement(FS_334); - Requirement* FS_338 = new Requirement("FS_338", + Requirement* FS_338 = new Requirement( + "FS_338", "The image for the minimap background shall be loaded from the R/art/ui folder with the filename minimap.png", - "The image for the minimap background has been loaded into the program"); + "The image for the minimap background has been loaded into the program" + ); add_requirement(FS_338); - Requirement* FS_343 = new Requirement("FS_343", - "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", - "The textures making up the cosmetic terrain map have been loaded into the program"); + Requirement* FS_343 = new Requirement( + "FS_343", "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", + "The textures making up the cosmetic terrain map have been loaded into the program" + ); add_requirement(FS_343); - Requirement* FS_341 = new Requirement("FS_341", - "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", - "'R/map/region.txt' defines state areas with lists of province IDs"); + Requirement* FS_341 = new Requirement( + "FS_341", "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", + "'R/map/region.txt' defines state areas with lists of province IDs" + ); add_requirement(FS_341); - Requirement* SND_10 = new Requirement("SND_10", - "SFX shall be refered to by their filename, without the extension", - "Sound effects are identified by their filename without extension"); + Requirement* SND_10 = new Requirement( + "SND_10", "SFX shall be refered to by their filename, without the extension", + "Sound effects are identified by their filename without extension" + ); add_requirement(SND_10); } void execute_script() { // FS_44 - // The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename Canned Food.png - // The icon for the Canned Food good has been loaded into the program + // The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename Canned + // Food.png The icon for the Canned Food good has been loaded into the program // TODO: Write test steps for FS_44... @@ -125,8 +154,8 @@ namespace OpenVic { // TODO: Write test steps for FS_63... // FS_67 - // The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename Machine Parts.png - // The icon for the Machine Parts good has been loaded into the program + // The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename + // Machine Parts.png The icon for the Machine Parts good has been loaded into the program // TODO: Write test steps for FS_67... @@ -213,7 +242,6 @@ namespace OpenVic { // Sound effects are identified by their filename without extension // TODO: Write test steps for SND_10... - } }; } diff --git a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp index 5e1f317..ffe1ee9 100644 --- a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_002_economy_tests : public TestScript { @@ -11,197 +11,245 @@ namespace OpenVic { } void add_requirements() { - Requirement* ECON_123 = new Requirement("ECON_123", - "The base price for Aeroplanes shall be 110", - "The base price of 110 for Aeroplanes can be seen in program output data"); + Requirement* ECON_123 = new Requirement( + "ECON_123", "The base price for Aeroplanes shall be 110", + "The base price of 110 for Aeroplanes can be seen in program output data" + ); add_requirement(ECON_123); - Requirement* ECON_124 = new Requirement("ECON_124", - "The base price for Ammunition shall be 17.5", - "The base price of 17.5 for Ammunition can be seen in program output data"); + Requirement* ECON_124 = new Requirement( + "ECON_124", "The base price for Ammunition shall be 17.5", + "The base price of 17.5 for Ammunition can be seen in program output data" + ); add_requirement(ECON_124); - Requirement* ECON_125 = new Requirement("ECON_125", - "The base price for Artillery shall be 60", - "The base price of 60 for Artillery can be seen in program output data"); + Requirement* ECON_125 = new Requirement( + "ECON_125", "The base price for Artillery shall be 60", + "The base price of 60 for Artillery can be seen in program output data" + ); add_requirement(ECON_125); - Requirement* ECON_126 = new Requirement("ECON_126", - "The base price for Automobiles shall be 70", - "The base price of 70 for Automobiles can be seen in program output data"); + Requirement* ECON_126 = new Requirement( + "ECON_126", "The base price for Automobiles shall be 70", + "The base price of 70 for Automobiles can be seen in program output data" + ); add_requirement(ECON_126); - Requirement* ECON_127 = new Requirement("ECON_127", - "The base price for Canned Food shall be 16", - "The base price of 16 for Canned Food can be seen in program output data"); + Requirement* ECON_127 = new Requirement( + "ECON_127", "The base price for Canned Food shall be 16", + "The base price of 16 for Canned Food can be seen in program output data" + ); add_requirement(ECON_127); - Requirement* ECON_128 = new Requirement("ECON_128", - "The base price for Cattle shall be 2", - "The base price of 2 for Cattle can be seen in program output data"); + Requirement* ECON_128 = new Requirement( + "ECON_128", "The base price for Cattle shall be 2", + "The base price of 2 for Cattle can be seen in program output data" + ); add_requirement(ECON_128); - Requirement* ECON_129 = new Requirement("ECON_129", - "The base price for Cement shall be 16", - "The base price of 16 for Cement can be seen in program output data"); + Requirement* ECON_129 = new Requirement( + "ECON_129", "The base price for Cement shall be 16", + "The base price of 16 for Cement can be seen in program output data" + ); add_requirement(ECON_129); - Requirement* ECON_130 = new Requirement("ECON_130", - "The base price for Clipper Convoys shall be 42", - "The base price of 42 for Clipper Convoys can be seen in program output data"); + Requirement* ECON_130 = new Requirement( + "ECON_130", "The base price for Clipper Convoys shall be 42", + "The base price of 42 for Clipper Convoys can be seen in program output data" + ); add_requirement(ECON_130); - Requirement* ECON_131 = new Requirement("ECON_131", - "The base price for Coal shall be 2.3", - "The base price of 2.3 for Coal can be seen in program output data"); + Requirement* ECON_131 = new Requirement( + "ECON_131", "The base price for Coal shall be 2.3", + "The base price of 2.3 for Coal can be seen in program output data" + ); add_requirement(ECON_131); - Requirement* ECON_132 = new Requirement("ECON_132", - "The base price for Coffee shall be 2.1", - "The base price of 2.1 for Coffee can be seen in program output data"); + Requirement* ECON_132 = new Requirement( + "ECON_132", "The base price for Coffee shall be 2.1", + "The base price of 2.1 for Coffee can be seen in program output data" + ); add_requirement(ECON_132); - Requirement* ECON_133 = new Requirement("ECON_133", - "The base price for Cotton shall be 2", - "The base price of 2 for Cotton can be seen in program output data"); + Requirement* ECON_133 = new Requirement( + "ECON_133", "The base price for Cotton shall be 2", + "The base price of 2 for Cotton can be seen in program output data" + ); add_requirement(ECON_133); - Requirement* ECON_134 = new Requirement("ECON_134", - "The base price for Dye shall be 12", - "The base price of 12 for Dye can be seen in program output data"); + Requirement* ECON_134 = new Requirement( + "ECON_134", "The base price for Dye shall be 12", + "The base price of 12 for Dye can be seen in program output data" + ); add_requirement(ECON_134); - Requirement* ECON_135 = new Requirement("ECON_135", - "The base price for Electric Gear shall be 16", - "The base price of 16 for Electric Gear can be seen in program output data"); + Requirement* ECON_135 = new Requirement( + "ECON_135", "The base price for Electric Gear shall be 16", + "The base price of 16 for Electric Gear can be seen in program output data" + ); add_requirement(ECON_135); - Requirement* ECON_136 = new Requirement("ECON_136", - "The base price for Explosives shall be 20", - "The base price of 20 for Explosives can be seen in program output data"); + Requirement* ECON_136 = new Requirement( + "ECON_136", "The base price for Explosives shall be 20", + "The base price of 20 for Explosives can be seen in program output data" + ); add_requirement(ECON_136); - Requirement* ECON_137 = new Requirement("ECON_137", - "The base price for Fabric shall be 1.8", - "The base price of 1.8 for Fabric can be seen in program output data"); + Requirement* ECON_137 = new Requirement( + "ECON_137", "The base price for Fabric shall be 1.8", + "The base price of 1.8 for Fabric can be seen in program output data" + ); add_requirement(ECON_137); - Requirement* ECON_138 = new Requirement("ECON_138", - "The base price for Fertilizer shall be 10", - "The base price of 10 for Fertilizer can be seen in program output data"); + Requirement* ECON_138 = new Requirement( + "ECON_138", "The base price for Fertilizer shall be 10", + "The base price of 10 for Fertilizer can be seen in program output data" + ); add_requirement(ECON_138); - Requirement* ECON_139 = new Requirement("ECON_139", - "The base price for Fish shall be 1.5", - "The base price of 1.5 for Fish can be seen in program output data"); + Requirement* ECON_139 = new Requirement( + "ECON_139", "The base price for Fish shall be 1.5", + "The base price of 1.5 for Fish can be seen in program output data" + ); add_requirement(ECON_139); - Requirement* ECON_140 = new Requirement("ECON_140", - "The base price for Fruit shall be 1.8", - "The base price of 1.8 for Fruit can be seen in program output data"); + Requirement* ECON_140 = new Requirement( + "ECON_140", "The base price for Fruit shall be 1.8", + "The base price of 1.8 for Fruit can be seen in program output data" + ); add_requirement(ECON_140); - Requirement* ECON_141 = new Requirement("ECON_141", - "The base price for Fuel shall be 25", - "The base price of 25 for Fuel can be seen in program output data"); + Requirement* ECON_141 = new Requirement( + "ECON_141", "The base price for Fuel shall be 25", + "The base price of 25 for Fuel can be seen in program output data" + ); add_requirement(ECON_141); - Requirement* ECON_142 = new Requirement("ECON_142", - "The base price for Furniture shall be 4.9", - "The base price of 4.9 for Furniture can be seen in program output data"); + Requirement* ECON_142 = new Requirement( + "ECON_142", "The base price for Furniture shall be 4.9", + "The base price of 4.9 for Furniture can be seen in program output data" + ); add_requirement(ECON_142); - Requirement* ECON_234 = new Requirement("ECON_234", - "The base price for Glass shall be 2.9", - "The base price of 2.9 for Glass can be seen in program output data"); + Requirement* ECON_234 = new Requirement( + "ECON_234", "The base price for Glass shall be 2.9", + "The base price of 2.9 for Glass can be seen in program output data" + ); add_requirement(ECON_234); - Requirement* ECON_235 = new Requirement("ECON_235", - "The base price for Grain shall be 2.2", - "The base price of 2.2 for Grain can be seen in program output data"); + Requirement* ECON_235 = new Requirement( + "ECON_235", "The base price for Grain shall be 2.2", + "The base price of 2.2 for Grain can be seen in program output data" + ); add_requirement(ECON_235); - Requirement* ECON_236 = new Requirement("ECON_236", - "The base price for Iron shall be 3.5", - "The base price of 3.5 for Iron can be seen in program output data"); + Requirement* ECON_236 = new Requirement( + "ECON_236", "The base price for Iron shall be 3.5", + "The base price of 3.5 for Iron can be seen in program output data" + ); add_requirement(ECON_236); - Requirement* ECON_237 = new Requirement("ECON_237", - "The base price for Liquor shall be 6.4", - "The base price of 6.4 for Liquor can be seen in program output data"); + Requirement* ECON_237 = new Requirement( + "ECON_237", "The base price for Liquor shall be 6.4", + "The base price of 6.4 for Liquor can be seen in program output data" + ); add_requirement(ECON_237); - Requirement* ECON_238 = new Requirement("ECON_238", - "The base price for Lumber shall be 1", - "The base price of 1 for Lumber can be seen in program output data"); + Requirement* ECON_238 = new Requirement( + "ECON_238", "The base price for Lumber shall be 1", + "The base price of 1 for Lumber can be seen in program output data" + ); add_requirement(ECON_238); - Requirement* ECON_239 = new Requirement("ECON_239", - "The base price for Luxury Clothes shall be 65", - "The base price of 65 for Luxury Clothes can be seen in program output data"); + Requirement* ECON_239 = new Requirement( + "ECON_239", "The base price for Luxury Clothes shall be 65", + "The base price of 65 for Luxury Clothes can be seen in program output data" + ); add_requirement(ECON_239); - Requirement* ECON_240 = new Requirement("ECON_240", - "The base price for Luxury Furniture shall be 59", - "The base price of 59 for Luxury Furniture can be seen in program output data"); + Requirement* ECON_240 = new Requirement( + "ECON_240", "The base price for Luxury Furniture shall be 59", + "The base price of 59 for Luxury Furniture can be seen in program output data" + ); add_requirement(ECON_240); - Requirement* ECON_241 = new Requirement("ECON_241", - "The base price for Machine Parts shall be 36.5", - "The base price of 36.5 for Machine Parts can be seen in program output data"); + Requirement* ECON_241 = new Requirement( + "ECON_241", "The base price for Machine Parts shall be 36.5", + "The base price of 36.5 for Machine Parts can be seen in program output data" + ); add_requirement(ECON_241); - Requirement* ECON_242 = new Requirement("ECON_242", - "The base price for Oil shall be 12", - "The base price of 12 for Oil can be seen in program output data"); + Requirement* ECON_242 = new Requirement( + "ECON_242", "The base price for Oil shall be 12", + "The base price of 12 for Oil can be seen in program output data" + ); add_requirement(ECON_242); - Requirement* ECON_243 = new Requirement("ECON_243", - "The base price for Opium shall be 3.2", - "The base price of 3.2 for Opium can be seen in program output data"); + Requirement* ECON_243 = new Requirement( + "ECON_243", "The base price for Opium shall be 3.2", + "The base price of 3.2 for Opium can be seen in program output data" + ); add_requirement(ECON_243); - Requirement* ECON_244 = new Requirement("ECON_244", - "The base price for Paper shall be 3.4", - "The base price of 3.4 for Paper can be seen in program output data"); + Requirement* ECON_244 = new Requirement( + "ECON_244", "The base price for Paper shall be 3.4", + "The base price of 3.4 for Paper can be seen in program output data" + ); add_requirement(ECON_244); - Requirement* ECON_245 = new Requirement("ECON_245", - "The base price for Precious Metal shall be 8", - "The base price of 8 for Precious Metal can be seen in program output data"); + Requirement* ECON_245 = new Requirement( + "ECON_245", "The base price for Precious Metal shall be 8", + "The base price of 8 for Precious Metal can be seen in program output data" + ); add_requirement(ECON_245); - Requirement* ECON_246 = new Requirement("ECON_246", - "The base price for Radios shall be 16", - "The base price of 16 for Radios can be seen in program output data"); + Requirement* ECON_246 = new Requirement( + "ECON_246", "The base price for Radios shall be 16", + "The base price of 16 for Radios can be seen in program output data" + ); add_requirement(ECON_246); - Requirement* ECON_247 = new Requirement("ECON_247", - "The base price for Regular Clothes shall be 5.8", - "The base price of 5.8 for Regular Clothes can be seen in program output data"); + Requirement* ECON_247 = new Requirement( + "ECON_247", "The base price for Regular Clothes shall be 5.8", + "The base price of 5.8 for Regular Clothes can be seen in program output data" + ); add_requirement(ECON_247); - Requirement* ECON_248 = new Requirement("ECON_248", - "The base price for Rubber shall be 7", - "The base price of 7 for Rubber can be seen in program output data"); + Requirement* ECON_248 = new Requirement( + "ECON_248", "The base price for Rubber shall be 7", + "The base price of 7 for Rubber can be seen in program output data" + ); add_requirement(ECON_248); - Requirement* ECON_249 = new Requirement("ECON_249", - "The base price for Silk shall be 10", - "The base price of 10 for Silk can be seen in program output data"); + Requirement* ECON_249 = new Requirement( + "ECON_249", "The base price for Silk shall be 10", + "The base price of 10 for Silk can be seen in program output data" + ); add_requirement(ECON_249); - Requirement* ECON_250 = new Requirement("ECON_250", - "The base price for Small Arms shall be 37", - "The base price of 37 for Small Arms can be seen in program output data"); + Requirement* ECON_250 = new Requirement( + "ECON_250", "The base price for Small Arms shall be 37", + "The base price of 37 for Small Arms can be seen in program output data" + ); add_requirement(ECON_250); - Requirement* ECON_251 = new Requirement("ECON_251", - "The base price for Steamer Convoys shall be 65", - "The base price of 65 for Steamer Convoys can be seen in program output data"); + Requirement* ECON_251 = new Requirement( + "ECON_251", "The base price for Steamer Convoys shall be 65", + "The base price of 65 for Steamer Convoys can be seen in program output data" + ); add_requirement(ECON_251); - Requirement* ECON_252 = new Requirement("ECON_252", - "The base price for Steel shall be 4.7", - "The base price of 4.7 for Steel can be seen in program output data"); + Requirement* ECON_252 = new Requirement( + "ECON_252", "The base price for Steel shall be 4.7", + "The base price of 4.7 for Steel can be seen in program output data" + ); add_requirement(ECON_252); - Requirement* ECON_253 = new Requirement("ECON_253", - "The base price for Sulphur shall be 6", - "The base price of 6 for Sulphur can be seen in program output data"); + Requirement* ECON_253 = new Requirement( + "ECON_253", "The base price for Sulphur shall be 6", + "The base price of 6 for Sulphur can be seen in program output data" + ); add_requirement(ECON_253); - Requirement* ECON_254 = new Requirement("ECON_254", - "The base price for Tanks shall be 98", - "The base price of 98 for Tanks can be seen in program output data"); + Requirement* ECON_254 = new Requirement( + "ECON_254", "The base price for Tanks shall be 98", + "The base price of 98 for Tanks can be seen in program output data" + ); add_requirement(ECON_254); - Requirement* ECON_255 = new Requirement("ECON_255", - "The base price for Tea shall be 2.6", - "The base price of 2.6 for Tea can be seen in program output data"); + Requirement* ECON_255 = new Requirement( + "ECON_255", "The base price for Tea shall be 2.6", + "The base price of 2.6 for Tea can be seen in program output data" + ); add_requirement(ECON_255); - Requirement* ECON_256 = new Requirement("ECON_256", - "The base price for Telephones shall be 16", - "The base price of 16 for Telephones can be seen in program output data"); + Requirement* ECON_256 = new Requirement( + "ECON_256", "The base price for Telephones shall be 16", + "The base price of 16 for Telephones can be seen in program output data" + ); add_requirement(ECON_256); - Requirement* ECON_257 = new Requirement("ECON_257", - "The base price for Timber shall be 0.9", - "The base price of 0.9 for Timber can be seen in program output data"); + Requirement* ECON_257 = new Requirement( + "ECON_257", "The base price for Timber shall be 0.9", + "The base price of 0.9 for Timber can be seen in program output data" + ); add_requirement(ECON_257); - Requirement* ECON_258 = new Requirement("ECON_258", - "The base price for Tobacco shall be 1.1", - "The base price of 1.1 for Tobacco can be seen in program output data"); + Requirement* ECON_258 = new Requirement( + "ECON_258", "The base price for Tobacco shall be 1.1", + "The base price of 1.1 for Tobacco can be seen in program output data" + ); add_requirement(ECON_258); - Requirement* ECON_259 = new Requirement("ECON_259", - "The base price for Tropical Wood shall be 5.4", - "The base price of 5.4 for Tropical Wood can be seen in program output data"); + Requirement* ECON_259 = new Requirement( + "ECON_259", "The base price for Tropical Wood shall be 5.4", + "The base price of 5.4 for Tropical Wood can be seen in program output data" + ); add_requirement(ECON_259); - Requirement* ECON_260 = new Requirement("ECON_260", - "The base price for Wine shall be 9.7", - "The base price of 9.7 for Wine can be seen in program output data"); + Requirement* ECON_260 = new Requirement( + "ECON_260", "The base price for Wine shall be 9.7", + "The base price of 9.7 for Wine can be seen in program output data" + ); add_requirement(ECON_260); - Requirement* ECON_261 = new Requirement("ECON_261", - "The base price for Wool shall be 0.7", - "The base price of 0.7 for Wool can be seen in program output data"); + Requirement* ECON_261 = new Requirement( + "ECON_261", "The base price for Wool shall be 0.7", + "The base price of 0.7 for Wool can be seen in program output data" + ); add_requirement(ECON_261); } diff --git a/src/openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp index 7fd2184..cf572d0 100644 --- a/src/openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_003_military_unit_tests : public TestScript { @@ -10,10 +10,8 @@ namespace OpenVic { add_requirements(); } - void add_requirements() { - } + void add_requirements() {} - void execute_script() { - } + void execute_script() {} }; } diff --git a/src/openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp index 5cdc86e..0e05540 100644 --- a/src/openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_004_networking_tests : public TestScript { @@ -10,10 +10,8 @@ namespace OpenVic { add_requirements(); } - void add_requirements() { - } + void add_requirements() {} - void execute_script() { - } + void execute_script() {} }; } diff --git a/src/openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp index 494604f..6f91ac2 100644 --- a/src/openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_005_nation_tests : public TestScript { @@ -10,10 +10,8 @@ namespace OpenVic { add_requirements(); } - void add_requirements() { - } + void add_requirements() {} - void execute_script() { - } + void execute_script() {} }; } diff --git a/src/openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp index 6fe9ca9..091075c 100644 --- a/src/openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp @@ -1,5 +1,5 @@ -# include -# include +#include "openvic-simulation/GameManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { class A_006_politics_tests : public TestScript { @@ -10,10 +10,8 @@ namespace OpenVic { add_requirements(); } - void add_requirements() { - } + void add_requirements() {} - void execute_script() { - } + void execute_script() {} }; } diff --git a/src/openvic-simulation/types/Date.cpp b/src/openvic-simulation/types/Date.cpp index 68d0941..8fbb859 100644 --- a/src/openvic-simulation/types/Date.cpp +++ b/src/openvic-simulation/types/Date.cpp @@ -89,8 +89,7 @@ Timespan Timespan::fromYears(day_t num) { } Timespan Timespan::fromMonths(day_t num) { - return (num / Date::MONTHS_IN_YEAR) * Date::DAYS_IN_YEAR + - Date::DAYS_UP_TO_MONTH[num % Date::MONTHS_IN_YEAR]; + return (num / Date::MONTHS_IN_YEAR) * Date::DAYS_IN_YEAR + Date::DAYS_UP_TO_MONTH[num % Date::MONTHS_IN_YEAR]; } Timespan Timespan::fromDays(day_t num) { @@ -112,8 +111,11 @@ Timespan::day_t const* Date::DAYS_UP_TO_MONTH = generate_days_up_to_month(); Timespan::day_t const* Date::generate_days_up_to_month() { static Timespan::day_t days_up_to_month[MONTHS_IN_YEAR]; Timespan::day_t days = 0; - for (int month = 0; month < MONTHS_IN_YEAR; - days_up_to_month[month] = days, days += DAYS_IN_MONTH[month++]); + int month = 0; + while (month < MONTHS_IN_YEAR) { + days_up_to_month[month] = days; + days += DAYS_IN_MONTH[month++]; + } assert(days == DAYS_IN_YEAR); return days_up_to_month; } @@ -123,9 +125,11 @@ Date::month_t const* Date::MONTH_FROM_DAY_IN_YEAR = generate_month_from_day_in_y Date::month_t const* Date::generate_month_from_day_in_year() { static month_t month_from_day_in_year[DAYS_IN_YEAR]; Timespan::day_t days_left = 0; - for (int day = 0, month = 0; day < DAYS_IN_YEAR; - days_left = (days_left > 0 ? days_left : DAYS_IN_MONTH[month++]) - 1, - month_from_day_in_year[day++] = month); + int day = 0, month = 0; + while (day < DAYS_IN_YEAR) { + days_left = (days_left > 0 ? days_left : DAYS_IN_MONTH[month++]) - 1; + month_from_day_in_year[day++] = month; + } assert(days_left == 0); assert(month_from_day_in_year[DAYS_IN_YEAR - 1] == MONTHS_IN_YEAR); return month_from_day_in_year; @@ -211,8 +215,8 @@ Date::operator std::string() const { } std::ostream& OpenVic::operator<<(std::ostream& out, Date const& date) { - return out << static_cast(date.getYear()) << Date::SEPARATOR_CHARACTER - << static_cast(date.getMonth()) << Date::SEPARATOR_CHARACTER << static_cast(date.getDay()); + return out << static_cast(date.getYear()) << Date::SEPARATOR_CHARACTER << static_cast(date.getMonth()) + << Date::SEPARATOR_CHARACTER << static_cast(date.getDay()); } // Parsed from string of the form YYYY.MM.DD @@ -227,8 +231,9 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe if (str == nullptr || end <= str) { if (!quiet) { - Logger::error("Invalid string start/end pointers: ", static_cast(str), - " - ", static_cast(end)); + Logger::error( + "Invalid string start/end pointers: ", static_cast(str), " - ", static_cast(end) + ); } if (successful != nullptr) { *successful = false; @@ -237,12 +242,11 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe } char const* year_end = str; - while (std::isdigit(*year_end) && ++year_end < end); + while (std::isdigit(*year_end) && ++year_end < end) {} if (year_end <= str) { if (!quiet) { - Logger::error("Failed to find year digits in date: ", - std::string_view { str, static_cast(end - str) }); + Logger::error("Failed to find year digits in date: ", std::string_view { str, static_cast(end - str) }); } if (successful != nullptr) { *successful = false; @@ -267,12 +271,13 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe char const* const month_start = year_end + 1; char const* month_end = month_start; if (month_start < end) { - while (std::isdigit(*month_end) && ++month_end < end); + while (std::isdigit(*month_end) && ++month_end < end) {} } if (month_start >= month_end) { if (!quiet) { - Logger::error("Failed to find month digits in date: ", - std::string_view { str, static_cast(end - str) }); + Logger::error( + "Failed to find month digits in date: ", std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; @@ -282,8 +287,7 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe val = StringUtils::string_to_uint64(month_start, month_end, &sub_successful, 10); if (!sub_successful || val < 1 || val > MONTHS_IN_YEAR) { if (!quiet) { - Logger::error("Failed to read month: ", - std::string_view { str, static_cast(end - str) }); + Logger::error("Failed to read month: ", std::string_view { str, static_cast(end - str) }); } if (successful != nullptr) { *successful = false; @@ -295,12 +299,14 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe char const* const day_start = month_end + 1; char const* day_end = day_start; if (day_start < end) { - while (std::isdigit(*day_end) && ++day_end < end); + while (std::isdigit(*day_end) && ++day_end < end) {} } if (day_start >= day_end) { if (!quiet) { - Logger::error("Failed to find day digits in date: ", - std::string_view { str, static_cast(end - str) }); + Logger::error( + "Failed to find day digits in date: ", + std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; @@ -310,8 +316,9 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe val = StringUtils::string_to_uint64(day_start, day_end, &sub_successful); if (!sub_successful || val < 1 || val > DAYS_IN_MONTH[month - 1]) { if (!quiet) { - Logger::error("Failed to read day: ", - std::string_view { str, static_cast(end - str) }); + Logger::error( + "Failed to read day: ", std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; @@ -324,7 +331,8 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe "Unexpected string \"", std::string_view { day_end, static_cast(end - day_end) }, "\" at the end of date ", - std::string_view { str, static_cast(end - str) }); + std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; @@ -334,8 +342,10 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe } } else { if (!quiet) { - Logger::error("Unexpected character \"", *month_end, "\" in month of date ", - std::string_view { str, static_cast(end - str) }); + Logger::error( + "Unexpected character \"", *month_end, "\" in month of date ", + std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; @@ -346,8 +356,10 @@ Date Date::from_string(char const* const str, char const* const end, bool* succe } } else { if (!quiet) { - Logger::error("Unexpected character \"", *year_end, "\" in year of date ", - std::string_view { str, static_cast(end - str) }); + Logger::error( + "Unexpected character \"", *year_end, "\" in year of date ", + std::string_view { str, static_cast(end - str) } + ); } if (successful != nullptr) { *successful = false; diff --git a/src/openvic-simulation/types/IdentifierRegistry.cpp b/src/openvic-simulation/types/IdentifierRegistry.cpp index 1bc3747..faddd75 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.cpp +++ b/src/openvic-simulation/types/IdentifierRegistry.cpp @@ -4,8 +4,7 @@ using namespace OpenVic; -HasIdentifier::HasIdentifier(std::string_view new_identifier) - : identifier { new_identifier } { +HasIdentifier::HasIdentifier(std::string_view new_identifier) : identifier { new_identifier } { assert(!identifier.empty()); } @@ -33,7 +32,6 @@ std::string HasColour::colour_to_hex_string() const { return OpenVic::colour_to_hex_string(colour); } -HasIdentifierAndColour::HasIdentifierAndColour(std::string_view new_identifier, - const colour_t new_colour, bool can_be_null, bool can_have_alpha) - : HasIdentifier { new_identifier }, - HasColour { new_colour, can_be_null, can_have_alpha } {} +HasIdentifierAndColour::HasIdentifierAndColour( + std::string_view new_identifier, const colour_t new_colour, bool can_be_null, bool can_have_alpha +) : HasIdentifier { new_identifier }, HasColour { new_colour, can_be_null, can_have_alpha } {} diff --git a/src/openvic-simulation/types/IdentifierRegistry.hpp b/src/openvic-simulation/types/IdentifierRegistry.hpp index 0c5c5ab..bcb8e33 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.hpp +++ b/src/openvic-simulation/types/IdentifierRegistry.hpp @@ -9,8 +9,12 @@ #include "openvic-simulation/utility/Logger.hpp" #define REF_GETTERS(var) \ - constexpr decltype(var)& get_##var() { return var; } \ - constexpr decltype(var) const& get_##var() const { return var; } + constexpr decltype(var)& get_##var() { \ + return var; \ + } \ + constexpr decltype(var) const& get_##var() const { \ + return var; \ + } namespace OpenVic { /* @@ -46,7 +50,9 @@ namespace OpenVic { #define HASID_PROPERTY(NAME) \ const NAME; \ public: \ - auto get_##NAME() const->decltype(get_property(NAME)) { return get_property(NAME); } \ + auto get_##NAME() const->decltype(get_property(NAME)) { \ + return get_property(NAME); \ + } \ private: }; @@ -78,8 +84,9 @@ private: */ class HasIdentifierAndColour : public HasIdentifier, public HasColour { protected: - HasIdentifierAndColour(std::string_view new_identifier, const colour_t new_colour, - bool can_be_null, bool can_have_alpha); + HasIdentifierAndColour( + std::string_view new_identifier, const colour_t new_colour, bool can_be_null, bool can_have_alpha + ); public: HasIdentifierAndColour(HasIdentifierAndColour const&) = delete; @@ -96,8 +103,7 @@ private: constexpr auto pred = [](typename decimal_map_t::value_type a, typename decimal_map_t::value_type b) -> bool { return a.second < b.second; }; - const typename decimal_map_t::const_iterator result = - std::max_element(map.begin(), map.end(), pred); + const typename decimal_map_t::const_iterator result = std::max_element(map.begin(), map.end(), pred); if (result != map.end()) { return *result; } else { @@ -109,13 +115,17 @@ private: /* Callbacks for trying to add duplicate keys via UniqueKeyRegistry::add_item */ static bool duplicate_fail_callback(std::string_view registry_name, std::string_view duplicate_identifier) { - Logger::error("Failure adding item to the ", registry_name, " registry - an item with the identifier \"", - duplicate_identifier, "\" already exists!"); + Logger::error( + "Failure adding item to the ", registry_name, " registry - an item with the identifier \"", duplicate_identifier, + "\" already exists!" + ); return false; } static bool duplicate_warning_callback(std::string_view registry_name, std::string_view duplicate_identifier) { - Logger::warning("Warning adding item to the ", registry_name, " registry - an item with the identifier \"", - duplicate_identifier, "\" already exists!"); + Logger::warning( + "Warning adding item to the ", registry_name, " registry - an item with the identifier \"", duplicate_identifier, + "\" already exists!" + ); return true; } static bool duplicate_ignore_callback(std::string_view registry_name, std::string_view duplicate_identifier) { @@ -141,16 +151,19 @@ private: using value_type = _Type; using storage_type = _Storage; - UniqueKeyRegistry(std::string_view new_name, bool new_log_lock = true, - _GetIdentifier new_GetIdentifier = {}, _GetPointer new_GetPointer = {}) - : name { new_name }, log_lock { new_log_lock }, GetIdentifier { new_GetIdentifier }, GetPointer { new_GetPointer } {} + UniqueKeyRegistry( + std::string_view new_name, bool new_log_lock = true, _GetIdentifier new_GetIdentifier = {}, + _GetPointer new_GetPointer = {} + ) : name { new_name }, log_lock { new_log_lock }, GetIdentifier { new_GetIdentifier }, GetPointer { new_GetPointer } {} std::string_view get_name() const { return name; } - bool add_item(storage_type&& item, - NodeTools::callback_t duplicate_callback = duplicate_fail_callback) { + bool add_item( + storage_type&& item, + NodeTools::callback_t duplicate_callback = duplicate_fail_callback + ) { if (locked) { Logger::error("Cannot add item to the ", name, " registry - locked!"); return false; @@ -212,7 +225,9 @@ private: #define GETTERS \ value_type _const* get_item_by_identifier(std::string_view identifier) _const { \ const typename decltype(identifier_index_map)::const_iterator it = identifier_index_map.find(identifier); \ - if (it != identifier_index_map.end()) return GetPointer(items[it->second]); \ + if (it != identifier_index_map.end()) { \ + return GetPointer(items[it->second]); \ + } \ return nullptr; \ } \ value_type _const* get_item_by_index(size_t index) _const { \ @@ -221,7 +236,9 @@ private: NodeTools::callback_t expect_item_str(NodeTools::callback_t callback) _const { \ return [this, callback](std::string_view identifier) -> bool { \ value_type _const* item = get_item_by_identifier(identifier); \ - if (item != nullptr) return callback(*item); \ + if (item != nullptr) { \ + return callback(*item); \ + } \ Logger::error("Invalid ", name, ": ", identifier); \ return false; \ }; \ @@ -229,7 +246,8 @@ private: NodeTools::node_callback_t expect_item_identifier(NodeTools::callback_t callback) _const { \ return NodeTools::expect_identifier(expect_item_str(callback)); \ } \ - NodeTools::node_callback_t expect_item_dictionary(NodeTools::callback_t callback) _const { \ + NodeTools::node_callback_t expect_item_dictionary(NodeTools::callback_t callback) \ + _const { \ return NodeTools::expect_dictionary([this, callback](std::string_view key, ast::NodeCPtr value) -> bool { \ return expect_item_str(std::bind(callback, std::placeholders::_1, value))(key); \ }); \ @@ -262,8 +280,8 @@ private: return identifiers; } - NodeTools::node_callback_t expect_item_decimal_map( - NodeTools::callback_t&&> callback) const { + NodeTools::node_callback_t expect_item_decimal_map(NodeTools::callback_t&&> callback) + const { return [this, callback](ast::NodeCPtr node) -> bool { decimal_map_t map; bool ret = expect_item_dictionary([&map](value_type const& key, ast::NodeCPtr value) -> bool { @@ -321,8 +339,12 @@ private: using IdentifierInstanceRegistry = InstanceRegistry<_Type, _get_identifier<_Type>>; #define IDENTIFIER_REGISTRY_ACCESSORS_CUSTOM_PLURAL(singular, plural) \ - void lock_##plural() { plural.lock(); } \ - bool plural##_are_locked() const { return plural.is_locked(); } \ + void lock_##plural() { \ + plural.lock(); \ + } \ + bool plural##_are_locked() const { \ + return plural.is_locked(); \ + } \ decltype(plural)::value_type const* get_##singular##_by_identifier(std::string_view identifier) const { \ return plural.get_item_by_identifier(identifier); \ } \ @@ -338,16 +360,24 @@ private: std::vector get_##singular##_identifiers() const { \ return plural.get_item_identifiers(); \ } \ - NodeTools::callback_t expect_##singular##_str(NodeTools::callback_t callback) const { \ + NodeTools::callback_t expect_##singular##_str( \ + NodeTools::callback_t callback \ + ) const { \ return plural.expect_item_str(callback); \ } \ - NodeTools::node_callback_t expect_##singular##_identifier(NodeTools::callback_t callback) const { \ + NodeTools::node_callback_t expect_##singular##_identifier( \ + NodeTools::callback_t callback \ + ) const { \ return plural.expect_item_identifier(callback); \ } \ - NodeTools::node_callback_t expect_##singular##_dictionary(NodeTools::callback_t callback) const { \ + NodeTools::node_callback_t expect_##singular##_dictionary( \ + NodeTools::callback_t callback \ + ) const { \ return plural.expect_item_dictionary(callback); \ } \ - NodeTools::node_callback_t expect_##singular##_decimal_map(NodeTools::callback_t&&> callback) const { \ + NodeTools::node_callback_t expect_##singular##_decimal_map( \ + NodeTools::callback_t&&> callback \ + ) const { \ return plural.expect_item_decimal_map(callback); \ } @@ -355,13 +385,17 @@ private: decltype(plural)::value_type* get_##singular##_by_identifier(std::string_view identifier) { \ return plural.get_item_by_identifier(identifier); \ } \ - NodeTools::callback_t expect_##singular##_str(NodeTools::callback_t callback) { \ + NodeTools::callback_t expect_##singular##_str( \ + NodeTools::callback_t callback \ + ) { \ return plural.expect_item_str(callback); \ } \ NodeTools::node_callback_t expect_##singular##_identifier(NodeTools::callback_t callback) { \ return plural.expect_item_identifier(callback); \ } \ - NodeTools::node_callback_t expect_##singular##_dictionary(NodeTools::callback_t callback) { \ + NodeTools::node_callback_t expect_##singular##_dictionary( \ + NodeTools::callback_t callback \ + ) { \ return plural.expect_item_dictionary(callback); \ } diff --git a/src/openvic-simulation/types/Vector.cpp b/src/openvic-simulation/types/Vector.cpp index 5065084..28f30bf 100644 --- a/src/openvic-simulation/types/Vector.cpp +++ b/src/openvic-simulation/types/Vector.cpp @@ -10,7 +10,7 @@ constexpr vec2_t::vec2_t(T new_x, T new_y) : x { new_x }, y { new_y } {} template constexpr vec2_t vec2_t::abs() const { - return { }; + return {}; } template diff --git a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp index 16e400f..4bf5716 100644 --- a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp +++ b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp @@ -304,7 +304,7 @@ namespace OpenVic { } char const* dot_pointer = str; - while (*dot_pointer != '.' && ++dot_pointer != end); + while (*dot_pointer != '.' && ++dot_pointer != end) {} if (dot_pointer == str && dot_pointer + 1 == end) { // Invalid: ".", "+." or "-." diff --git a/src/openvic-simulation/utility/BMP.cpp b/src/openvic-simulation/utility/BMP.cpp index cdd8ead..d4e7cf7 100644 --- a/src/openvic-simulation/utility/BMP.cpp +++ b/src/openvic-simulation/utility/BMP.cpp @@ -69,8 +69,10 @@ bool BMP::read_header() { // Validate sizes and dimensions // TODO - image_size_bytes can be 0 for non-compressed BMPs if (header.file_size != header.offset + header.image_size_bytes) { - Logger::error("Invalid BMP memory sizes: file size = ", header.file_size, " != ", header.offset + header.image_size_bytes, - " = ", header.offset, " + ", header.image_size_bytes, " = image data offset + image data size"); + Logger::error( + "Invalid BMP memory sizes: file size = ", header.file_size, " != ", header.offset + header.image_size_bytes, " = ", + header.offset, " + ", header.image_size_bytes, " = image data offset + image data size" + ); header_validated = false; } // TODO - support negative widths (i.e. horizontal flip) @@ -91,24 +93,25 @@ bool BMP::read_header() { #define STR(x) #x static const std::set BITS_PER_PIXEL { VALID_BITS_PER_PIXEL }; if (!BITS_PER_PIXEL.contains(header.bits_per_pixel)) { - Logger::error("Invalid BMP bits per pixel: ", header.bits_per_pixel, - " (must be one of " STR(VALID_BITS_PER_PIXEL) ")"); + Logger::error("Invalid BMP bits per pixel: ", header.bits_per_pixel, " (must be one of " STR(VALID_BITS_PER_PIXEL) ")"); header_validated = false; } #undef VALID_BITS_PER_PIXEL #undef STR static constexpr uint16_t PALETTE_BITS_PER_PIXEL_LIMIT = 8; if (header.num_colours != 0 && header.bits_per_pixel > PALETTE_BITS_PER_PIXEL_LIMIT) { - Logger::error("Invalid BMP palette size: ", header.num_colours, - " (should be 0 as bits per pixel is ", header.bits_per_pixel, " > 8)"); + Logger::error( + "Invalid BMP palette size: ", header.num_colours, " (should be 0 as bits per pixel is ", header.bits_per_pixel, + " > 8)" + ); header_validated = false; } // TODO - validate important_colours palette_size = header.bits_per_pixel > PALETTE_BITS_PER_PIXEL_LIMIT ? 0 // Use header.num_colours if it's greater than 0 and at most 1 << header.bits_per_pixel - : 0 < header.num_colours && header.num_colours - 1 >> header.bits_per_pixel == 0 ? header.num_colours - : 1 << header.bits_per_pixel; + : (0 < header.num_colours && header.num_colours - 1 >> header.bits_per_pixel == 0 + ? header.num_colours : 1 << header.bits_per_pixel); const uint32_t expected_offset = palette_size * PALETTE_COLOUR_SIZE + sizeof(header); if (header.offset != expected_offset) { diff --git a/src/openvic-simulation/utility/ConstexprIntToStr.hpp b/src/openvic-simulation/utility/ConstexprIntToStr.hpp index e383365..e346ebe 100644 --- a/src/openvic-simulation/utility/ConstexprIntToStr.hpp +++ b/src/openvic-simulation/utility/ConstexprIntToStr.hpp @@ -33,7 +33,9 @@ namespace OpenVic::ConstexprIntToStr { constexpr std::size_t next_value = value / 10; if constexpr (next_value != 0) { - return append_sequence(integer_to_string_sequence(), std::integer_sequence {}); + return append_sequence( + integer_to_string_sequence(), std::integer_sequence {} + ); } else { return std::integer_sequence {}; } @@ -53,4 +55,4 @@ namespace OpenVic::ConstexprIntToStr { constexpr auto make_itosv_array() { return generate_itosv_array(std::make_integer_sequence()); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/Logger.hpp b/src/openvic-simulation/utility/Logger.hpp index b2395ac..a1c599d 100644 --- a/src/openvic-simulation/utility/Logger.hpp +++ b/src/openvic-simulation/utility/Logger.hpp @@ -23,8 +23,9 @@ namespace OpenVic { source_location(std::string f, int l, std::string n) : _file(f), _line(l), _function(n) {} public: - static source_location current(std::string f = __builtin_FILE(), int l = __builtin_LINE(), - std::string n = __builtin_FUNCTION()) { + static source_location current( + std::string f = __builtin_FILE(), int l = __builtin_LINE(), std::string n = __builtin_FUNCTION() + ) { return source_location(f, l, n); } @@ -83,7 +84,7 @@ namespace OpenVic { #define LOG_FUNC(name) \ private: \ - static inline log_channel_t name##_channel{}; \ + static inline log_channel_t name##_channel {}; \ public: \ static inline void set_##name##_func(log_func_t log_func) { \ name##_channel.func = log_func; \ @@ -91,7 +92,7 @@ namespace OpenVic { template \ struct name { \ name(Ts&&... ts, source_location const& location = source_location::current()) { \ - log{ name##_channel, std::forward(ts)..., location }; \ + log { name##_channel, std::forward(ts)..., location }; \ } \ }; \ template \ -- cgit v1.2.3-56-ga3b1