diff --git a/.astylesrc b/.astylesrc deleted file mode 100644 index 7891dcc56..000000000 --- a/.astylesrc +++ /dev/null @@ -1,217 +0,0 @@ -# @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/.clang-format b/.clang-format index 8400c69e4..c1e6b00ad 100644 --- a/.clang-format +++ b/.clang-format @@ -71,6 +71,13 @@ InsertNewlineAtEOF: true InsertBraces: true MaxEmptyLinesToKeep: 2 RequiresClausePosition: OwnLine +AttributeMacros: + - OV_ALWAYS_INLINE + - OV_SPEED_INLINE + - OV_NO_UNIQUE_ADDRESS +IfMacros: + - CHECK_IF + - CHECK_FALSE_IF IncludeCategories: - Regex: <[[:alnum:]_]+> Priority: 1 @@ -90,7 +97,11 @@ IncludeCategories: Priority: 8 - Regex: ^& m SPDLOG_INFO("===== Setting up instance... ====="); ret &= game_manager.setup_instance( - game_manager.get_definition_manager() - .get_history_manager() - .get_bookmark_manager() - .get_front_bookmark() + game_manager.get_definition_manager().get_history_manager().get_bookmark_manager().get_front_bookmark() ); print_memory_usage("Instance Setup"); @@ -267,7 +264,7 @@ static bool run_headless(fs::path const& root, memory::vector& m "\n\t{} - Total #{} ({}), Prestige #{} ({}), Industry #{} ({}), Military #{} ({})", // country, // country.get_total_rank(), country.total_score.get_untracked().to_string(1), // - country.get_prestige_rank(), country.get_prestige_untracked().to_string(1), + country.get_prestige_rank(), country.get_prestige_untracked().to_string(1), // country.get_industrial_rank(), country.get_industrial_power_untracked().to_string(1), country.get_military_rank(), country.military_power.get_untracked().to_string(1) ); @@ -275,9 +272,11 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("{}:{}", title, countries_str); }; - CountryInstanceManager const& country_instance_manager = game_manager.get_instance_manager()->get_country_instance_manager(); + CountryInstanceManager const& country_instance_manager = + game_manager.get_instance_manager()->get_country_instance_manager(); - OpenVic::forwardable_span> great_powers = country_instance_manager.get_great_powers(); + OpenVic::forwardable_span> great_powers = + country_instance_manager.get_great_powers(); print_ranking_list("Great Powers", great_powers); print_ranking_list("Secondary Powers", country_instance_manager.get_secondary_powers()); print_ranking_list("All countries", country_instance_manager.get_total_ranking()); diff --git a/src/openvic-simulation/DefinitionManager.hpp b/src/openvic-simulation/DefinitionManager.hpp index e30d44d5f..3a870109b 100644 --- a/src/openvic-simulation/DefinitionManager.hpp +++ b/src/openvic-simulation/DefinitionManager.hpp @@ -19,7 +19,6 @@ #include "openvic-simulation/population/PopManager.hpp" #include "openvic-simulation/research/ResearchManager.hpp" #include "openvic-simulation/scripts/ScriptManager.hpp" -#include "openvic-simulation/interface/UI.hpp" namespace OpenVic { struct DefinitionManager { diff --git a/src/openvic-simulation/GameManager.cpp b/src/openvic-simulation/GameManager.cpp index a4d0594be..03cc5902d 100644 --- a/src/openvic-simulation/GameManager.cpp +++ b/src/openvic-simulation/GameManager.cpp @@ -29,11 +29,10 @@ GameManager::elapsed_time_getter_func_t GameManager::get_elapsed_msec_time_callb GameManager::GameManager( InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, - elapsed_time_getter_func_t new_get_elapsed_usec_callback, - elapsed_time_getter_func_t new_get_elapsed_msec_callback -) : gamestate_updated_callback { - new_gamestate_updated_callback ? std::move(new_gamestate_updated_callback) : []() {} - }, definitions_loaded { false }, mod_descriptors_loaded { false } { + elapsed_time_getter_func_t new_get_elapsed_usec_callback, elapsed_time_getter_func_t new_get_elapsed_msec_callback +) + : gamestate_updated_callback { new_gamestate_updated_callback ? std::move(new_gamestate_updated_callback) : []() {} }, + definitions_loaded { false }, mod_descriptors_loaded { false } { if (new_get_elapsed_usec_callback) { get_elapsed_usec_time_callback = { std::move(new_get_elapsed_usec_callback) }; } @@ -83,11 +82,10 @@ bool GameManager::load_mods(memory::vector const& mods_to_find) * (Historical Project Mod 0.4.6 or HPM both valid, for example), and load them plus their dependencies. */ for (std::string_view requested_mod : mods_to_find) { - memory::vector::const_iterator it = ranges::find_if(mod_manager.get_mods(), - [&requested_mod](Mod const& mod) -> bool { + memory::vector::const_iterator it = + ranges::find_if(mod_manager.get_mods(), [&requested_mod](Mod const& mod) -> bool { return mod.get_identifier() == requested_mod || mod.get_user_dir() == requested_mod; - } - ); + }); if (it == mod_manager.get_mods().end()) { spdlog::warn_s("Requested mod \"{}\" does not exist!", requested_mod); @@ -97,7 +95,7 @@ bool GameManager::load_mods(memory::vector const& mods_to_find) Mod const& mod = *it; vector_ordered_set> dependencies = mod.generate_dependency_list(&ret); - if(!ret) { + if (!ret) { continue; } @@ -177,11 +175,7 @@ bool GameManager::setup_instance(Bookmark const& bookmark) { SPDLOG_INFO("Initialising new game instance."); - instance_manager.emplace( - game_rules_manager, - definition_manager, - gamestate_updated_callback - ); + instance_manager.emplace(game_rules_manager, definition_manager, gamestate_updated_callback); SPDLOG_INFO("Setting up new game instance."); diff --git a/src/openvic-simulation/GameManager.hpp b/src/openvic-simulation/GameManager.hpp index 974db0bcd..b13c47934 100644 --- a/src/openvic-simulation/GameManager.hpp +++ b/src/openvic-simulation/GameManager.hpp @@ -3,16 +3,16 @@ #include #include +#include + #include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/InstanceManager.hpp" -#include "openvic-simulation/dataloader/ModManager.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" -#include "openvic-simulation/misc/GameRulesManager.hpp" +#include "openvic-simulation/dataloader/ModManager.hpp" #include "openvic-simulation/gen/commit_info.gen.hpp" +#include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include - namespace OpenVic { struct GameManager { using elapsed_time_getter_func_t = fu2::function_base; @@ -34,8 +34,7 @@ namespace OpenVic { public: GameManager( InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, - elapsed_time_getter_func_t new_get_elapsed_usec_callback, - elapsed_time_getter_func_t new_get_elapsed_msec_callback + elapsed_time_getter_func_t new_get_elapsed_usec_callback, elapsed_time_getter_func_t new_get_elapsed_msec_callback ); ~GameManager(); diff --git a/src/openvic-simulation/InstanceManager.cpp b/src/openvic-simulation/InstanceManager.cpp index ce7bb6358..91383e110 100644 --- a/src/openvic-simulation/InstanceManager.cpp +++ b/src/openvic-simulation/InstanceManager.cpp @@ -8,104 +8,75 @@ using namespace OpenVic; InstanceManager::InstanceManager( - GameRulesManager const& new_game_rules_manager, - DefinitionManager const& new_definition_manager, + GameRulesManager const& new_game_rules_manager, DefinitionManager const& new_definition_manager, gamestate_updated_func_t gamestate_updated_callback -) : thread_pool { today }, - definition_manager { new_definition_manager }, - game_action_manager { *this }, - game_rules_manager { new_game_rules_manager }, - good_instance_manager { - new_definition_manager.get_economy_manager().get_good_definition_manager(), - new_game_rules_manager - }, - market_instance { - thread_pool, - new_definition_manager.get_define_manager().get_country_defines(), - good_instance_manager - }, - artisanal_producer_deps { - new_definition_manager.get_define_manager().get_economy_defines(), - new_definition_manager.get_economy_manager().get_good_definition_manager().get_good_definitions(), - new_definition_manager.get_modifier_manager().get_modifier_effect_cache() - }, - country_instance_deps { - new_definition_manager.get_economy_manager().get_building_type_manager().get_building_types(), - new_definition_manager.get_define_manager().get_country_defines(), - country_relation_manager, - new_definition_manager.get_crime_manager().get_crime_modifiers(), - new_definition_manager.get_define_manager().get_end_date(), - new_definition_manager.get_define_manager().get_diplomacy_defines(), - new_definition_manager.get_define_manager().get_economy_defines(), - new_definition_manager.get_research_manager().get_invention_manager().get_inventions(), - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), - new_game_rules_manager, - good_instance_manager.get_good_instances(), - good_instance_manager, - new_definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), - market_instance, - new_definition_manager.get_define_manager().get_military_defines(), - new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), - new_definition_manager.get_pop_manager().get_pop_types(), - new_definition_manager.get_politics_manager().get_issue_manager().get_reform_groups(), - new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), - new_definition_manager.get_military_manager().get_unit_type_manager().get_ship_types(), - new_definition_manager.get_pop_manager().get_stratas(), - new_definition_manager.get_research_manager().get_technology_manager().get_technologies(), - new_definition_manager.get_military_manager().get_unit_type_manager() - }, - pop_deps { - artisanal_producer_deps, - market_instance - }, - rgo_deps { - market_instance, - new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), - new_definition_manager.get_pop_manager().get_pop_types() - }, - province_instance_deps { - new_definition_manager.get_economy_manager().get_building_type_manager(), - new_game_rules_manager, - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), - new_definition_manager.get_pop_manager().get_pop_types(), - rgo_deps, - new_definition_manager.get_pop_manager().get_stratas() - }, - global_flags { "global" }, - country_instance_manager { - new_definition_manager.get_define_manager().get_country_defines(), - new_definition_manager.get_country_definition_manager(), - country_instance_deps, - good_instance_manager, - new_definition_manager.get_define_manager().get_pops_defines(), - new_definition_manager.get_pop_manager().get_pop_types(), - thread_pool - }, - unit_instance_manager { - new_definition_manager.get_pop_manager().get_culture_manager(), - new_definition_manager.get_military_manager().get_leader_trait_manager(), - new_definition_manager.get_define_manager().get_military_defines() - }, - politics_instance_manager { - *this, - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies() - }, - map_instance { - new_definition_manager.get_map_definition(), - province_instance_deps, - thread_pool - }, - simulation_clock { - [this]() -> void { - queue_game_action(); - }, - [this]() -> void { - execute_game_actions(); - update_gamestate(); - } - }, - console_instance { *this }, - gamestate_updated { gamestate_updated_callback ? std::move(gamestate_updated_callback) : []() {} } {} +) + : thread_pool { today }, definition_manager { new_definition_manager }, game_action_manager { *this }, + game_rules_manager { new_game_rules_manager }, + good_instance_manager { new_definition_manager.get_economy_manager().get_good_definition_manager(), + new_game_rules_manager }, + market_instance { thread_pool, new_definition_manager.get_define_manager().get_country_defines(), good_instance_manager }, + artisanal_producer_deps { + new_definition_manager.get_define_manager().get_economy_defines(), + new_definition_manager.get_economy_manager().get_good_definition_manager().get_good_definitions(), + new_definition_manager.get_modifier_manager().get_modifier_effect_cache() + }, + country_instance_deps { + new_definition_manager.get_economy_manager().get_building_type_manager().get_building_types(), + new_definition_manager.get_define_manager().get_country_defines(), + country_relation_manager, + new_definition_manager.get_crime_manager().get_crime_modifiers(), + new_definition_manager.get_define_manager().get_end_date(), + new_definition_manager.get_define_manager().get_diplomacy_defines(), + new_definition_manager.get_define_manager().get_economy_defines(), + new_definition_manager.get_research_manager().get_invention_manager().get_inventions(), + new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), + new_game_rules_manager, + good_instance_manager.get_good_instances(), + good_instance_manager, + new_definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), + market_instance, + new_definition_manager.get_define_manager().get_military_defines(), + new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), + new_definition_manager.get_pop_manager().get_pop_types(), + new_definition_manager.get_politics_manager().get_issue_manager().get_reform_groups(), + new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), + new_definition_manager.get_military_manager().get_unit_type_manager().get_ship_types(), + new_definition_manager.get_pop_manager().get_stratas(), + new_definition_manager.get_research_manager().get_technology_manager().get_technologies(), + new_definition_manager.get_military_manager().get_unit_type_manager() + }, + pop_deps { artisanal_producer_deps, market_instance }, + rgo_deps { market_instance, new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), + new_definition_manager.get_pop_manager().get_pop_types() }, + province_instance_deps { new_definition_manager.get_economy_manager().get_building_type_manager(), + new_game_rules_manager, + new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), + new_definition_manager.get_pop_manager().get_pop_types(), + rgo_deps, + new_definition_manager.get_pop_manager().get_stratas() }, + global_flags { "global" }, country_instance_manager { new_definition_manager.get_define_manager().get_country_defines(), + new_definition_manager.get_country_definition_manager(), + country_instance_deps, + good_instance_manager, + new_definition_manager.get_define_manager().get_pops_defines(), + new_definition_manager.get_pop_manager().get_pop_types(), + thread_pool }, + unit_instance_manager { new_definition_manager.get_pop_manager().get_culture_manager(), + new_definition_manager.get_military_manager().get_leader_trait_manager(), + new_definition_manager.get_define_manager().get_military_defines() }, + politics_instance_manager { *this, + new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies() }, + map_instance { new_definition_manager.get_map_definition(), province_instance_deps, thread_pool }, + simulation_clock { [this]() -> void { + queue_game_action(); + }, + [this]() -> void { + execute_game_actions(); + update_gamestate(); + } }, + console_instance { *this }, + gamestate_updated { gamestate_updated_callback ? std::move(gamestate_updated_callback) : []() {} } {} void InstanceManager::set_gamestate_needs_update() { if (!currently_updating_gamestate) { @@ -198,16 +169,12 @@ bool InstanceManager::setup() { } thread_pool.initialise_threadpool( - game_rules_manager, - good_instance_manager, - definition_manager.get_modifier_manager().get_modifier_effect_cache(), + game_rules_manager, good_instance_manager, definition_manager.get_modifier_manager().get_modifier_effect_cache(), definition_manager.get_define_manager().get_pops_defines(), definition_manager.get_economy_manager().get_production_type_manager(), definition_manager.get_economy_manager().get_good_definition_manager().get_good_definitions(), - definition_manager.get_pop_manager().get_stratas(), - good_instance_manager.get_good_instances(), - country_instance_manager.get_country_instances(), - map_instance.get_province_instances() + definition_manager.get_pop_manager().get_stratas(), good_instance_manager.get_good_instances(), + country_instance_manager.get_country_instances(), map_instance.get_province_instances() ); game_instance_setup = true; @@ -238,12 +205,10 @@ bool InstanceManager::load_bookmark(Bookmark const& new_bookmark) { politics_instance_manager.setup_starting_ideologies(); bool ret = map_instance.apply_history_to_provinces( - definition_manager.get_history_manager().get_province_manager(), today, - country_instance_manager, + definition_manager.get_history_manager().get_province_manager(), today, country_instance_manager, // TODO - the following argument is for generating test pop attributes definition_manager.get_politics_manager().get_issue_manager(), - definition_manager.get_define_manager().get_military_defines(), - pop_deps + definition_manager.get_define_manager().get_military_defines(), pop_deps ); // It is important that province history is applied before country history as province history includes @@ -252,9 +217,7 @@ bool InstanceManager::load_bookmark(Bookmark const& new_bookmark) { ret &= country_instance_manager.apply_history_to_countries(*this); ret &= map_instance.get_state_manager().generate_states( - definition_manager.get_map_definition(), - map_instance, - definition_manager.get_pop_manager().get_stratas(), + definition_manager.get_map_definition(), map_instance, definition_manager.get_pop_manager().get_stratas(), definition_manager.get_pop_manager().get_pop_types(), definition_manager.get_politics_manager().get_ideology_manager().get_ideologies() ); @@ -324,12 +287,8 @@ void InstanceManager::update_modifier_sums() { // full copy of all the modifiers affecting them in their modifier sum, but provinces only having their directly/locally // applied modifiers in their modifier sum, hence requiring owner country modifier effect values to be looked up when // determining the value of a global effect on the province. - country_instance_manager.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); - map_instance.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); + country_instance_manager.update_modifier_sums(today, definition_manager.get_modifier_manager().get_static_modifier_cache()); + map_instance.update_modifier_sums(today, definition_manager.get_modifier_manager().get_static_modifier_cache()); } bool InstanceManager::queue_game_action(game_action_t&& game_action) { diff --git a/src/openvic-simulation/InstanceManager.hpp b/src/openvic-simulation/InstanceManager.hpp index 311727432..1c29c23f6 100644 --- a/src/openvic-simulation/InstanceManager.hpp +++ b/src/openvic-simulation/InstanceManager.hpp @@ -5,8 +5,8 @@ #include #include "openvic-simulation/console/ConsoleInstance.hpp" -#include "openvic-simulation/country/CountryInstanceManager.hpp" #include "openvic-simulation/country/CountryInstanceDeps.hpp" +#include "openvic-simulation/country/CountryInstanceManager.hpp" #include "openvic-simulation/diplomacy/CountryRelation.hpp" #include "openvic-simulation/economy/GoodInstance.hpp" #include "openvic-simulation/economy/production/ArtisanalProducerDeps.hpp" @@ -22,8 +22,8 @@ #include "openvic-simulation/population/PopDeps.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/FlagStrings.hpp" -#include "openvic-simulation/utility/ThreadPool.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/ThreadPool.hpp" namespace OpenVic { @@ -43,7 +43,7 @@ namespace OpenVic { GameRulesManager const& game_rules_manager; GoodInstanceManager PROPERTY_REF(good_instance_manager); MarketInstance PROPERTY_REF(market_instance); - + ArtisanalProducerDeps artisanal_producer_deps; CountryInstanceDeps country_instance_deps; PopDeps pop_deps; @@ -82,8 +82,7 @@ namespace OpenVic { DefinitionManager const& definition_manager; InstanceManager( - GameRulesManager const& new_game_rules_manager, - DefinitionManager const& new_definition_manager, + GameRulesManager const& new_game_rules_manager, DefinitionManager const& new_definition_manager, gamestate_updated_func_t gamestate_updated_callback ); @@ -101,12 +100,7 @@ namespace OpenVic { template bool queue_game_action(Args&&... args) { - return queue_game_action( - game_action_t( - std::in_place_type, - std::forward(args)... - ) - ); + return queue_game_action(game_action_t(std::in_place_type, std::forward(args)...)); } bool queue_game_action(game_action_t&& game_action); }; diff --git a/src/openvic-simulation/console/ConsoleInstance.cpp b/src/openvic-simulation/console/ConsoleInstance.cpp index 6f0393770..f5fe572e1 100644 --- a/src/openvic-simulation/console/ConsoleInstance.cpp +++ b/src/openvic-simulation/console/ConsoleInstance.cpp @@ -188,8 +188,10 @@ std::optional ConsoleInstance::validate_boolean(std::string_view value_str if (value_string == TRUE_VALUE || value_string == YES_VALUE || // value_string == ONE_VALUE || value_string == ON_VALUE) { return true; - } else if (value_string == FALSE_VALUE || value_string == NO_VALUE || // - value_string == ZERO_VALUE || value_string == OFF_VALUE) { + } else if ( + value_string == FALSE_VALUE || value_string == NO_VALUE || // + value_string == ZERO_VALUE || value_string == OFF_VALUE + ) { return false; } diff --git a/src/openvic-simulation/console/ConsoleInstance.hpp b/src/openvic-simulation/console/ConsoleInstance.hpp index a3ebcca37..6c933a9c8 100644 --- a/src/openvic-simulation/console/ConsoleInstance.hpp +++ b/src/openvic-simulation/console/ConsoleInstance.hpp @@ -7,14 +7,14 @@ #include #include +#include + #include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include - namespace OpenVic { struct ProvinceInstance; struct CountryInstance; diff --git a/src/openvic-simulation/core/Hash.hpp b/src/openvic-simulation/core/Hash.hpp index cd839663c..2c6ee5e2c 100644 --- a/src/openvic-simulation/core/Hash.hpp +++ b/src/openvic-simulation/core/Hash.hpp @@ -53,7 +53,7 @@ namespace OpenVic { } s |= std::hash {}(args); }(), - ... + ... // ); } } diff --git a/src/openvic-simulation/core/Math.hpp b/src/openvic-simulation/core/Math.hpp index 8050714c0..92a4e3397 100644 --- a/src/openvic-simulation/core/Math.hpp +++ b/src/openvic-simulation/core/Math.hpp @@ -8,8 +8,8 @@ #include "openvic-simulation/core/Typedefs.hpp" namespace OpenVic { - template - [[nodiscard]] OV_SPEED_INLINE constexpr T abs(T num); + template + [[nodiscard]] OV_SPEED_INLINE constexpr T abs(T num); template requires std::integral || std::floating_point @@ -21,8 +21,8 @@ namespace OpenVic { } } - template - requires (!(std::integral || std::floating_point)) + template + requires(!(std::integral || std::floating_point)) [[nodiscard]] OV_SPEED_INLINE constexpr T abs(T num); template diff --git a/src/openvic-simulation/core/error/ErrorMacros.hpp b/src/openvic-simulation/core/error/ErrorMacros.hpp index 3949d7180..4e7b2ea54 100644 --- a/src/openvic-simulation/core/error/ErrorMacros.hpp +++ b/src/openvic-simulation/core/error/ErrorMacros.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/utility/Logger.hpp" // IWYU pragma: keep for loggers #include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep for macros +#include "openvic-simulation/utility/Logger.hpp" // IWYU pragma: keep for loggers /** * Try using `OV_ERR_FAIL_COND_MSG`. diff --git a/src/openvic-simulation/core/portable/ForwardableSpan.hpp b/src/openvic-simulation/core/portable/ForwardableSpan.hpp index fe117bc0f..32eb5fe86 100644 --- a/src/openvic-simulation/core/portable/ForwardableSpan.hpp +++ b/src/openvic-simulation/core/portable/ForwardableSpan.hpp @@ -152,14 +152,16 @@ namespace OpenVic::_detail::forwardable_span { template OtherElementType, std::size_t OtherExtent> requires(Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) - constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) - span(span const& s) + constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) span( + span const& s + ) : _ptr(s.data()), _extent(s.size()) {} template OtherElementType, std::size_t OtherExtent> requires(Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) - constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) - span(std::span const& s) + constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) span( + std::span const& s + ) : _ptr(s.data()), _extent(s.size()) {} diff --git a/src/openvic-simulation/core/random/RandomGenerator.hpp b/src/openvic-simulation/core/random/RandomGenerator.hpp index f569f5001..7e2fd5aa3 100644 --- a/src/openvic-simulation/core/random/RandomGenerator.hpp +++ b/src/openvic-simulation/core/random/RandomGenerator.hpp @@ -78,6 +78,10 @@ namespace OpenVic { T _generator; }; - struct RandomU32 : RandomGenerator { using RandomGenerator::RandomGenerator; }; - struct RandomU64 : RandomGenerator { using RandomGenerator::RandomGenerator; }; + struct RandomU32 : RandomGenerator { + using RandomGenerator::RandomGenerator; + }; + struct RandomU64 : RandomGenerator { + using RandomGenerator::RandomGenerator; + }; } diff --git a/src/openvic-simulation/core/random/WeightedSampling.hpp b/src/openvic-simulation/core/random/WeightedSampling.hpp index c82ea0a2d..56426d0ca 100644 --- a/src/openvic-simulation/core/random/WeightedSampling.hpp +++ b/src/openvic-simulation/core/random/WeightedSampling.hpp @@ -9,9 +9,7 @@ namespace OpenVic { OV_SPEED_INLINE static size_t sample_weighted_index( - const uint32_t random_value, - const std::span positive_weights, - const fixed_point_t weights_sum + const uint32_t random_value, const std::span positive_weights, const fixed_point_t weights_sum ) { if (positive_weights.empty() || weights_sum <= 0) { return -1; @@ -31,4 +29,4 @@ namespace OpenVic { return static_cast(positive_weights.size() - 1); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/template/Concepts.hpp b/src/openvic-simulation/core/template/Concepts.hpp index dd4fba1e7..d9c1186f0 100644 --- a/src/openvic-simulation/core/template/Concepts.hpp +++ b/src/openvic-simulation/core/template/Concepts.hpp @@ -111,12 +111,11 @@ namespace OpenVic { concept is_strongly_typed = derived_from_specialization_of; template - concept has_index = requires { typename T::index_t; } && - is_strongly_typed && requires { - static_cast( - static_cast().index)>>(std::declval().index) - ); - }; + concept has_index = requires { typename T::index_t; } && is_strongly_typed && requires { + static_cast( + static_cast().index)>>(std::declval().index) + ); + }; // helper to avoid error 'index_t': is not a member of T template @@ -196,7 +195,7 @@ namespace OpenVic { template> concept multipliable = requires(Lhs const& lhs, Rhs const& rhs) { - { lhs* rhs } -> std::convertible_to; + { lhs * rhs } -> std::convertible_to; }; template> @@ -234,4 +233,4 @@ namespace OpenVic { concept strict_regular_invocable_r = std::regular_invocable && requires(F f, Args&&... args) { { f(static_cast(args)...) } -> std::same_as; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/template/EnumBitfield.hpp b/src/openvic-simulation/core/template/EnumBitfield.hpp index 87534490f..35f2825e5 100644 --- a/src/openvic-simulation/core/template/EnumBitfield.hpp +++ b/src/openvic-simulation/core/template/EnumBitfield.hpp @@ -7,7 +7,7 @@ namespace OpenVic { struct is_scoped_enum final : std::bool_constant < requires { requires std::is_enum_v; requires !std::is_convertible_v>; - } > {}; + }> {}; template inline constexpr bool is_scoped_enum_v = is_scoped_enum::value; @@ -16,8 +16,7 @@ namespace OpenVic { concept IsScopedEnum = is_scoped_enum_v; template - struct enable_bitfield final : std::false_type { - }; + struct enable_bitfield final : std::false_type {}; template inline constexpr bool enable_bitfield_v = enable_bitfield::value; diff --git a/src/openvic-simulation/core/template/Functional.hpp b/src/openvic-simulation/core/template/Functional.hpp index e24d926a4..774802676 100644 --- a/src/openvic-simulation/core/template/Functional.hpp +++ b/src/openvic-simulation/core/template/Functional.hpp @@ -6,12 +6,12 @@ // bug fix for std::hash & std::equal_to to work with std::reference_wrapper namespace std { - template + template struct hash> { using BaseType = std::remove_cv_t; [[nodiscard]] size_t operator()(T const& val) const noexcept { - return std::hash{}(val); + return std::hash {}(val); } }; } @@ -21,29 +21,27 @@ namespace concepts { namespace detail { template constexpr bool _is_ref_wrapper = false; - + template constexpr bool _is_ref_wrapper> = true; - + template - concept _ref_wrap_common_reference_with = _is_ref_wrapper - && requires { typename std::common_reference_t; } - && std::convertible_to>; + concept _ref_wrap_common_reference_with = _is_ref_wrapper && requires { + typename std::common_reference_t; + } && std::convertible_to>; } template class RQual, template class TQual> - requires detail::_ref_wrap_common_reference_with, TQual> - && (!detail::_ref_wrap_common_reference_with, RQual>) - struct basic_common_reference - { + requires detail::_ref_wrap_common_reference_with, TQual> && + (!detail::_ref_wrap_common_reference_with, RQual>) + struct basic_common_reference { using type = std::common_reference_t>; }; template class TQual, template class RQual> - requires detail::_ref_wrap_common_reference_with, TQual> - && (!detail::_ref_wrap_common_reference_with, RQual>) - struct basic_common_reference - { + requires detail::_ref_wrap_common_reference_with, TQual> && + (!detail::_ref_wrap_common_reference_with, RQual>) + struct basic_common_reference { using type = std::common_reference_t>; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/ui/TextFormat.hpp b/src/openvic-simulation/core/ui/TextFormat.hpp index 453c11e1d..a3abe8eaf 100644 --- a/src/openvic-simulation/core/ui/TextFormat.hpp +++ b/src/openvic-simulation/core/ui/TextFormat.hpp @@ -2,7 +2,5 @@ #include namespace OpenVic { - enum class text_format_t : uint8_t { - left, centre, right, justified - }; + enum class text_format_t : uint8_t { left, centre, right, justified }; } diff --git a/src/openvic-simulation/country/CountryDefinition.cpp b/src/openvic-simulation/country/CountryDefinition.cpp index cb61f80ab..04591558b 100644 --- a/src/openvic-simulation/country/CountryDefinition.cpp +++ b/src/openvic-simulation/country/CountryDefinition.cpp @@ -4,9 +4,9 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/politics/Government.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/politics/PartyPolicy.hpp" @@ -19,27 +19,16 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; CountryDefinition::CountryDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - GraphicalCultureType const& new_graphical_culture, - IdentifierRegistry&& new_parties, - unit_names_map_t&& new_unit_names, - bool new_is_dynamic_tag, - government_colour_map_t&& new_alternative_colours, - colour_t new_primary_unit_colour, - colour_t new_secondary_unit_colour, + std::string_view new_identifier, colour_t new_colour, index_t new_index, GraphicalCultureType const& new_graphical_culture, + IdentifierRegistry&& new_parties, unit_names_map_t&& new_unit_names, bool new_is_dynamic_tag, + government_colour_map_t&& new_alternative_colours, colour_t new_primary_unit_colour, colour_t new_secondary_unit_colour, colour_t new_tertiary_unit_colour -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - graphical_culture { new_graphical_culture }, - parties { std::move(new_parties) }, - unit_names { std::move(new_unit_names) }, - is_dynamic_tag { new_is_dynamic_tag }, - alternative_colours { std::move(new_alternative_colours) }, - primary_unit_colour { new_primary_unit_colour }, - secondary_unit_colour { new_secondary_unit_colour }, - tertiary_unit_colour { new_tertiary_unit_colour } {} +) + : HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, + graphical_culture { new_graphical_culture }, parties { std::move(new_parties) }, unit_names { std::move(new_unit_names) }, + is_dynamic_tag { new_is_dynamic_tag }, alternative_colours { std::move(new_alternative_colours) }, + primary_unit_colour { new_primary_unit_colour }, secondary_unit_colour { new_secondary_unit_colour }, + tertiary_unit_colour { new_tertiary_unit_colour } {} bool CountryDefinitionManager::add_country( std::string_view identifier, colour_t colour, GraphicalCultureType const* graphical_culture, @@ -78,9 +67,8 @@ bool CountryDefinitionManager::load_countries( static constexpr std::string_view common_dir = "common/"; bool is_dynamic = false; - const bool ret = expect_dictionary_reserve_length( - country_definitions, - [this, &definition_manager, &is_dynamic, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { + const bool ret = + expect_dictionary_reserve_length(country_definitions, [this, &definition_manager, &is_dynamic, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { if (key == "dynamic_tags") { return expect_bool([&is_dynamic](bool val) -> bool { if (val == is_dynamic) { @@ -94,26 +82,24 @@ bool CountryDefinitionManager::load_countries( return true; })(value); } - if (expect_string( - [this, &definition_manager, is_dynamic, &dataloader, &key](std::string_view filepath) -> bool { + if (expect_string([this, &definition_manager, is_dynamic, &dataloader, &key](std::string_view filepath) -> bool { if (load_country_data_file( - definition_manager, key, is_dynamic, - Dataloader::parse_defines( - dataloader.lookup_file(append_string_views(common_dir, filepath)) - ).get_file_node() - )) { + definition_manager, key, is_dynamic, + Dataloader::parse_defines( + dataloader.lookup_file(append_string_views(common_dir, filepath)) // + ) + .get_file_node() + )) { return true; } spdlog::critical_s("Failed to load country data file: {}", filepath); return false; - } - )(value)) { + })(value)) { return true; } spdlog::critical_s("Failed to load country: {}", key); return false; - } - )(root); + })(root); lock_country_definitions(); return ret; } @@ -141,7 +127,9 @@ node_callback_t CountryDefinitionManager::load_country_party( std::string_view party_name; Date start_date, end_date; Ideology const* ideology = nullptr; - IndexedFlatMap policies { politics_manager.get_issue_manager().get_party_policy_groups() }; + IndexedFlatMap policies { + politics_manager.get_issue_manager().get_party_policy_groups() + }; bool ret = expect_dictionary_keys_and_default( [&politics_manager, &policies, &party_name](std::string_view key, ast::NodeCPtr value) -> bool { @@ -189,9 +177,7 @@ node_callback_t CountryDefinitionManager::load_country_party( } ret &= country_parties.emplace_item( - party_name, - duplicate_warning_callback, - party_name, start_date, end_date, ideology, std::move(policies) + party_name, duplicate_warning_callback, party_name, start_date, end_date, ideology, std::move(policies) ); return ret; diff --git a/src/openvic-simulation/country/CountryDefinition.hpp b/src/openvic-simulation/country/CountryDefinition.hpp index 47a07c250..f9744cd0f 100644 --- a/src/openvic-simulation/country/CountryDefinition.hpp +++ b/src/openvic-simulation/country/CountryDefinition.hpp @@ -24,7 +24,7 @@ namespace OpenVic { /* Generic information about a TAG */ struct CountryDefinition : HasIdentifierAndColour, HasIndex { friend struct CountryDefinitionManager; - + using unit_names_map_t = ordered_map; using government_colour_map_t = ordered_map; @@ -64,7 +64,7 @@ namespace OpenVic { IdentifierRegistry IDENTIFIER_REGISTRY(country_definition); NodeTools::node_callback_t load_country_party( - PoliticsManager const& politics_manager, IdentifierRegistry& country_parties + PoliticsManager const& politics_manager, IdentifierRegistry& country_parties // ) const; public: diff --git a/src/openvic-simulation/country/CountryInstance.cpp b/src/openvic-simulation/country/CountryInstance.cpp index 341247069..66567f455 100644 --- a/src/openvic-simulation/country/CountryInstance.cpp +++ b/src/openvic-simulation/country/CountryInstance.cpp @@ -1,6 +1,4 @@ #include "CountryInstance.hpp" -#include "CountryInstanceDeps.hpp" -#include "CountryInstanceManager.hpp" #include #include @@ -10,9 +8,10 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" -#include "openvic-simulation/country/SharedCountryValues.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" +#include "openvic-simulation/country/SharedCountryValues.hpp" #include "openvic-simulation/defines/CountryDefines.hpp" #include "openvic-simulation/defines/DiplomacyDefines.hpp" #include "openvic-simulation/defines/EconomyDefines.hpp" @@ -26,9 +25,9 @@ #include "openvic-simulation/history/CountryHistory.hpp" #include "openvic-simulation/map/Crime.hpp" #include "openvic-simulation/map/MapInstance.hpp" -#include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/military/UnitInstanceGroup.hpp" #include "openvic-simulation/military/UnitType.hpp" +#include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/modifier/StaticModifierCache.hpp" #include "openvic-simulation/politics/Government.hpp" @@ -39,19 +38,21 @@ #include "openvic-simulation/politics/RuleSet.hpp" #include "openvic-simulation/population/Culture.hpp" #include "openvic-simulation/population/Pop.hpp" +#include "openvic-simulation/population/PopSize.hpp" +#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/population/PopType.hpp" #include "openvic-simulation/research/Invention.hpp" #include "openvic-simulation/research/Technology.hpp" #include "openvic-simulation/types/ClampedValue.hpp" #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" -#include "openvic-simulation/population/PopSize.hpp" -#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/Logger.hpp" -#include "openvic-simulation/core/Typedefs.hpp" + +#include "CountryInstanceDeps.hpp" +#include "CountryInstanceManager.hpp" using namespace OpenVic; @@ -61,180 +62,163 @@ static constexpr size_t DAYS_OF_BALANCE_HISTORY = 30; static constexpr colour_t ERROR_COLOUR = colour_t::from_integer(0xFF0000); CountryInstance::CountryInstance( - CountryDefinition const& new_country_definition, - SharedCountryValues& new_shared_country_values, + CountryDefinition const& new_country_definition, SharedCountryValues& new_shared_country_values, CountryInstanceDeps const& country_instance_deps -) : FlagStrings { "country" }, - HasIndex { new_country_definition.index }, - PopsAggregate { - country_instance_deps.stratas, - country_instance_deps.pop_types, - country_instance_deps.ideologies - }, - /* Main attributes */ - country_definition { new_country_definition }, - shared_country_values { new_shared_country_values }, - - country_relations_manager { country_instance_deps.country_relations_manager }, - game_rules_manager { country_instance_deps.game_rules_manager }, - good_instance_manager { country_instance_deps.good_instance_manager }, - market_instance { country_instance_deps.market_instance }, - modifier_effect_cache { country_instance_deps.modifier_effect_cache }, - unit_type_manager { country_instance_deps.unit_type_manager }, - - fallback_date_for_never_completing_research { country_instance_deps.fallback_date_for_never_completing_research }, - country_defines { country_instance_deps.country_defines }, - diplomacy_defines { country_instance_deps.diplomacy_defines }, - economy_defines { country_instance_deps.economy_defines }, - military_defines { country_instance_deps.military_defines }, - - colour { ERROR_COLOUR }, - - /* Production */ - building_type_unlock_levels { country_instance_deps.building_types }, - - /* Budget */ - balance_history{DAYS_OF_BALANCE_HISTORY}, - taxable_income_by_pop_type { country_instance_deps.pop_types }, - effective_tax_rate_by_strata { - country_instance_deps.stratas, - [this](Strata const& strata)->auto { - return [this,&strata](DependencyTracker& tracker)->fixed_point_t { - return tax_efficiency.get(tracker) * tax_rate_slider_value_by_strata.at(strata).get_value(tracker); - }; - } - }, - administration_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_administration_salary_base(tracker); - }; - } - }, - education_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_education_salary_base(tracker); - }; - } - }, - military_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_military_salary_base(tracker); - }; - } - }, - social_income_variant_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_social_income_variant_base(tracker); - }; - } - }, - tax_rate_slider_value_by_strata { country_instance_deps.stratas }, - - /* Technology */ - technology_unlock_levels { country_instance_deps.technologies }, - invention_unlock_levels { country_instance_deps.inventions }, - - /* Politics */ - upper_house_proportion_by_ideology { country_instance_deps.ideologies }, - reforms { country_instance_deps.reforms }, - flag_overrides_by_government_type { country_instance_deps.government_types }, - crime_unlock_levels { country_instance_deps.crimes }, - - /* Trade */ - goods_data { country_instance_deps.good_instances }, - - /* Diplomacy */ - - /* Military */ - regiment_type_unlock_levels { country_instance_deps.regiment_types }, - ship_type_unlock_levels { country_instance_deps.ship_types }, - - /* DerivedState */ - flag_government_type { [this](DependencyTracker& tracker)->GovernmentType const* { - GovernmentType const* current_government_type = government_type.get(tracker); - if (current_government_type == nullptr) { - return nullptr; - } - GovernmentType const* flag_override = flag_overrides_by_government_type.at(*current_government_type); - return flag_override == nullptr - ? current_government_type - : flag_override; - }}, - total_score{[this](DependencyTracker& tracker)->fixed_point_t { - return prestige.get(tracker) + industrial_power.get(tracker) + military_power.get(tracker); - }}, - military_power{[this](DependencyTracker& tracker)->fixed_point_t { - return military_power_from_land.get(tracker) + military_power_from_sea.get(tracker) + military_power_from_leaders.get(tracker); - }}, - research_progress{[this](DependencyTracker& tracker)->fixed_point_t { - const fixed_point_t current_research_cost_copy = current_research_cost.get(tracker); - return current_research_cost_copy > 0 - ? invested_research_points.get(tracker) / current_research_cost_copy - : fixed_point_t::_0; - }}, - desired_administrator_percentage{[this](DependencyTracker& tracker)->fixed_point_t { - return country_defines.get_max_bureaucracy_percentage() - + total_administrative_multiplier.get(tracker) * country_defines.get_bureaucracy_percentage_increment(); - }}, - corruption_cost_multiplier{[this](DependencyTracker& tracker)->fixed_point_t { - return 2 - administrative_efficiency_from_administrators.get(tracker); - }}, - tariff_efficiency{[this](DependencyTracker& tracker)->fixed_point_t { - return std::min( - fixed_point_t::_1, - administrative_efficiency_from_administrators.get(tracker) + country_defines.get_base_country_tax_efficiency() - ); - }}, - effective_tariff_rate{[this](DependencyTracker& tracker)->fixed_point_t { - return administrative_efficiency_from_administrators.get(tracker) * tariff_rate_slider_value.get_value(tracker); - }}, - projected_administration_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return administration_spending_slider_value.get_value(tracker) * projected_administration_spending_unscaled_by_slider.get(tracker); - }}, - projected_education_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return education_spending_slider_value.get_value(tracker) * projected_education_spending_unscaled_by_slider.get(tracker); - }}, - projected_military_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return military_spending_slider_value.get_value(tracker) * projected_military_spending_unscaled_by_slider.get(tracker); - }}, - projected_social_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return social_spending_slider_value.get_value(tracker) * projected_social_spending_unscaled_by_slider.get(tracker); - }}, - projected_social_spending_unscaled_by_slider{[this](DependencyTracker& tracker)->fixed_point_t { - return projected_pensions_spending_unscaled_by_slider.get(tracker) - + projected_unemployment_subsidies_spending_unscaled_by_slider.get(tracker); - }}, - projected_import_subsidies{[this](DependencyTracker& tracker)->fixed_point_t { - return has_import_subsidies.get(tracker) - ? -effective_tariff_rate.get(tracker) * get_yesterdays_import_value(tracker) - : fixed_point_t::_0; - }}, - projected_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return projected_administration_spending.get(tracker) - + projected_education_spending.get(tracker) - + projected_military_spending.get(tracker) - + projected_social_spending.get(tracker) - + projected_import_subsidies.get(tracker); - }}, - has_import_subsidies{[this](DependencyTracker& tracker)->bool { - return effective_tariff_rate.get(tracker) < 0; - }} { +) + : FlagStrings { "country" }, HasIndex { new_country_definition.index }, + PopsAggregate { country_instance_deps.stratas, country_instance_deps.pop_types, country_instance_deps.ideologies }, + /* Main attributes */ + country_definition { new_country_definition }, shared_country_values { new_shared_country_values }, + + country_relations_manager { country_instance_deps.country_relations_manager }, + game_rules_manager { country_instance_deps.game_rules_manager }, + good_instance_manager { country_instance_deps.good_instance_manager }, + market_instance { country_instance_deps.market_instance }, + modifier_effect_cache { country_instance_deps.modifier_effect_cache }, + unit_type_manager { country_instance_deps.unit_type_manager }, + + fallback_date_for_never_completing_research { country_instance_deps.fallback_date_for_never_completing_research }, + country_defines { country_instance_deps.country_defines }, diplomacy_defines { country_instance_deps.diplomacy_defines }, + economy_defines { country_instance_deps.economy_defines }, military_defines { country_instance_deps.military_defines }, + + colour { ERROR_COLOUR }, + + /* Production */ + building_type_unlock_levels { country_instance_deps.building_types }, + + /* Budget */ + balance_history { DAYS_OF_BALANCE_HISTORY }, taxable_income_by_pop_type { country_instance_deps.pop_types }, + effective_tax_rate_by_strata { country_instance_deps.stratas, + [this](Strata const& strata) -> auto { + return [this, &strata](DependencyTracker& tracker) -> fixed_point_t { + return tax_efficiency.get(tracker) * + tax_rate_slider_value_by_strata.at(strata).get_value(tracker); + }; + } }, + administration_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_administration_salary_base(tracker); + }; + } + }, + education_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_education_salary_base(tracker); + }; + } + }, + military_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_military_salary_base(tracker); + }; + } + }, + social_income_variant_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_social_income_variant_base(tracker); + }; + } + }, + tax_rate_slider_value_by_strata { country_instance_deps.stratas }, + + /* Technology */ + technology_unlock_levels { country_instance_deps.technologies }, + invention_unlock_levels { country_instance_deps.inventions }, + + /* Politics */ + upper_house_proportion_by_ideology { country_instance_deps.ideologies }, reforms { country_instance_deps.reforms }, + flag_overrides_by_government_type { country_instance_deps.government_types }, + crime_unlock_levels { country_instance_deps.crimes }, + + /* Trade */ + goods_data { country_instance_deps.good_instances }, + + /* Diplomacy */ + + /* Military */ + regiment_type_unlock_levels { country_instance_deps.regiment_types }, + ship_type_unlock_levels { country_instance_deps.ship_types }, + + /* DerivedState */ + flag_government_type { [this](DependencyTracker& tracker) -> GovernmentType const* { + GovernmentType const* current_government_type = government_type.get(tracker); + if (current_government_type == nullptr) { + return nullptr; + } + GovernmentType const* flag_override = flag_overrides_by_government_type.at(*current_government_type); + return flag_override == nullptr ? current_government_type : flag_override; + } }, + total_score { [this](DependencyTracker& tracker) -> fixed_point_t { + return prestige.get(tracker) + industrial_power.get(tracker) + military_power.get(tracker); + } }, + military_power { [this](DependencyTracker& tracker) -> fixed_point_t { + return military_power_from_land.get(tracker) + military_power_from_sea.get(tracker) + + military_power_from_leaders.get(tracker); + } }, + research_progress { [this](DependencyTracker& tracker) -> fixed_point_t { + const fixed_point_t current_research_cost_copy = current_research_cost.get(tracker); + return current_research_cost_copy > 0 ? invested_research_points.get(tracker) / current_research_cost_copy + : fixed_point_t::_0; + } }, + desired_administrator_percentage { [this](DependencyTracker& tracker) -> fixed_point_t { + return country_defines.get_max_bureaucracy_percentage() + + total_administrative_multiplier.get(tracker) * country_defines.get_bureaucracy_percentage_increment(); + } }, + corruption_cost_multiplier { [this](DependencyTracker& tracker) -> fixed_point_t { + return 2 - administrative_efficiency_from_administrators.get(tracker); + } }, + tariff_efficiency { [this](DependencyTracker& tracker) -> fixed_point_t { + return std::min( + fixed_point_t::_1, + administrative_efficiency_from_administrators.get(tracker) + country_defines.get_base_country_tax_efficiency() + ); + } }, + effective_tariff_rate { [this](DependencyTracker& tracker) -> fixed_point_t { + return administrative_efficiency_from_administrators.get(tracker) * tariff_rate_slider_value.get_value(tracker); + } }, + projected_administration_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return administration_spending_slider_value.get_value(tracker) * + projected_administration_spending_unscaled_by_slider.get(tracker); + } }, + projected_education_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return education_spending_slider_value.get_value(tracker) * + projected_education_spending_unscaled_by_slider.get(tracker); + } }, + projected_military_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return military_spending_slider_value.get_value(tracker) * + projected_military_spending_unscaled_by_slider.get(tracker); + } }, + projected_social_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return social_spending_slider_value.get_value(tracker) * projected_social_spending_unscaled_by_slider.get(tracker); + } }, + projected_social_spending_unscaled_by_slider { [this](DependencyTracker& tracker) -> fixed_point_t { + return projected_pensions_spending_unscaled_by_slider.get(tracker) + + projected_unemployment_subsidies_spending_unscaled_by_slider.get(tracker); + } }, + projected_import_subsidies { [this](DependencyTracker& tracker) -> fixed_point_t { + return has_import_subsidies.get(tracker) ? -effective_tariff_rate.get(tracker) * get_yesterdays_import_value(tracker) + : fixed_point_t::_0; + } }, + projected_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return projected_administration_spending.get(tracker) + projected_education_spending.get(tracker) + + projected_military_spending.get(tracker) + projected_social_spending.get(tracker) + + projected_import_subsidies.get(tracker); + } }, + has_import_subsidies { [this](DependencyTracker& tracker) -> bool { + return effective_tariff_rate.get(tracker) < 0; + } } { modifier_sum.set_this_source(this); // Exclude PROVINCE (local) modifier effects from the country's modifier sum modifier_sum.set_this_excluded_targets(ModifierEffect::target_t::PROVINCE); @@ -254,9 +238,7 @@ CountryInstance::CountryInstance( navy_spending_slider_value.set_bounds(economy_defines.get_minimum_navy_spending_slider_value(), 1); navy_spending_slider_value.set_value(1); - construction_spending_slider_value.set_bounds( - economy_defines.get_minimum_construction_spending_slider_value(), 1 - ); + construction_spending_slider_value.set_bounds(economy_defines.get_minimum_construction_spending_slider_value(), 1); construction_spending_slider_value.set_value(1); education_spending_slider_value.set_bounds(0, 1); @@ -337,28 +319,27 @@ bool CountryInstance::is_neighbour(CountryInstance const& country) const { return neighbouring_countries.contains(&country); } -bool CountryInstance::may_build_in(const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location) const { +bool CountryInstance::may_build_in( + const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location +) const { CountryInstance const* const owner_ptr = location.get_owner(); if (owner_ptr == nullptr) { - //Can't build in uncolonised provinces + // Can't build in uncolonised provinces return false; } CountryInstance const& owner = *owner_ptr; if (owner == *this) { - switch(restriction_category) { - case BuildingRestrictionCategory::UNRESTRICTED: - return true; - case BuildingRestrictionCategory::INFRASTRUCTURE: - return rule_set.may_expand_infrastructure_domestically(); - case BuildingRestrictionCategory::FACTORY: - return rule_set.may_build_factory_domestically(); + switch (restriction_category) { + case BuildingRestrictionCategory::UNRESTRICTED: return true; + case BuildingRestrictionCategory::INFRASTRUCTURE: return rule_set.may_expand_infrastructure_domestically(); + case BuildingRestrictionCategory::FACTORY: return rule_set.may_build_factory_domestically(); } } - + if (is_at_war_with(owner)) { - //Not allowed to build in hostile lands. + // Not allowed to build in hostile lands. return false; } @@ -366,13 +347,10 @@ bool CountryInstance::may_build_in(const BuildingRestrictionCategory restriction return false; } - switch(restriction_category) { - case BuildingRestrictionCategory::UNRESTRICTED: - return false; //For example you can't invest in foreign forts. - case BuildingRestrictionCategory::INFRASTRUCTURE: - return rule_set.may_invest_in_expanding_infrastructure_abroad(); - case BuildingRestrictionCategory::FACTORY: - return rule_set.may_invest_in_building_factory_abroad(); + switch (restriction_category) { + case BuildingRestrictionCategory::UNRESTRICTED: return false; // For example you can't invest in foreign forts. + case BuildingRestrictionCategory::INFRASTRUCTURE: return rule_set.may_invest_in_expanding_infrastructure_abroad(); + case BuildingRestrictionCategory::FACTORY: return rule_set.may_invest_in_building_factory_abroad(); } } @@ -444,7 +422,9 @@ CountryRelationManager::OpinionType CountryInstance::get_opinion_of(CountryInsta } void CountryInstance::set_opinion_of(CountryInstance& country, CountryRelationManager::OpinionType opinion) { - if (OV_unlikely(country.sphere_owner.get_untracked() != nullptr && opinion == CountryRelationManager::OpinionType::Sphere)) { + if (OV_unlikely( + country.sphere_owner.get_untracked() != nullptr && opinion == CountryRelationManager::OpinionType::Sphere + )) { spdlog::warn_s("Attempting to add '{}' to a sphere when it is already included in a sphere.", country); } country_relations_manager.set_country_opinion(this, &country, opinion); @@ -475,11 +455,14 @@ void CountryInstance::set_influence_with(CountryInstance& country, CountryRelati country_relations_manager.set_influence_with(this, &country, influence); } -CountryRelationManager::influence_priority_value_type CountryInstance::get_influence_priority_with(CountryInstance const& country) const { +CountryRelationManager::influence_priority_value_type +CountryInstance::get_influence_priority_with(CountryInstance const& country) const { return country_relations_manager.get_influence_priority_with(this, &country); } -void CountryInstance::set_influence_priority_with(CountryInstance& country, CountryRelationManager::influence_priority_value_type influence) { +void CountryInstance::set_influence_priority_with( + CountryInstance& country, CountryRelationManager::influence_priority_value_type influence +) { country_relations_manager.set_influence_priority_with(this, &country, influence); } @@ -534,7 +517,7 @@ fixed_point_t CountryInstance::get_taxable_income_by_strata(Strata const& strata running_total += taxable_income; } } - + return running_total; } DerivedState& CountryInstance::get_effective_tax_rate_by_strata(Strata const& strata) { @@ -705,15 +688,11 @@ bool CountryInstance::add_unit_instance_group(UnitInstanceGroup& group) { using enum unit_branch_t; switch (group.branch) { - case LAND: - armies.emplace_back(static_cast(group)); - return true; - case NAVAL: - navies.emplace_back(static_cast(group)); - return true; + case LAND: armies.emplace_back(static_cast(group)); return true; + case NAVAL: navies.emplace_back(static_cast(group)); return true; default: spdlog::error_s( - "Trying to add unit group \"{}\" with invalid branch {} to country {}", + "Trying to add unit group \"{}\" with invalid branch {} to country {}", // group.get_name(), static_cast(group.branch), *this ); return false; @@ -721,21 +700,18 @@ bool CountryInstance::add_unit_instance_group(UnitInstanceGroup& group) { } bool CountryInstance::remove_unit_instance_group(UnitInstanceGroup const& group) { - const auto remove_from_vector = [this, &group]( - memory::vector>>& unit_instance_groups - ) -> bool { - const auto it = std::find( - unit_instance_groups.begin(), - unit_instance_groups.end(), - group - ); + const auto remove_from_vector = + [this, &group]( + memory::vector>>& unit_instance_groups + ) -> bool { + const auto it = std::find(unit_instance_groups.begin(), unit_instance_groups.end(), group); if (it != unit_instance_groups.end()) { unit_instance_groups.erase(it); return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from country {}", + "Trying to remove non-existent {} \"{}\" from country {}", // get_branched_unit_group_name(Branch), group.get_name(), *this ); return false; @@ -745,13 +721,11 @@ bool CountryInstance::remove_unit_instance_group(UnitInstanceGroup const& group) using enum unit_branch_t; switch (group.branch) { - case LAND: - return remove_from_vector(armies); - case NAVAL: - return remove_from_vector(navies); + case LAND: return remove_from_vector(armies); + case NAVAL: return remove_from_vector(navies); default: spdlog::error_s( - "Trying to remove unit group \"{}\" with invalid branch {} from country {}", + "Trying to remove unit group \"{}\" with invalid branch {} from country {}", // group.get_name(), static_cast(group.branch), *this ); return false; @@ -762,15 +736,11 @@ bool CountryInstance::add_leader(LeaderInstance& leader) { using enum unit_branch_t; switch (leader.branch) { - case LAND: - generals.push_back(leader); - return true; - case NAVAL: - admirals.push_back(leader); - return true; + case LAND: generals.push_back(leader); return true; + case NAVAL: admirals.push_back(leader); return true; default: spdlog::error_s( - "Trying to add leader \"{}\" with invalid branch {} to country {}", + "Trying to add leader \"{}\" with invalid branch {} to country {}", // leader.get_name(), static_cast(leader.branch), *this ); return false; @@ -783,15 +753,11 @@ bool CountryInstance::remove_leader(LeaderInstance const& leader) { memory::vector>* leaders; switch (leader.branch) { - case LAND: - leaders = &generals; - break; - case NAVAL: - leaders = &admirals; - break; + case LAND: leaders = &generals; break; + case NAVAL: leaders = &admirals; break; default: spdlog::error_s( - "Trying to remove leader \"{}\" with invalid branch {} from country {}", + "Trying to remove leader \"{}\" with invalid branch {} from country {}", // leader.get_name(), static_cast(leader.branch), *this ); return false; @@ -804,17 +770,15 @@ bool CountryInstance::remove_leader(LeaderInstance const& leader) { return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from country {}", - get_branched_leader_name(leader.branch), leader.get_name(), *this + "Trying to remove non-existent {} \"{}\" from country {}", // + get_branched_leader_name(leader.branch), leader.get_name(), *this ); return false; } } bool CountryInstance::has_leader_with_name(std::string_view name) const { - const auto check_leaders = [name]( - memory::vector> const& leaders - ) -> bool { + const auto check_leaders = [name](memory::vector> const& leaders) -> bool { for (LeaderInstance const& leader : leaders) { if (leader.get_name() == name) { return true; @@ -827,16 +791,19 @@ bool CountryInstance::has_leader_with_name(std::string_view name) const { } template -bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const& unit_type, technology_unlock_level_t unlock_level_change) { - IndexedFlatMap, technology_unlock_level_t>& unlocked_unit_types = get_unit_type_unlock_levels(); +bool CountryInstance::modify_unit_type_unlock( + UnitTypeBranched const& unit_type, technology_unlock_level_t unlock_level_change +) { + IndexedFlatMap, technology_unlock_level_t>& unlocked_unit_types = + get_unit_type_unlock_levels(); technology_unlock_level_t& unlock_level = unlocked_unit_types.at(unit_type); // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for unit type {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - unit_type, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for unit type {} in country {} to invalid value: current level = {}, " + "change = {}, invalid new value = {}", + unit_type, *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); return false; } @@ -850,7 +817,7 @@ bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const& un if (was_unlocked != is_unlocked) { if (was_unlocked) { - //recalculate entirely + // recalculate entirely allowed_regiment_cultures = regiment_allowed_cultures_t::NO_CULTURES; for (RegimentType const& regiment_type : unlocked_unit_types.get_keys()) { if (!is_unit_type_unlocked(regiment_type)) { @@ -858,15 +825,12 @@ bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const& un } allowed_regiment_cultures = RegimentType::allowed_cultures_get_most_permissive( - allowed_regiment_cultures, - regiment_type.allowed_cultures + allowed_regiment_cultures, regiment_type.allowed_cultures ); } } else { - allowed_regiment_cultures = RegimentType::allowed_cultures_get_most_permissive( - allowed_regiment_cultures, - unit_type.allowed_cultures - ); + allowed_regiment_cultures = + RegimentType::allowed_cultures_get_most_permissive(allowed_regiment_cultures, unit_type.allowed_cultures); } } } @@ -875,19 +839,18 @@ bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const& un } template bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const&, technology_unlock_level_t); -template bool CountryInstance::modify_unit_type_unlock(UnitTypeBranched const&, technology_unlock_level_t); +template bool +CountryInstance::modify_unit_type_unlock(UnitTypeBranched const&, technology_unlock_level_t); bool CountryInstance::modify_unit_type_unlock(UnitType const& unit_type, technology_unlock_level_t unlock_level_change) { using enum unit_branch_t; switch (unit_type.branch) { - case LAND: - return modify_unit_type_unlock(static_cast const&>(unit_type), unlock_level_change); - case NAVAL: - return modify_unit_type_unlock(static_cast const&>(unit_type), unlock_level_change); + case LAND: return modify_unit_type_unlock(static_cast const&>(unit_type), unlock_level_change); + case NAVAL: return modify_unit_type_unlock(static_cast const&>(unit_type), unlock_level_change); default: spdlog::error_s( - "Attempted to change unlock level for unit type \"{}\" with invalid branch {} for country {}", + "Attempted to change unlock level for unit type \"{}\" with invalid branch {} for country {}", // unit_type, static_cast(unit_type.branch), *this ); return false; @@ -902,13 +865,11 @@ bool CountryInstance::is_unit_type_unlocked(UnitType const& unit_type) const { using enum unit_branch_t; switch (unit_type.branch) { - case LAND: - return regiment_type_unlock_levels.at(static_cast const&>(unit_type)) > 0; - case NAVAL: - return ship_type_unlock_levels.at(static_cast const&>(unit_type)) > 0; + case LAND: return regiment_type_unlock_levels.at(static_cast const&>(unit_type)) > 0; + case NAVAL: return ship_type_unlock_levels.at(static_cast const&>(unit_type)) > 0; default: spdlog::error_s( - "Attempted to check if unit type \"{}\" with invalid branch {} is unlocked for country {}", + "Attempted to check if unit type \"{}\" with invalid branch {} is unlocked for country {}", // unit_type, static_cast(unit_type.branch), *this ); return false; @@ -924,9 +885,9 @@ bool CountryInstance::modify_building_type_unlock( // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < building_level_t(0)) { spdlog::error_s( - "Attempted to change unlock level for building type {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - building_type, *this, unlock_level, unlock_level_change, - unlock_level + unlock_level_change + "Attempted to change unlock level for building type {} in country {} to invalid value: current level = {}, " + "change = {}, invalid new value = {}", + building_type, *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); return false; } @@ -958,9 +919,9 @@ bool CountryInstance::modify_crime_unlock(Crime const& crime, technology_unlock_ // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for crime {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - crime, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for crime {} in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + crime, *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); return false; } @@ -982,9 +943,9 @@ bool CountryInstance::modify_gas_attack_unlock(technology_unlock_level_t unlock_ // This catches subtracting below 0 or adding above the int types maximum value if (gas_attack_unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for gas attack in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - *this, gas_attack_unlock_level, - unlock_level_change, gas_attack_unlock_level + unlock_level_change + "Attempted to change unlock level for gas attack in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + *this, gas_attack_unlock_level, unlock_level_change, gas_attack_unlock_level + unlock_level_change ); return false; } @@ -1006,9 +967,9 @@ bool CountryInstance::modify_gas_defence_unlock(technology_unlock_level_t unlock // This catches subtracting below 0 or adding above the int types maximum value if (gas_defence_unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for gas defence in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - *this, gas_defence_unlock_level, - unlock_level_change, gas_defence_unlock_level + unlock_level_change + "Attempted to change unlock level for gas defence in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + *this, gas_defence_unlock_level, unlock_level_change, gas_defence_unlock_level + unlock_level_change ); return false; } @@ -1043,9 +1004,9 @@ bool CountryInstance::modify_unit_variant_unlock(unit_variant_t unit_variant, te // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for unit variant {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - static_cast(unit_variant), *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for unit variant {} in country {} to invalid value: current level = {}, " + "change = {}, invalid new value = {}", + static_cast(unit_variant), *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); ret = false; } else { @@ -1067,17 +1028,15 @@ unit_variant_t CountryInstance::get_max_unlocked_unit_variant() const { return unit_variant_unlock_levels.size(); } -bool CountryInstance::modify_technology_unlock( - Technology const& technology, technology_unlock_level_t unlock_level_change -) { +bool CountryInstance::modify_technology_unlock(Technology const& technology, technology_unlock_level_t unlock_level_change) { technology_unlock_level_t& unlock_level = technology_unlock_levels.at(technology); // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for technology {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - technology, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for technology {} in country {} to invalid value: current level = {}, " + "change = {}, invalid new value = {}", + technology, *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); return false; } @@ -1101,9 +1060,7 @@ bool CountryInstance::modify_technology_unlock( return ret; } -bool CountryInstance::set_technology_unlock_level( - Technology const& technology, technology_unlock_level_t unlock_level -) { +bool CountryInstance::set_technology_unlock_level(Technology const& technology, technology_unlock_level_t unlock_level) { const technology_unlock_level_t unlock_level_change = unlock_level - technology_unlock_levels.at(technology); return unlock_level_change != 0 ? modify_technology_unlock(technology, unlock_level_change) : true; } @@ -1116,17 +1073,15 @@ bool CountryInstance::is_technology_unlocked(Technology const& technology) const return technology_unlock_levels.at(technology) > 0; } -bool CountryInstance::modify_invention_unlock( - Invention const& invention, technology_unlock_level_t unlock_level_change -) { +bool CountryInstance::modify_invention_unlock(Invention const& invention, technology_unlock_level_t unlock_level_change) { technology_unlock_level_t& unlock_level = invention_unlock_levels.at(invention); // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for invention {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - invention, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for invention {} in country {} to invalid value: current level = {}, " + "change = {}, invalid new value = {}", + invention, *this, unlock_level, unlock_level_change, unlock_level + unlock_level_change ); return false; } @@ -1135,9 +1090,9 @@ bool CountryInstance::modify_invention_unlock( unlock_level += unlock_level_change; if (invention_was_unlocked != (unlock_level > 0)) { if (invention_was_unlocked) { - inventions_count-=1; + inventions_count -= 1; } else { - inventions_count+=1; + inventions_count += 1; } } @@ -1164,9 +1119,7 @@ bool CountryInstance::modify_invention_unlock( return ret; } -bool CountryInstance::set_invention_unlock_level( - Invention const& invention, technology_unlock_level_t unlock_level -) { +bool CountryInstance::set_invention_unlock_level(Invention const& invention, technology_unlock_level_t unlock_level) { const technology_unlock_level_t unlock_level_change = unlock_level - invention_unlock_levels.at(invention); return unlock_level_change != 0 ? modify_invention_unlock(invention, unlock_level_change) : true; } @@ -1193,19 +1146,15 @@ bool CountryInstance::is_primary_or_accepted_culture(Culture const& culture) con fixed_point_t CountryInstance::calculate_research_cost(Technology const& technology) const { // TODO - what if research bonus is -100%? Divide by 0 -> infinite cost? - return technology.cost / (fixed_point_t::_1 + get_modifier_effect_value( - *modifier_effect_cache.get_research_bonus_effects(technology.area.folder) - )); + return technology.cost / + (fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_research_bonus_effects(technology.area.folder))); } bool CountryInstance::can_research_tech(Technology const& technology, const Date today) const { Technology const* current_research_copy = current_research.get_untracked(); - if ( - technology.year > today.get_year() - || !is_civilised() - || is_technology_unlocked(technology) - || (current_research_copy && technology == *current_research_copy) - ) { + if (technology.year > today.get_year() || !is_civilised() || is_technology_unlocked(technology) || + (current_research_copy && technology == *current_research_copy)) { return false; } @@ -1217,7 +1166,7 @@ bool CountryInstance::can_research_tech(Technology const& technology, const Date void CountryInstance::start_research(Technology const& technology, const Date today) { if (OV_unlikely(!can_research_tech(technology, today))) { spdlog::warn_s( - "Attempting to start research for country \"{}\" on technology \"{}\" - cannot research this tech!", + "Attempting to start research for country \"{}\" on technology \"{}\" - cannot research this tech!", // *this, technology ); return; @@ -1238,9 +1187,7 @@ void CountryInstance::apply_foreign_investments( } bool CountryInstance::apply_history_to_country( - CountryHistoryEntry const& entry, - CountryInstanceManager const& country_instance_manager, - FlagStrings& global_flags, + CountryHistoryEntry const& entry, CountryInstanceManager const& country_instance_manager, FlagStrings& global_flags, MapInstance& map_instance ) { constexpr auto set_optional = [](T& target, std::optional const& source) { @@ -1331,11 +1278,8 @@ void CountryInstance::_update_production() { for (auto const& [country, money_invested] : foreign_investments) { if (country.get().exists()) { - const fixed_point_t investment_industrial_power = fixed_point_t::mul_div( - money_invested, - country_defines.get_country_investment_industrial_score_factor(), - 100 - ); + const fixed_point_t investment_industrial_power = + fixed_point_t::mul_div(money_invested, country_defines.get_country_investment_industrial_score_factor(), 100); if (investment_industrial_power != 0) { industrial_power += investment_industrial_power; @@ -1347,12 +1291,15 @@ void CountryInstance::_update_production() { industrial_power.set(industrial_power_running_total); std::stable_sort( - industrial_power_from_states.begin(), industrial_power_from_states.end(), - [](auto const& a, auto const& b) -> bool { return a.second > b.second; } + industrial_power_from_states.begin(), industrial_power_from_states.end(), [](auto const& a, auto const& b) -> bool { + return a.second > b.second; + } ); std::stable_sort( industrial_power_from_investments.begin(), industrial_power_from_investments.end(), - [](auto const& a, auto const& b) -> bool { return a.second > b.second; } + [](auto const& a, auto const& b) -> bool { + return a.second > b.second; + } ); } @@ -1387,9 +1334,9 @@ void CountryInstance::_update_budget() { // as they might change if their sliders' bounds shrink past their previous values. tax_efficiency.set( - country_defines.get_base_country_tax_efficiency() - + get_modifier_effect_value(*modifier_effect_cache.get_tax_efficiency()) - + get_modifier_effect_value(*modifier_effect_cache.get_tax_eff()) / 100 + country_defines.get_base_country_tax_efficiency() + + get_modifier_effect_value(*modifier_effect_cache.get_tax_efficiency()) + + get_modifier_effect_value(*modifier_effect_cache.get_tax_eff()) / 100 ); /* @@ -1424,30 +1371,28 @@ void CountryInstance::_update_budget() { if (total_non_colonial_population == 0) { administrative_efficiency_from_administrators.set(fixed_point_t::_1); administrator_percentage.set(fixed_point_t::_0); - } else { + } else { administrator_percentage.set(fixed_point_t::from_fraction(administrators, total_non_colonial_population)); - const pop_sum_t desired_administrators = fixed_point_t::multiply_truncate( - total_non_colonial_population, - desired_administrator_percentage.get_untracked() - ); + const pop_sum_t desired_administrators = + fixed_point_t::multiply_truncate(total_non_colonial_population, desired_administrator_percentage.get_untracked()); const pop_sum_t effective_administrators = fixed_point_t::multiply_truncate( administrators, fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency()) ); - const fixed_point_t administrative_efficiency_from_administrators_unclamped = - desired_administrators == 0 + const fixed_point_t administrative_efficiency_from_administrators_unclamped = desired_administrators == 0 ? fixed_point_t::_1 : std::min( - fixed_point_t::from_fraction(effective_administrators, desired_administrators) - * (fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency_modifier())), - fixed_point_t::_1 - ); + fixed_point_t::from_fraction(effective_administrators, desired_administrators) * + (fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency_modifier())), + fixed_point_t::_1 + ); administrative_efficiency_from_administrators.set( game_rules_manager.get_prevent_negative_administration_efficiency() - ? std::max(fixed_point_t::_0, administrative_efficiency_from_administrators_unclamped) - : administrative_efficiency_from_administrators_unclamped + ? std::max(fixed_point_t::_0, administrative_efficiency_from_administrators_unclamped) + : administrative_efficiency_from_administrators_unclamped ); } @@ -1459,46 +1404,51 @@ void CountryInstance::_update_budget() { for (auto const& [pop_type, pop_size] : get_population_by_type()) { const int64_t size = type_safe::get(pop_size); - projected_administration_spending_unscaled_by_slider_running_total += size * administration_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_education_spending_unscaled_by_slider_running_total += size * education_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_military_spending_unscaled_by_slider_running_total += size * military_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_pensions_spending_unscaled_by_slider_running_total += size * calculate_pensions_base(pop_type).get_raw_value(); - projected_unemployment_subsidies_spending_unscaled_by_slider_running_total += type_safe::get(get_unemployed_pops_by_type(pop_type)) - * calculate_unemployment_subsidies_base(pop_type).get_raw_value(); + projected_administration_spending_unscaled_by_slider_running_total += + size * administration_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_education_spending_unscaled_by_slider_running_total += + size * education_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_military_spending_unscaled_by_slider_running_total += + size * military_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_pensions_spending_unscaled_by_slider_running_total += + size * calculate_pensions_base(pop_type).get_raw_value(); + projected_unemployment_subsidies_spending_unscaled_by_slider_running_total += + type_safe::get(get_unemployed_pops_by_type(pop_type)) * + calculate_unemployment_subsidies_base(pop_type).get_raw_value(); } const int64_t denominator = type_safe::get(Pop::size_denominator); - projected_administration_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_administration_spending_unscaled_by_slider_running_total / denominator - )); - projected_education_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_education_spending_unscaled_by_slider_running_total / denominator - )); - projected_military_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_military_spending_unscaled_by_slider_running_total / denominator - )); - projected_pensions_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_pensions_spending_unscaled_by_slider_running_total / denominator - )); - projected_unemployment_subsidies_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_unemployment_subsidies_spending_unscaled_by_slider_running_total / denominator - )); + projected_administration_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_administration_spending_unscaled_by_slider_running_total / denominator) + ); + projected_education_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_education_spending_unscaled_by_slider_running_total / denominator) + ); + projected_military_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_military_spending_unscaled_by_slider_running_total / denominator) + ); + projected_pensions_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_pensions_spending_unscaled_by_slider_running_total / denominator) + ); + projected_unemployment_subsidies_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_unemployment_subsidies_spending_unscaled_by_slider_running_total / denominator) + ); } fixed_point_t CountryInstance::calculate_pensions_base(PopType const& pop_type) { - return get_modifier_effect_value(*modifier_effect_cache.get_pension_level()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_pension_level()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } fixed_point_t CountryInstance::calculate_unemployment_subsidies_base(PopType const& pop_type) { - return get_modifier_effect_value(*modifier_effect_cache.get_unemployment_benefit()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_unemployment_benefit()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } fixed_point_t CountryInstance::calculate_minimum_wage_base(PopType const& pop_type) { if (pop_type.is_slave) { return 0; } - return get_modifier_effect_value(*modifier_effect_cache.get_minimum_wage()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_minimum_wage()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } void CountryInstance::_update_current_tech(const Date today) { @@ -1507,19 +1457,18 @@ void CountryInstance::_update_current_tech(const Date today) { return; } - current_research_cost.set( - calculate_research_cost(*current_research_copy) - ); + current_research_cost.set(calculate_research_cost(*current_research_copy)); const fixed_point_t daily_research_points_copy = daily_research_points.get_untracked(); if (daily_research_points_copy > 0) { expected_research_completion_date.set( - today - + static_cast( + today + + static_cast( ( - (current_research_cost.get_untracked() - invested_research_points.get_untracked()) - / daily_research_points_copy - ).ceil() + (current_research_cost.get_untracked() - invested_research_points.get_untracked()) / + daily_research_points_copy // + ) + .ceil() // ) ); } else { @@ -1544,9 +1493,7 @@ void CountryInstance::_update_technology(const Date today) { _update_current_tech(today); } -void CountryInstance::_update_politics() { - -} +void CountryInstance::_update_politics() {} void CountryInstance::_update_population() { clear_pops_aggregate(); @@ -1564,18 +1511,11 @@ void CountryInstance::_update_population() { for (auto const& [pop_type, pop_size] : get_population_by_type()) { if (pop_type.research_leadership_optimum > 0 && pop_size > 0) { - const pop_sum_t optimum_size = fixed_point_t::multiply_truncate( - get_total_population(), - pop_type.research_leadership_optimum - ); + const pop_sum_t optimum_size = + fixed_point_t::multiply_truncate(get_total_population(), pop_type.research_leadership_optimum); const fixed_point_t factor = optimum_size == 0 ? fixed_point_t::_1 - : std::min( - fixed_point_t::from_fraction( - pop_size, - optimum_size - ), fixed_point_t::_1 - ); + : std::min(fixed_point_t::from_fraction(pop_size, optimum_size), fixed_point_t::_1); if (pop_type.research_points != 0) { const fixed_point_t research_points = pop_type.research_points * factor; @@ -1638,9 +1578,9 @@ void CountryInstance::_update_military() { } military_power_from_land.set( - supply_consumption * fixed_point_t::mul_div( - sum_of_regiment_type_stats, - fixed_point_t::parse_raw(regular_army_size), + supply_consumption * + fixed_point_t::mul_div( + sum_of_regiment_type_stats, fixed_point_t::parse_raw(regular_army_size), fixed_point_t::parse_raw(7 * (1 + unit_type_manager.get_regiment_type_count())) ) ); @@ -1658,20 +1598,15 @@ void CountryInstance::_update_military() { // TODO - include gun power and hull modifiers + naval attack and defense modifiers - military_power_from_sea_running_total += (ship_type.gun_power /*+ naval_attack_modifier*/) - * (ship_type.hull /* + naval_defense_modifier*/); + military_power_from_sea_running_total += + (ship_type.gun_power /*+ naval_attack_modifier*/) * (ship_type.hull /* + naval_defense_modifier*/); } } } military_power_from_sea.set(military_power_from_sea_running_total / 250); military_power_from_leaders.set( - fixed_point_t::parse_capped( - std::min( - get_leader_count(), - deployed_non_mobilised_regiments - ) - ) + fixed_point_t::parse_capped(std::min(get_leader_count(), deployed_non_mobilised_regiments)) ); // Mobilisation calculations @@ -1679,10 +1614,10 @@ void CountryInstance::_update_military() { mobilisation_economy_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_tech()) + get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_country()); - // TODO - use country_defines.get_min_mobilize_limit(); (wiki: "lowest maximum of brigades you can mobilize. (by default 3)") + // TODO - use country_defines.get_min_mobilize_limit(); (wiki: "lowest maximum of brigades you can mobilize. (by default + // 3)") - mobilisation_max_regiment_count = regiment_count - + fixed_point_t::multiply_truncate(regiment_count, mobilisation_impact); + mobilisation_max_regiment_count = regiment_count + fixed_point_t::multiply_truncate(regiment_count, mobilisation_impact); mobilisation_potential_regiment_count = 0; // TODO - calculate max regiments from poor citizens if (mobilisation_potential_regiment_count > mobilisation_max_regiment_count) { @@ -1692,12 +1627,10 @@ void CountryInstance::_update_military() { // Limit max war exhaustion to non-negative values. This technically diverges from the base game where // max war exhaustion can be negative, but in such cases the war exhaustion clamping behaviour is // very buggy and regardless it doesn't seem to make any modifier effect contributions. - war_exhaustion_max = std::max( - get_modifier_effect_value(*modifier_effect_cache.get_max_war_exhaustion()), fixed_point_t::_0 - ); + war_exhaustion_max = + std::max(get_modifier_effect_value(*modifier_effect_cache.get_max_war_exhaustion()), fixed_point_t::_0); - organisation_regain = fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + + organisation_regain = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); land_organisation = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_land_organisation()); @@ -1710,12 +1643,11 @@ void CountryInstance::_update_military() { recruit_time = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_unit_recruitment_time()); combat_width = fixed_point_t::multiply_truncate( - military_defines.get_base_combat_width(), - get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()) + military_defines.get_base_combat_width(), get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()) ); dig_in_cap = get_modifier_effect_value(*modifier_effect_cache.get_dig_in_cap()).floor(); - military_tactics = military_defines.get_base_military_tactics() + - get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); + military_tactics = + military_defines.get_base_military_tactics() + get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); if (leadership_point_stockpile < 0) { leadership_point_stockpile = 0; @@ -1723,8 +1655,8 @@ void CountryInstance::_update_military() { create_leader_count = (leadership_point_stockpile / military_defines.get_leader_recruit_cost()).floor(); monthly_leadership_points += get_modifier_effect_value(*modifier_effect_cache.get_leadership()); - monthly_leadership_points *= fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); + monthly_leadership_points *= + fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); if (monthly_leadership_points < 0) { monthly_leadership_points = 0; @@ -1759,10 +1691,10 @@ static constexpr Modifier const& get_country_status_static_effect( using enum CountryInstance::country_status_t; switch (country_status) { - case COUNTRY_STATUS_GREAT_POWER: return static_modifier_cache.get_great_power(); + case COUNTRY_STATUS_GREAT_POWER: return static_modifier_cache.get_great_power(); case COUNTRY_STATUS_SECONDARY_POWER: return static_modifier_cache.get_secondary_power(); - case COUNTRY_STATUS_CIVILISED: return static_modifier_cache.get_civilised(); - default: return static_modifier_cache.get_uncivilised(); + case COUNTRY_STATUS_CIVILISED: return static_modifier_cache.get_civilised(); + default: return static_modifier_cache.get_uncivilised(); } } @@ -1863,9 +1795,8 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan } } - owns_colonial_province = std::any_of( - owned_provinces.begin(), owned_provinces.end(), std::bind_front(&ProvinceInstance::is_colonial_province) - ); + owns_colonial_province = + std::any_of(owned_provinces.begin(), owned_provinces.end(), std::bind_front(&ProvinceInstance::is_colonial_province)); { has_unowned_cores = false; @@ -2009,16 +1940,13 @@ void CountryInstance::after_sell(void* actor, SellResult const& sell_result, mem void CountryInstance::country_tick_before_map( IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, memory::vector& reusable_good_index_vector ) { - //TODO AI sliders - // + reparations + war subsidies - // + industrial subsidies - // + loan interest + // TODO AI sliders + // + reparations + war subsidies + // + industrial subsidies + // + loan interest fixed_point_t available_funds = cash_stockpile_start_of_tick = cash_stockpile; const fixed_point_t projected_administration_spending_copy = projected_administration_spending.get_untracked(); @@ -2026,7 +1954,7 @@ void CountryInstance::country_tick_before_map( const fixed_point_t projected_military_spending_copy = projected_military_spending.get_untracked(); const fixed_point_t projected_social_spending_copy = projected_social_spending.get_untracked(); const fixed_point_t projected_import_subsidies_copy = projected_import_subsidies.get_untracked(); - //excluding national stockpile + // excluding national stockpile const fixed_point_t projected_total_spending = projected_spending.get_untracked(); if (projected_total_spending <= available_funds) { actual_administration_budget = projected_administration_spending_copy; @@ -2036,8 +1964,8 @@ void CountryInstance::country_tick_before_map( actual_import_subsidies_budget = projected_import_subsidies_copy; available_funds -= projected_total_spending; } else { - //TODO try take loan (callback?) - //update available_funds with loan + // TODO try take loan (callback?) + // update available_funds with loan if (available_funds < projected_education_spending_copy) { actual_education_budget = available_funds; @@ -2097,31 +2025,19 @@ void CountryInstance::country_tick_before_map( calculate_government_good_needs(); - manage_national_stockpile( - reusable_goods_mask, - reusable_vectors, - reusable_good_index_vector, - available_funds - ); + manage_national_stockpile(reusable_goods_mask, reusable_vectors, reusable_good_index_vector, available_funds); - //TODO market maker orders + // TODO market maker orders taxable_income_by_pop_type.fill(0); - actual_administration_spending - = actual_education_spending - = actual_military_spending - = actual_pensions_spending - = actual_unemployment_subsidies_spending - = actual_import_subsidies_spending - = actual_tariff_income - = actual_national_stockpile_spending - = actual_national_stockpile_income - = 0; + actual_administration_spending = actual_education_spending = actual_military_spending = actual_pensions_spending = + actual_unemployment_subsidies_spending = actual_import_subsidies_spending = actual_tariff_income = + actual_national_stockpile_spending = actual_national_stockpile_income = 0; } void CountryInstance::calculate_government_good_needs() { - //TODO calculate government_needs, max_government_consumption, army_needs & navy_needs - //for each construction/recruitment + // TODO calculate government_needs, max_government_consumption, army_needs & navy_needs + // for each construction/recruitment // for each good // remainder = resources_total - already_consumed // daily_needs = exact_vic_2_game_rule @@ -2133,12 +2049,8 @@ void CountryInstance::calculate_government_good_needs() { void CountryInstance::manage_national_stockpile( IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector, - fixed_point_t& available_funds + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector, fixed_point_t& available_funds ) { IndexedFlatMap& wants_more_mask = reusable_goods_mask; const size_t mask_size = wants_more_mask.get_keys().size(); @@ -2158,7 +2070,7 @@ void CountryInstance::manage_national_stockpile( for (auto [good_instance, good_data] : goods_data) { const good_index_t good_index = good_instance.index; if (good_data.is_automated || !good_data.is_selling) { - const fixed_point_t quantity_to_allocate_for = good_data.is_automated + const fixed_point_t quantity_to_allocate_for = good_data.is_automated ? good_data.government_needs - good_data.stockpile_amount : good_data.stockpile_cutoff - good_data.stockpile_amount; const fixed_point_t max_quantity_to_buy = good_data.is_automated @@ -2171,10 +2083,10 @@ void CountryInstance::manage_national_stockpile( good_indices_to_buy.push_back(good_index); max_quantity_to_buy_per_good[good_index] = max_quantity_to_buy; - const fixed_point_t max_money_to_spend = max_costs_per_good[good_index] = market_instance.get_max_money_to_allocate_to_buy_quantity( - good_instance.good_definition, - quantity_to_allocate_for - ); + const fixed_point_t max_money_to_spend = max_costs_per_good[good_index] = + market_instance.get_max_money_to_allocate_to_buy_quantity( + good_instance.good_definition, quantity_to_allocate_for + ); wants_more_mask.set(good_instance.good_definition, true); const fixed_point_t weight = weights[good_index] = fixed_point_t::usable_max / max_money_to_spend; weights_sum += weight; @@ -2191,7 +2103,7 @@ void CountryInstance::manage_national_stockpile( this, after_sell, }, - reusable_vectors[3] //temporarily used here and later used as money_to_spend_per_good + reusable_vectors[3] // temporarily used here and later used as money_to_spend_per_good ); } } @@ -2212,13 +2124,9 @@ void CountryInstance::manage_national_stockpile( const fixed_point_t weight = weights[good_index]; const fixed_point_t max_costs = max_costs_per_good[good_index]; - - fixed_point_t cash_available_for_good = fixed_point_t::mul_div( - cash_left_to_spend_draft, - weight, - weights_sum - ); - + + fixed_point_t cash_available_for_good = fixed_point_t::mul_div(cash_left_to_spend_draft, weight, weights_sum); + if (cash_available_for_good >= max_costs) { cash_left_to_spend_draft -= max_costs; money_to_spend_per_good[good_index] = max_costs; @@ -2230,7 +2138,8 @@ void CountryInstance::manage_national_stockpile( GoodInstance const& good_instance = goods_data.get_key_at_index(good_index); GoodDefinition const& good_definition = good_instance.good_definition; - const fixed_point_t max_possible_quantity_bought = cash_available_for_good / market_instance.get_min_next_price(good_definition); + const fixed_point_t max_possible_quantity_bought = + cash_available_for_good / market_instance.get_min_next_price(good_definition); if (max_possible_quantity_bought < fixed_point_t::epsilon) { money_to_spend_per_good[good_index] = 0; } else { @@ -2238,7 +2147,7 @@ void CountryInstance::manage_national_stockpile( } } } - + for (const good_index_t good_index : good_indices_to_buy) { const fixed_point_t max_quantity_to_buy = max_quantity_to_buy_per_good[good_index]; const fixed_point_t money_to_spend = money_to_spend_per_good[good_index]; @@ -2250,14 +2159,7 @@ void CountryInstance::manage_national_stockpile( GoodDefinition const& good_definition = good_instance.good_definition; available_funds -= money_to_spend; market_instance.place_buy_up_to_order( - { - good_definition, - index, - max_quantity_to_buy, - money_to_spend, - this, - after_buy - } + { good_definition, index, max_quantity_to_buy, money_to_spend, this, after_buy } ); } } @@ -2333,7 +2235,8 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_administration_spending_copy = actual_administration_spending.load(); if (OV_unlikely(actual_administration_spending_copy > actual_administration_budget)) { spdlog::error_s( - "Country {} has overspend on administration. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", + "Country {} has overspend on administration. Spending {} instead of the allocated {}. " + "This indicates a severe bug in the economy code.", *this, actual_administration_spending_copy, actual_administration_budget ); } @@ -2342,7 +2245,8 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_education_spending_copy = actual_education_spending.load(); if (OV_unlikely(actual_education_spending_copy > actual_education_budget)) { spdlog::error_s( - "Country {} has overspend on education. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", + "Country {} has overspend on education. Spending {} instead of the allocated {}. " + "This indicates a severe bug in the economy code.", *this, actual_education_spending_copy, actual_education_budget ); } @@ -2351,13 +2255,15 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_military_spending_copy = actual_military_spending.load(); if (OV_unlikely(actual_military_spending_copy > actual_military_budget)) { spdlog::error_s( - "Country {} has overspend on military. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", + "Country {} has overspend on military. Spending {} instead of the allocated {}. " + "This indicates a severe bug in the economy code.", *this, actual_military_spending_copy, actual_military_budget ); } cash_stockpile -= actual_military_spending; - const fixed_point_t actual_social_spending_copy = actual_pensions_spending.load() + actual_unemployment_subsidies_spending.load(); + const fixed_point_t actual_social_spending_copy = + actual_pensions_spending.load() + actual_unemployment_subsidies_spending.load(); if (OV_unlikely(actual_social_spending_copy > actual_social_budget)) { spdlog::error_s( "Country {} has overspend on pensions and/or unemployment subsidies. " @@ -2372,7 +2278,8 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_import_subsidies_spending_copy = actual_import_subsidies_spending.load(); if (OV_unlikely(actual_import_subsidies_spending_copy > actual_import_subsidies_budget)) { spdlog::error_s( - "Country {} has overspend on import subsidies. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", + "Country {} has overspend on import subsidies. Spending {} instead of the allocated {}. " + "This indicates a severe bug in the economy code.", *this, actual_import_subsidies_spending_copy, actual_import_subsidies_budget ); } @@ -2388,69 +2295,68 @@ void CountryInstance::country_tick_after_map(const Date today) { cash_stockpile += actual_tariff_income; - const fixed_point_t gold_income_value = country_defines.get_gold_to_cash_rate() * total_gold_production;; + const fixed_point_t gold_income_value = country_defines.get_gold_to_cash_rate() * total_gold_production; + ; gold_income.set(gold_income_value); cash_stockpile += gold_income_value; const fixed_point_t yesterdays_balance = cash_stockpile - cash_stockpile_start_of_tick; balance_history.push_back(yesterdays_balance); } -CountryInstance::good_data_t::good_data_t() - : mutex { memory::make_unique() } - { } +CountryInstance::good_data_t::good_data_t() : mutex { memory::make_unique() } {} void CountryInstance::good_data_t::clear_daily_recorded_data() { const std::lock_guard lock_guard { *mutex }; - stockpile_change_yesterday - = quantity_traded_yesterday - = money_traded_yesterday - = exported_amount - = max_government_consumption - = government_needs - = army_needs - = navy_needs - = overseas_maintenance - = factory_demand - = pop_demand - = available_amount - = 0; + stockpile_change_yesterday = quantity_traded_yesterday = money_traded_yesterday = exported_amount = + max_government_consumption = government_needs = army_needs = navy_needs = overseas_maintenance = factory_demand = + pop_demand = available_amount = 0; need_consumption_per_pop_type.clear(); input_consumption_per_production_type.clear(); production_per_production_type.clear(); } -void CountryInstance::report_pop_income_tax(PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax) { +void CountryInstance::report_pop_income_tax( + PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax +) { const std::lock_guard lock_guard { taxable_income_mutex }; taxable_income_by_pop_type.at(pop_type) += gross_income; cash_stockpile += paid_as_tax; } -void CountryInstance::report_pop_need_consumption(PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity) { +void CountryInstance::report_pop_need_consumption( + PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity +) { good_data_t& good_data = get_good_data(good); const std::lock_guard lock_guard { *good_data.mutex }; good_data.need_consumption_per_pop_type[&pop_type] += quantity; } -void CountryInstance::report_pop_need_demand(PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity) { +void CountryInstance::report_pop_need_demand( + PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity +) { good_data_t& good_data = get_good_data(good); const std::lock_guard lock_guard { *good_data.mutex }; good_data.pop_demand += quantity; } -void CountryInstance::report_input_consumption(ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity) { +void CountryInstance::report_input_consumption( + ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity +) { good_data_t& good_data = get_good_data(good); const std::lock_guard lock_guard { *good_data.mutex }; good_data.input_consumption_per_production_type[&production_type] += quantity; } -void CountryInstance::report_input_demand(ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity) { +void CountryInstance::report_input_demand( + ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity +) { if (production_type.template_type == ProductionType::template_type_t::ARTISAN) { switch (game_rules_manager.get_artisanal_input_demand_category()) { - case demand_category::FactoryNeeds: break; - case demand_category::PopNeeds: { - good_data_t& good_data = get_good_data(good); - const std::lock_guard lock_guard { *good_data.mutex }; - good_data.pop_demand += quantity; - return; - } - default: return; //demand_category::None + case demand_category::FactoryNeeds: break; + case demand_category::PopNeeds: { + good_data_t& good_data = get_good_data(good); + const std::lock_guard lock_guard { *good_data.mutex }; + good_data.pop_demand += quantity; + return; + } + default: return; // demand_category::None } } @@ -2470,11 +2376,12 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop SharedPopTypeValues const& pop_type_values = shared_country_values.get_shared_pop_type_values(pop_type); if (actual_administration_budget > 0) { - const fixed_point_t administration_salary = fixed_point_t::mul_div( - pop_size * administration_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_administration_budget, - projected_administration_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t administration_salary = + fixed_point_t::mul_div( + pop_size * administration_salary_base_by_pop_type.at(pop_type).get_untracked(), actual_administration_budget, + projected_administration_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (administration_salary > 0) { pop.add_government_salary_administration(administration_salary); actual_administration_spending += administration_salary; @@ -2482,11 +2389,12 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop } if (actual_education_budget > 0) { - const fixed_point_t education_salary = fixed_point_t::mul_div( - pop_size * education_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_education_budget, - projected_education_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t education_salary = + fixed_point_t::mul_div( + pop_size * education_salary_base_by_pop_type.at(pop_type).get_untracked(), actual_education_budget, + projected_education_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (education_salary > 0) { pop.add_government_salary_education(education_salary); actual_education_spending += education_salary; @@ -2494,11 +2402,12 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop } if (actual_military_budget > 0) { - const fixed_point_t military_salary = fixed_point_t::mul_div( - pop_size * military_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_military_budget, - projected_military_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t military_salary = + fixed_point_t::mul_div( + pop_size * military_salary_base_by_pop_type.at(pop_type).get_untracked(), actual_military_budget, + projected_military_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (military_salary > 0) { pop.add_government_salary_military(military_salary); actual_military_spending += military_salary; @@ -2507,20 +2416,21 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop if (actual_social_budget > 0) { const fixed_point_t pension_income = fixed_point_t::mul_div( - pop_size * calculate_pensions_base(pop_type), - actual_social_budget, - projected_social_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + pop_size * calculate_pensions_base(pop_type), actual_social_budget, + projected_social_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (pension_income > 0) { pop.add_pensions(pension_income); actual_pensions_spending += pension_income; } - const fixed_point_t unemployment_subsidies = fixed_point_t::mul_div( - pop.get_unemployed() * calculate_unemployment_subsidies_base(pop_type), - actual_social_budget, - projected_social_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t unemployment_subsidies = + fixed_point_t::mul_div( + pop.get_unemployed() * calculate_unemployment_subsidies_base(pop_type), actual_social_budget, + projected_social_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (unemployment_subsidies > 0) { pop.add_unemployment_subsidies(unemployment_subsidies); actual_unemployment_subsidies_spending += unemployment_subsidies; @@ -2533,7 +2443,7 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop * pop.get_yesterdays_import_value().get_copy_of_value(), actual_import_subsidies_budget, // < 0 projected_import_subsidies.get_untracked() // > 0 - ); //effective_tariff_rate * actual_net_tariffs cancel out the negative + ); // effective_tariff_rate * actual_net_tariffs cancel out the negative pop.add_import_subsidies(import_subsidies); actual_import_subsidies_spending += import_subsidies; } diff --git a/src/openvic-simulation/country/CountryInstance.hpp b/src/openvic-simulation/country/CountryInstance.hpp index 655e73138..c41441f46 100644 --- a/src/openvic-simulation/country/CountryInstance.hpp +++ b/src/openvic-simulation/country/CountryInstance.hpp @@ -13,21 +13,21 @@ #include "openvic-simulation/modifier/ModifierSum.hpp" #include "openvic-simulation/politics/RuleSet.hpp" #include "openvic-simulation/population/PopsAggregate.hpp" +#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" #include "openvic-simulation/types/ClampedValue.hpp" #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/Atomic.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/FlagStrings.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/UnitVariant.hpp" #include "openvic-simulation/types/ValueHistory.hpp" -#include "openvic-simulation/utility/Getters.hpp" +#include "openvic-simulation/types/fixed_point/Atomic.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/reactive/DerivedState.hpp" #include "openvic-simulation/utility/reactive/MutableState.hpp" @@ -154,8 +154,10 @@ namespace OpenVic { /* Production */ OV_STATE_PROPERTY(fixed_point_t, industrial_power); - memory::vector, fixed_point_t>> SPAN_PROPERTY(industrial_power_from_states); - memory::vector, fixed_point_t>> SPAN_PROPERTY(industrial_power_from_investments); + memory::vector, fixed_point_t>> + SPAN_PROPERTY(industrial_power_from_states); + memory::vector, fixed_point_t>> + SPAN_PROPERTY(industrial_power_from_investments); size_t PROPERTY(industrial_rank, 0); fixed_point_map_t> PROPERTY(foreign_investments); OV_IFLATMAP_PROPERTY(BuildingType, building_level_t, building_type_unlock_levels); @@ -170,23 +172,26 @@ namespace OpenVic { OV_IFLATMAP_PROPERTY(PopType, fixed_point_t, taxable_income_by_pop_type); OV_STATE_PROPERTY(fixed_point_t, tax_efficiency); IndexedFlatMap> PROPERTY(effective_tax_rate_by_strata); + public: DerivedState& get_effective_tax_rate_by_strata(Strata const& strata); + private: IndexedFlatMap tax_rate_slider_value_by_strata; + public: [[nodiscard]] constexpr IndexedFlatMap const& get_tax_rate_slider_value_by_strata() const { return tax_rate_slider_value_by_strata; } [[nodiscard]] ReadOnlyClampedValue& get_tax_rate_slider_value_by_strata(Strata const& strata); [[nodiscard]] ReadOnlyClampedValue const& get_tax_rate_slider_value_by_strata(Strata const& strata) const; - private: + private: OV_STATE_PROPERTY(fixed_point_t, administrative_efficiency_from_administrators); OV_STATE_PROPERTY(fixed_point_t, administrator_percentage); - //store per slider per good: desired, bought & cost - //store purchase record from last tick and prediction next tick + // store per slider per good: desired, bought & cost + // store purchase record from last tick and prediction next tick OV_CLAMPED_PROPERTY(army_spending_slider_value); OV_CLAMPED_PROPERTY(navy_spending_slider_value); OV_CLAMPED_PROPERTY(construction_spending_slider_value); @@ -218,8 +223,8 @@ namespace OpenVic { bool PROPERTY(was_social_budget_cut_yesterday, false); atomic_fixed_point_t PROPERTY(actual_pensions_spending); atomic_fixed_point_t PROPERTY(actual_unemployment_subsidies_spending); - - //base here means not scaled by slider or pop size + + // base here means not scaled by slider or pop size IndexedFlatMap> administration_salary_base_by_pop_type; IndexedFlatMap> education_salary_base_by_pop_type; IndexedFlatMap> military_salary_base_by_pop_type; @@ -234,8 +239,8 @@ namespace OpenVic { return actual_tariff_income.load() - actual_import_subsidies_spending.load(); } - //TODO actual factory subsidies - //projected cost is UI only and lists the different factories + // TODO actual factory subsidies + // projected cost is UI only and lists the different factories /* Technology */ OV_IFLATMAP_PROPERTY(Technology, technology_unlock_level_t, technology_unlock_levels); @@ -296,7 +301,7 @@ namespace OpenVic { DerivedState projected_import_subsidies; DerivedState projected_spending; DerivedState has_import_subsidies; - + fixed_point_t get_taxable_income_by_strata(Strata const& strata) const; // TODO - national foci @@ -314,8 +319,8 @@ namespace OpenVic { fixed_point_t exported_amount; // negative if net importing - fixed_point_t max_government_consumption; //for automated BuyUpToOrder - fixed_point_t government_needs; //quantity to allocate for while automated + fixed_point_t max_government_consumption; // for automated BuyUpToOrder + fixed_point_t government_needs; // quantity to allocate for while automated fixed_point_t army_needs; fixed_point_t navy_needs; fixed_point_t overseas_maintenance; @@ -331,7 +336,7 @@ namespace OpenVic { good_data_t(good_data_t&&) = default; good_data_t& operator=(good_data_t&&) = default; - //thread safe + // thread safe void clear_daily_recorded_data(); }; @@ -398,8 +403,7 @@ namespace OpenVic { public: CountryInstance( - CountryDefinition const& new_country_definition, - SharedCountryValues& new_shared_country_values, + CountryDefinition const& new_country_definition, SharedCountryValues& new_shared_country_values, CountryInstanceDeps const& country_instance_deps ); CountryInstance(CountryInstance const&) = delete; @@ -453,7 +457,9 @@ namespace OpenVic { [[nodiscard]] bool is_secondary_power() const; [[nodiscard]] bool is_at_war() const; [[nodiscard]] bool is_neighbour(CountryInstance const& country) const; - [[nodiscard]] bool may_build_in(const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location) const; + [[nodiscard]] bool may_build_in( + const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location // + ) const; // Double-sided diplomacy functions @@ -493,7 +499,9 @@ namespace OpenVic { void set_influence_with(CountryInstance& country, CountryRelationManager::influence_value_type influence); CountryRelationManager::influence_priority_value_type get_influence_priority_with(CountryInstance const& country) const; - void set_influence_priority_with(CountryInstance& country, CountryRelationManager::influence_priority_value_type influence); + void set_influence_priority_with( + CountryInstance& country, CountryRelationManager::influence_priority_value_type influence // + ); std::optional get_decredited_from_date(CountryInstance const& country) const; void set_discredited_from(CountryInstance& country, Date until); @@ -557,9 +565,7 @@ namespace OpenVic { bool unlock_unit_type(UnitType const& unit_type); [[nodiscard]] bool is_unit_type_unlocked(UnitType const& unit_type) const; - bool modify_building_type_unlock( - BuildingType const& building_type, technology_unlock_level_t unlock_level_change - ); + bool modify_building_type_unlock(BuildingType const& building_type, technology_unlock_level_t unlock_level_change); bool unlock_building_type(BuildingType const& building_type); [[nodiscard]] bool is_building_type_unlocked(BuildingType const& building_type) const; @@ -579,21 +585,13 @@ namespace OpenVic { bool unlock_unit_variant(unit_variant_t unit_variant); [[nodiscard]] unit_variant_t get_max_unlocked_unit_variant() const; - bool modify_technology_unlock( - Technology const& technology, technology_unlock_level_t unlock_level_change - ); - bool set_technology_unlock_level( - Technology const& technology, technology_unlock_level_t unlock_level - ); + bool modify_technology_unlock(Technology const& technology, technology_unlock_level_t unlock_level_change); + bool set_technology_unlock_level(Technology const& technology, technology_unlock_level_t unlock_level); bool unlock_technology(Technology const& technology); [[nodiscard]] bool is_technology_unlocked(Technology const& technology) const; - bool modify_invention_unlock( - Invention const& invention, technology_unlock_level_t unlock_level_change - ); - bool set_invention_unlock_level( - Invention const& invention, technology_unlock_level_t unlock_level - ); + bool modify_invention_unlock(Invention const& invention, technology_unlock_level_t unlock_level_change); + bool set_invention_unlock_level(Invention const& invention, technology_unlock_level_t unlock_level); bool unlock_invention(Invention const& invention); [[nodiscard]] bool is_invention_unlocked(Invention const& invention) const; @@ -613,33 +611,27 @@ namespace OpenVic { ); bool apply_history_to_country( - CountryHistoryEntry const& entry, - CountryInstanceManager const& country_instance_manager, - FlagStrings& global_flags, + CountryHistoryEntry const& entry, CountryInstanceManager const& country_instance_manager, FlagStrings& global_flags, MapInstance& map_instance ); private: static void after_buy(void* actor, BuyResult const& buy_result); - //matching GoodMarketSellOrder::callback_t + // matching GoodMarketSellOrder::callback_t static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector); void calculate_government_good_needs(); void manage_national_stockpile( IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector, - fixed_point_t& available_funds + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector, fixed_point_t& available_funds ); void _update_production(); void _update_budget(); - //base here means not scaled by slider or pop size + // base here means not scaled by slider or pop size fixed_point_t calculate_pensions_base(PopType const& pop_type); fixed_point_t calculate_unemployment_subsidies_base(PopType const& pop_type); @@ -658,7 +650,7 @@ namespace OpenVic { void contribute_province_modifier_sum(ModifierSum const& province_modifier_sum); fixed_point_t get_modifier_effect_value(ModifierEffect const& effect) const; constexpr void for_each_contributing_modifier( - ModifierEffect const& effect, ContributingModifierCallback auto callback + ModifierEffect const& effect, ContributingModifierCallback auto callback // ) const { return modifier_sum.for_each_contributing_modifier(effect, std::move(callback)); } @@ -666,10 +658,7 @@ namespace OpenVic { void update_gamestate(const Date today, MapInstance& map_instance); void country_tick_before_map( IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, memory::vector& reusable_good_index_vector ); void country_tick_after_map(const Date today); @@ -679,12 +668,16 @@ namespace OpenVic { good_data_t& get_good_data(GoodDefinition const& good_definition); good_data_t const& get_good_data(GoodDefinition const& good_definition) const; - //thread safe + // thread safe void report_pop_income_tax(PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax); void report_pop_need_consumption(PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity); void report_pop_need_demand(PopType const& pop_type, GoodDefinition const& good, const fixed_point_t quantity); - void report_input_consumption(ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity); - void report_input_demand(ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity); + void report_input_consumption( + ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity + ); + void report_input_demand( + ProductionType const& production_type, GoodDefinition const& good, const fixed_point_t quantity // + ); void report_output(ProductionType const& production_type, const fixed_point_t quantity); void request_salaries_and_welfare_and_import_subsidies(Pop& pop); fixed_point_t calculate_minimum_wage_base(PopType const& pop_type); @@ -692,4 +685,4 @@ namespace OpenVic { }; } -extern template struct fmt::formatter; \ No newline at end of file +extern template struct fmt::formatter; diff --git a/src/openvic-simulation/country/CountryInstanceDeps.hpp b/src/openvic-simulation/country/CountryInstanceDeps.hpp index 2d95041b7..c0b998ac3 100644 --- a/src/openvic-simulation/country/CountryInstanceDeps.hpp +++ b/src/openvic-simulation/country/CountryInstanceDeps.hpp @@ -1,8 +1,8 @@ #pragma once +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" namespace OpenVic { struct BuildingType; @@ -51,4 +51,4 @@ namespace OpenVic { forwardable_span technologies; UnitTypeManager const& unit_type_manager; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/country/CountryInstanceManager.cpp b/src/openvic-simulation/country/CountryInstanceManager.cpp index 1c7d6a940..08289776b 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.cpp +++ b/src/openvic-simulation/country/CountryInstanceManager.cpp @@ -3,10 +3,10 @@ #include #include -#include "openvic-simulation/country/CountryDefinition.hpp" -#include "openvic-simulation/defines/CountryDefines.hpp" #include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/InstanceManager.hpp" +#include "openvic-simulation/country/CountryDefinition.hpp" +#include "openvic-simulation/defines/CountryDefines.hpp" #include "openvic-simulation/history/CountryHistory.hpp" #include "openvic-simulation/military/UnitInstanceGroup.hpp" #include "openvic-simulation/population/Pop.hpp" @@ -15,35 +15,20 @@ using namespace OpenVic; CountryInstanceManager::CountryInstanceManager( - CountryDefines const& new_country_defines, - CountryDefinitionManager const& new_country_definition_manager, - CountryInstanceDeps const& country_instance_deps, - GoodInstanceManager const& new_good_instance_manager, - PopsDefines const& new_pop_defines, - forwardable_span pop_type_keys, - ThreadPool& new_thread_pool -) : thread_pool { new_thread_pool }, - country_definition_manager { new_country_definition_manager }, - country_defines { new_country_defines }, - shared_country_values { - new_pop_defines, - new_good_instance_manager, - pop_type_keys - }, - country_instance_by_definition { - new_country_definition_manager.get_country_definitions(), - [ - this, - &country_instance_deps - ](CountryDefinition const& country_definition)->auto{ - return std::make_tuple( - std::ref(country_definition), - std::ref(shared_country_values), - std::ref(country_instance_deps) - ); - } - } -{ + CountryDefines const& new_country_defines, CountryDefinitionManager const& new_country_definition_manager, + CountryInstanceDeps const& country_instance_deps, GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, forwardable_span pop_type_keys, ThreadPool& new_thread_pool +) + : thread_pool { new_thread_pool }, country_definition_manager { new_country_definition_manager }, + country_defines { new_country_defines }, + shared_country_values { new_pop_defines, new_good_instance_manager, pop_type_keys }, + country_instance_by_definition { new_country_definition_manager.get_country_definitions(), + [this, &country_instance_deps](CountryDefinition const& country_definition) -> auto { + return std::make_tuple( + std::ref(country_definition), std::ref(shared_country_values), + std::ref(country_instance_deps) + ); + } } { assert(new_country_definition_manager.country_definitions_are_locked()); great_powers.reserve(new_country_defines.get_great_power_rank()); secondary_powers.reserve(new_country_defines.get_max_secondary_power_count()); @@ -62,17 +47,13 @@ void CountryInstanceManager::update_rankings(const Date today) { industrial_power_ranking = total_ranking; military_power_ranking = total_ranking; + std::stable_sort(total_ranking.begin(), total_ranking.end(), [](CountryInstance& a, CountryInstance& b) -> bool { + const bool a_civilised = a.is_civilised(); + const bool b_civilised = b.is_civilised(); + return a_civilised != b_civilised ? a_civilised : a.total_score.get_untracked() > b.total_score.get_untracked(); + }); std::stable_sort( - total_ranking.begin(), total_ranking.end(), - [](CountryInstance& a, CountryInstance& b) -> bool { - const bool a_civilised = a.is_civilised(); - const bool b_civilised = b.is_civilised(); - return a_civilised != b_civilised ? a_civilised : a.total_score.get_untracked() > b.total_score.get_untracked(); - } - ); - std::stable_sort( - prestige_ranking.begin(), prestige_ranking.end(), - [](CountryInstance const& a, CountryInstance const& b) -> bool { + prestige_ranking.begin(), prestige_ranking.end(), [](CountryInstance const& a, CountryInstance const& b) -> bool { return a.get_prestige_untracked() > b.get_prestige_untracked(); } ); @@ -83,8 +64,7 @@ void CountryInstanceManager::update_rankings(const Date today) { } ); std::stable_sort( - military_power_ranking.begin(), military_power_ranking.end(), - [](CountryInstance& a, CountryInstance& b) -> bool { + military_power_ranking.begin(), military_power_ranking.end(), [](CountryInstance& a, CountryInstance& b) -> bool { return a.military_power.get_untracked() > b.military_power.get_untracked(); } ); @@ -108,8 +88,8 @@ void CountryInstanceManager::update_rankings(const Date today) { std::erase_if(great_powers, [max_great_power_rank, today](CountryInstance& great_power) -> bool { if (OV_likely(great_power.get_country_status() == COUNTRY_STATUS_GREAT_POWER)) { if (OV_unlikely( - great_power.get_total_rank() > max_great_power_rank && great_power.get_lose_great_power_date() < today - )) { + great_power.get_total_rank() > max_great_power_rank && great_power.get_lose_great_power_date() < today + )) { great_power.country_status = COUNTRY_STATUS_CIVILISED; return true; } else { @@ -176,30 +156,23 @@ void CountryInstanceManager::update_rankings(const Date today) { CountryInstance* CountryInstanceManager::get_country_instance_by_identifier(std::string_view identifier) { CountryDefinition const* country_definition = country_definition_manager.get_country_definition_by_identifier(identifier); - return country_definition == nullptr - ? nullptr - : &get_country_instance_by_definition(*country_definition); + return country_definition == nullptr ? nullptr : &get_country_instance_by_definition(*country_definition); } CountryInstance const* CountryInstanceManager::get_country_instance_by_identifier(std::string_view identifier) const { CountryDefinition const* country_definition = country_definition_manager.get_country_definition_by_identifier(identifier); - return country_definition == nullptr - ? nullptr - : &get_country_instance_by_definition(*country_definition); + return country_definition == nullptr ? nullptr : &get_country_instance_by_definition(*country_definition); } CountryInstance* CountryInstanceManager::get_country_instance_by_index(typename CountryInstance::index_t index) { - return country_instance_by_definition.contains_index(index) - ? &country_instance_by_definition.at_index(index) - : nullptr; + return country_instance_by_definition.contains_index(index) ? &country_instance_by_definition.at_index(index) : nullptr; } CountryInstance const* CountryInstanceManager::get_country_instance_by_index(typename CountryInstance::index_t index) const { - return country_instance_by_definition.contains_index(index) - ? &country_instance_by_definition.at_index(index) - : nullptr; + return country_instance_by_definition.contains_index(index) ? &country_instance_by_definition.at_index(index) : nullptr; } CountryInstance& CountryInstanceManager::get_country_instance_by_definition(CountryDefinition const& country_definition) { return country_instance_by_definition.at(country_definition); } -CountryInstance const& CountryInstanceManager::get_country_instance_by_definition(CountryDefinition const& country_definition) const { +CountryInstance const& +CountryInstanceManager::get_country_instance_by_definition(CountryDefinition const& country_definition) const { return country_instance_by_definition.at(country_definition); } @@ -220,9 +193,7 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc country_instance.last_war_loss_date = starting_last_war_loss_date; if (!country_instance.country_definition.is_dynamic_tag) { - CountryHistoryMap const* history_map = history_manager.get_country_history( - country_instance.country_definition - ); + CountryHistoryMap const* history_map = history_manager.get_country_history(country_instance.country_definition); if (history_map != nullptr) { static constexpr fixed_point_t DEFAULT_STATE_CULTURE_LITERACY = fixed_point_t::_0_50; @@ -234,12 +205,7 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc for (auto const& [entry_date, entry] : history_map->get_entries()) { if (entry_date <= today) { - ret &= country_instance.apply_history_to_country( - *entry, - *this, - global_flags, - map_instance - ); + ret &= country_instance.apply_history_to_country(*entry, *this, global_flags, map_instance); if (entry->get_initial_oob() != nullptr) { oob_history_entry = entry.get(); @@ -263,9 +229,10 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc } if (oob_history_entry != nullptr) { - ret &= oob_history_entry->get_initial_oob() != nullptr && unit_instance_manager.generate_deployment( - map_instance, country_instance, *oob_history_entry->get_initial_oob() - ); + ret &= oob_history_entry->get_initial_oob() != nullptr && + unit_instance_manager.generate_deployment( + map_instance, country_instance, *oob_history_entry->get_initial_oob() + ); } // TODO - check if better to do "if"s then "for"s, so looping multiple times rather than having lots of diff --git a/src/openvic-simulation/country/CountryInstanceManager.hpp b/src/openvic-simulation/country/CountryInstanceManager.hpp index b43ed5e99..ac53a06ba 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.hpp +++ b/src/openvic-simulation/country/CountryInstanceManager.hpp @@ -45,13 +45,9 @@ namespace OpenVic { public: CountryInstanceManager( - CountryDefines const& new_country_defines, - CountryDefinitionManager const& new_country_definition_manager, - CountryInstanceDeps const& country_instance_deps, - GoodInstanceManager const& new_good_instance_manager, - PopsDefines const& new_pop_defines, - forwardable_span pop_type_keys, - ThreadPool& new_thread_pool + CountryDefines const& new_country_defines, CountryDefinitionManager const& new_country_definition_manager, + CountryInstanceDeps const& country_instance_deps, GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, forwardable_span pop_type_keys, ThreadPool& new_thread_pool ); constexpr std::span get_country_instances() { @@ -65,7 +61,9 @@ namespace OpenVic { CountryInstance const* get_country_instance_by_identifier(std::string_view identifier) const; CountryInstance* get_country_instance_by_index(typename CountryInstance::index_t index); CountryInstance const* get_country_instance_by_index(typename CountryInstance::index_t index) const; - CountryInstance& get_country_instance_by_definition(CountryDefinition const& country_definition); //const variant comes from OV_IFLATMAP_PROPERTY + CountryInstance& get_country_instance_by_definition( + CountryDefinition const& country_definition + ); // const variant comes from OV_IFLATMAP_PROPERTY bool apply_history_to_countries(InstanceManager& instance_manager); @@ -74,4 +72,4 @@ namespace OpenVic { void country_manager_tick_before_map(); void country_manager_tick_after_map(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/country/CountryParty.cpp b/src/openvic-simulation/country/CountryParty.cpp index 0a4f83a5e..b225e4cc5 100644 --- a/src/openvic-simulation/country/CountryParty.cpp +++ b/src/openvic-simulation/country/CountryParty.cpp @@ -8,16 +8,12 @@ using namespace OpenVic; CountryParty::CountryParty( std::string_view new_identifier, Date new_start_date, Date new_end_date, Ideology const* new_ideology, decltype(policies)&& new_policies -) : HasIdentifierAndColour { - new_identifier, - new_ideology != nullptr ? new_ideology->get_colour() : Ideology::NO_IDEOLOGY_COLOUR, - false - }, - start_date { new_start_date }, - end_date { new_end_date }, - ideology { new_ideology }, - policies { std::move(new_policies) } {} +) + : HasIdentifierAndColour { new_identifier, + new_ideology != nullptr ? new_ideology->get_colour() : Ideology::NO_IDEOLOGY_COLOUR, false }, + start_date { new_start_date }, end_date { new_end_date }, ideology { new_ideology }, + policies { std::move(new_policies) } {} PartyPolicy const* CountryParty::get_policies(PartyPolicyGroup const& key) const { return policies.at(key); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/country/CountryParty.hpp b/src/openvic-simulation/country/CountryParty.hpp index d22c1599d..48ec4b751 100644 --- a/src/openvic-simulation/country/CountryParty.hpp +++ b/src/openvic-simulation/country/CountryParty.hpp @@ -19,12 +19,9 @@ namespace OpenVic { Ideology const* const ideology; // Can be nullptr, shows up as "No Ideology" in game CountryParty( - std::string_view new_identifier, - Date new_start_date, - Date new_end_date, - Ideology const* new_ideology, + std::string_view new_identifier, Date new_start_date, Date new_end_date, Ideology const* new_ideology, decltype(policies)&& new_policies ); CountryParty(CountryParty&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/country/SharedCountryValues.cpp b/src/openvic-simulation/country/SharedCountryValues.cpp index 045c75772..9dd7087cd 100644 --- a/src/openvic-simulation/country/SharedCountryValues.cpp +++ b/src/openvic-simulation/country/SharedCountryValues.cpp @@ -9,13 +9,11 @@ using namespace OpenVic; SharedCountryValues::SharedCountryValues( - PopsDefines const& new_pop_defines, - GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, GoodInstanceManager const& new_good_instance_manager, decltype(shared_pop_type_values)::keys_span_type pop_type_keys -) : pop_defines { new_pop_defines }, - good_instance_manager { new_good_instance_manager }, - shared_pop_type_values { pop_type_keys } - {} +) + : pop_defines { new_pop_defines }, good_instance_manager { new_good_instance_manager }, + shared_pop_type_values { pop_type_keys } {} SharedPopTypeValues& SharedCountryValues::get_shared_pop_type_values(PopType const& pop_type) { return shared_pop_type_values.at(pop_type); @@ -33,26 +31,26 @@ void SharedPopTypeValues::update_costs(PopsDefines const& pop_defines, GoodInsta fixed_point_t military_salary_base_running_total = 0; using enum PopType::income_type_t; - #define UPDATE_NEED_COSTS(need_category) \ - base_##need_category##_need_costs = 0; \ - for (auto const& [good_definition_ptr, quantity] : pop_type.get_##need_category##_needs()) { \ - GoodInstance const& good_instance = good_instance_manager.get_good_instance_by_definition(*good_definition_ptr); \ - base_##need_category##_need_costs += good_instance.get_price() * quantity; \ - } \ - base_##need_category##_need_costs *= pop_defines.get_base_goods_demand(); \ - if ((pop_type.get_##need_category##_needs_income_types() & ADMINISTRATION) == ADMINISTRATION) { \ - administration_salary_base_running_total += base_##need_category##_need_costs; \ - } \ - if ((pop_type.get_##need_category##_needs_income_types() & EDUCATION) == EDUCATION) { \ - education_salary_base_running_total += base_##need_category##_need_costs; \ - } \ - if ((pop_type.get_##need_category##_needs_income_types() & MILITARY) == MILITARY) { \ - military_salary_base_running_total += base_##need_category##_need_costs; \ - } +#define UPDATE_NEED_COSTS(need_category) \ + base_##need_category##_need_costs = 0; \ + for (auto const& [good_definition_ptr, quantity] : pop_type.get_##need_category##_needs()) { \ + GoodInstance const& good_instance = good_instance_manager.get_good_instance_by_definition(*good_definition_ptr); \ + base_##need_category##_need_costs += good_instance.get_price() * quantity; \ + } \ + base_##need_category##_need_costs *= pop_defines.get_base_goods_demand(); \ + if ((pop_type.get_##need_category##_needs_income_types() & ADMINISTRATION) == ADMINISTRATION) { \ + administration_salary_base_running_total += base_##need_category##_need_costs; \ + } \ + if ((pop_type.get_##need_category##_needs_income_types() & EDUCATION) == EDUCATION) { \ + education_salary_base_running_total += base_##need_category##_need_costs; \ + } \ + if ((pop_type.get_##need_category##_needs_income_types() & MILITARY) == MILITARY) { \ + military_salary_base_running_total += base_##need_category##_need_costs; \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(UPDATE_NEED_COSTS) - #undef UPDATE_NEED_COSTS +#undef UPDATE_NEED_COSTS administration_salary_base.set(administration_salary_base_running_total); education_salary_base.set(education_salary_base_running_total); diff --git a/src/openvic-simulation/country/SharedCountryValues.hpp b/src/openvic-simulation/country/SharedCountryValues.hpp index c163b3b8e..e6e28f2c2 100644 --- a/src/openvic-simulation/country/SharedCountryValues.hpp +++ b/src/openvic-simulation/country/SharedCountryValues.hpp @@ -14,15 +14,15 @@ namespace OpenVic { struct SharedPopTypeValues { friend SharedCountryValues; + private: PopType const& pop_type; - #define NEED_COST_FIELD(need_category) \ - fixed_point_t base_##need_category##_need_costs; +#define NEED_COST_FIELD(need_category) fixed_point_t base_##need_category##_need_costs; OV_DO_FOR_ALL_NEED_CATEGORIES(NEED_COST_FIELD) - #undef NEED_COST_FIELD +#undef NEED_COST_FIELD OV_STATE_PROPERTY(fixed_point_t, administration_salary_base); OV_STATE_PROPERTY(fixed_point_t, education_salary_base); @@ -30,12 +30,14 @@ namespace OpenVic { OV_STATE_PROPERTY(fixed_point_t, social_income_variant_base); void update_costs(PopsDefines const& pop_defines, GoodInstanceManager const& good_instance_manager); + public: constexpr SharedPopTypeValues(PopType const& new_pop_type) : pop_type { new_pop_type } {}; }; struct SharedCountryValues { friend CountryInstanceManager; + private: PopsDefines const& pop_defines; GoodInstanceManager const& good_instance_manager; @@ -47,8 +49,7 @@ namespace OpenVic { SharedPopTypeValues& get_shared_pop_type_values(PopType const& pop_type); SharedCountryValues( - PopsDefines const& new_pop_defines, - GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, GoodInstanceManager const& new_good_instance_manager, decltype(shared_pop_type_values)::keys_span_type pop_type_keys ); SharedCountryValues(SharedCountryValues&&) = delete; diff --git a/src/openvic-simulation/dataloader/Dataloader.cpp b/src/openvic-simulation/dataloader/Dataloader.cpp index 4d7fd6d39..212f504cd 100644 --- a/src/openvic-simulation/dataloader/Dataloader.cpp +++ b/src/openvic-simulation/dataloader/Dataloader.cpp @@ -13,13 +13,13 @@ #include #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/core/string/Utility.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/interface/UI.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/misc/SoundEffect.hpp" -#include "openvic-simulation/utility/Logger.hpp" -#include "openvic-simulation/core/string/Utility.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/utility/Logger.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -148,7 +148,7 @@ bool Dataloader::should_ignore_path(fs::path const& path, path_span_t replace_pa template Dataloader::path_vector_t Dataloader::_lookup_files_in_dir( - std::string_view path, fs::path const& extension, _UniqueKey const& unique_key + std::string_view path, fs::path const& extension, _UniqueKey const& unique_key // ) const { const fs::path dirpath { ensure_forward_slash_path(path) }; path_vector_t ret; @@ -167,7 +167,7 @@ Dataloader::path_vector_t Dataloader::_lookup_files_in_dir( if (entry.is_regular_file()) { fs::path file = entry; if (extension.empty() || file.extension() == extension) { - const memory::string full_path = file.string(memory::string::allocator_type{}); + const memory::string full_path = file.string(memory::string::allocator_type {}); std::string_view relative_path = full_path; relative_path.remove_prefix(root_len); relative_path = remove_leading_slashes(relative_path); @@ -204,13 +204,13 @@ static std::string_view _extract_basic_identifier_prefix_from_path(std::string_v }; Dataloader::path_vector_t Dataloader::lookup_basic_identifier_prefixed_files_in_dir( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension // ) const { return _lookup_files_in_dir(path, extension, _extract_basic_identifier_prefix_from_path); } Dataloader::path_vector_t Dataloader::lookup_basic_identifier_prefixed_files_in_dir_recursive( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension // ) const { return _lookup_files_in_dir(path, extension, _extract_basic_identifier_prefix_from_path); } @@ -315,15 +315,12 @@ bool Dataloader::load_mod_descriptors(ModManager& mod_manager) const { static constexpr std::string_view mod_directory = "mod"; static constexpr std::string_view mod_descriptor_extension = ".mod"; - apply_to_files( - lookup_files_in_dir(mod_directory, mod_descriptor_extension), - [&mod_manager](fs::path const& file) -> bool { - if (!mod_manager.load_mod_file(parse_defines(file).get_file_node())) { - spdlog::warn_s("Invalid mod descriptor at path: {} could not be loaded!", file); - } - return true; + apply_to_files(lookup_files_in_dir(mod_directory, mod_descriptor_extension), [&mod_manager](fs::path const& file) -> bool { + if (!mod_manager.load_mod_file(parse_defines(file).get_file_node())) { + spdlog::warn_s("Invalid mod descriptor at path: {} could not be loaded!", file); } - ); + return true; + }); mod_manager.lock_mods(); @@ -333,12 +330,9 @@ bool Dataloader::load_mod_descriptors(ModManager& mod_manager) const { bool Dataloader::_load_interface_files(UIManager& ui_manager) const { static constexpr std::string_view interface_directory = "interface/"; - bool ret = apply_to_files( - lookup_files_in_dir(interface_directory, ".gfx"), - [&ui_manager](fs::path const& file) -> bool { - return ui_manager.load_gfx_file(parse_defines(file).get_file_node()); - } - ); + bool ret = apply_to_files(lookup_files_in_dir(interface_directory, ".gfx"), [&ui_manager](fs::path const& file) -> bool { + return ui_manager.load_gfx_file(parse_defines(file).get_file_node()); + }); ui_manager.lock_gfx_registries(); /* Hard-coded GUI file names, might be replaced with a dynamic system but everything should still be loaded on startup. */ @@ -360,10 +354,10 @@ bool Dataloader::_load_interface_files(UIManager& ui_manager) const { for (std::string_view const& gui_file : gui_files) { if (!ui_manager.load_gui_file( - gui_file, parse_defines(lookup_file( - append_string_views(interface_directory, gui_file, gui_file_extension) - )).get_file_node() - )) { + gui_file, + parse_defines(lookup_file(append_string_views(interface_directory, gui_file, gui_file_extension))) + .get_file_node() + )) { spdlog::critical_s("Failed to load interface gui file: {}", gui_file); ret = false; } @@ -390,8 +384,7 @@ bool Dataloader::_load_pop_types(DefinitionManager& definition_manager) { pop_manager.reserve_pop_types_and_delayed_nodes(pop_type_files.size()); ret &= apply_to_files( - pop_type_files, - [this, &pop_manager, &good_definition_manager, &ideology_manager](fs::path const& file) -> bool { + pop_type_files, [this, &pop_manager, &good_definition_manager, &ideology_manager](fs::path const& file) -> bool { return pop_manager.load_pop_type_file( file.stem().string(), good_definition_manager, ideology_manager, parse_defines_cached(file).get_file_node() ); @@ -426,17 +419,13 @@ bool Dataloader::_load_units(DefinitionManager& definition_manager) const { unit_type_manager.reserve_all_unit_types(unit_files.size()); - bool ret = apply_to_files( - unit_files, - [&definition_manager, &unit_type_manager](fs::path const& file) -> bool { - return unit_type_manager.load_unit_type_file( - definition_manager.get_economy_manager().get_good_definition_manager(), - definition_manager.get_map_definition().get_terrain_type_manager(), - definition_manager.get_modifier_manager(), - parse_defines(file) - ); - } - ); + bool ret = apply_to_files(unit_files, [&definition_manager, &unit_type_manager](fs::path const& file) -> bool { + return unit_type_manager.load_unit_type_file( + definition_manager.get_economy_manager().get_good_definition_manager(), + definition_manager.get_map_definition().get_terrain_type_manager(), definition_manager.get_modifier_manager(), + parse_defines(file) + ); + }); unit_type_manager.lock_all_unit_types(); @@ -507,16 +496,15 @@ bool Dataloader::_load_technologies(DefinitionManager& definition_manager) { static constexpr std::string_view technologies_directory = "technologies"; if (!apply_to_files( - lookup_files_in_dir(technologies_directory, ".txt"), - [this, &definition_manager, &technology_manager, &modifier_manager](fs::path const& file) -> bool { - return technology_manager.load_technologies_file( - modifier_manager, - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_economy_manager().get_building_type_manager(), - parse_defines_cached(file).get_file_node() - ); - } - )) { + lookup_files_in_dir(technologies_directory, ".txt"), + [this, &definition_manager, &technology_manager, &modifier_manager](fs::path const& file) -> bool { + return technology_manager.load_technologies_file( + modifier_manager, definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_economy_manager().get_building_type_manager(), + parse_defines_cached(file).get_file_node() + ); + } + )) { spdlog::critical_s("Failed to load technologies!"); ret = false; } @@ -536,17 +524,15 @@ bool Dataloader::_load_inventions(DefinitionManager& definition_manager) { TechnologyManager& technology_manager = research_manager.get_technology_manager(); bool ret = apply_to_files( - lookup_files_in_dir(inventions_directory, ".txt"), - [this, &definition_manager, &invention_manager, &technology_manager](fs::path const& file) -> bool { - return invention_manager.load_inventions_file( - technology_manager, - definition_manager.get_modifier_manager(), - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_economy_manager().get_building_type_manager(), - definition_manager.get_crime_manager(), - parse_defines_cached(file).get_file_node() - ); - } + lookup_files_in_dir(inventions_directory, ".txt"), + [this, &definition_manager, &invention_manager, &technology_manager](fs::path const& file) -> bool { + return invention_manager.load_inventions_file( + technology_manager, definition_manager.get_modifier_manager(), + definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_economy_manager().get_building_type_manager(), definition_manager.get_crime_manager(), + parse_defines_cached(file).get_file_node() + ); + } ); invention_manager.lock_inventions(); @@ -565,8 +551,7 @@ bool Dataloader::_load_decisions(DefinitionManager& definition_manager) { DecisionManager& decision_manager = definition_manager.get_decision_manager(); bool ret = apply_to_files( - lookup_files_in_dir(decisions_directory, ".txt"), - [this, &decision_manager](fs::path const& file) -> bool { + lookup_files_in_dir(decisions_directory, ".txt"), [this, &decision_manager](fs::path const& file) -> bool { return decision_manager.load_decision_file(parse_defines_cached(file).get_file_node()); } ); @@ -595,7 +580,7 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse ret &= apply_to_files( country_history_files, [this, &definition_manager, &country_history_manager, unused_history_file_warnings](fs::path const& file) -> bool { - const memory::string filename = file.stem().string(memory::string::allocator_type{}); + const memory::string filename = file.stem().string(memory::string::allocator_type {}); const std::string_view country_id = extract_basic_identifier_prefix(filename); CountryDefinition const* country = @@ -637,10 +622,9 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse ret &= apply_to_files( province_history_files, - [this, &definition_manager, &province_history_manager, &map_definition, unused_history_file_warnings]( - fs::path const& file - ) -> bool { - const memory::string filename = file.stem().string(memory::string::allocator_type{}); + [this, &definition_manager, &province_history_manager, &map_definition, + unused_history_file_warnings](fs::path const& file) -> bool { + const memory::string filename = file.stem().string(memory::string::allocator_type {}); const std::string_view province_id = extract_basic_identifier_prefix(filename); ProvinceDefinition const* province = map_definition.get_province_definition_by_identifier(province_id); @@ -668,14 +652,13 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse Date::from_chars_result result; const Date date = Date::from_string_log(dir, &result); - if (result.ec == std::errc{} && date <= last_bookmark_date) { + if (result.ec == std::errc {} && date <= last_bookmark_date) { bool non_integer_size = false; ret &= apply_to_files( lookup_files_in_dir(append_string_views(pop_history_directory, dir), ".txt"), - [this, &definition_manager, &province_history_manager, date, &non_integer_size]( - fs::path const& file - ) -> bool { + [this, &definition_manager, &province_history_manager, date, + &non_integer_size](fs::path const& file) -> bool { return province_history_manager.load_pop_history_file( definition_manager, date, parse_defines(file).get_file_node(), &non_integer_size ); @@ -693,8 +676,7 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse { /* Diplomacy History */ - DiplomaticHistoryManager& diplomatic_history_manager = - definition_manager.get_history_manager().get_diplomacy_manager(); + DiplomaticHistoryManager& diplomatic_history_manager = definition_manager.get_history_manager().get_diplomacy_manager(); static constexpr std::string_view diplomacy_history_directory = "history/diplomacy"; @@ -714,8 +696,7 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse diplomatic_history_manager.reserve_more_wars(war_history_files.size()); ret &= apply_to_files( - war_history_files, - [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { + war_history_files, [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { return diplomatic_history_manager.load_war_history_file( definition_manager, parse_defines(file).get_file_node() ); @@ -732,8 +713,7 @@ bool Dataloader::_load_events(DefinitionManager& definition_manager) { static constexpr std::string_view events_directory = "events"; const bool ret = apply_to_files( - lookup_files_in_dir(events_directory, ".txt"), - [this, &definition_manager](fs::path const& file) -> bool { + lookup_files_in_dir(events_directory, ".txt"), [this, &definition_manager](fs::path const& file) -> bool { return definition_manager.get_event_manager().load_event_file( definition_manager.get_politics_manager().get_issue_manager(), parse_defines_cached(file).get_file_node() ); @@ -813,8 +793,8 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { } if (!map_definition.load_province_definitions( - parse_csv(lookup_file(append_string_views(map_directory, definitions))).get_lines() - )) { + parse_csv(lookup_file(append_string_views(map_directory, definitions))).get_lines() + )) { spdlog::critical_s("Failed to load province definitions file!"); ret = false; } @@ -835,16 +815,17 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { colours.push_back(0xFFFFFF_rgb); /* This ensures there is always at least one region colour. */ if (!map_definition.load_region_file( - parse_defines(lookup_file(append_string_views(map_directory, region))).get_file_node(), colours)) { + parse_defines(lookup_file(append_string_views(map_directory, region))).get_file_node(), colours + )) { spdlog::critical_s("Failed to load region file!"); ret = false; } } if (!map_definition.get_terrain_type_manager().load_terrain_types( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, terrain_definition))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, terrain_definition))).get_file_node() + )) { spdlog::critical_s("Failed to load terrain types!"); ret = false; } @@ -854,17 +835,17 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { } if (!map_definition.load_map_images( - lookup_file(append_string_views(map_directory, provinces)), - lookup_file(append_string_views(map_directory, terrain)), - lookup_file(append_string_views(map_directory, rivers)), false - )) { + lookup_file(append_string_views(map_directory, provinces)), + lookup_file(append_string_views(map_directory, terrain)), lookup_file(append_string_views(map_directory, rivers)), + false + )) { spdlog::critical_s("Failed to load map images!"); ret = false; } if (map_definition.generate_and_load_province_adjacencies( - parse_csv(lookup_file(append_string_views(map_directory, adjacencies))).get_lines() - )) { + parse_csv(lookup_file(append_string_views(map_directory, adjacencies))).get_lines() + )) { SPDLOG_INFO("Successfully generated and loaded province adjacencies!"); } else { spdlog::critical_s("Failed to generate and load province adjacencies!"); @@ -873,25 +854,25 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { /* Must be loaded after adjacencies so we know what provinces are coastal, and so can have a port */ if (!map_definition.load_province_positions( - definition_manager.get_economy_manager().get_building_type_manager(), - parse_defines(lookup_file(append_string_views(map_directory, positions))).get_file_node() - )) { + definition_manager.get_economy_manager().get_building_type_manager(), + parse_defines(lookup_file(append_string_views(map_directory, positions))).get_file_node() + )) { spdlog::critical_s("Failed to load province positions file!"); ret = false; } if (!map_definition.load_climate_file( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, climate_file))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, climate_file))).get_file_node() + )) { spdlog::critical_s("Failed to load climates!"); ret = false; } if (!map_definition.load_continent_file( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, continent))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, continent))).get_file_node() + )) { spdlog::critical_s("Failed to load continents!"); ret = false; } @@ -929,13 +910,9 @@ bool Dataloader::_load_sound_effect_defines(DefinitionManager& definition_manage sound_effect_manager.lock_sound_effects(); return ret; - } -bool Dataloader::load_defines( - GameRulesManager const& game_rules_manager, - DefinitionManager& definition_manager -) { +bool Dataloader::load_defines(GameRulesManager const& game_rules_manager, DefinitionManager& definition_manager) { if (roots.empty()) { spdlog::critical_s("Cannot load defines - Dataloader has no roots!"); return false; @@ -978,8 +955,8 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_define_manager().load_defines_file( - parse_lua_defines(lookup_file(defines_file)).get_file_node() - )) { + parse_lua_defines(lookup_file(defines_file)).get_file_node() + )) { spdlog::critical_s("Failed to load defines!"); ret = false; } @@ -988,26 +965,26 @@ bool Dataloader::load_defines( ret = false; } if (!definition_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() + )) { spdlog::critical_s("Failed to load graphical culture types!"); ret = false; } if (!definition_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() + )) { spdlog::critical_s("Failed to load religions!"); ret = false; } if (!definition_manager.get_politics_manager().get_ideology_manager().load_ideology_file( - parse_defines_cached(lookup_file(ideology_file)).get_file_node() - )) { + parse_defines_cached(lookup_file(ideology_file)).get_file_node() + )) { spdlog::critical_s("Failed to load ideologies!"); ret = false; } if (!definition_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() + )) { spdlog::critical_s("Failed to load government types!"); ret = false; } @@ -1016,23 +993,20 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_economy_manager().load_production_types_file( - game_rules_manager, - definition_manager.get_pop_manager(), - parse_defines_cached(lookup_file(production_types_file)) - )) { + game_rules_manager, definition_manager.get_pop_manager(), parse_defines_cached(lookup_file(production_types_file)) + )) { spdlog::critical_s("Failed to load production types!"); ret = false; } - if (!definition_manager.get_economy_manager().load_buildings_file(definition_manager.get_modifier_manager(), - parse_defines(lookup_file(buildings_file)).get_file_node() - )) { + if (!definition_manager.get_economy_manager().load_buildings_file( + definition_manager.get_modifier_manager(), parse_defines(lookup_file(buildings_file)).get_file_node() + )) { spdlog::critical_s("Failed to load buildings!"); ret = false; } if (!definition_manager.get_mapmode_manager().setup_mapmodes( - definition_manager.get_map_definition(), - definition_manager.get_economy_manager().get_building_type_manager() - )) { + definition_manager.get_map_definition(), definition_manager.get_economy_manager().get_building_type_manager() + )) { spdlog::critical_s("Failed to set up mapmodes!"); ret = false; } @@ -1055,56 +1029,55 @@ bool Dataloader::load_defines( } definition_manager.get_modifier_manager().lock_base_country_modifier_effects(); if (!definition_manager.get_politics_manager().load_issues_file( - definition_manager.get_modifier_manager(), - parse_defines_cached(lookup_file(issues_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(issues_file)).get_file_node() + )) { spdlog::critical_s("Failed to load issues and reforms!"); ret = false; } if (!definition_manager.get_pop_manager().load_delayed_parse_pop_type_data( - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_politics_manager().get_issue_manager() - )) { + definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_politics_manager().get_issue_manager() + )) { spdlog::critical_s("Failed to load delayed parse pop type data (promotion and issue weights)!"); ret = false; } if (!definition_manager.get_politics_manager().load_national_foci_file( - definition_manager.get_pop_manager(), definition_manager.get_economy_manager().get_good_definition_manager(), - definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(national_foci_file)).get_file_node() - )) { + definition_manager.get_pop_manager(), definition_manager.get_economy_manager().get_good_definition_manager(), + definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(national_foci_file)).get_file_node() + )) { spdlog::critical_s("Failed to load national foci!"); ret = false; } if (!definition_manager.get_politics_manager().get_national_value_manager().load_national_values_file( - definition_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() + )) { spdlog::critical_s("Failed to load national values!"); ret = false; } if (!definition_manager.get_crime_manager().load_crime_modifiers( - definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(crime_modifiers_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(crime_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load crime modifiers!"); ret = false; } if (!definition_manager.get_modifier_manager().load_event_modifiers( - parse_defines(lookup_file(event_modifiers_file)).get_file_node() - )) { + parse_defines(lookup_file(event_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load event modifiers!"); ret = false; } if (!definition_manager.get_modifier_manager().load_static_modifiers( - parse_defines(lookup_file(static_modifiers_file)).get_file_node() - )) { + parse_defines(lookup_file(static_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load static modifiers!"); ret = false; } definition_manager.get_modifier_manager().lock_event_modifiers(); if (!definition_manager.get_modifier_manager().load_triggered_modifiers( - parse_defines_cached(lookup_file(triggered_modifiers_file)).get_file_node() - )) { + parse_defines_cached(lookup_file(triggered_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load triggered modifiers!"); ret = false; } @@ -1113,46 +1086,45 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_military_manager().get_leader_trait_manager().load_leader_traits_file( - definition_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() + )) { spdlog::critical_s("Failed to load leader traits!"); ret = false; } if (!definition_manager.get_military_manager().get_leader_trait_manager().setup_leader_prestige_modifier( - definition_manager.get_modifier_manager().get_modifier_effect_cache(), - definition_manager.get_define_manager().get_military_defines() - )) { + definition_manager.get_modifier_manager().get_modifier_effect_cache(), + definition_manager.get_define_manager().get_military_defines() + )) { spdlog::critical_s("Failed to set up leader prestige modifier!"); ret = false; } if (!definition_manager.get_military_manager().get_wargoal_type_manager().load_wargoal_file( - parse_defines_cached(lookup_file(cb_types_file)) - )) { + parse_defines_cached(lookup_file(cb_types_file)) + )) { spdlog::critical_s("Failed to load wargoals!"); ret = false; } if (!definition_manager.get_history_manager().get_bookmark_manager().load_bookmark_file( - definition_manager.get_map_definition().get_height(), - parse_defines(lookup_file(bookmark_file)).get_file_node() - )) { + definition_manager.get_map_definition().get_height(), parse_defines(lookup_file(bookmark_file)).get_file_node() + )) { spdlog::critical_s("Failed to load bookmarks!"); ret = false; } if (!definition_manager.get_country_definition_manager().load_countries( - definition_manager, *this, parse_defines(lookup_file(countries_file)).get_file_node() - )) { + definition_manager, *this, parse_defines(lookup_file(countries_file)).get_file_node() + )) { spdlog::critical_s("Failed to load countries!"); ret = false; } if (!definition_manager.get_country_definition_manager().load_country_colours( - parse_defines(lookup_file(country_colours_file)).get_file_node() - )) { + parse_defines(lookup_file(country_colours_file)).get_file_node() + )) { spdlog::critical_s("Failed to load country colours!"); ret = false; } if (!definition_manager.get_pop_manager().get_culture_manager().load_culture_file( - definition_manager.get_country_definition_manager(), parse_defines(lookup_file(culture_file)).get_file_node() - )) { + definition_manager.get_country_definition_manager(), parse_defines(lookup_file(culture_file)).get_file_node() + )) { spdlog::critical_s("Failed to load cultures!"); ret = false; } @@ -1177,8 +1149,8 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_event_manager().load_on_action_file( - parse_defines(lookup_file(on_actions_file)).get_file_node() - )) { + parse_defines(lookup_file(on_actions_file)).get_file_node() + )) { spdlog::critical_s("Failed to load on actions!"); ret = false; } @@ -1245,10 +1217,7 @@ static bool _load_localisation_file(Dataloader::localisation_callback_t callback } bool Dataloader::load_localisation_files(localisation_callback_t callback, std::string_view localisation_dir) const { - return apply_to_files( - lookup_files_in_dir(localisation_dir, ".csv"), - [callback](fs::path path) -> bool { - return _load_localisation_file(callback, parse_csv(path).get_lines()); - } - ); + return apply_to_files(lookup_files_in_dir(localisation_dir, ".csv"), [callback](fs::path path) -> bool { + return _load_localisation_file(callback, parse_csv(path).get_lines()); + }); } diff --git a/src/openvic-simulation/dataloader/Dataloader.hpp b/src/openvic-simulation/dataloader/Dataloader.hpp index ef268f275..f4efc5ea8 100644 --- a/src/openvic-simulation/dataloader/Dataloader.hpp +++ b/src/openvic-simulation/dataloader/Dataloader.hpp @@ -6,12 +6,12 @@ #include #include -#include "openvic-simulation/dataloader/NodeTools.hpp" +#include + +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/dataloader/ModManager.hpp" +#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" - -#include namespace OpenVic { namespace fs = std::filesystem; @@ -51,7 +51,7 @@ namespace OpenVic { * or matches an earlier found path's key is discarded, ensuring each looked up path's key is non-empty and unique. */ template path_vector_t _lookup_files_in_dir( - std::string_view path, fs::path const& extension, _UniqueKey const& unique_key + std::string_view path, fs::path const& extension, _UniqueKey const& unique_key // ) const; public: @@ -114,16 +114,18 @@ namespace OpenVic { path_vector_t lookup_files_in_dir_recursive(std::string_view path, fs::path const& extension) const; path_vector_t lookup_basic_identifier_prefixed_files_in_dir(std::string_view path, fs::path const& extension) const; path_vector_t lookup_basic_identifier_prefixed_files_in_dir_recursive( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension // ) const; static constexpr size_t apply_callback_stack_size = sizeof(std::intptr_t) * 4; - using apply_files_callback_t = fu2::function_base, false, false, bool(fs::path const&)>; + using apply_files_callback_t = fu2::function_base< + true, true, fu2::capacity_fixed, false, false, bool(fs::path const&)>; bool apply_to_files(path_span_t files, apply_files_callback_t callback) const; string_set_t lookup_dirs_in_dir(std::string_view path) const; - /* Load all mod descriptors present in the mod/ directory. Importantly, loads dependencies and replace_paths for us to check. */ + /* Load all mod descriptors present in the mod/ directory. Importantly, loads dependencies and replace_paths for us to + * check. */ bool load_mod_descriptors(ModManager& mod_manager) const; /* Load and parse all of the text defines data, including parsing cached condition and effect scripts after all the @@ -137,18 +139,30 @@ namespace OpenVic { public: enum locale_t : size_t { - English, French, German, Polish, Spanish, Italian, Swedish, - Czech, Hungarian, Dutch, Portuguese, Russian, Finnish, _LocaleCount + English, + French, + German, + Polish, + Spanish, + Italian, + Swedish, + Czech, + Hungarian, + Dutch, + Portuguese, + Russian, + 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" + "cs_CZ", "hu_HU", "nl_NL", "pt_PT", "ru_RU", "fi_FI" // }; /* Args: key, locale, localisation */ using localisation_callback_t = NodeTools::callback_t; bool load_localisation_files( - localisation_callback_t callback, std::string_view localisation_dir = "localisation" + localisation_callback_t callback, std::string_view localisation_dir = "localisation" // ) const; }; } diff --git a/src/openvic-simulation/dataloader/ModManager.cpp b/src/openvic-simulation/dataloader/ModManager.cpp index 8a970883b..f1d83e9a4 100644 --- a/src/openvic-simulation/dataloader/ModManager.cpp +++ b/src/openvic-simulation/dataloader/ModManager.cpp @@ -13,19 +13,12 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Mod::Mod( - ModManager const& manager, - std::string_view new_identifier, - std::string_view new_path, - std::optional new_user_dir, - memory::vector new_replace_paths, + ModManager const& manager, std::string_view new_identifier, std::string_view new_path, + std::optional new_user_dir, memory::vector new_replace_paths, memory::vector new_dependencies ) - : HasIdentifier { new_identifier }, - mod_manager { manager }, - dataloader_root_path { new_path }, - user_dir { new_user_dir }, - replace_paths { new_replace_paths }, - dependencies { new_dependencies } {} + : HasIdentifier { new_identifier }, mod_manager { manager }, dataloader_root_path { new_path }, user_dir { new_user_dir }, + replace_paths { new_replace_paths }, dependencies { new_dependencies } {} vector_ordered_set> Mod::generate_dependency_list(bool* success) const { static constexpr size_t MAX_RECURSE = 16; @@ -34,27 +27,20 @@ vector_ordered_set> Mod::generate_dependency_l vector_ordered_set> result; auto dep_cycle = [this, ¤t_recurse]( - auto self, - Mod const& mod, - vector_ordered_set>& dep_list - ) -> bool { + auto self, Mod const& mod, vector_ordered_set>& dep_list + ) -> bool { bool ret = true; for (std::string_view dep_identifier : mod.get_dependencies()) { Mod const* dep_ptr = mod_manager.get_mod_by_identifier(dep_identifier); if (dep_ptr == nullptr) { - spdlog::error_s( - "Mod \"{}\" has unmet dependency \"{}\" and cannot be loaded!", - mod, dep_identifier - ); + spdlog::error_s("Mod \"{}\" has unmet dependency \"{}\" and cannot be loaded!", mod, dep_identifier); return false; } Mod const& dep = *dep_ptr; - /* The poor man's cycle checking (cycles should be very rare and hard to accomplish with vic2 modding, this is a failsafe) */ + /* The poor man's cycle checking (cycles should be very rare and hard to accomplish with vic2 modding, this is a + * failsafe) */ if (current_recurse == MAX_RECURSE) { - spdlog::error_s( - "Mod \"{}\" has cyclical or broken dependency chain and cannot be loaded!", - mod - ); + spdlog::error_s("Mod \"{}\" has cyclical or broken dependency chain and cannot be loaded!", mod); return false; } else { current_recurse++; @@ -84,25 +70,20 @@ bool ModManager::load_mod_file(ast::NodeCPtr root) { memory::vector replace_paths; memory::vector dependencies; - bool ret = NodeTools::expect_dictionary_keys_and_default_map( - map_key_value_ignore_invalid_callback>, - "name", ONE_EXACTLY, expect_string(assign_variable_callback(identifier)), - "path", ONE_EXACTLY, expect_string(assign_variable_callback(path)), - "user_dir", ZERO_OR_ONE, expect_string(assign_variable_callback_opt(user_dir)), - "replace_path", ZERO_OR_MORE, expect_string(vector_callback_string(replace_paths)), - "dependencies", ZERO_OR_ONE, expect_list_reserve_length(dependencies, expect_string(vector_callback_string(dependencies))) - )(root); + bool + ret = + NodeTools:: + expect_dictionary_keys_and_default_map(map_key_value_ignore_invalid_callback>, "name", ONE_EXACTLY, expect_string(assign_variable_callback(identifier)), "path", ONE_EXACTLY, expect_string(assign_variable_callback(path)), "user_dir", ZERO_OR_ONE, expect_string(assign_variable_callback_opt(user_dir)), "replace_path", ZERO_OR_MORE, expect_string(vector_callback_string(replace_paths)), "dependencies", ZERO_OR_ONE, expect_list_reserve_length(dependencies, expect_string(vector_callback_string(dependencies))))( + root + ); if (!ret) { - //NodeTools already logs and an invalid (unloaded) mod won't stop the game. + // NodeTools already logs and an invalid (unloaded) mod won't stop the game. return true; } SPDLOG_INFO("Loaded mod descriptor for \"{}\"", identifier); - mods.emplace_item( - identifier, - *this, identifier, path, user_dir, std::move(replace_paths), std::move(dependencies) - ); + mods.emplace_item(identifier, *this, identifier, path, user_dir, std::move(replace_paths), std::move(dependencies)); return true; } diff --git a/src/openvic-simulation/dataloader/ModManager.hpp b/src/openvic-simulation/dataloader/ModManager.hpp index 20a6837bc..28a9e4f93 100644 --- a/src/openvic-simulation/dataloader/ModManager.hpp +++ b/src/openvic-simulation/dataloader/ModManager.hpp @@ -4,9 +4,9 @@ #include #include +#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -24,14 +24,9 @@ namespace OpenVic { const memory::vector SPAN_PROPERTY(dependencies); public: - Mod( - ModManager const& manager, - std::string_view new_identifier, - std::string_view new_path, - std::optional new_user_dir, - memory::vector new_replace_paths, - memory::vector new_dependencies - ); + Mod(ModManager const& manager, std::string_view new_identifier, std::string_view new_path, + std::optional new_user_dir, memory::vector new_replace_paths, + memory::vector new_dependencies); Mod(Mod&&) = default; vector_ordered_set> generate_dependency_list(bool* success = nullptr) const; @@ -51,4 +46,4 @@ namespace OpenVic { void set_loaded_mods(memory::vector>&& new_loaded_mods); size_t get_loaded_mod_count() const; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/dataloader/NodeTools.cpp b/src/openvic-simulation/dataloader/NodeTools.cpp index 0ccb2e631..b660a356c 100644 --- a/src/openvic-simulation/dataloader/NodeTools.cpp +++ b/src/openvic-simulation/dataloader/NodeTools.cpp @@ -15,8 +15,8 @@ #include #include -#include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/core/ui/TextFormat.hpp" +#include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/Vector.hpp" #include "openvic-simulation/utility/Getters.hpp" @@ -34,10 +34,7 @@ static NodeCallback auto _expect_type(Callback auto&& callback) { if (cast_node != nullptr) { return callback(cast_node); } - spdlog::error_s( - "Invalid node type {} when expecting {}", - ast::get_type_name(node->kind()), type_name() - ); + spdlog::error_s("Invalid node type {} when expecting {}", ast::get_type_name(node->kind()), type_name()); } else { spdlog::error_s("Null node when expecting {}", type_name()); } @@ -58,14 +55,11 @@ static NodeCallback auto _abstract_statement_node_callback(Callback<_NodeStateme return callback(list_value->statements()); } spdlog::error_s( - "Invalid node type {} when expecting {} or {}", - ast::get_type_name(node->kind()), type_name(), type_name() + "Invalid node type {} when expecting {} or {}", ast::get_type_name(node->kind()), type_name(), + type_name() ); } else { - spdlog::error_s( - "Null node when expecting {} or {}", - type_name(), type_name() - ); + spdlog::error_s("Null node when expecting {} or {}", type_name(), type_name()); } return false; }; @@ -121,13 +115,12 @@ node_callback_t NodeTools::expect_identifier_or_string(callback_t(FWD(callback), allow_empty)(cast_node); } spdlog::error_s( - "Invalid node type {} when expecting {} or {}", - ast::get_type_name(node->kind()), type_name(), type_name() + "Invalid node type {} when expecting {} or {}", ast::get_type_name(node->kind()), + type_name(), type_name() ); } else { spdlog::error_s( - "Null node when expecting {} or {}", - type_name(), type_name() + "Null node when expecting {} or {}", type_name(), type_name() ); } return false; @@ -152,7 +145,7 @@ node_callback_t NodeTools::expect_int64(callback_t callback, int base) return expect_identifier([callback, base](std::string_view identifier) mutable -> bool { int64_t val; std::from_chars_result result = string_to_int64(identifier, val, base); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(val); } spdlog::error_s("Invalid int identifier text: {}", identifier); @@ -164,7 +157,7 @@ node_callback_t NodeTools::expect_uint64(callback_t callback, int base return expect_identifier([callback, base](std::string_view identifier) mutable -> bool { uint64_t val; std::from_chars_result result = string_to_uint64(identifier, val, base); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(val); } spdlog::error_s("Invalid uint identifier text: {}", identifier); @@ -192,25 +185,23 @@ node_callback_t NodeTools::expect_colour(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { colour_t col = colour_t::null(); int32_t components = 0; - bool ret = expect_list_of_length(3, expect_fixed_point( - [&col, &components](fixed_point_t val) -> bool { - if (val < 0 || val > 255) { - spdlog::error_s( - "Invalid colour component #{}: {}", - components++, val - ); - return false; - } else { - if (val <= 1) { - val *= 255; - } else if (!val.is_integer()) { - spdlog::warn_s("Fractional part of colour component #{} will be truncated: {}", components, val); - } - col[components++] = val.truncate(); - return true; - } - } - ))(node); + bool ret = expect_list_of_length(3, expect_fixed_point([&col, &components](fixed_point_t val) -> bool { + if (val < 0 || val > 255) { + spdlog::error_s("Invalid colour component #{}: {}", components++, val); + return false; + } else { + if (val <= 1) { + val *= 255; + } else if (!val.is_integer()) { + spdlog::warn_s( + "Fractional part of colour component #{} will be truncated: {}", + components, val + ); + } + col[components++] = val.truncate(); + return true; + } + }))(node); if (ret) { ret &= callback(col); } @@ -219,16 +210,19 @@ node_callback_t NodeTools::expect_colour(callback_t callback) { } node_callback_t NodeTools::expect_colour_hex(callback_t callback) { - return expect_uint([callback](colour_argb_t::integer_type val) mutable -> bool { - return callback(colour_argb_t::from_argb(val)); - }, 16); + return expect_uint( + [callback](colour_argb_t::integer_type val) mutable -> bool { + return callback(colour_argb_t::from_argb(val)); + }, + 16 + ); } callback_t NodeTools::expect_date_str(callback_t callback) { return [callback](std::string_view identifier) mutable -> bool { Date::from_chars_result result; const Date date = Date::from_string_log(identifier, &result); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(date); } spdlog::error_s("Invalid date identifier text: {}", identifier); @@ -270,10 +264,10 @@ template)> NodeCallback auto _expect_vec2(Callback> auto&& callback) { return [callback = FWD(callback)](ast::NodeCPtr node) mutable -> bool { vec2_t vec; - bool ret = expect_dictionary_keys( - "x", ONE_EXACTLY, expect_func(assign_variable_callback(vec.x)), - "y", ONE_EXACTLY, expect_func(assign_variable_callback(vec.y)) - )(node); + bool ret = + expect_dictionary_keys("x", ONE_EXACTLY, expect_func(assign_variable_callback(vec.x)), "y", ONE_EXACTLY, expect_func(assign_variable_callback(vec.y)))( + node + ); if (ret) { ret &= callback(vec); } @@ -285,11 +279,7 @@ node_callback_t NodeTools::expect_text_format(callback_t callback using enum text_format_t; static const string_map_t format_map = { - { "left", left }, - { "right", right }, - { "centre", centre }, - { "center", centre }, - { "justified", justified } + { "left", left }, { "right", right }, { "centre", centre }, { "center", centre }, { "justified", justified } }; return expect_identifier(expect_mapped_string(format_map, callback)); @@ -313,12 +303,10 @@ node_callback_t NodeTools::expect_fvec3(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { fvec3_t vec; int32_t components = 0; - bool ret = expect_list_of_length(3, expect_fixed_point( - [&vec, &components](fixed_point_t val) -> bool { - vec[components++] = val; - return true; - } - ))(node); + bool ret = expect_list_of_length(3, expect_fixed_point([&vec, &components](fixed_point_t val) -> bool { + vec[components++] = val; + return true; + }))(node); if (ret) { ret &= callback(vec); } @@ -330,12 +318,10 @@ node_callback_t NodeTools::expect_fvec4(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { fvec4_t vec; int32_t components = 0; - bool ret = expect_list_of_length(4, expect_fixed_point( - [&vec, &components](fixed_point_t val) -> bool { - vec[components++] = val; - return true; - } - ))(node); + bool ret = expect_list_of_length(4, expect_fixed_point([&vec, &components](fixed_point_t val) -> bool { + vec[components++] = val; + return true; + }))(node); if (ret) { ret &= callback(vec); } @@ -366,10 +352,7 @@ node_callback_t NodeTools::expect_list_and_length(length_callback_t length_callb size_t size = length_callback(dist); if (size > dist) { - spdlog::error_s( - "Trying to read more values than the list contains: {} > {}", - size, dist - ); + spdlog::error_s("Trying to read more values than the list contains: {} > {}", size, dist); size = dist; ret = false; } @@ -450,55 +433,54 @@ static node_callback_t _expect_key(Key key, NodeCallback auto&& callback, bool* } }; - return _abstract_statement_node_callback([key, callback = FWD(callback), key_found, allow_duplicates](_NodeStatementRange list) mutable -> bool { - bool ret = true; - size_t keys_found = 0; - for (ast::Statement const* sub_node : list) { - auto const* assign_node = dryad::node_try_cast(sub_node); - if (assign_node == nullptr) { - continue; - } - Key left; - if (!assign_left(left)(assign_node->left())) { - continue; - } - if (left == key) { - if (keys_found++ == 0) { - ret &= callback(assign_node->right()); - if (allow_duplicates) { - break; + return _abstract_statement_node_callback( + [key, callback = FWD(callback), key_found, allow_duplicates](_NodeStatementRange list) mutable -> bool { + bool ret = true; + size_t keys_found = 0; + for (ast::Statement const* sub_node : list) { + auto const* assign_node = dryad::node_try_cast(sub_node); + if (assign_node == nullptr) { + continue; + } + Key left; + if (!assign_left(left)(assign_node->left())) { + continue; + } + if (left == key) { + if (keys_found++ == 0) { + ret &= callback(assign_node->right()); + if (allow_duplicates) { + break; + } } } } - } - std::string_view key_str = [&] { - if constexpr (std::same_as) { - return key; - } else { - return key.view(); - } - }(); - if (keys_found == 0) { - if (key_found != nullptr) { - *key_found = false; - } else { - spdlog::error_s("Failed to find expected key: \"{}\"", key_str); - } - ret = false; - } else { - if (key_found != nullptr) { - *key_found = true; - } - if (!allow_duplicates && keys_found > 1) { - spdlog::error_s( - "Found {} instances of key: \"{}\" (expected 1)", - keys_found, key_str - ); + std::string_view key_str = [&] { + if constexpr (std::same_as) { + return key; + } else { + return key.view(); + } + }(); + if (keys_found == 0) { + if (key_found != nullptr) { + *key_found = false; + } else { + spdlog::error_s("Failed to find expected key: \"{}\"", key_str); + } ret = false; + } else { + if (key_found != nullptr) { + *key_found = true; + } + if (!allow_duplicates && keys_found > 1) { + spdlog::error_s("Found {} instances of key: \"{}\" (expected 1)", keys_found, key_str); + ret = false; + } } + return ret; } - return ret; - }); + ); } node_callback_t NodeTools::expect_key(std::string_view key, node_callback_t callback, bool* key_found, bool allow_duplicates) { @@ -521,9 +503,7 @@ node_callback_t NodeTools::expect_dictionary(key_value_callback_t callback) { node_callback_t NodeTools::name_list_callback(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { name_list_t list; - bool ret = expect_list_reserve_length( - list, expect_identifier_or_string(vector_callback(list)) - )(node); + bool ret = expect_list_reserve_length(list, expect_identifier_or_string(vector_callback(list)))(node); ret &= callback(std::move(list)); return ret; }; diff --git a/src/openvic-simulation/dataloader/NodeTools.hpp b/src/openvic-simulation/dataloader/NodeTools.hpp index cd76905f4..831f9550e 100644 --- a/src/openvic-simulation/dataloader/NodeTools.hpp +++ b/src/openvic-simulation/dataloader/NodeTools.hpp @@ -14,21 +14,21 @@ #include +#include + #include +#include "openvic-simulation/core/FormatValidate.hpp" +#include "openvic-simulation/core/string/Utility.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/core/ui/TextFormat.hpp" #include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/core/ui/TextFormat.hpp" #include "openvic-simulation/types/Vector.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" -#include "openvic-simulation/utility/TslHelper.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/string/Utility.hpp" - -#include +#include "openvic-simulation/utility/TslHelper.hpp" #define MOV(...) static_cast&&>(__VA_ARGS__) #define FWD(...) static_cast(__VA_ARGS__) @@ -40,7 +40,7 @@ namespace OpenVic { static constexpr std::string_view get_type_name(NodeKind kind) { #ifdef _MSC_VER // type_name starts with "struct " -using namespace std::string_view_literals; + using namespace std::string_view_literals; #define NODE_CASE(Node) \ case Node: return OpenVic::type_name().substr("struct "sv.size()); #else @@ -95,14 +95,11 @@ using namespace std::string_view_literals; template concept MapKeyValueCallback = Callback; - + template constexpr static MapKeyValueCallback auto ignore_map(KeyValueCallback auto&& callback) { - return [default_callback = MOV(callback)]( - Map const& key_map, - std::string_view key, - ast::NodeCPtr value - ) mutable -> bool { + return [default_callback = + MOV(callback)](Map const& key_map, std::string_view key, ast::NodeCPtr value) mutable -> bool { return default_callback(key, value); }; } @@ -133,19 +130,13 @@ using namespace std::string_view_literals; template inline bool map_key_value_invalid_callback(Map const& key_map, std::string_view key, ast::NodeCPtr) { - spdlog::error_s( - "Invalid dictionary key \"{}\". Valid values are [{}]", - key, string_join(key_map) - ); + spdlog::error_s("Invalid dictionary key \"{}\". Valid values are [{}]", key, string_join(key_map)); return false; } template inline bool map_key_value_ignore_invalid_callback(Map const& key_map, std::string_view key, ast::NodeCPtr) { - spdlog::warn_s( - "Invalid dictionary key \"{}\" is ignored. Valid values are [{}]", - key, string_join(key_map) - ); + spdlog::warn_s("Invalid dictionary key \"{}\" is ignored. Valid values are [{}]", key, string_join(key_map)); return true; } @@ -161,19 +152,20 @@ using namespace std::string_view_literals; template NodeCallback auto expect_int(callback_t& callback, int base = 10) { - return expect_int64([callback](int64_t val) mutable -> bool { - if (static_cast(std::numeric_limits::lowest()) <= val && - val <= static_cast(std::numeric_limits::max())) { - return callback(val); - } - spdlog::error_s( - "Invalid int: {} (valid range: [{}, {}])", - val, - static_cast(std::numeric_limits::lowest()), - static_cast(std::numeric_limits::max()) - ); - return false; - }, base); + return expect_int64( + [callback](int64_t val) mutable -> bool { + if (static_cast(std::numeric_limits::lowest()) <= val && + val <= static_cast(std::numeric_limits::max())) { + return callback(val); + } + spdlog::error_s( + "Invalid int: {} (valid range: [{}, {}])", val, static_cast(std::numeric_limits::lowest()), + static_cast(std::numeric_limits::max()) + ); + return false; + }, + base + ); } template NodeCallback auto expect_int(callback_t&& callback, int base = 10) { @@ -182,16 +174,18 @@ using namespace std::string_view_literals; template NodeCallback auto expect_uint(callback_t& callback, int base = 10) { - return expect_uint64([callback](uint64_t val) mutable -> bool { - if (val <= static_cast(std::numeric_limits::max())) { - return callback(val); - } - spdlog::error_s( - "Invalid uint: {} (valid range: [0, {}])", - val, static_cast(std::numeric_limits::max()) - ); - return false; - }, base); + return expect_uint64( + [callback](uint64_t val) mutable -> bool { + if (val <= static_cast(std::numeric_limits::max())) { + return callback(val); + } + spdlog::error_s( + "Invalid uint: {} (valid range: [0, {}])", val, static_cast(std::numeric_limits::max()) + ); + return false; + }, + base + ); } template NodeCallback auto expect_uint(callback_t&& callback, int base = 10) { @@ -281,13 +275,11 @@ using namespace std::string_view_literals; node_callback_t expect_list(node_callback_t callback); node_callback_t expect_length(callback_t callback); - node_callback_t expect_key( - ovdl::symbol key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false - ); + node_callback_t + expect_key(ovdl::symbol key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false); - node_callback_t expect_key( - std::string_view key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false - ); + node_callback_t + expect_key(std::string_view key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false); node_callback_t expect_dictionary_and_length(length_callback_t length_callback, key_value_callback_t callback); node_callback_t expect_dictionary(key_value_callback_t callback); @@ -346,10 +338,9 @@ using namespace std::string_view_literals; } template - KeyValueCallback auto dictionary_keys_callback( - Map&& key_map, MapKeyValueCallback auto&& default_callback - ) { - return [&key_map, default_callback = FWD(default_callback)](std::string_view key, ast::NodeCPtr value) mutable -> bool { + KeyValueCallback auto dictionary_keys_callback(Map&& key_map, MapKeyValueCallback auto&& default_callback) { + return [&key_map, + default_callback = FWD(default_callback)](std::string_view key, ast::NodeCPtr value) mutable -> bool { typename std::remove_reference_t::iterator it = key_map.find(key); if (it == key_map.end()) { return default_callback(key_map, key, value); @@ -401,30 +392,27 @@ using namespace std::string_view_literals; NodeCallback auto expect_dictionary_key_map_and_length_and_default( Map&& key_map, LengthCallback auto&& length_callback, MapKeyValueCallback auto&& default_callback ) { - return [length_callback = FWD(length_callback), default_callback = FWD(default_callback), key_map = MOV(key_map)]( - ast::NodeCPtr node - ) mutable -> bool { - bool ret = expect_dictionary_and_length( - FWD(length_callback), dictionary_keys_callback(key_map, FWD(default_callback)) - )(node); + return [length_callback = FWD(length_callback), default_callback = FWD(default_callback), + key_map = MOV(key_map)](ast::NodeCPtr node) mutable -> bool { + bool ret = + expect_dictionary_and_length(FWD(length_callback), dictionary_keys_callback(key_map, FWD(default_callback)))( + node + ); ret &= check_key_map_counts(key_map); return ret; }; } template - NodeCallback auto expect_dictionary_key_map_and_length( - Map&& key_map, LengthCallback auto&& length_callback - ) { + NodeCallback auto expect_dictionary_key_map_and_length(Map&& key_map, LengthCallback auto&& length_callback) { return expect_dictionary_key_map_and_length_and_default( FWD(key_map), FWD(length_callback), map_key_value_invalid_callback ); } template - NodeCallback auto expect_dictionary_key_map_and_default( - Map&& key_map, MapKeyValueCallback auto&& default_callback - ) { + NodeCallback auto + expect_dictionary_key_map_and_default(Map&& key_map, MapKeyValueCallback auto&& default_callback) { return expect_dictionary_key_map_and_length_and_default( FWD(key_map), default_length_callback, FWD(default_callback) ); @@ -433,7 +421,10 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_key_map(template_key_map_t&& key_map) { return expect_dictionary_key_map_and_length_and_default( - MOV(key_map), default_length_callback, map_key_value_ignore_invalid_callback> // we use map_key_value_ignore_invalid_callback here as some mods add extraneous keys (like maxWidth) which V2 ignores, so we must too + MOV(key_map), default_length_callback, + map_key_value_ignore_invalid_callback> // we use map_key_value_ignore_invalid_callback + // here as some mods add extraneous keys (like + // maxWidth) which V2 ignores, so we must too ); } @@ -448,9 +439,8 @@ using namespace std::string_view_literals; } template - NodeCallback auto expect_dictionary_key_map_and_length( - Map&& key_map, LengthCallback auto&& length_callback, Args&&... args - ) { + NodeCallback auto + expect_dictionary_key_map_and_length(Map&& key_map, LengthCallback auto&& length_callback, Args&&... args) { add_key_map_entries(FWD(key_map), FWD(args)...); return expect_dictionary_key_map_and_length(FWD(key_map), FWD(length_callback)); } @@ -463,14 +453,9 @@ using namespace std::string_view_literals; return expect_dictionary_key_map_and_default(FWD(key_map), FWD(default_callback)); } template - NodeCallback auto expect_dictionary_key_map_and_default( - Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args - ) { - return expect_dictionary_key_map_and_default_map( - key_map, - ignore_map(FWD(default_callback)), - FWD(args)... - ); + NodeCallback auto + expect_dictionary_key_map_and_default(Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args) { + return expect_dictionary_key_map_and_default_map(key_map, ignore_map(FWD(default_callback)), FWD(args)...); } template @@ -481,7 +466,8 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_keys_and_length_and_default( - LengthCallback auto&& length_callback, MapKeyValueCallback> auto&& default_callback, Args&&... args + LengthCallback auto&& length_callback, MapKeyValueCallback> auto&& default_callback, + Args&&... args ) { return expect_dictionary_key_map_and_length_and_default( template_key_map_t {}, FWD(length_callback), FWD(default_callback), FWD(args)... @@ -491,12 +477,15 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_keys_and_length(LengthCallback auto&& length_callback, Args&&... args) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, FWD(length_callback), map_key_value_invalid_callback>, FWD(args)... + template_key_map_t {}, FWD(length_callback), map_key_value_invalid_callback>, + FWD(args)... ); } template - NodeCallback auto expect_dictionary_keys_and_default_map(MapKeyValueCallback> auto&& default_callback, Args&&... args) { + NodeCallback auto expect_dictionary_keys_and_default_map( + MapKeyValueCallback> auto&& default_callback, Args&&... args + ) { return expect_dictionary_key_map_and_length_and_default( template_key_map_t {}, default_length_callback, FWD(default_callback), FWD(args)... ); @@ -504,15 +493,15 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_keys_and_default(KeyValueCallback auto&& default_callback, Args&&... args) { return expect_dictionary_keys_and_default_map( - ignore_map>(FWD(default_callback)), - FWD(args)... + ignore_map>(FWD(default_callback)), FWD(args)... ); } template NodeCallback auto expect_dictionary_keys(Args&&... args) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, default_length_callback, map_key_value_invalid_callback>, FWD(args)... + template_key_map_t {}, default_length_callback, map_key_value_invalid_callback>, + FWD(args)... ); } @@ -530,17 +519,14 @@ using namespace std::string_view_literals; } template NodeCallback auto expect_dictionary_key_map_reserve_length_and_default( - reservable auto& reservable, Map&& key_map, KeyValueCallback auto&& default_callback, - Args&&... args + reservable auto& reservable, Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args ) { return expect_dictionary_key_map_and_length_and_default( FWD(key_map), reserve_length_callback(reservable), FWD(default_callback), FWD(args)... ); } template - NodeCallback auto expect_dictionary_key_map_reserve_length( - reservable auto& reservable, Map&& key_map, Args&&... args - ) { + NodeCallback auto expect_dictionary_key_map_reserve_length(reservable auto& reservable, Map&& key_map, Args&&... args) { return expect_dictionary_key_map_and_length(FWD(key_map), reserve_length_callback(reservable), FWD(args)...); } @@ -557,9 +543,7 @@ using namespace std::string_view_literals; reservable auto& reservable, KeyValueCallback auto&& default_callback, Args&&... args ) { return expect_dictionary_keys_reserve_length_and_default_map( - reservable, - ignore_map>(FWD(default_callback)), - FWD(args)... + reservable, ignore_map>(FWD(default_callback)), FWD(args)... ); } @@ -571,18 +555,16 @@ using namespace std::string_view_literals; node_callback_t name_list_callback(callback_t callback); template - Callback auto expect_mapped_string( - template_string_map_t const& map, Callback auto&& callback, bool warn = false - ) { + Callback auto + expect_mapped_string(template_string_map_t const& map, Callback auto&& callback, bool warn = false) { return [&map, callback = FWD(callback), warn](std::string_view string) mutable -> bool { const typename template_string_map_t::const_iterator it = map.find(string); if (it != map.end()) { return callback(it->second); } spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "\"{}\" is not a valid key. Valid keys: [{}]", - string, string_join(map) + warn ? spdlog::level::warn : spdlog::level::err, "\"{}\" is not a valid key. Valid keys: [{}]", string, + string_join(map) ); return warn; }; @@ -613,9 +595,7 @@ using namespace std::string_view_literals; /* By default this will only allow an optional to be set once. Set allow_overwrite * to true to allow multiple assignments, with the last taking precedence. */ template - Callback auto assign_variable_callback_opt( - std::optional& var, bool allow_overwrite = false - ) { + Callback auto assign_variable_callback_opt(std::optional& var, bool allow_overwrite = false) { return [&var, allow_overwrite](T const& val) -> bool { if (!allow_overwrite && var.has_value()) { spdlog::error_s("Cannot assign value to already-initialised optional!"); @@ -629,9 +609,7 @@ using namespace std::string_view_literals; /* By default this will only allow an optional to be set once. Set allow_overwrite * to true to allow multiple assignments, with the last taking precedence. */ template - auto emplace_opt_callback( - std::optional& var, bool allow_overwrite = false - ) { + auto emplace_opt_callback(std::optional& var, bool allow_overwrite = false) { return [&var, allow_overwrite](auto&&... args) -> bool { if (!allow_overwrite && var.has_value()) { spdlog::error_s("Cannot assign value to already-initialised optional!"); @@ -689,9 +667,8 @@ using namespace std::string_view_literals; /* By default this will only allow an optional to be set once. Set allow_overwrite * to true to allow multiple assignments, with the last taking precedence. */ template - Callback auto assign_variable_callback_pointer_opt( - std::optional& var, bool allow_overwrite = false - ) { + Callback auto + assign_variable_callback_pointer_opt(std::optional& var, bool allow_overwrite = false) { return [&var, allow_overwrite](T const& val) -> bool { if (!allow_overwrite && var.has_value()) { spdlog::error_s("Cannot assign pointer value to already-initialised optional!"); @@ -739,10 +716,7 @@ using namespace std::string_view_literals; if (set.emplace(std::move(val)).second) { return true; } - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate set entry: \"{}\"", val - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate set entry: \"{}\"", val); return warn; }; } @@ -753,42 +727,31 @@ using namespace std::string_view_literals; if (set.emplace(&val).second) { return true; } - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate set entry: \"{}\"", - val - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate set entry: \"{}\"", val); return warn; }; } template - Callback auto map_callback( - tsl::ordered_map& map, Key key, bool warn = false - ) { + Callback auto map_callback(tsl::ordered_map& map, Key key, bool warn = false) { return [&map, key, warn](Value value) -> bool { if (map.emplace(key, std::move(value)).second) { return true; } - if constexpr(std::is_pointer_v) { + if constexpr (std::is_pointer_v) { spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate map entry with key: \"{}\"", ovfmt::validate(key) + warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", + ovfmt::validate(key) ); } else { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate map entry with key: \"{}\"", key - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", key); } return warn; }; } template - Callback auto map_callback( - IndexedFlatMap& map, Key const* key, bool warn = false - ) { + Callback auto map_callback(IndexedFlatMap& map, Key const* key, bool warn = false) { return [&map, key, warn](Value value) -> bool { if (key == nullptr) { spdlog::error_s("Null key in map_callback"); @@ -797,7 +760,9 @@ using namespace std::string_view_literals; Value& map_value = map.at(*key); bool ret = true; if (map_value != Value {}) { - spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", *key); + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", *key + ); ret = warn; } map_value = std::move(value); diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp index 11c079dc7..aa713134b 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp @@ -262,7 +262,8 @@ static fs::path _search_for_game_path(fs::path hint_path) { current_node = std::visit(visit_node, it->second); if (!current_node.has_value()) { - return search_log(hint_empty, "Expected libraryfolders.vdf's libraryfolders key to be a KeyValue dictionary.").result(); + return search_log(hint_empty, "Expected libraryfolders.vdf's libraryfolders key to be a KeyValue dictionary.") + .result(); } // Array of strings contain "0" to std::to_string(max_amount_of_steam_libraries - 1) diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp index c1c456c59..82e4dd6b3 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp @@ -9,8 +9,8 @@ #include -#include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/utility/Containers.hpp" namespace OpenVic::Windows { inline memory::wstring convert(std::string_view as) { diff --git a/src/openvic-simulation/defines/AIDefines.cpp b/src/openvic-simulation/defines/AIDefines.cpp index c57e3d00d..793ea2d93 100644 --- a/src/openvic-simulation/defines/AIDefines.cpp +++ b/src/openvic-simulation/defines/AIDefines.cpp @@ -11,51 +11,47 @@ std::string_view AIDefines::get_name() const { node_callback_t AIDefines::expect_defines() { return expect_dictionary_keys( - "COLONY_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colony_weight)), - "ADMINISTRATOR_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(administrator_weight)), - "INDUSTRYWORKER_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(industryworker_weight)), - "EDUCATOR_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(educator_weight)), - "SOLDIER_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_weight)), - "SOLDIER_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_fraction)), - "CAPITALIST_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(capitalist_fraction)), - "PRODUCTION_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(production_weight)), - "SPAM_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spam_penalty)), - "ONE_SIDE_MAX_WARSCORE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(one_side_max_warscore)), - "POP_PROJECT_INVESTMENT_MAX_BUDGET_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_project_investment_max_budget_factor)), + "COLONY_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colony_weight)), "ADMINISTRATOR_WEIGHT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(administrator_weight)), "INDUSTRYWORKER_WEIGHT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(industryworker_weight)), "EDUCATOR_WEIGHT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(educator_weight)), "SOLDIER_WEIGHT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(soldier_weight)), "SOLDIER_FRACTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(soldier_fraction)), "CAPITALIST_FRACTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(capitalist_fraction)), "PRODUCTION_WEIGHT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(production_weight)), "SPAM_PENALTY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spam_penalty)), "ONE_SIDE_MAX_WARSCORE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(one_side_max_warscore)), "POP_PROJECT_INVESTMENT_MAX_BUDGET_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_project_investment_max_budget_factor)), "RELATION_LIMIT_NO_ALLIANCE_OFFER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(relation_limit_no_alliance_offer)), - "NAVAL_SUPPLY_PENALTY_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_supply_penalty_limit)), - "CHANCE_BUILD_RAILROAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_railroad)), - "CHANCE_BUILD_NAVAL_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_naval_base)), - "CHANCE_BUILD_FORT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_fort)), - "CHANCE_INVEST_POP_PROJ", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_invest_pop_proj)), - "CHANCE_FOREIGN_INVEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_foreign_invest)), - "TWS_AWARENESS_SCORE_LOW_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_awareness_score_low_cap)), - "TWS_AWARENESS_SCORE_ASPECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_awareness_score_aspect)), - "PEACE_BASE_RELUCTANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_base_reluctance)), - "PEACE_TIME_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(peace_time_duration)), - "PEACE_TIME_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_time_factor)), - "PEACE_TIME_FACTOR_NO_GOALS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_time_factor_no_goals)), - "PEACE_WAR_EXHAUSTION_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_war_exhaustion_factor)), - "PEACE_WAR_DIRECTION_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_war_direction_factor)), - "PEACE_WAR_DIRECTION_WINNING_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_war_direction_winning_mult)), + expect_fixed_point(assign_variable_callback(relation_limit_no_alliance_offer)), "NAVAL_SUPPLY_PENALTY_LIMIT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_supply_penalty_limit)), "CHANCE_BUILD_RAILROAD", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_railroad)), "CHANCE_BUILD_NAVAL_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_naval_base)), "CHANCE_BUILD_FORT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_build_fort)), "CHANCE_INVEST_POP_PROJ", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_invest_pop_proj)), "CHANCE_FOREIGN_INVEST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_foreign_invest)), "TWS_AWARENESS_SCORE_LOW_CAP", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_awareness_score_low_cap)), "TWS_AWARENESS_SCORE_ASPECT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_awareness_score_aspect)), "PEACE_BASE_RELUCTANCE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_base_reluctance)), "PEACE_TIME_MONTHS", ONE_EXACTLY, + expect_months(assign_variable_callback(peace_time_duration)), "PEACE_TIME_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_time_factor)), "PEACE_TIME_FACTOR_NO_GOALS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_time_factor_no_goals)), "PEACE_WAR_EXHAUSTION_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_war_exhaustion_factor)), "PEACE_WAR_DIRECTION_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_war_direction_factor)), "PEACE_WAR_DIRECTION_WINNING_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_war_direction_winning_mult)), "PEACE_FORCE_BALANCE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_force_balance_factor)), "PEACE_ALLY_BASE_RELUCTANCE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_base_reluctance_mult)), - "PEACE_ALLY_TIME_MULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_ally_time_mult)), - "PEACE_ALLY_WAR_EXHAUSTION_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_war_exhaustion_mult)), - "PEACE_ALLY_WAR_DIRECTION_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_war_direction_mult)), + expect_fixed_point(assign_variable_callback(peace_ally_base_reluctance_mult)), "PEACE_ALLY_TIME_MULT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_time_mult)), "PEACE_ALLY_WAR_EXHAUSTION_MULT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_war_exhaustion_mult)), "PEACE_ALLY_WAR_DIRECTION_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_ally_war_direction_mult)), "PEACE_ALLY_FORCE_BALANCE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_force_balance_mult)), - "AGGRESSION_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(aggression_base)), - "AGGRESSION_UNCIV_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(aggression_unciv_bonus)), - "FLEET_SIZE", ONE_EXACTLY, expect_uint(assign_variable_callback(fleet_size)), - "MIN_FLEETS", ONE_EXACTLY, expect_uint(assign_variable_callback(min_fleets)), - "MAX_FLEETS", ONE_EXACTLY, expect_uint(assign_variable_callback(max_fleets)), - "MONTHS_BEFORE_DISBAND", ONE_EXACTLY, expect_months(assign_variable_callback(time_before_disband)) + expect_fixed_point(assign_variable_callback(peace_ally_force_balance_mult)), "AGGRESSION_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(aggression_base)), "AGGRESSION_UNCIV_BONUS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(aggression_unciv_bonus)), "FLEET_SIZE", ONE_EXACTLY, + expect_uint(assign_variable_callback(fleet_size)), "MIN_FLEETS", ONE_EXACTLY, + expect_uint(assign_variable_callback(min_fleets)), "MAX_FLEETS", ONE_EXACTLY, + expect_uint(assign_variable_callback(max_fleets)), "MONTHS_BEFORE_DISBAND", ONE_EXACTLY, + expect_months(assign_variable_callback(time_before_disband)) ); } diff --git a/src/openvic-simulation/defines/CountryDefines.cpp b/src/openvic-simulation/defines/CountryDefines.cpp index fe28cf070..0f75d9a76 100644 --- a/src/openvic-simulation/defines/CountryDefines.cpp +++ b/src/openvic-simulation/defines/CountryDefines.cpp @@ -13,129 +13,110 @@ node_callback_t CountryDefines::expect_defines() { return expect_dictionary_keys( "YEARS_OF_NATIONALISM", ONE_EXACTLY, expect_years(assign_variable_callback(nationalism_duration)), "MONTHS_UNTIL_BROKEN", ZERO_OR_ONE, // NOT USED - expect_months(assign_variable_callback(rebels_hold_capital_success_duration)), - "REBEL_ACCEPTANCE_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(rebel_success_duration)), - "BASE_COUNTRY_TAX_EFFICIENCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_country_tax_efficiency)), - "BASE_COUNTRY_ADMIN_EFFICIENCY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(base_country_admin_efficiency)), - "GOLD_TO_CASH_RATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gold_to_cash_rate)), - "GOLD_TO_WORKER_PAY_RATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gold_to_worker_pay_rate)), - "GREAT_NATIONS_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(great_power_rank)), - "GREATNESS_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(lose_great_power_grace_days)), - "BADBOY_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_containment_limit)), - "MAX_BUREAUCRACY_PERCENTAGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_bureaucracy_percentage)), - "BUREAUCRACY_PERCENTAGE_INCREMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(bureaucracy_percentage_increment)), - "MIN_CRIMEFIGHT_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_crimefight_percent)), - "MAX_CRIMEFIGHT_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_crimefight_percent)), + expect_months(assign_variable_callback(rebels_hold_capital_success_duration)), "REBEL_ACCEPTANCE_MONTHS", ONE_EXACTLY, + expect_months(assign_variable_callback(rebel_success_duration)), "BASE_COUNTRY_TAX_EFFICIENCY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_country_tax_efficiency)), "BASE_COUNTRY_ADMIN_EFFICIENCY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_country_admin_efficiency)), "GOLD_TO_CASH_RATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gold_to_cash_rate)), "GOLD_TO_WORKER_PAY_RATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gold_to_worker_pay_rate)), "GREAT_NATIONS_COUNT", ONE_EXACTLY, + expect_uint(assign_variable_callback(great_power_rank)), "GREATNESS_DAYS", ONE_EXACTLY, + expect_days(assign_variable_callback(lose_great_power_grace_days)), "BADBOY_LIMIT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_containment_limit)), "MAX_BUREAUCRACY_PERCENTAGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_bureaucracy_percentage)), "BUREAUCRACY_PERCENTAGE_INCREMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bureaucracy_percentage_increment)), "MIN_CRIMEFIGHT_PERCENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_crimefight_percent)), "MAX_CRIMEFIGHT_PERCENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_crimefight_percent)), "ADMIN_EFFICIENCY_CRIMEFIGHT_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(admin_efficiency_crimefight_percent)), - "CONSERVATIVE_INCREASE_AFTER_REFORM", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(conservative_increase_after_reform)), + expect_fixed_point(assign_variable_callback(admin_efficiency_crimefight_percent)), "CONSERVATIVE_INCREASE_AFTER_REFORM", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(conservative_increase_after_reform)), "CAMPAIGN_EVENT_BASE_TIME", ONE_EXACTLY, expect_days(assign_variable_callback(campaign_event_base_duration)), "CAMPAIGN_EVENT_MIN_TIME", ZERO_OR_ONE, expect_days(assign_variable_callback(campaign_event_min_duration)), // NOT USED "CAMPAIGN_EVENT_STATE_SCALE", ZERO_OR_ONE, // NOT USED - expect_days(assign_variable_callback(campaign_event_state_duration_modifier)), - "CAMPAIGN_DURATION", ONE_EXACTLY, expect_months(assign_variable_callback(campaign_duration)), - "COLONIAL_RANK", ONE_EXACTLY, expect_uint(assign_variable_callback(secondary_power_rank)), - "COLONY_TO_STATE_PRESTIGE_GAIN", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colony_to_state_prestige_gain)), - "COLONIAL_LIFERATING", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(colonial_liferating)), - "BASE_GREATPOWER_DAILY_INFLUENCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(base_greatpower_daily_influence)), - "AI_SUPPORT_REFORM", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_support_reform)), - "BASE_MONTHLY_DIPLOPOINTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_monthly_diplopoints)), - "DIPLOMAT_TRAVEL_TIME", ONE_EXACTLY, expect_days(assign_variable_callback(diplomat_travel_duration)), - "PROVINCE_OVERSEAS_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(province_overseas_penalty)), - "NONCORE_TAX_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(noncore_tax_penalty)), - "BASE_TARIFF_EFFICIENCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_tariff_efficiency)), - "COLONY_FORMED_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colony_formed_prestige)), - "CREATED_CB_VALID_TIME", ONE_EXACTLY, expect_months(assign_variable_callback(created_cb_valid_time)), - "LOYALTY_BOOST_ON_PARTY_WIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(loyalty_boost_on_party_win)), - "MOVEMENT_RADICALISM_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_radicalism_base)), - "MOVEMENT_RADICALISM_PASSED_REFORM_EFFECT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(movement_radicalism_passed_reform_effect)), + expect_days(assign_variable_callback(campaign_event_state_duration_modifier)), "CAMPAIGN_DURATION", ONE_EXACTLY, + expect_months(assign_variable_callback(campaign_duration)), "COLONIAL_RANK", ONE_EXACTLY, + expect_uint(assign_variable_callback(secondary_power_rank)), "COLONY_TO_STATE_PRESTIGE_GAIN", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colony_to_state_prestige_gain)), "COLONIAL_LIFERATING", ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(colonial_liferating)), "BASE_GREATPOWER_DAILY_INFLUENCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_greatpower_daily_influence)), "AI_SUPPORT_REFORM", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_support_reform)), "BASE_MONTHLY_DIPLOPOINTS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_monthly_diplopoints)), "DIPLOMAT_TRAVEL_TIME", ONE_EXACTLY, + expect_days(assign_variable_callback(diplomat_travel_duration)), "PROVINCE_OVERSEAS_PENALTY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(province_overseas_penalty)), "NONCORE_TAX_PENALTY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(noncore_tax_penalty)), "BASE_TARIFF_EFFICIENCY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_tariff_efficiency)), "COLONY_FORMED_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colony_formed_prestige)), "CREATED_CB_VALID_TIME", ONE_EXACTLY, + expect_months(assign_variable_callback(created_cb_valid_time)), "LOYALTY_BOOST_ON_PARTY_WIN", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(loyalty_boost_on_party_win)), "MOVEMENT_RADICALISM_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_radicalism_base)), "MOVEMENT_RADICALISM_PASSED_REFORM_EFFECT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_radicalism_passed_reform_effect)), "MOVEMENT_RADICALISM_NATIONALISM_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(movement_radicalism_nationalism_factor)), - "SUPPRESSION_POINTS_GAIN_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(suppression_points_gain_base)), - "SUPPRESS_BUREAUCRAT_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(suppress_bureaucrat_factor)), - "WRONG_REFORM_MILITANCY_IMPACT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(wrong_reform_militancy_impact)), + expect_fixed_point(assign_variable_callback(movement_radicalism_nationalism_factor)), "SUPPRESSION_POINTS_GAIN_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(suppression_points_gain_base)), "SUPPRESS_BUREAUCRAT_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(suppress_bureaucrat_factor)), "WRONG_REFORM_MILITANCY_IMPACT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(wrong_reform_militancy_impact)), "SUPPRESSION_RADICALISATION_HIT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(suppression_radicalisation_hit)), - "INVESTMENT_SCORE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(country_investment_industrial_score_factor)), - "UNCIV_TECH_SPREAD_MAX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_tech_spread_max)), - "UNCIV_TECH_SPREAD_MIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_tech_spread_min)), - "MIN_DELAY_BETWEEN_REFORMS", ONE_EXACTLY, expect_months(assign_variable_callback(min_delay_duration_between_reforms)), - "ECONOMIC_REFORM_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(economic_reform_uh_factor)), - "MILITARY_REFORM_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(military_reform_uh_factor)), - "WRONG_REFORM_RADICAL_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(wrong_reform_radical_impact)), - "TECH_YEAR_SPAN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tech_year_span)), - "TECH_FACTOR_VASSAL", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tech_factor_vassal)), - "MAX_SUPPRESSION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_suppression)), - "PRESTIGE_HIT_ON_BREAK_COUNTRY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_hit_on_break_country)), - "MIN_MOBILIZE_LIMIT", ONE_EXACTLY, expect_uint(assign_variable_callback(min_mobilize_limit)), - "POP_GROWTH_COUNTRY_CACHE_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(pop_growth_country_cache_days)), - "NEWSPAPER_PRINTING_FREQUENCY", ONE_EXACTLY, expect_days(assign_variable_callback(newspaper_printing_frequency)), - "NEWSPAPER_TIMEOUT_PERIOD", ONE_EXACTLY, expect_days(assign_variable_callback(newspaper_timeout_period)), - "NEWSPAPER_MAX_TENSION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(newspaper_max_tension)), - "NAVAL_BASE_SUPPLY_SCORE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_supply_score_base)), - "NAVAL_BASE_SUPPLY_SCORE_EMPTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_supply_score_empty)), + expect_fixed_point(assign_variable_callback(suppression_radicalisation_hit)), "INVESTMENT_SCORE_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(country_investment_industrial_score_factor)), "UNCIV_TECH_SPREAD_MAX", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_tech_spread_max)), "UNCIV_TECH_SPREAD_MIN", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unciv_tech_spread_min)), "MIN_DELAY_BETWEEN_REFORMS", ONE_EXACTLY, + expect_months(assign_variable_callback(min_delay_duration_between_reforms)), "ECONOMIC_REFORM_UH_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(economic_reform_uh_factor)), "MILITARY_REFORM_UH_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(military_reform_uh_factor)), "WRONG_REFORM_RADICAL_IMPACT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(wrong_reform_radical_impact)), "TECH_YEAR_SPAN", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tech_year_span)), "TECH_FACTOR_VASSAL", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tech_factor_vassal)), "MAX_SUPPRESSION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_suppression)), "PRESTIGE_HIT_ON_BREAK_COUNTRY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_hit_on_break_country)), "MIN_MOBILIZE_LIMIT", ONE_EXACTLY, + expect_uint(assign_variable_callback(min_mobilize_limit)), "POP_GROWTH_COUNTRY_CACHE_DAYS", ONE_EXACTLY, + expect_days(assign_variable_callback(pop_growth_country_cache_days)), "NEWSPAPER_PRINTING_FREQUENCY", ONE_EXACTLY, + expect_days(assign_variable_callback(newspaper_printing_frequency)), "NEWSPAPER_TIMEOUT_PERIOD", ONE_EXACTLY, + expect_days(assign_variable_callback(newspaper_timeout_period)), "NEWSPAPER_MAX_TENSION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(newspaper_max_tension)), "NAVAL_BASE_SUPPLY_SCORE_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_base_supply_score_base)), "NAVAL_BASE_SUPPLY_SCORE_EMPTY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_base_supply_score_empty)), "NAVAL_BASE_NON_CORE_SUPPLY_SCORE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_non_core_supply_score)), - "COLONIAL_POINTS_FROM_SUPPLY_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonial_points_from_supply_factor)), + expect_fixed_point(assign_variable_callback(naval_base_non_core_supply_score)), "COLONIAL_POINTS_FROM_SUPPLY_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonial_points_from_supply_factor)), "COLONIAL_POINTS_FOR_NON_CORE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonial_points_for_non_core_base)), - "MOBILIZATION_SPEED_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mobilization_speed_base)), - "MOBILIZATION_SPEED_RAILS_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(mobilization_speed_rails_mult)), - "COLONIZATION_INTEREST_LEAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_interest_lead)), - "COLONIZATION_INFLUENCE_LEAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_influence_lead)), - "COLONIZATION_MONTHS_TO_COLONIZE", ONE_EXACTLY, expect_months(assign_variable_callback(colonization_duration)), - "COLONIZATION_DAYS_BETWEEN_INVESTMENT", ONE_EXACTLY, - expect_days(assign_variable_callback(colonization_days_between_investment)), + expect_fixed_point(assign_variable_callback(colonial_points_for_non_core_base)), "MOBILIZATION_SPEED_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mobilization_speed_base)), "MOBILIZATION_SPEED_RAILS_MULT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mobilization_speed_rails_mult)), "COLONIZATION_INTEREST_LEAD", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_interest_lead)), "COLONIZATION_INFLUENCE_LEAD", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_influence_lead)), "COLONIZATION_MONTHS_TO_COLONIZE", + ONE_EXACTLY, expect_months(assign_variable_callback(colonization_duration)), "COLONIZATION_DAYS_BETWEEN_INVESTMENT", + ONE_EXACTLY, expect_days(assign_variable_callback(colonization_days_between_investment)), "COLONIZATION_DAYS_FOR_INITIAL_INVESTMENT", ONE_EXACTLY, - expect_days(assign_variable_callback(colonization_days_for_initial_investment)), + expect_days(assign_variable_callback(colonization_days_for_initial_investment)), "COLONIZATION_PROTECTORATE_PROVINCE_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_protectorate_province_maintenance)), + expect_fixed_point(assign_variable_callback(colonization_protectorate_province_maintenance)), "COLONIZATION_COLONY_PROVINCE_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_province_maintenance)), + expect_fixed_point(assign_variable_callback(colonization_colony_province_maintenance)), "COLONIZATION_COLONY_INDUSTRY_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_industry_maintenance)), + expect_fixed_point(assign_variable_callback(colonization_colony_industry_maintenance)), "COLONIZATION_COLONY_RAILWAY_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_railway_maintenance)), + expect_fixed_point(assign_variable_callback(colonization_colony_railway_maintenance)), "COLONIZATION_INTEREST_COST_INITIAL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_interest_cost_initial)), + expect_fixed_point(assign_variable_callback(colonization_interest_cost_initial)), "COLONIZATION_INTEREST_COST_NEIGHBOR_MODIFIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_interest_cost_neighbor_modifier)), + expect_fixed_point(assign_variable_callback(colonization_interest_cost_neighbor_modifier)), "COLONIZATION_INTEREST_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_interest_cost)), "COLONIZATION_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_influence_cost)), "COLONIZATION_EXTRA_GUARD_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_extra_guard_cost)), - "COLONIZATION_RELEASE_DOMINION_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_release_dominion_cost)), + expect_fixed_point(assign_variable_callback(colonization_extra_guard_cost)), "COLONIZATION_RELEASE_DOMINION_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_release_dominion_cost)), "COLONIZATION_CREATE_STATE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_state_cost)), - "COLONIZATION_CREATE_PROTECTORATE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_protectorate_cost)), + expect_fixed_point(assign_variable_callback(colonization_create_state_cost)), "COLONIZATION_CREATE_PROTECTORATE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_create_protectorate_cost)), "COLONIZATION_CREATE_COLONY_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_colony_cost)), - "COLONIZATION_COLONY_STATE_DISTANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_colony_state_distance)), + expect_fixed_point(assign_variable_callback(colonization_create_colony_cost)), "COLONIZATION_COLONY_STATE_DISTANCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_colony_state_distance)), "COLONIZATION_INFLUENCE_TEMPERATURE_PER_DAY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_day)), + expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_day)), "COLONIZATION_INFLUENCE_TEMPERATURE_PER_LEVEL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_level)), + expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_level)), "PARTY_LOYALTY_HIT_ON_WAR_LOSS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(party_loyalty_hit_on_war_loss)), - "RESEARCH_POINTS_ON_CONQUER_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(research_points_on_conquer_mult)), - "MAX_RESEARCH_POINTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_research_points)) + expect_fixed_point(assign_variable_callback(party_loyalty_hit_on_war_loss)), "RESEARCH_POINTS_ON_CONQUER_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(research_points_on_conquer_mult)), "MAX_RESEARCH_POINTS", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_research_points)) ); } diff --git a/src/openvic-simulation/defines/CountryDefines.hpp b/src/openvic-simulation/defines/CountryDefines.hpp index 2bff371ad..c02e91272 100644 --- a/src/openvic-simulation/defines/CountryDefines.hpp +++ b/src/openvic-simulation/defines/CountryDefines.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/dataloader/NodeTools.hpp" +#include "openvic-simulation/map/LifeRating.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/map/LifeRating.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -30,10 +30,12 @@ namespace OpenVic { fixed_point_t PROPERTY(min_crimefight_percent); fixed_point_t PROPERTY(max_crimefight_percent); fixed_point_t PROPERTY(admin_efficiency_crimefight_percent); + public: constexpr fixed_point_t get_admin_spending_crimefight_percent() const { return fixed_point_t::_1 - admin_efficiency_crimefight_percent; } + private: fixed_point_t PROPERTY(conservative_increase_after_reform); Timespan PROPERTY(campaign_event_base_duration); diff --git a/src/openvic-simulation/defines/DiplomacyDefines.cpp b/src/openvic-simulation/defines/DiplomacyDefines.cpp index 15c148b45..6d0ec05f9 100644 --- a/src/openvic-simulation/defines/DiplomacyDefines.cpp +++ b/src/openvic-simulation/defines/DiplomacyDefines.cpp @@ -16,551 +16,464 @@ node_callback_t DiplomacyDefines::expect_defines() { key_map_t key_map; add_key_map_entries( - key_map, - "PEACE_COST_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_add_to_sphere)), - "PEACE_COST_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_release_puppet)), - "PEACE_COST_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_make_puppet)), - "PEACE_COST_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_disarmament)), - "PEACE_COST_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_destroy_forts)), - "PEACE_COST_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_destroy_naval_bases)), - "PEACE_COST_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_reparations)), - "PEACE_COST_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_transfer_provinces)), - "PEACE_COST_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_remove_cores)), - "PEACE_COST_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_prestige)), - "PEACE_COST_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_concede)), - "PEACE_COST_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_status_quo)), - "PEACE_COST_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_annex)), - "PEACE_COST_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_demand_state)), - "PEACE_COST_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_install_communist_gov_type)), + key_map, "PEACE_COST_ADD_TO_SPHERE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_add_to_sphere)), "PEACE_COST_RELEASE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_release_puppet)), "PEACE_COST_MAKE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_make_puppet)), "PEACE_COST_DISARMAMENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_disarmament)), "PEACE_COST_DESTROY_FORTS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_destroy_forts)), "PEACE_COST_DESTROY_NAVAL_BASES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_destroy_naval_bases)), "PEACE_COST_REPARATIONS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_reparations)), "PEACE_COST_TRANSFER_PROVINCES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_transfer_provinces)), "PEACE_COST_REMOVE_CORES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_remove_cores)), "PEACE_COST_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_prestige)), "PEACE_COST_CONCEDE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_concede)), "PEACE_COST_STATUS_QUO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_status_quo)), "PEACE_COST_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_annex)), "PEACE_COST_DEMAND_STATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_demand_state)), "PEACE_COST_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_install_communist_gov_type)), "PEACE_COST_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_uninstall_communist_gov_type)), - "PEACE_COST_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_colony)), - "INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_add_to_sphere)), - "INFAMY_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_release_puppet)), - "INFAMY_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_make_puppet)), - "INFAMY_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_disarmament)), - "INFAMY_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_destroy_forts)), - "INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_destroy_naval_bases)), - "INFAMY_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_reparations)), - "INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_transfer_provinces)), - "INFAMY_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_remove_cores)), - "INFAMY_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_prestige)), - "INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_concede)), - "INFAMY_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_status_quo)), - "INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_annex)), - "INFAMY_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_demand_state)), - "INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(infamy_install_communist_gov_type)), - "INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(infamy_uninstall_communist_gov_type)), - "INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_colony)), - "PRESTIGE_ADD_TO_SPHERE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_add_to_sphere_base)), - "PRESTIGE_RELEASE_PUPPET_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_release_puppet_base)), - "PRESTIGE_MAKE_PUPPET_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_make_puppet_base)), - "PRESTIGE_DISARMAMENT_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_disarmament_base)), - "PRESTIGE_DESTROY_FORTS_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_destroy_forts_base)), - "PRESTIGE_DESTROY_NAVAL_BASES_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases_base)), + expect_fixed_point(assign_variable_callback(peace_cost_uninstall_communist_gov_type)), "PEACE_COST_COLONY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_colony)), "INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_add_to_sphere)), "INFAMY_RELEASE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_release_puppet)), "INFAMY_MAKE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_make_puppet)), "INFAMY_DISARMAMENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_disarmament)), "INFAMY_DESTROY_FORTS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_destroy_forts)), "INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_destroy_naval_bases)), "INFAMY_REPARATIONS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_reparations)), "INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_transfer_provinces)), "INFAMY_REMOVE_CORES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_remove_cores)), "INFAMY_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_prestige)), "INFAMY_CONCEDE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_concede)), "INFAMY_STATUS_QUO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_status_quo)), "INFAMY_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_annex)), "INFAMY_DEMAND_STATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_demand_state)), "INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_install_communist_gov_type)), "INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_uninstall_communist_gov_type)), "INFAMY_COLONY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_colony)), "PRESTIGE_ADD_TO_SPHERE_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_add_to_sphere_base)), "PRESTIGE_RELEASE_PUPPET_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_release_puppet_base)), "PRESTIGE_MAKE_PUPPET_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_make_puppet_base)), "PRESTIGE_DISARMAMENT_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_disarmament_base)), "PRESTIGE_DESTROY_FORTS_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_forts_base)), "PRESTIGE_DESTROY_NAVAL_BASES_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases_base)), "PRESTIGE_REPARATIONS_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reparations_base)), "PRESTIGE_TRANSFER_PROVINCES_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_transfer_provinces_base)), - "PRESTIGE_REMOVE_CORES_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_remove_cores_base)), - "PRESTIGE_PRESTIGE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_prestige_base)), - "PRESTIGE_CONCEDE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_concede_base)), - "PRESTIGE_STATUS_QUO_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_status_quo_base)), - "PRESTIGE_ANNEX_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_annex_base)), - "PRESTIGE_DEMAND_STATE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_demand_state_base)), - "PRESTIGE_CLEAR_UNION_SPHERE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere_base)), - "PRESTIGE_GUNBOAT_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_gunboat_base)), + expect_fixed_point(assign_variable_callback(prestige_transfer_provinces_base)), "PRESTIGE_REMOVE_CORES_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_remove_cores_base)), "PRESTIGE_PRESTIGE_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_prestige_base)), "PRESTIGE_CONCEDE_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_concede_base)), "PRESTIGE_STATUS_QUO_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_status_quo_base)), "PRESTIGE_ANNEX_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_annex_base)), "PRESTIGE_DEMAND_STATE_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_demand_state_base)), "PRESTIGE_CLEAR_UNION_SPHERE_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere_base)), "PRESTIGE_GUNBOAT_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_gunboat_base)), "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type_base)), + expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type_base)), "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type_base)), - "PRESTIGE_COLONY_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_colony_base)), - "PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_add_to_sphere)), - "PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_release_puppet)), - "PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_make_puppet)), - "PRESTIGE_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_disarmament)), - "PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_destroy_forts)), - "PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases)), - "PRESTIGE_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reparations)), - "PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_transfer_provinces)), - "PRESTIGE_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_remove_cores)), - "PRESTIGE_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_prestige)), - "PRESTIGE_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_concede)), - "PRESTIGE_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_status_quo)), - "PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_annex)), - "PRESTIGE_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_demand_state)), - "PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere)), - "PRESTIGE_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_gunboat)), - "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type_base)), "PRESTIGE_COLONY_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_colony_base)), "PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_add_to_sphere)), "PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_release_puppet)), "PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_make_puppet)), "PRESTIGE_DISARMAMENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_disarmament)), "PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_forts)), "PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases)), "PRESTIGE_REPARATIONS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reparations)), "PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_transfer_provinces)), "PRESTIGE_REMOVE_CORES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_remove_cores)), "PRESTIGE_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_prestige)), "PRESTIGE_CONCEDE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_concede)), "PRESTIGE_STATUS_QUO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_status_quo)), "PRESTIGE_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_annex)), "PRESTIGE_DEMAND_STATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_demand_state)), "PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere)), "PRESTIGE_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_gunboat)), "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type)), "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type)), - "PRESTIGE_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_colony)), - "BREAKTRUCE_INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_add_to_sphere)), - "BREAKTRUCE_INFAMY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_release_puppet)), + expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type)), "PRESTIGE_COLONY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_colony)), "BREAKTRUCE_INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_add_to_sphere)), "BREAKTRUCE_INFAMY_RELEASE_PUPPET", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_release_puppet)), "BREAKTRUCE_INFAMY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_make_puppet)), - "BREAKTRUCE_INFAMY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_disarmament)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_make_puppet)), "BREAKTRUCE_INFAMY_DISARMAMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_disarmament)), "BREAKTRUCE_INFAMY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_forts)), - "BREAKTRUCE_INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_forts)), "BREAKTRUCE_INFAMY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_naval_bases)), "BREAKTRUCE_INFAMY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_reparations)), - "BREAKTRUCE_INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_transfer_provinces)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_reparations)), "BREAKTRUCE_INFAMY_TRANSFER_PROVINCES", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_transfer_provinces)), "BREAKTRUCE_INFAMY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_remove_cores)), - "BREAKTRUCE_INFAMY_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_prestige)), - "BREAKTRUCE_INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_concede)), - "BREAKTRUCE_INFAMY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_status_quo)), - "BREAKTRUCE_INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_annex)), - "BREAKTRUCE_INFAMY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_demand_state)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_remove_cores)), "BREAKTRUCE_INFAMY_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_prestige)), "BREAKTRUCE_INFAMY_CONCEDE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_concede)), "BREAKTRUCE_INFAMY_STATUS_QUO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_status_quo)), "BREAKTRUCE_INFAMY_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_annex)), "BREAKTRUCE_INFAMY_DEMAND_STATE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_demand_state)), "BREAKTRUCE_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_install_communist_gov_type)), "BREAKTRUCE_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_uninstall_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_uninstall_communist_gov_type)), "BREAKTRUCE_INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_colony)), "BREAKTRUCE_PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_add_to_sphere)), - "BREAKTRUCE_PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_release_puppet)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_add_to_sphere)), "BREAKTRUCE_PRESTIGE_RELEASE_PUPPET", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_release_puppet)), "BREAKTRUCE_PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_make_puppet)), - "BREAKTRUCE_PRESTIGE_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_disarmament)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_make_puppet)), "BREAKTRUCE_PRESTIGE_DISARMAMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_disarmament)), "BREAKTRUCE_PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_forts)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_forts)), "BREAKTRUCE_PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_naval_bases)), "BREAKTRUCE_PRESTIGE_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_reparations)), - "BREAKTRUCE_PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_transfer_provinces)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_reparations)), "BREAKTRUCE_PRESTIGE_TRANSFER_PROVINCES", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_transfer_provinces)), "BREAKTRUCE_PRESTIGE_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_remove_cores)), - "BREAKTRUCE_PRESTIGE_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_prestige)), - "BREAKTRUCE_PRESTIGE_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_concede)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_remove_cores)), "BREAKTRUCE_PRESTIGE_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_prestige)), "BREAKTRUCE_PRESTIGE_CONCEDE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_concede)), "BREAKTRUCE_PRESTIGE_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_status_quo)), - "BREAKTRUCE_PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_annex)), - "BREAKTRUCE_PRESTIGE_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_demand_state)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_status_quo)), "BREAKTRUCE_PRESTIGE_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_annex)), "BREAKTRUCE_PRESTIGE_DEMAND_STATE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_demand_state)), "BREAKTRUCE_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_install_communist_gov_type)), "BREAKTRUCE_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_uninstall_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_uninstall_communist_gov_type)), "BREAKTRUCE_PRESTIGE_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_colony)), "BREAKTRUCE_MILITANCY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_add_to_sphere)), - "BREAKTRUCE_MILITANCY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_release_puppet)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_add_to_sphere)), "BREAKTRUCE_MILITANCY_RELEASE_PUPPET", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_release_puppet)), "BREAKTRUCE_MILITANCY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_make_puppet)), - "BREAKTRUCE_MILITANCY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_disarmament)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_make_puppet)), "BREAKTRUCE_MILITANCY_DISARMAMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_disarmament)), "BREAKTRUCE_MILITANCY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_forts)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_forts)), "BREAKTRUCE_MILITANCY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_naval_bases)), "BREAKTRUCE_MILITANCY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_reparations)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_reparations)), "BREAKTRUCE_MILITANCY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_transfer_provinces)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_transfer_provinces)), "BREAKTRUCE_MILITANCY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_remove_cores)), - "BREAKTRUCE_MILITANCY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_prestige)), - "BREAKTRUCE_MILITANCY_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_concede)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_remove_cores)), "BREAKTRUCE_MILITANCY_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_prestige)), + "BREAKTRUCE_MILITANCY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_concede)), "BREAKTRUCE_MILITANCY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_status_quo)), - "BREAKTRUCE_MILITANCY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_annex)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_status_quo)), "BREAKTRUCE_MILITANCY_ANNEX", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_annex)), "BREAKTRUCE_MILITANCY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_demand_state)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_demand_state)), "BREAKTRUCE_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_install_communist_gov_type)), "BREAKTRUCE_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_uninstall_communist_gov_type)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_uninstall_communist_gov_type)), "BREAKTRUCE_MILITANCY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_colony)), "GOODRELATION_INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_add_to_sphere)), - "GOODRELATION_INFAMY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_release_puppet)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_add_to_sphere)), "GOODRELATION_INFAMY_RELEASE_PUPPET", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_release_puppet)), "GOODRELATION_INFAMY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_make_puppet)), - "GOODRELATION_INFAMY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_disarmament)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_make_puppet)), "GOODRELATION_INFAMY_DISARMAMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_disarmament)), "GOODRELATION_INFAMY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_forts)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_forts)), "GOODRELATION_INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_naval_bases)), "GOODRELATION_INFAMY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_reparations)), - "GOODRELATION_INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_transfer_provinces)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_reparations)), "GOODRELATION_INFAMY_TRANSFER_PROVINCES", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_transfer_provinces)), "GOODRELATION_INFAMY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_remove_cores)), - "GOODRELATION_INFAMY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_prestige)), - "GOODRELATION_INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_concede)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_remove_cores)), "GOODRELATION_INFAMY_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_prestige)), "GOODRELATION_INFAMY_CONCEDE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_concede)), "GOODRELATION_INFAMY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_status_quo)), - "GOODRELATION_INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_annex)), - "GOODRELATION_INFAMY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_demand_state)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_status_quo)), "GOODRELATION_INFAMY_ANNEX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_annex)), "GOODRELATION_INFAMY_DEMAND_STATE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_demand_state)), "GOODRELATION_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_install_communist_gov_type)), "GOODRELATION_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_uninstall_communist_gov_type)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_uninstall_communist_gov_type)), "GOODRELATION_INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_colony)), "GOODRELATION_PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_add_to_sphere)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_add_to_sphere)), "GOODRELATION_PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_release_puppet)), - "GOODRELATION_PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_make_puppet)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_release_puppet)), "GOODRELATION_PRESTIGE_MAKE_PUPPET", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_make_puppet)), "GOODRELATION_PRESTIGE_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_disarmament)), - "GOODRELATION_PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_forts)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_disarmament)), "GOODRELATION_PRESTIGE_DESTROY_FORTS", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_forts)), "GOODRELATION_PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_naval_bases)), "GOODRELATION_PRESTIGE_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_reparations)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_reparations)), "GOODRELATION_PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_transfer_provinces)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_transfer_provinces)), "GOODRELATION_PRESTIGE_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_remove_cores)), - "GOODRELATION_PRESTIGE_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_prestige)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_remove_cores)), "GOODRELATION_PRESTIGE_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_prestige)), "GOODRELATION_PRESTIGE_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_concede)), - "GOODRELATION_PRESTIGE_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_status_quo)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_concede)), "GOODRELATION_PRESTIGE_STATUS_QUO", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_status_quo)), "GOODRELATION_PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_annex)), "GOODRELATION_PRESTIGE_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_demand_state)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_demand_state)), "GOODRELATION_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_install_communist_gov_type)), "GOODRELATION_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_uninstall_communist_gov_type)), - "GOODRELATION_PRESTIGE_COLONY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_colony)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_uninstall_communist_gov_type)), + "GOODRELATION_PRESTIGE_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_colony)), "GOODRELATION_MILITANCY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_add_to_sphere)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_add_to_sphere)), "GOODRELATION_MILITANCY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_release_puppet)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_release_puppet)), "GOODRELATION_MILITANCY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_make_puppet)), - "GOODRELATION_MILITANCY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_disarmament)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_make_puppet)), "GOODRELATION_MILITANCY_DISARMAMENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_militancy_disarmament)), "GOODRELATION_MILITANCY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_forts)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_forts)), "GOODRELATION_MILITANCY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_naval_bases)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_naval_bases)), "GOODRELATION_MILITANCY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_reparations)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_reparations)), "GOODRELATION_MILITANCY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_transfer_provinces)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_transfer_provinces)), "GOODRELATION_MILITANCY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_remove_cores)), - "GOODRELATION_MILITANCY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_prestige)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_remove_cores)), "GOODRELATION_MILITANCY_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_militancy_prestige)), "GOODRELATION_MILITANCY_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_concede)), - "GOODRELATION_MILITANCY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_status_quo)), - "GOODRELATION_MILITANCY_ANNEX", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_annex)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_concede)), "GOODRELATION_MILITANCY_STATUS_QUO", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_militancy_status_quo)), + "GOODRELATION_MILITANCY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_militancy_annex)), "GOODRELATION_MILITANCY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_demand_state)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_demand_state)), "GOODRELATION_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_install_communist_gov_type)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_install_communist_gov_type)), "GOODRELATION_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_uninstall_communist_gov_type)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_uninstall_communist_gov_type)), "GOODRELATION_MILITANCY_COLONY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_colony)) + expect_fixed_point(assign_variable_callback(goodrelation_militancy_colony)) ); add_key_map_entries( - key_map, - "WAR_PRESTIGE_COST_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_base)), + key_map, "WAR_PRESTIGE_COST_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_base)), "WAR_PRESTIGE_COST_HIGH_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_high_prestige)), - "WAR_PRESTIGE_COST_NEG_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_neg_prestige)), - "WAR_PRESTIGE_COST_TRUCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_truce)), - "WAR_PRESTIGE_COST_HONOR_ALLIANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_alliance)), - "WAR_PRESTIGE_COST_HONOR_GUARNATEE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_guarantee)), - "WAR_PRESTIGE_COST_UNCIVILIZED", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_uncivilized)), - "WAR_PRESTIGE_COST_CORE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_core)), - "WAR_FAILED_GOAL_MILITANCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_militancy)), - "WAR_FAILED_GOAL_PRESTIGE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_failed_goal_prestige_base)), - "WAR_FAILED_GOAL_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_prestige)), - "DISCREDIT_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(discredit_days)), - "DISCREDIT_INFLUENCE_COST_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_influence_cost_factor)), - "DISCREDIT_INFLUENCE_GAIN_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_influence_gain_factor)), - "BANEMBASSY_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(banembassy_days)), - "DECLAREWAR_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(declarewar_relation_on_accept)), - "DECLAREWAR_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(declarewar_diplomatic_cost)), - "ADDWARGOAL_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(addwargoal_relation_on_accept)), - "ADDWARGOAL_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(addwargoal_diplomatic_cost)), - "ADD_UNJUSTIFIED_GOAL_BADBOY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(add_unjustified_goal_badboy)), - "PEACE_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_relation_on_accept)), - "PEACE_RELATION_ON_DECLINE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_relation_on_decline)), - "PEACE_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_diplomatic_cost)), - "ALLIANCE_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(alliance_relation_on_accept)), - "ALLIANCE_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(alliance_relation_on_decline)), - "ALLIANCE_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(alliance_diplomatic_cost)), - "CANCELALLIANCE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelalliance_relation_on_accept)), + expect_fixed_point(assign_variable_callback(war_prestige_cost_high_prestige)), "WAR_PRESTIGE_COST_NEG_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_neg_prestige)), "WAR_PRESTIGE_COST_TRUCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_truce)), "WAR_PRESTIGE_COST_HONOR_ALLIANCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_alliance)), + "WAR_PRESTIGE_COST_HONOR_GUARNATEE", ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_guarantee)), "WAR_PRESTIGE_COST_UNCIVILIZED", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_uncivilized)), "WAR_PRESTIGE_COST_CORE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_core)), "WAR_FAILED_GOAL_MILITANCY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_militancy)), "WAR_FAILED_GOAL_PRESTIGE_BASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_prestige_base)), "WAR_FAILED_GOAL_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_prestige)), "DISCREDIT_DAYS", ONE_EXACTLY, + expect_days(assign_variable_callback(discredit_days)), "DISCREDIT_INFLUENCE_COST_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(discredit_influence_cost_factor)), "DISCREDIT_INFLUENCE_GAIN_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discredit_influence_gain_factor)), "BANEMBASSY_DAYS", + ONE_EXACTLY, expect_days(assign_variable_callback(banembassy_days)), "DECLAREWAR_RELATION_ON_ACCEPT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(declarewar_relation_on_accept)), "DECLAREWAR_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(declarewar_diplomatic_cost)), "ADDWARGOAL_RELATION_ON_ACCEPT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addwargoal_relation_on_accept)), "ADDWARGOAL_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addwargoal_diplomatic_cost)), "ADD_UNJUSTIFIED_GOAL_BADBOY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(add_unjustified_goal_badboy)), "PEACE_RELATION_ON_ACCEPT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_relation_on_accept)), "PEACE_RELATION_ON_DECLINE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_relation_on_decline)), "PEACE_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_diplomatic_cost)), "ALLIANCE_RELATION_ON_ACCEPT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_relation_on_accept)), "ALLIANCE_RELATION_ON_DECLINE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_relation_on_decline)), "ALLIANCE_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_diplomatic_cost)), "CANCELALLIANCE_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cancelalliance_relation_on_accept)), "CANCELALLIANCE_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelalliance_diplomatic_cost)), - "CALLALLY_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_relation_on_accept)), - "CALLALLY_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(callally_relation_on_decline)), - "CALLALLY_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_diplomatic_cost)), - "ASKMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_accept)), + expect_fixed_point(assign_variable_callback(cancelalliance_diplomatic_cost)), "CALLALLY_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_relation_on_accept)), "CALLALLY_RELATION_ON_DECLINE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_relation_on_decline)), "CALLALLY_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_diplomatic_cost)), "ASKMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_accept)), "ASKMILACCESS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_decline)), - "ASKMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_decline)), "ASKMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(askmilaccess_diplomatic_cost)), "CANCELASKMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelaskmilaccess_relation_on_accept)), + expect_fixed_point(assign_variable_callback(cancelaskmilaccess_relation_on_accept)), "CANCELASKMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelaskmilaccess_diplomatic_cost)), - "GIVEMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_accept)), + expect_fixed_point(assign_variable_callback(cancelaskmilaccess_diplomatic_cost)), "GIVEMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_accept)), "GIVEMILACCESS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_decline)), - "GIVEMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_decline)), "GIVEMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(givemilaccess_diplomatic_cost)), "CANCELGIVEMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelgivemilaccess_relation_on_accept)), + expect_fixed_point(assign_variable_callback(cancelgivemilaccess_relation_on_accept)), "CANCELGIVEMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelgivemilaccess_diplomatic_cost)), - "WARSUBSIDY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(warsubsidy_relation_on_accept)), - "WARSUBSIDY_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidy_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(cancelgivemilaccess_diplomatic_cost)), "WARSUBSIDY_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidy_relation_on_accept)), "WARSUBSIDY_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidy_diplomatic_cost)), "CANCELWARSUBSIDY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelwarsubsidy_relation_on_accept)), - "CANCELWARSUBSIDY_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelwarsubsidy_diplomatic_cost)), - "DISCREDIT_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_relation_on_accept)), + expect_fixed_point(assign_variable_callback(cancelwarsubsidy_relation_on_accept)), "CANCELWARSUBSIDY_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cancelwarsubsidy_diplomatic_cost)), + "DISCREDIT_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discredit_relation_on_accept)), "DISCREDIT_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discredit_influence_cost)), "EXPELADVISORS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(expeladvisors_relation_on_accept)), - "EXPELADVISORS_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(expeladvisors_influence_cost)), + expect_fixed_point(assign_variable_callback(expeladvisors_relation_on_accept)), "EXPELADVISORS_INFLUENCE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(expeladvisors_influence_cost)), "CEASECOLONIZATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_accept)), + expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_accept)), "CEASECOLONIZATION_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_decline)), + expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_decline)), "CEASECOLONIZATION_DIPLOMATIC_COST", ONE_OR_MORE, // Appears twice in vanilla! - expect_fixed_point(assign_variable_callback(ceasecolonization_diplomatic_cost)), - "BANEMBASSY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(banembassy_relation_on_accept)), - "BANEMBASSY_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(banembassy_influence_cost)), + expect_fixed_point(assign_variable_callback(ceasecolonization_diplomatic_cost)), "BANEMBASSY_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(banembassy_relation_on_accept)), "BANEMBASSY_INFLUENCE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(banembassy_influence_cost)), "INCREASERELATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_relation_on_accept)), + expect_fixed_point(assign_variable_callback(increaserelation_relation_on_accept)), "INCREASERELATION_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_relation_on_decline)), - "INCREASERELATION_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(increaserelation_relation_on_decline)), "INCREASERELATION_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(increaserelation_diplomatic_cost)), "DECREASERELATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaserelation_relation_on_accept)), - "DECREASERELATION_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaserelation_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(decreaserelation_relation_on_accept)), "DECREASERELATION_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(decreaserelation_diplomatic_cost)), "ADDTOSPHERE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(addtosphere_relation_on_accept)), - "ADDTOSPHERE_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(addtosphere_influence_cost)), - "REMOVEFROMSPHERE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_relation_on_accept)), + expect_fixed_point(assign_variable_callback(addtosphere_relation_on_accept)), "ADDTOSPHERE_INFLUENCE_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addtosphere_influence_cost)), "REMOVEFROMSPHERE_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(removefromsphere_relation_on_accept)), "REMOVEFROMSPHERE_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_influence_cost)), - "REMOVEFROMSPHERE_PRESTIGE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_prestige_cost)), - "REMOVEFROMSPHERE_INFAMY_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_infamy_cost)), + expect_fixed_point(assign_variable_callback(removefromsphere_influence_cost)), "REMOVEFROMSPHERE_PRESTIGE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(removefromsphere_prestige_cost)), + "REMOVEFROMSPHERE_INFAMY_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(removefromsphere_infamy_cost)), "INCREASEOPINION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaseopinion_relation_on_accept)), - "INCREASEOPINION_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaseopinion_influence_cost)), + expect_fixed_point(assign_variable_callback(increaseopinion_relation_on_accept)), "INCREASEOPINION_INFLUENCE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(increaseopinion_influence_cost)), "DECREASEOPINION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaseopinion_relation_on_accept)), - "DECREASEOPINION_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaseopinion_influence_cost)), - "MAKE_CB_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_diplomatic_cost)), - "MAKE_CB_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_relation_on_accept)), - "DISARMAMENT_ARMY_HIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(disarmed_penalty)), - "REPARATIONS_TAX_HIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reparations_tax_hit)), - "PRESTIGE_REDUCTION_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reduction_base)), - "PRESTIGE_REDUCTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reduction)), - "REPARATIONS_YEARS", ONE_EXACTLY, expect_years(assign_variable_callback(reparations_duration)), - "MIN_WARSCORE_TO_INTERVENE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_warscore_to_intervene)), - "MIN_MONTHS_TO_INTERVENE", ONE_EXACTLY, expect_months(assign_variable_callback(min_time_to_intervene)), - "MAX_WARSCORE_FROM_BATTLES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_warscore_from_battles)), - "GUNBOAT_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_diplomatic_cost)), - "GUNBOAT_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_relation_on_accept)), - "WARGOAL_JINGOISM_REQUIREMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(wargoal_jingoism_requirement)), - "LIBERATE_STATE_RELATION_INCREASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(liberate_state_relation_increase)), + expect_fixed_point(assign_variable_callback(decreaseopinion_relation_on_accept)), "DECREASEOPINION_INFLUENCE_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(decreaseopinion_influence_cost)), "MAKE_CB_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_diplomatic_cost)), "MAKE_CB_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_relation_on_accept)), "DISARMAMENT_ARMY_HIT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(disarmed_penalty)), "REPARATIONS_TAX_HIT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reparations_tax_hit)), "PRESTIGE_REDUCTION_BASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reduction_base)), "PRESTIGE_REDUCTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reduction)), "REPARATIONS_YEARS", ONE_EXACTLY, + expect_years(assign_variable_callback(reparations_duration)), "MIN_WARSCORE_TO_INTERVENE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(min_warscore_to_intervene)), "MIN_MONTHS_TO_INTERVENE", ONE_EXACTLY, + expect_months(assign_variable_callback(min_time_to_intervene)), "MAX_WARSCORE_FROM_BATTLES", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_warscore_from_battles)), "GUNBOAT_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_diplomatic_cost)), "GUNBOAT_RELATION_ON_ACCEPT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_relation_on_accept)), "WARGOAL_JINGOISM_REQUIREMENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(wargoal_jingoism_requirement)), "LIBERATE_STATE_RELATION_INCREASE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(liberate_state_relation_increase)), "DISHONORED_CALLALLY_PRESTIGE_PENALTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(dishonored_callally_prestige_penalty)), - "BASE_TRUCE_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(base_truce_duration)), - "MAX_INFLUENCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_influence)), - "WARSUBSIDIES_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidies_percent)), - "NEIGHBOUR_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(neighbour_bonus_influence_percent)), + expect_fixed_point(assign_variable_callback(dishonored_callally_prestige_penalty)), "BASE_TRUCE_MONTHS", ONE_EXACTLY, + expect_months(assign_variable_callback(base_truce_duration)), "MAX_INFLUENCE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_influence)), "WARSUBSIDIES_PERCENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(warsubsidies_percent)), "NEIGHBOUR_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(neighbour_bonus_influence_percent)), "SPHERE_NEIGHBOUR_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(sphere_neighbour_bonus_influence_percent)), + expect_fixed_point(assign_variable_callback(sphere_neighbour_bonus_influence_percent)), "OTHER_CONTINENT_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(other_continent_bonus_influence_percent)), - "PUPPET_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(puppet_bonus_influence_percent)), - "RELEASE_NATION_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_prestige)), - "RELEASE_NATION_INFAMY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_infamy)), - "INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(other_continent_bonus_influence_percent)), "PUPPET_BONUS_INFLUENCE_PERCENT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(puppet_bonus_influence_percent)), "RELEASE_NATION_PRESTIGE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_prestige)), "RELEASE_NATION_INFAMY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_infamy)), "INFAMY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_clear_union_sphere)), "BREAKTRUCE_INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(breaktruce_infamy_clear_union_sphere)), "BREAKTRUCE_PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(breaktruce_prestige_clear_union_sphere)), "BREAKTRUCE_MILITANCY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(breaktruce_militancy_clear_union_sphere)), "GOODRELATION_INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(goodrelation_infamy_clear_union_sphere)), "GOODRELATION_PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(goodrelation_prestige_clear_union_sphere)), "GOODRELATION_MILITANCY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_clear_union_sphere)), + expect_fixed_point(assign_variable_callback(goodrelation_militancy_clear_union_sphere)), "PEACE_COST_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_clear_union_sphere)), - "GOOD_PEACE_REFUSAL_MILITANCY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(good_peace_refusal_militancy)), - "GOOD_PEACE_REFUSAL_WAREXH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(good_peace_refusal_warexh)), - "PEACE_COST_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_gunboat)), - "INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_gunboat)), - "BREAKTRUCE_INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_gunboat)), - "BREAKTRUCE_PRESTIGE_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_gunboat)), - "BREAKTRUCE_MILITANCY_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_gunboat)), - "GOODRELATION_INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_gunboat)), - "GOODRELATION_PRESTIGE_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_gunboat)), - "GOODRELATION_MILITANCY_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_gunboat)), - "CB_GENERATION_BASE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cb_generation_base_speed)), + expect_fixed_point(assign_variable_callback(peace_cost_clear_union_sphere)), "GOOD_PEACE_REFUSAL_MILITANCY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(good_peace_refusal_militancy)), "GOOD_PEACE_REFUSAL_WAREXH", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(good_peace_refusal_warexh)), "PEACE_COST_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_gunboat)), "INFAMY_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_gunboat)), "BREAKTRUCE_INFAMY_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_gunboat)), "BREAKTRUCE_PRESTIGE_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_gunboat)), "BREAKTRUCE_MILITANCY_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_gunboat)), "GOODRELATION_INFAMY_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_gunboat)), "GOODRELATION_PRESTIGE_GUNBOAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_gunboat)), "GOODRELATION_MILITANCY_GUNBOAT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_militancy_gunboat)), "CB_GENERATION_BASE_SPEED", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cb_generation_base_speed)), "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition)), - "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION_TROOPS_PRESENCE", ONE_EXACTLY, expect_fixed_point( - assign_variable_callback(cb_generation_speed_bonus_on_colony_competition_troops_presence) - ), + expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition)), + "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION_TROOPS_PRESENCE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition_troops_presence)), "MAKE_CB_RELATION_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_relation_limit)), "CB_DETECTION_CHANCE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cb_detection_chance_base)), - "INVESTMENT_INFLUENCE_DEFENSE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(investment_influence_defense)), + "INVESTMENT_INFLUENCE_DEFENSE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(investment_influence_defense)), "RELATION_INFLUENCE_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(relation_influence_modifier)), "ON_CB_DETECTED_RELATION_CHANGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(on_cb_detected_relation_change)), - "GW_INTERVENE_MIN_RELATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_intervene_min_relations)), - "GW_INTERVENE_MAX_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_intervene_max_exhaustion)), - "GW_JUSTIFY_CB_BADBOY_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_justify_cb_badboy_impact)), - "GW_CB_CONSTRUCTION_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_cb_construction_speed)), - "GW_WARGOAL_JINGOISM_REQUIREMENT_MOD", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(gw_wargoal_jingoism_requirement_mod)), - "GW_WARSCORE_COST_MOD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod)), - "GW_WARSCORE_COST_MOD_2", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod_2)), - "GW_WARSCORE_2_THRESHOLD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_2_threshold)), - "TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_decay)), - "TENSION_FROM_CB", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_cb)), - "TENSION_FROM_MOVEMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_movement)), - "TENSION_FROM_MOVEMENT_MAX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_movement_max)), - "AT_WAR_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(at_war_tension_decay)), - "TENSION_ON_CB_DISCOVERED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_on_cb_discovered)), - "TENSION_ON_REVOLT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_on_revolt)), - "TENSION_WHILE_CRISIS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_while_crisis)), - "CRISIS_COOLDOWN_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(crisis_cooldown_duration)), - "CRISIS_BASE_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_base_chance)), - "CRISIS_TEMPERATURE_INCREASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_temperature_increase)), - "CRISIS_OFFER_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_diplomatic_cost)), - "CRISIS_OFFER_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_accept)), + expect_fixed_point(assign_variable_callback(on_cb_detected_relation_change)), "GW_INTERVENE_MIN_RELATIONS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_intervene_min_relations)), "GW_INTERVENE_MAX_EXHAUSTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_intervene_max_exhaustion)), "GW_JUSTIFY_CB_BADBOY_IMPACT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_justify_cb_badboy_impact)), "GW_CB_CONSTRUCTION_SPEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_cb_construction_speed)), "GW_WARGOAL_JINGOISM_REQUIREMENT_MOD", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_wargoal_jingoism_requirement_mod)), "GW_WARSCORE_COST_MOD", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod)), "GW_WARSCORE_COST_MOD_2", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod_2)), "GW_WARSCORE_2_THRESHOLD", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_warscore_2_threshold)), "TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_decay)), "TENSION_FROM_CB", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_cb)), "TENSION_FROM_MOVEMENT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_movement)), "TENSION_FROM_MOVEMENT_MAX", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_movement_max)), "AT_WAR_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(at_war_tension_decay)), "TENSION_ON_CB_DISCOVERED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_on_cb_discovered)), "TENSION_ON_REVOLT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_on_revolt)), "TENSION_WHILE_CRISIS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_while_crisis)), "CRISIS_COOLDOWN_MONTHS", ONE_EXACTLY, + expect_months(assign_variable_callback(crisis_cooldown_duration)), "CRISIS_BASE_CHANCE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_base_chance)), "CRISIS_TEMPERATURE_INCREASE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_temperature_increase)), "CRISIS_OFFER_DIPLOMATIC_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_offer_diplomatic_cost)), "CRISIS_OFFER_RELATION_ON_ACCEPT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_accept)), "CRISIS_OFFER_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_decline)), + expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_decline)), "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_base)), + expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_base)), "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_YEAR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_year)), + expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_year)), "CRISIS_WINNER_PRESTIGE_FACTOR_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_base)), - "CRISIS_WINNER_PRESTIGE_FACTOR_YEAR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_year)), + expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_base)), "CRISIS_WINNER_PRESTIGE_FACTOR_YEAR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_year)), "CRISIS_WINNER_RELATIONS_IMPACT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_relations_impact)), - "BACK_CRISIS_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(back_crisis_diplomatic_cost)), + expect_fixed_point(assign_variable_callback(crisis_winner_relations_impact)), "BACK_CRISIS_DIPLOMATIC_COST", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(back_crisis_diplomatic_cost)), "BACK_CRISIS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(back_crisis_relation_on_accept)), - "BACK_CRISIS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(back_crisis_relation_on_decline)), + expect_fixed_point(assign_variable_callback(back_crisis_relation_on_accept)), "BACK_CRISIS_RELATION_ON_DECLINE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(back_crisis_relation_on_decline)), "CRISIS_TEMPERATURE_ON_OFFER_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_on_offer_decline)), + expect_fixed_point(assign_variable_callback(crisis_temperature_on_offer_decline)), "CRISIS_TEMPERATURE_PARTICIPANT_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_participant_factor)), - "CRISIS_TEMPERATURE_ON_MOBILIZE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_on_mobilize)), - "CRISIS_WARGOAL_INFAMY_MULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_wargoal_infamy_mult)), - "CRISIS_WARGOAL_PRESTIGE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_wargoal_prestige_mult)), + expect_fixed_point(assign_variable_callback(crisis_temperature_participant_factor)), "CRISIS_TEMPERATURE_ON_MOBILIZE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_temperature_on_mobilize)), "CRISIS_WARGOAL_INFAMY_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_wargoal_infamy_mult)), "CRISIS_WARGOAL_PRESTIGE_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_wargoal_prestige_mult)), "CRISIS_WARGOAL_MILITANCY_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_wargoal_militancy_mult)), - "CRISIS_INTEREST_WAR_EXHAUSTION_LIMIT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_interest_war_exhaustion_limit)), - "RANK_1_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_1_tension_decay)), - "RANK_2_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_2_tension_decay)), - "RANK_3_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_3_tension_decay)), - "RANK_4_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_4_tension_decay)), - "RANK_5_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_5_tension_decay)), - "RANK_6_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_6_tension_decay)), - "RANK_7_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_7_tension_decay)), - "RANK_8_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_8_tension_decay)), - "TWS_FULFILLED_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_fulfilled_speed)), - "TWS_NOT_FULFILLED_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_not_fulfilled_speed)), - "TWS_GRACE_PERIOD_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(tws_grace_period_days)), - "TWS_CB_LIMIT_DEFAULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_cb_limit_default)), - "TWS_FULFILLED_IDLE_SPACE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_fulfilled_idle_space)), - "TWS_BATTLE_MIN_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(tws_battle_min_count)), - "TWS_BATTLE_MAX_ASPECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_battle_max_aspect)), - "LARGE_POPULATION_INFLUENCE_PENALTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(large_population_influence_penalty)), - "LONE_BACKER_PRESTIGE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(lone_backer_prestige_factor)) + expect_fixed_point(assign_variable_callback(crisis_wargoal_militancy_mult)), "CRISIS_INTEREST_WAR_EXHAUSTION_LIMIT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_interest_war_exhaustion_limit)), "RANK_1_TENSION_DECAY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_1_tension_decay)), "RANK_2_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_2_tension_decay)), "RANK_3_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_3_tension_decay)), "RANK_4_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_4_tension_decay)), "RANK_5_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_5_tension_decay)), "RANK_6_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_6_tension_decay)), "RANK_7_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_7_tension_decay)), "RANK_8_TENSION_DECAY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_8_tension_decay)), "TWS_FULFILLED_SPEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_fulfilled_speed)), "TWS_NOT_FULFILLED_SPEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_not_fulfilled_speed)), "TWS_GRACE_PERIOD_DAYS", ONE_EXACTLY, + expect_days(assign_variable_callback(tws_grace_period_days)), "TWS_CB_LIMIT_DEFAULT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_cb_limit_default)), "TWS_FULFILLED_IDLE_SPACE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_fulfilled_idle_space)), "TWS_BATTLE_MIN_COUNT", ONE_EXACTLY, + expect_uint(assign_variable_callback(tws_battle_min_count)), "TWS_BATTLE_MAX_ASPECT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_battle_max_aspect)), "LARGE_POPULATION_INFLUENCE_PENALTY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(large_population_influence_penalty)), "LONE_BACKER_PRESTIGE_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(lone_backer_prestige_factor)) ); return expect_dictionary_key_map(std::move(key_map)); diff --git a/src/openvic-simulation/defines/EconomyDefines.cpp b/src/openvic-simulation/defines/EconomyDefines.cpp index 0ae597d97..88a571d3f 100644 --- a/src/openvic-simulation/defines/EconomyDefines.cpp +++ b/src/openvic-simulation/defines/EconomyDefines.cpp @@ -14,49 +14,49 @@ node_callback_t EconomyDefines::expect_defines() { "MAX_DAILY_RESEARCH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_daily_research)), "LOAN_BASE_INTEREST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(loan_base_interest)), "BANKRUPTCY_EXTERNAL_LOAN_YEARS", ONE_EXACTLY, - expect_years(assign_variable_callback(bankruptcy_external_loan_duration)), + expect_years(assign_variable_callback(bankruptcy_external_loan_duration)), // "BANKRUPTCY_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bankruptcy_factor)), "SHADOWY_FINANCIERS_MAX_LOAN_AMOUNT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(shadowy_financiers_max_loan_amount)), + expect_fixed_point(assign_variable_callback(shadowy_financiers_max_loan_amount)), // "MAX_LOAN_CAP_FROM_BANKS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_loan_cap_from_banks)), "GUNBOAT_LOW_TAX_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_low_tax_cap)), "GUNBOAT_HIGH_TAX_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_high_tax_cap)), "GUNBOAT_FLEET_SIZE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_fleet_size_factor)), "PROVINCE_SIZE_DIVIDER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(province_size_divider)), "CAPITALIST_BUILD_FACTORY_STATE_EMPLOYMENT_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(capitalist_build_factory_state_employment_percent)), + expect_fixed_point(assign_variable_callback(capitalist_build_factory_state_employment_percent)), "GOODS_FOCUS_SWAP_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goods_focus_swap_chance)), "NUM_CLOSED_FACTORIES_PER_STATE_LASSIEZ_FAIRE", ONE_EXACTLY, - expect_uint(assign_variable_callback(num_closed_factories_per_state_lassiez_faire)), + expect_uint(assign_variable_callback(num_closed_factories_per_state_lassiez_faire)), "MIN_NUM_FACTORIES_PER_STATE_BEFORE_DELETING_LASSIEZ_FAIRE", ONE_EXACTLY, - expect_uint(assign_variable_callback(min_num_factories_per_state_before_deleting_lassiez_faire)), + expect_uint(assign_variable_callback(min_num_factories_per_state_before_deleting_lassiez_faire)), // "BANKRUPCY_DURATION", ONE_EXACTLY, expect_years(assign_variable_callback(bankruptcy_duration)), // paradox typo "SECOND_RANK_BASE_SHARE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(second_rank_base_share_factor)), + expect_fixed_point(assign_variable_callback(second_rank_base_share_factor)), // "CIV_BASE_SHARE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(civ_base_share_factor)), "UNCIV_BASE_SHARE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_base_share_factor)), "FACTORY_PAYCHECKS_LEFTOVER_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_paychecks_leftover_factor)), + expect_fixed_point(assign_variable_callback(factory_paychecks_leftover_factor)), // "MAX_FACTORY_MONEY_SAVE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_factory_money_save)), "SMALL_DEBT_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(small_debt_limit)), "FACTORY_UPGRADE_EMPLOYEE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_upgrade_employee_factor)), + expect_fixed_point(assign_variable_callback(factory_upgrade_employee_factor)), // "RGO_SUPPLY_DEMAND_FACTOR_HIRE_HI", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_hi)), + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_hi)), // "RGO_SUPPLY_DEMAND_FACTOR_HIRE_LO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_lo)), + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_lo)), // "RGO_SUPPLY_DEMAND_FACTOR_FIRE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_fire)), + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_fire)), // "EMPLOYMENT_HIRE_LOWEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(employment_hire_lowest)), "EMPLOYMENT_FIRE_LOWEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(employment_fire_lowest)), "TRADE_CAP_LOW_LIMIT_LAND", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_army_spending_slider_value)), + expect_fixed_point(assign_variable_callback(minimum_army_spending_slider_value)), // "TRADE_CAP_LOW_LIMIT_NAVAL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_navy_spending_slider_value)), + expect_fixed_point(assign_variable_callback(minimum_navy_spending_slider_value)), // "TRADE_CAP_LOW_LIMIT_CONSTRUCTIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_construction_spending_slider_value)), + expect_fixed_point(assign_variable_callback(minimum_construction_spending_slider_value)), // "FACTORY_PURCHASE_MIN_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(factory_purchase_min_factor)), "FACTORY_PURCHASE_DRAWDOWN_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_purchase_drawdown_factor)) + expect_fixed_point(assign_variable_callback(factory_purchase_drawdown_factor)) ); } diff --git a/src/openvic-simulation/defines/GraphicsDefines.cpp b/src/openvic-simulation/defines/GraphicsDefines.cpp index adaf8dce0..314e7409f 100644 --- a/src/openvic-simulation/defines/GraphicsDefines.cpp +++ b/src/openvic-simulation/defines/GraphicsDefines.cpp @@ -11,20 +11,17 @@ std::string_view GraphicsDefines::get_name() const { node_callback_t GraphicsDefines::expect_defines() { return expect_dictionary_keys( - "CITIES_SPRAWL_OFFSET", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_offset)), - "CITIES_SPRAWL_WIDTH", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_width)), - "CITIES_SPRAWL_HEIGHT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_height)), - "CITIES_SPRAWL_ITERATIONS", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_iterations)), - "CITIES_MESH_POOL_SIZE_FOR_COUNTRY", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_country)), - "CITIES_MESH_POOL_SIZE_FOR_CULTURE", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_culture)), + "CITIES_SPRAWL_OFFSET", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_offset)), "CITIES_SPRAWL_WIDTH", + ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_width)), "CITIES_SPRAWL_HEIGHT", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_height)), "CITIES_SPRAWL_ITERATIONS", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_iterations)), "CITIES_MESH_POOL_SIZE_FOR_COUNTRY", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_pool_size_for_country)), "CITIES_MESH_POOL_SIZE_FOR_CULTURE", + ONE_EXACTLY, expect_uint(assign_variable_callback(cities_mesh_pool_size_for_culture)), "CITIES_MESH_POOL_SIZE_FOR_GENERIC", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_generic)), - "CITIES_MESH_TYPES_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_mesh_types_count)), - "CITIES_MESH_SIZES_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_mesh_sizes_count)), - "CITIES_SPECIAL_BUILDINGS_POOL_SIZE", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_special_buildings_pool_size)), - "CITIES_SIZE_MAX_POPULATION_K", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_size_max_population_k)) + expect_uint(assign_variable_callback(cities_mesh_pool_size_for_generic)), "CITIES_MESH_TYPES_COUNT", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_types_count)), "CITIES_MESH_SIZES_COUNT", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_sizes_count)), "CITIES_SPECIAL_BUILDINGS_POOL_SIZE", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_special_buildings_pool_size)), "CITIES_SIZE_MAX_POPULATION_K", ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_size_max_population_k)) ); } diff --git a/src/openvic-simulation/defines/MilitaryDefines.cpp b/src/openvic-simulation/defines/MilitaryDefines.cpp index 74ad976aa..fcefd503b 100644 --- a/src/openvic-simulation/defines/MilitaryDefines.cpp +++ b/src/openvic-simulation/defines/MilitaryDefines.cpp @@ -1,9 +1,9 @@ #include "MilitaryDefines.hpp" -#include "openvic-simulation/military/CombatWidth.hpp" - #include +#include "openvic-simulation/military/CombatWidth.hpp" + using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -19,90 +19,82 @@ node_callback_t MilitaryDefines::expect_defines() { "REINFORCE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reinforce_speed)), "COMBAT_DIFFICULTY_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(combat_difficulty_impact)), "BASE_COMBAT_WIDTH", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(base_combat_width)), - "POP_MIN_SIZE_FOR_REGIMENT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(min_pop_size_for_regiment)), - "POP_SIZE_PER_REGIMENT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(pop_size_per_regiment)), + "POP_MIN_SIZE_FOR_REGIMENT", ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(min_pop_size_for_regiment)), "POP_SIZE_PER_REGIMENT", + ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(pop_size_per_regiment)), "SOLDIER_TO_POP_DAMAGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_to_pop_damage)), "LAND_SPEED_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(land_speed_modifier)), - "NAVAL_SPEED_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_speed_modifier)), - "EXP_GAIN_DIV", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(exp_gain_div)), - "LEADER_RECRUIT_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_recruit_cost)), - "SUPPLY_RANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(supply_range)), - "POP_MIN_SIZE_FOR_REGIMENT_PROTECTORATE_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_protectorate_multiplier)), + "NAVAL_SPEED_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_speed_modifier)), "EXP_GAIN_DIV", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(exp_gain_div)), "LEADER_RECRUIT_COST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_recruit_cost)), "SUPPLY_RANGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(supply_range)), "POP_MIN_SIZE_FOR_REGIMENT_PROTECTORATE_MULTIPLIER", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_size_per_regiment_protectorate_multiplier)), "POP_MIN_SIZE_FOR_REGIMENT_COLONY_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_colony_multiplier)), + expect_fixed_point(assign_variable_callback(pop_size_per_regiment_colony_multiplier)), "POP_MIN_SIZE_FOR_REGIMENT_NONCORE_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_non_core_multiplier)), - "GAS_ATTACK_MODIFIER", ONE_EXACTLY, expect_uint(assign_variable_callback(gas_attack_modifier)), - "COMBATLOSS_WAR_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(combatloss_war_exhaustion)), - "LEADER_MAX_RANDOM_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_max_random_prestige)), - "LEADER_AGE_DEATH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_age_death_factor)), - "LEADER_PRESTIGE_TO_MORALE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_prestige_to_morale_factor)), - "LEADER_PRESTIGE_TO_MAX_ORG_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_prestige_to_max_org_factor)), + expect_fixed_point(assign_variable_callback(pop_size_per_regiment_non_core_multiplier)), "GAS_ATTACK_MODIFIER", + ONE_EXACTLY, expect_uint(assign_variable_callback(gas_attack_modifier)), "COMBATLOSS_WAR_EXHAUSTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(combatloss_war_exhaustion)), "LEADER_MAX_RANDOM_PRESTIGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_max_random_prestige)), "LEADER_AGE_DEATH_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_age_death_factor)), "LEADER_PRESTIGE_TO_MORALE_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_prestige_to_morale_factor)), "LEADER_PRESTIGE_TO_MAX_ORG_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_to_max_org_factor)), "LEADER_TRANSFER_PENALTY_ON_COUNTRY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_transfer_penalty_on_country_prestige)), - "LEADER_PRESTIGE_LAND_GAIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_land_gain)), - "LEADER_PRESTIGE_NAVAL_GAIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_naval_gain)), - "NAVAL_COMBAT_SEEKING_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance)), + expect_fixed_point(assign_variable_callback(leader_transfer_penalty_on_country_prestige)), "LEADER_PRESTIGE_LAND_GAIN", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_land_gain)), "LEADER_PRESTIGE_NAVAL_GAIN", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_naval_gain)), "NAVAL_COMBAT_SEEKING_CHANCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance)), "NAVAL_COMBAT_SEEKING_CHANCE_MIN", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance_min)), - "NAVAL_COMBAT_SELF_DEFENCE_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_self_defence_chance)), + expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance_min)), "NAVAL_COMBAT_SELF_DEFENCE_CHANCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_self_defence_chance)), "NAVAL_COMBAT_SHIFT_BACK_ON_NEXT_TARGET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_shift_back_on_next_target)), + expect_fixed_point(assign_variable_callback(naval_combat_shift_back_on_next_target)), "NAVAL_COMBAT_SHIFT_BACK_DURATION_SCALE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_shift_back_duration_scale)), + expect_fixed_point(assign_variable_callback(naval_combat_shift_back_duration_scale)), "NAVAL_COMBAT_SPEED_TO_DISTANCE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_speed_to_distance_factor)), + expect_fixed_point(assign_variable_callback(naval_combat_speed_to_distance_factor)), "NAVAL_COMBAT_CHANGE_TARGET_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_change_target_chance)), - "NAVAL_COMBAT_DAMAGE_ORG_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_org_mult)), - "NAVAL_COMBAT_DAMAGE_STR_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_str_mult)), + expect_fixed_point(assign_variable_callback(naval_combat_change_target_chance)), "NAVAL_COMBAT_DAMAGE_ORG_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_damage_org_mult)), "NAVAL_COMBAT_DAMAGE_STR_MULT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_damage_str_mult)), "NAVAL_COMBAT_DAMAGE_MULT_NO_ORG", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_mult_no_org)), - "NAVAL_COMBAT_RETREAT_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_retreat_chance)), + expect_fixed_point(assign_variable_callback(naval_combat_damage_mult_no_org)), "NAVAL_COMBAT_RETREAT_CHANCE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_retreat_chance)), "NAVAL_COMBAT_RETREAT_STR_ORG_LEVEL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_str_org_level)), - "NAVAL_COMBAT_RETREAT_SPEED_MOD", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_speed_mod)), + expect_fixed_point(assign_variable_callback(naval_combat_retreat_str_org_level)), "NAVAL_COMBAT_RETREAT_SPEED_MOD", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_retreat_speed_mod)), "NAVAL_COMBAT_RETREAT_MIN_DISTANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_min_distance)), + expect_fixed_point(assign_variable_callback(naval_combat_retreat_min_distance)), "NAVAL_COMBAT_DAMAGED_TARGET_SELECTION", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damaged_target_selection)), + expect_fixed_point(assign_variable_callback(naval_combat_damaged_target_selection)), "NAVAL_COMBAT_STACKING_TARGET_CHANGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_change)), + expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_change)), "NAVAL_COMBAT_STACKING_TARGET_SELECT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_select)), - "NAVAL_COMBAT_MAX_TARGETS", ONE_EXACTLY, expect_uint(assign_variable_callback(naval_combat_max_targets)), - "AI_BIGSHIP_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_bigship_proportion)), - "AI_LIGHTSHIP_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_lightship_proportion)), - "AI_TRANSPORT_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_transport_proportion)), - "AI_CAVALRY_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_cavalry_proportion)), - "AI_SUPPORT_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_support_proportion)), - "AI_SPECIAL_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_special_proportion)), - "AI_ESCORT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_escort_ratio)), - "AI_ARMY_TAXBASE_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_army_taxbase_fraction)), - "AI_NAVY_TAXBASE_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_navy_taxbase_fraction)), - "AI_BLOCKADE_RANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_blockade_range)), - "RECON_UNIT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(recon_unit_ratio)), - "ENGINEER_UNIT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(engineer_unit_ratio)), - "SIEGE_BRIGADES_MIN", ONE_EXACTLY, expect_uint(assign_variable_callback(siege_brigades_min)), - "SIEGE_BRIGADES_MAX", ONE_EXACTLY, expect_uint(assign_variable_callback(siege_brigades_max)), - "SIEGE_BRIGADES_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(siege_brigades_bonus)), - "RECON_SIEGE_EFFECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(recon_siege_effect)), - "SIEGE_ATTRITION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(siege_attrition)), - "BASE_MILITARY_TACTICS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_military_tactics)), - "NAVAL_LOW_SUPPLY_DAMAGE_SUPPLY_STATUS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_supply_status)), + expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_select)), "NAVAL_COMBAT_MAX_TARGETS", + ONE_EXACTLY, expect_uint(assign_variable_callback(naval_combat_max_targets)), "AI_BIGSHIP_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_bigship_proportion)), "AI_LIGHTSHIP_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_lightship_proportion)), "AI_TRANSPORT_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_transport_proportion)), "AI_CAVALRY_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_cavalry_proportion)), "AI_SUPPORT_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_support_proportion)), "AI_SPECIAL_PROPORTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_special_proportion)), "AI_ESCORT_RATIO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_escort_ratio)), "AI_ARMY_TAXBASE_FRACTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_army_taxbase_fraction)), "AI_NAVY_TAXBASE_FRACTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_navy_taxbase_fraction)), "AI_BLOCKADE_RANGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_blockade_range)), "RECON_UNIT_RATIO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(recon_unit_ratio)), "ENGINEER_UNIT_RATIO", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(engineer_unit_ratio)), "SIEGE_BRIGADES_MIN", ONE_EXACTLY, + expect_uint(assign_variable_callback(siege_brigades_min)), "SIEGE_BRIGADES_MAX", ONE_EXACTLY, + expect_uint(assign_variable_callback(siege_brigades_max)), "SIEGE_BRIGADES_BONUS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(siege_brigades_bonus)), "RECON_SIEGE_EFFECT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(recon_siege_effect)), "SIEGE_ATTRITION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(siege_attrition)), "BASE_MILITARY_TACTICS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_military_tactics)), "NAVAL_LOW_SUPPLY_DAMAGE_SUPPLY_STATUS", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_low_supply_damage_supply_status)), "NAVAL_LOW_SUPPLY_DAMAGE_DAYS_DELAY", ONE_EXACTLY, - expect_days(assign_variable_callback(naval_low_supply_damage_days_delay)), - "NAVAL_LOW_SUPPLY_DAMAGE_MIN_STR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_min_str)), + expect_days(assign_variable_callback(naval_low_supply_damage_days_delay)), "NAVAL_LOW_SUPPLY_DAMAGE_MIN_STR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_low_supply_damage_min_str)), "NAVAL_LOW_SUPPLY_DAMAGE_PER_DAY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_per_day)) + expect_fixed_point(assign_variable_callback(naval_low_supply_damage_per_day)) ); } diff --git a/src/openvic-simulation/defines/MilitaryDefines.hpp b/src/openvic-simulation/defines/MilitaryDefines.hpp index c104893c0..76a67ca9d 100644 --- a/src/openvic-simulation/defines/MilitaryDefines.hpp +++ b/src/openvic-simulation/defines/MilitaryDefines.hpp @@ -2,9 +2,9 @@ #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/military/CombatWidth.hpp" +#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/defines/PopsDefines.cpp b/src/openvic-simulation/defines/PopsDefines.cpp index f28258985..0abd23a06 100644 --- a/src/openvic-simulation/defines/PopsDefines.cpp +++ b/src/openvic-simulation/defines/PopsDefines.cpp @@ -14,69 +14,65 @@ node_callback_t PopsDefines::expect_defines() { "BASE_CLERGY_FOR_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_clergy_for_literacy)), "MAX_CLERGY_FOR_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_clergy_for_literacy)), "LITERACY_CHANGE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(literacy_change_speed)), - "ASSIMILATION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(assimilation_scale)), - "CONVERSION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(conversion_scale)), - "IMMIGRATION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(immigration_scale)), - "PROMOTION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(promotion_scale)), - "PROMOTION_ASSIMILATION_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(promotion_assimilation_chance)), - "LUXURY_THRESHOLD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(luxury_threshold)), - "BASE_GOODS_DEMAND", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_goods_demand)), - "BASE_POPGROWTH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_popgrowth)), - "MIN_LIFE_RATING_FOR_GROWTH", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(min_life_rating_for_growth)), - "LIFE_RATING_GROWTH_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_rating_growth_bonus)), - "LIFE_NEED_STARVATION_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_need_starvation_limit)), - "MIL_LACK_EVERYDAY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_lack_everyday_need)), - "MIL_HAS_EVERYDAY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_has_everyday_need)), - "MIL_HAS_LUXURY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_has_luxury_need)), - "MIL_NO_LIFE_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_no_life_need)), - "MIL_REQUIRE_REFORM", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_require_reform)), - "MIL_IDEOLOGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_ideology)), - "MIL_RULING_PARTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_ruling_party)), - "MIL_REFORM_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_reform_impact)), - "MIL_WAR_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_war_exhaustion)), - "MIL_NON_ACCEPTED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_non_accepted)), - "CON_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_literacy)), - "CON_LUXURY_GOODS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_luxury_goods)), - "CON_POOR_CLERGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_poor_clergy)), - "CON_MIDRICH_CLERGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_midrich_clergy)), - "CON_REFORM_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_reform_impact)), - "CON_COLONIAL_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_colonial_factor)), - "RULING_PARTY_HAPPY_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ruling_party_happy_change)), - "RULING_PARTY_ANGRY_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ruling_party_angry_change)), - "PDEF_BASE_CON", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pdef_base_con)), - "NATIONAL_FOCUS_DIVIDER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(national_focus_divider)), - "POP_SAVINGS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_savings)), - "STATE_CREATION_ADMIN_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(state_creation_admin_limit)), - "MIL_TO_JOIN_REBEL", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_join_rebel)), - "MIL_TO_JOIN_RISING", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_join_rising)), - "MIL_TO_AUTORISE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_autorise)), - "REDUCTION_AFTER_RISEING", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reduction_after_riseing)), - "REDUCTION_AFTER_DEFEAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reduction_after_defeat)), - "POP_TO_LEADERSHIP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_to_leadership)), - "ARTISAN_MIN_PRODUCTIVITY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(artisan_min_productivity)), - "SLAVE_GROWTH_DIVISOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(slave_growth_divisor)), - "MIL_HIT_FROM_CONQUEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_hit_from_conquest)), - "LUXURY_CON_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(luxury_con_change)), - "INVENTION_IMPACT_ON_DEMAND", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(invention_impact_on_demand)), - "ARTISAN_SUPPRESSED_COLONIAL_GOODS_CATEGORY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(artisan_suppressed_colonial_goods_category)), + "ASSIMILATION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(assimilation_scale)), "CONVERSION_SCALE", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(conversion_scale)), "IMMIGRATION_SCALE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(immigration_scale)), "PROMOTION_SCALE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(promotion_scale)), "PROMOTION_ASSIMILATION_CHANCE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(promotion_assimilation_chance)), "LUXURY_THRESHOLD", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(luxury_threshold)), "BASE_GOODS_DEMAND", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_goods_demand)), "BASE_POPGROWTH", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_popgrowth)), "MIN_LIFE_RATING_FOR_GROWTH", ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(min_life_rating_for_growth)), "LIFE_RATING_GROWTH_BONUS", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_rating_growth_bonus)), "LIFE_NEED_STARVATION_LIMIT", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_need_starvation_limit)), "MIL_LACK_EVERYDAY_NEED", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_lack_everyday_need)), "MIL_HAS_EVERYDAY_NEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_has_everyday_need)), "MIL_HAS_LUXURY_NEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_has_luxury_need)), "MIL_NO_LIFE_NEED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_no_life_need)), "MIL_REQUIRE_REFORM", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_require_reform)), "MIL_IDEOLOGY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_ideology)), "MIL_RULING_PARTY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_ruling_party)), "MIL_REFORM_IMPACT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_reform_impact)), "MIL_WAR_EXHAUSTION", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_war_exhaustion)), "MIL_NON_ACCEPTED", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_non_accepted)), "CON_LITERACY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_literacy)), "CON_LUXURY_GOODS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_luxury_goods)), "CON_POOR_CLERGY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_poor_clergy)), "CON_MIDRICH_CLERGY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_midrich_clergy)), "CON_REFORM_IMPACT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_reform_impact)), "CON_COLONIAL_FACTOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_colonial_factor)), "RULING_PARTY_HAPPY_CHANGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ruling_party_happy_change)), "RULING_PARTY_ANGRY_CHANGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ruling_party_angry_change)), "PDEF_BASE_CON", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pdef_base_con)), "NATIONAL_FOCUS_DIVIDER", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(national_focus_divider)), "POP_SAVINGS", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_savings)), "STATE_CREATION_ADMIN_LIMIT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(state_creation_admin_limit)), "MIL_TO_JOIN_REBEL", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_join_rebel)), "MIL_TO_JOIN_RISING", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_join_rising)), "MIL_TO_AUTORISE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_autorise)), "REDUCTION_AFTER_RISEING", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reduction_after_riseing)), "REDUCTION_AFTER_DEFEAT", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reduction_after_defeat)), "POP_TO_LEADERSHIP", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_to_leadership)), "ARTISAN_MIN_PRODUCTIVITY", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(artisan_min_productivity)), "SLAVE_GROWTH_DIVISOR", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(slave_growth_divisor)), "MIL_HIT_FROM_CONQUEST", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_hit_from_conquest)), "LUXURY_CON_CHANGE", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(luxury_con_change)), "INVENTION_IMPACT_ON_DEMAND", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(invention_impact_on_demand)), "ARTISAN_SUPPRESSED_COLONIAL_GOODS_CATEGORY", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(artisan_suppressed_colonial_goods_category)), "ISSUE_MOVEMENT_JOIN_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(issue_movement_join_limit)), "ISSUE_MOVEMENT_LEAVE_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(issue_movement_leave_limit)), "MOVEMENT_CON_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_con_factor)), "MOVEMENT_LIT_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_lit_factor)), "MIL_ON_REB_MOVE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_on_reb_move)), "POPULATION_SUPPRESSION_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(population_suppression_factor)), - "POPULATION_MOVEMENT_RADICAL_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(population_movement_radical_factor)), - "NATIONALIST_MOVEMENT_MIL_CAP", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(nationalist_movement_mil_cap)), + expect_fixed_point(assign_variable_callback(population_suppression_factor)), "POPULATION_MOVEMENT_RADICAL_FACTOR", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(population_movement_radical_factor)), + "NATIONALIST_MOVEMENT_MIL_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(nationalist_movement_mil_cap)), "MOVEMENT_SUPPORT_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_support_uh_factor)), "REBEL_OCCUPATION_STRENGTH_BONUS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rebel_occupation_strength_bonus)), - "LARGE_POPULATION_LIMIT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(large_population_limit)), + expect_fixed_point(assign_variable_callback(rebel_occupation_strength_bonus)), "LARGE_POPULATION_LIMIT", ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(large_population_limit)), "LARGE_POPULATION_INFLUENCE_PENALTY_CHUNK", ONE_EXACTLY, - expect_strong_typedef(assign_variable_callback(large_population_influence_penalty_chunk)) + expect_strong_typedef(assign_variable_callback(large_population_influence_penalty_chunk)) ); } diff --git a/src/openvic-simulation/defines/PopsDefines.hpp b/src/openvic-simulation/defines/PopsDefines.hpp index 631ae7892..463c75634 100644 --- a/src/openvic-simulation/defines/PopsDefines.hpp +++ b/src/openvic-simulation/defines/PopsDefines.hpp @@ -1,9 +1,9 @@ #pragma once #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/map/LifeRating.hpp" +#include "openvic-simulation/population/PopSum.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/diplomacy/CountryRelation.cpp b/src/openvic-simulation/diplomacy/CountryRelation.cpp index dab393e14..5aa05ecd0 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.cpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.cpp @@ -353,7 +353,9 @@ influence_priority_value_type& CRM::assign_or_get_influence_priority_with( return it.value(); } -bool CRM::set_influence_priority_with(CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type value) { +bool CRM::set_influence_priority_with( + CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type value +) { decltype(influence_priority)::iterator it = influence_priority.find({ country, recipient }); if (it == influence_priority.end()) { it = influence_priority.insert({ { country, recipient }, value }).first; diff --git a/src/openvic-simulation/diplomacy/CountryRelation.hpp b/src/openvic-simulation/diplomacy/CountryRelation.hpp index 915e89763..9fc9a70d5 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.hpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.hpp @@ -9,9 +9,9 @@ #include #include +#include "openvic-simulation/core/Hash.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/core/Hash.hpp" namespace OpenVic { struct CountryInstance; @@ -46,9 +46,7 @@ namespace OpenVic { auto& rhs_comp_first = rhs_left > rhs_right ? rhs_left : rhs_right; auto& rhs_comp_second = rhs_left < rhs_right ? rhs_left : rhs_right; - return three_way_compare( - std::tie(lhs_comp_first, lhs_comp_second), std::tie(rhs_comp_first, rhs_comp_second) - ); + return three_way_compare(std::tie(lhs_comp_first, lhs_comp_second), std::tie(rhs_comp_first, rhs_comp_second)); } inline constexpr bool operator==(UnorderedCountryInstancePair const& rhs) const { @@ -266,7 +264,9 @@ public: \ RELATION_PAIR_MAP(CountryInstancePair, bool, vision, has_vision, const); RELATION_PAIR_MAP(CountryInstancePair, OpinionType, opinions, country_opinion, const); RELATION_PAIR_MAP(CountryInstancePair, influence_value_type, influence, influence_with, const); - RELATION_PAIR_MAP(CountryInstancePair, influence_priority_value_type, influence_priority, influence_priority_with, const); + RELATION_PAIR_MAP( + CountryInstancePair, influence_priority_value_type, influence_priority, influence_priority_with, const + ); vector_ordered_map discredits; vector_ordered_map embassy_bans; diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp index 92f7ea98c..d1bc02910 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp @@ -26,7 +26,7 @@ bool DiplomaticActionManager::add_diplomatic_action( spdlog::error_s("Invalid diplomatic action identifier - empty!"); return false; } - return diplomatic_action_types.emplace_item( identifier, identifier, DiplomaticActionType { std::move(initializer) } ); + return diplomatic_action_types.emplace_item(identifier, identifier, DiplomaticActionType { std::move(initializer) }); } bool DiplomaticActionManager::add_cancelable_diplomatic_action( @@ -36,7 +36,9 @@ bool DiplomaticActionManager::add_cancelable_diplomatic_action( spdlog::error_s("Invalid cancelable diplomatic action identifier - empty!"); return false; } - return diplomatic_action_types.emplace_item( identifier, identifier, CancelableDiplomaticActionType { std::move(initializer) } ); + return diplomatic_action_types.emplace_item( + identifier, identifier, CancelableDiplomaticActionType { std::move(initializer) } + ); } DiplomaticActionTickCache DiplomaticActionManager::create_diplomatic_action_tick( diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.hpp b/src/openvic-simulation/diplomacy/DiplomaticAction.hpp index 7b2eef30f..53db2c458 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.hpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.hpp @@ -7,12 +7,12 @@ #include #include +#include + #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/diplomacy/CountryRelation.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include - namespace OpenVic { struct InstanceManager; diff --git a/src/openvic-simulation/economy/BuildingInstance.cpp b/src/openvic-simulation/economy/BuildingInstance.cpp index 8cdbf432d..077fbd79e 100644 --- a/src/openvic-simulation/economy/BuildingInstance.cpp +++ b/src/openvic-simulation/economy/BuildingInstance.cpp @@ -5,33 +5,24 @@ using namespace OpenVic; BuildingInstance::BuildingInstance(BuildingType const& new_building_type, building_level_t new_level) - : HasIdentifier { new_building_type }, - building_type { new_building_type }, - level { new_level } {} + : HasIdentifier { new_building_type }, building_type { new_building_type }, level { new_level } {} bool BuildingInstance::_can_expand() const { return level < building_type.max_level; } bool BuildingInstance::expand( - ModifierEffectCache const& modifier_effect_cache, - CountryInstance& actor, - ProvinceInstance const& location + ModifierEffectCache const& modifier_effect_cache, CountryInstance& actor, ProvinceInstance const& location ) { if (expansion_state != ExpansionState::CanExpand) { return false; } - if (!building_type.can_be_built_in( - modifier_effect_cache, - level+1, - actor, - location - )) { + if (!building_type.can_be_built_in(modifier_effect_cache, level + 1, actor, location)) { return false; } - //TODO add construction costs to actor + // TODO add construction costs to actor expansion_state = ExpansionState::Preparing; expansion_progress = 0; return true; @@ -47,8 +38,8 @@ void BuildingInstance::update_gamestate(Date today) { end_date = start_date + building_type.build_time; break; case ExpansionState::Expanding: - expansion_progress = fixed_point_t { static_cast((today - start_date).to_int()) } - / static_cast((end_date - start_date).to_int()); + expansion_progress = fixed_point_t { static_cast((today - start_date).to_int()) } / + static_cast((end_date - start_date).to_int()); break; default: expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; } @@ -84,4 +75,4 @@ void BuildingInstance::set_level(const building_level_t new_level) { } else { level = new_level; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/BuildingInstance.hpp b/src/openvic-simulation/economy/BuildingInstance.hpp index 7fc5431b8..e8eb531f6 100644 --- a/src/openvic-simulation/economy/BuildingInstance.hpp +++ b/src/openvic-simulation/economy/BuildingInstance.hpp @@ -2,8 +2,8 @@ #include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { struct BuildingType; @@ -29,11 +29,7 @@ namespace OpenVic { BuildingInstance(BuildingType const& new_building_type, building_level_t new_level = building_level_t { 0 }); BuildingInstance(BuildingInstance&&) = default; - bool expand( - ModifierEffectCache const& modifier_effect_cache, - CountryInstance& actor, - ProvinceInstance const& location - ); + bool expand(ModifierEffectCache const& modifier_effect_cache, CountryInstance& actor, ProvinceInstance const& location); void update_gamestate(Date today); void tick(Date today); void set_level(const building_level_t new_level); diff --git a/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp b/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp index b2bf0e976..47e2c944f 100644 --- a/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp +++ b/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp @@ -1,9 +1,5 @@ #pragma once namespace OpenVic { - enum struct BuildingRestrictionCategory { - UNRESTRICTED, - INFRASTRUCTURE, - FACTORY - }; -} \ No newline at end of file + enum struct BuildingRestrictionCategory { UNRESTRICTED, INFRASTRUCTURE, FACTORY }; +} diff --git a/src/openvic-simulation/economy/BuildingType.cpp b/src/openvic-simulation/economy/BuildingType.cpp index 85033530f..a4c6bed1a 100644 --- a/src/openvic-simulation/economy/BuildingType.cpp +++ b/src/openvic-simulation/economy/BuildingType.cpp @@ -11,63 +11,45 @@ #include "openvic-simulation/map/State.hpp" #include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; BuildingType::BuildingType( - index_t new_index, - std::optional new_province_building_index, - std::string_view new_identifier, + index_t new_index, std::optional new_province_building_index, std::string_view new_identifier, building_type_args_t& building_type_args -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(building_type_args.modifier), modifier_type_t::BUILDING }, - province_building_index { new_province_building_index }, - type { building_type_args.type }, - on_completion { building_type_args.on_completion }, - completion_size { building_type_args.completion_size }, - max_level { building_type_args.max_level }, - goods_cost { std::move(building_type_args.goods_cost) }, - cost { building_type_args.cost }, - build_time { building_type_args.build_time }, - should_display_on_map { building_type_args.on_map }, - is_enabled_by_default { building_type_args.default_enabled }, - production_type { building_type_args.production_type }, - is_pop_build_factory { building_type_args.pop_build_factory }, - is_strategic_factory { building_type_args.strategic_factory }, - is_advanced_factory { building_type_args.advanced_factory }, - fort_level { building_type_args.fort_level }, - naval_capacity { building_type_args.naval_capacity }, - colonial_points { std::move(building_type_args.colonial_points) }, - is_in_province { building_type_args.in_province }, - restriction_category { - building_type_args.pop_build_factory - ? building_type_args.in_province - ? BuildingRestrictionCategory::INFRASTRUCTURE - : BuildingRestrictionCategory::FACTORY - : BuildingRestrictionCategory::UNRESTRICTED - }, - is_limited_to_one_per_state { building_type_args.one_per_state }, - colonial_range { building_type_args.colonial_range }, - infrastructure { building_type_args.infrastructure }, - should_spawn_railway_track { building_type_args.spawn_railway_track }, - is_sail { building_type_args.sail }, - is_steam { building_type_args.steam }, - capital { building_type_args.capital }, - is_port { building_type_args.port } {} +) + : HasIndex { new_index }, Modifier { new_identifier, std::move(building_type_args.modifier), modifier_type_t::BUILDING }, + province_building_index { new_province_building_index }, type { building_type_args.type }, + on_completion { building_type_args.on_completion }, completion_size { building_type_args.completion_size }, + max_level { building_type_args.max_level }, goods_cost { std::move(building_type_args.goods_cost) }, + cost { building_type_args.cost }, build_time { building_type_args.build_time }, + should_display_on_map { building_type_args.on_map }, is_enabled_by_default { building_type_args.default_enabled }, + production_type { building_type_args.production_type }, is_pop_build_factory { building_type_args.pop_build_factory }, + is_strategic_factory { building_type_args.strategic_factory }, + is_advanced_factory { building_type_args.advanced_factory }, fort_level { building_type_args.fort_level }, + naval_capacity { building_type_args.naval_capacity }, colonial_points { std::move(building_type_args.colonial_points) }, + is_in_province { building_type_args.in_province }, + restriction_category { building_type_args.pop_build_factory ? building_type_args.in_province + ? BuildingRestrictionCategory::INFRASTRUCTURE + : BuildingRestrictionCategory::FACTORY + : BuildingRestrictionCategory::UNRESTRICTED }, + is_limited_to_one_per_state { building_type_args.one_per_state }, colonial_range { building_type_args.colonial_range }, + infrastructure { building_type_args.infrastructure }, + should_spawn_railway_track { building_type_args.spawn_railway_track }, is_sail { building_type_args.sail }, + is_steam { building_type_args.steam }, capital { building_type_args.capital }, is_port { building_type_args.port } {} bool BuildingType::can_be_built_in( - ModifierEffectCache const& modifier_effect_cache, - const building_level_t desired_level, - CountryInstance const& actor, + ModifierEffectCache const& modifier_effect_cache, const building_level_t desired_level, CountryInstance const& actor, ProvinceInstance const& location ) const { OV_ERR_FAIL_COND_V_MSG( - !is_in_province, - false, - memory::fmt::format("BuildingType::can_be_built_in (province variant) was called on state level building {}", get_identifier()) + !is_in_province, false, + memory::fmt::format( + "BuildingType::can_be_built_in (province variant) was called on state level building {}", get_identifier() + ) ); if (desired_level > max_level) { @@ -94,7 +76,8 @@ bool BuildingType::can_be_built_in( continue; } - const building_level_t other_building_level = province_in_state.get_buildings()[province_building_index.value()].get_level(); + const building_level_t other_building_level = + province_in_state.get_buildings()[province_building_index.value()].get_level(); if (other_building_level > building_level_t(0)) { return false; } @@ -105,8 +88,8 @@ bool BuildingType::can_be_built_in( building_level_t const& unlocked_max_level = actor.get_building_type_unlock_levels(*this); ModifierEffectCache::building_type_effects_t const& effects = modifier_effect_cache.get_building_type_effects(*this); const fixed_point_t min_level_modifier = location.get_modifier_effect_value(*effects.get_min_level()); - return fixed_point_t { type_safe::get(unlocked_max_level) } - >= fixed_point_t { type_safe::get(desired_level) } + min_level_modifier; + return fixed_point_t { type_safe::get(unlocked_max_level) } >= + fixed_point_t { type_safe::get(desired_level) } + min_level_modifier; } bool BuildingType::can_be_built_in(ProvinceDefinition const& location) const { @@ -122,14 +105,13 @@ bool BuildingTypeManager::add_building_type( spdlog::error_s("Invalid building identifier - empty!"); return false; } - + std::optional province_building_index = building_type_args.in_province ? std::make_optional(province_building_types.size()) : std::nullopt; const bool ret = building_types.emplace_item( - identifier, - BuildingType::index_t { get_building_type_count() }, province_building_index, identifier, building_type_args + identifier, BuildingType::index_t { get_building_type_count() }, province_building_index, identifier, building_type_args ); if (ret) { @@ -146,10 +128,8 @@ bool BuildingTypeManager::load_buildings_file( GoodDefinitionManager const& good_definition_manager, ProductionTypeManager const& production_type_manager, ModifierManager& modifier_manager, ast::NodeCPtr root ) { - bool ret = expect_dictionary_reserve_length( - building_types, [this, &good_definition_manager, &production_type_manager, &modifier_manager]( - std::string_view key, ast::NodeCPtr value - ) -> bool { + bool ret = + expect_dictionary_reserve_length(building_types, [this, &good_definition_manager, &production_type_manager, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { BuildingType::building_type_args_t building_type_args {}; bool ret = NodeTools::expect_dictionary_keys_and_default( @@ -200,14 +180,11 @@ bool BuildingTypeManager::load_buildings_file( ret &= add_building_type(key, building_type_args); return ret; - } - )(root); + })(root); lock_building_types(); auto& building_type_effects = modifier_manager.modifier_effect_cache.building_type_effects; - building_type_effects = std::move( - decltype(ModifierEffectCache::building_type_effects){get_building_types()} - ); + building_type_effects = std::move(decltype(ModifierEffectCache::building_type_effects) { get_building_types() }); for (BuildingType const& building_type : get_building_types()) { using enum ModifierEffect::format_t; @@ -242,7 +219,8 @@ bool BuildingTypeManager::load_buildings_file( infrastructure_building_type = &building_type; } else { spdlog::error_s( - "Building type {} is marked as a infrastructure, but we are already using {} as the infrastructure building type!", + "Building type {} is marked as a infrastructure, but we are already using {} as the infrastructure " + "building type!", building_type, *infrastructure_building_type ); ret = false; @@ -250,9 +228,7 @@ bool BuildingTypeManager::load_buildings_file( } } else { if (building_type.is_port) { - spdlog::error_s( - "Building type {} is marked as a port, but is not a province building!", building_type - ); + spdlog::error_s("Building type {} is marked as a port, but is not a province building!", building_type); ret = false; } } @@ -273,8 +249,8 @@ bool BuildingTypeManager::load_buildings_file( ret = false; } else { SPDLOG_INFO( - "Found {} province building types out of {} total building types", - province_building_types.size(), get_building_type_count() + "Found {} province building types out of {} total building types", province_building_types.size(), + get_building_type_count() ); } diff --git a/src/openvic-simulation/economy/BuildingType.hpp b/src/openvic-simulation/economy/BuildingType.hpp index 9f2b5c828..ee95d4538 100644 --- a/src/openvic-simulation/economy/BuildingType.hpp +++ b/src/openvic-simulation/economy/BuildingType.hpp @@ -3,14 +3,14 @@ #include #include -#include "openvic-simulation/modifier/Modifier.hpp" #include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/economy/BuildingRestrictionCategory.hpp" +#include "openvic-simulation/modifier/Modifier.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -41,8 +41,8 @@ namespace OpenVic { fixed_point_map_t goods_cost; Timespan build_time; bool on_map = false, default_enabled = false, pop_build_factory = false, strategic_factory = false, - advanced_factory = false, in_province = false, one_per_state = false, spawn_railway_track = false, - sail = false, steam = false, capital = false, port = false; + advanced_factory = false, in_province = false, one_per_state = false, spawn_railway_track = false, + sail = false, steam = false, capital = false, port = false; ProductionType const* production_type = nullptr; naval_capacity_t naval_capacity = 0; memory::vector colonial_points; @@ -57,12 +57,12 @@ namespace OpenVic { const bool is_port; const bool capital; // only in naval base - const memory::string on_completion; //unknown + const memory::string on_completion; // unknown memory::vector SPAN_PROPERTY(colonial_points); public: - //general attributes + // general attributes const std::optional province_building_index; const bool is_pop_build_factory; @@ -80,12 +80,12 @@ namespace OpenVic { const building_level_t max_level; const fixed_point_t completion_size; - //costs + // costs const fixed_point_t cost; const Timespan build_time; const fixed_point_map_t goods_cost; - //effects + // effects ProductionType const* const production_type; const building_level_t fort_level; // fort bonus step-per-level const naval_capacity_t naval_capacity; @@ -93,18 +93,14 @@ namespace OpenVic { const fixed_point_t infrastructure; BuildingType( - index_t new_index, - std::optional new_province_building_index, - std::string_view new_identifier, - building_type_args_t& building_type_args + index_t new_index, std::optional new_province_building_index, + std::string_view new_identifier, building_type_args_t& building_type_args ); BuildingType(BuildingType&&) = default; [[nodiscard]] bool can_be_built_in( - ModifierEffectCache const& modifier_effect_cache, - const building_level_t desired_level, - CountryInstance const& actor, - ProvinceInstance const& location + ModifierEffectCache const& modifier_effect_cache, const building_level_t desired_level, + CountryInstance const& actor, ProvinceInstance const& location ) const; [[nodiscard]] bool can_be_built_in(ProvinceDefinition const& location) const; }; diff --git a/src/openvic-simulation/economy/EconomyManager.hpp b/src/openvic-simulation/economy/EconomyManager.hpp index 77226313c..e9cb2138f 100644 --- a/src/openvic-simulation/economy/EconomyManager.hpp +++ b/src/openvic-simulation/economy/EconomyManager.hpp @@ -15,15 +15,10 @@ namespace OpenVic { public: inline bool load_production_types_file( - GameRulesManager const& game_rules_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, PopManager const& pop_manager, ovdl::v2script::Parser const& parser ) { return production_type_manager.load_production_types_file( - game_rules_manager, - good_definition_manager, - pop_manager, - parser + game_rules_manager, good_definition_manager, pop_manager, parser ); } diff --git a/src/openvic-simulation/economy/GoodDefinition.cpp b/src/openvic-simulation/economy/GoodDefinition.cpp index 79d454330..d8ac0a0ed 100644 --- a/src/openvic-simulation/economy/GoodDefinition.cpp +++ b/src/openvic-simulation/economy/GoodDefinition.cpp @@ -1,7 +1,7 @@ #include "GoodDefinition.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/core/string/Utility.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -9,23 +9,13 @@ using namespace OpenVic::NodeTools; GoodCategory::GoodCategory(std::string_view new_identifier) : HasIdentifier { new_identifier } {} GoodDefinition::GoodDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - GoodCategory const& new_category, - fixed_point_t new_base_price, - bool new_is_available_from_start, - bool new_is_tradeable, - bool new_is_money, + std::string_view new_identifier, colour_t new_colour, index_t new_index, GoodCategory const& new_category, + fixed_point_t new_base_price, bool new_is_available_from_start, bool new_is_tradeable, bool new_is_money, bool new_counters_overseas_penalty -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - category { new_category }, - base_price { new_base_price }, - is_available_from_start { new_is_available_from_start }, - is_tradeable { new_is_tradeable }, - is_money { new_is_money }, - counters_overseas_penalty { new_counters_overseas_penalty } {} +) + : HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, category { new_category }, + base_price { new_base_price }, is_available_from_start { new_is_available_from_start }, is_tradeable { new_is_tradeable }, + is_money { new_is_money }, counters_overseas_penalty { new_counters_overseas_penalty } {} bool GoodDefinitionManager::add_good_category(std::string_view identifier, size_t expected_goods_in_category) { if (identifier.empty()) { @@ -56,16 +46,16 @@ bool GoodDefinitionManager::add_good_definition( if (is_tradeable == is_money) { spdlog::warn_s( - "Good {} has tradeable: {} and money: {}. Money goods are never tradeable. All other goods are tradeable. Setting tradeable has no effect.", + "Good {} has tradeable: {} and money: {}. Money goods are never tradeable. All other goods are tradeable. Setting " + "tradeable has no effect.", identifier, bool_to_yes_no(is_tradeable), bool_to_yes_no(is_money) ); } if (good_definitions.emplace_item( - identifier, - identifier, colour, GoodDefinition::index_t { get_good_definition_count() }, category, base_price, is_available_from_start, - is_tradeable, is_money, has_overseas_penalty - )) { + identifier, identifier, colour, GoodDefinition::index_t { get_good_definition_count() }, category, base_price, + is_available_from_start, is_tradeable, is_money, has_overseas_penalty + )) { category.good_definitions.emplace_back(get_back_good_definition()); return true; } else { @@ -76,9 +66,8 @@ bool GoodDefinitionManager::add_good_definition( bool GoodDefinitionManager::load_goods_file(ast::NodeCPtr root) { size_t total_expected_goods = 0; - bool ret = expect_dictionary_reserve_length( - good_categories, - [this, &total_expected_goods](std::string_view key, ast::NodeCPtr value) -> bool { + bool ret = + expect_dictionary_reserve_length(good_categories, [this, &total_expected_goods](std::string_view key, ast::NodeCPtr value) -> bool { size_t expected_goods_in_category = 0; bool ret = expect_length(assign_variable_callback(expected_goods_in_category))(value); @@ -90,40 +79,30 @@ bool GoodDefinitionManager::load_goods_file(ast::NodeCPtr root) { } return ret; - } - )(root); + })(root); lock_good_categories(); reserve_more_good_definitions(total_expected_goods); - ret &= good_categories.expect_item_dictionary( - [this](GoodCategory& good_category, ast::NodeCPtr good_category_value) -> bool { - return expect_dictionary( - [this, &good_category](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = colour_t::null(); - fixed_point_t base_price; - bool is_available_from_start = true, is_tradeable = true; - bool is_money = false, has_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(is_available_from_start)), - "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_tradeable)), - "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_money)), - "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(has_overseas_penalty)) - )(value); - - ret &= add_good_definition( - key, colour, good_category, base_price, is_available_from_start, is_tradeable, is_money, - has_overseas_penalty - ); - - return ret; - } - )(good_category_value); - } - )(root); + ret &= good_categories.expect_item_dictionary([this](GoodCategory& good_category, ast::NodeCPtr good_category_value) -> bool { + return expect_dictionary([this, &good_category](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = colour_t::null(); + fixed_point_t base_price; + bool is_available_from_start = true, is_tradeable = true; + bool is_money = false, has_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(is_available_from_start)), "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_tradeable)), "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_money)), "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(has_overseas_penalty)))( + value + ); + + ret &= add_good_definition( + key, colour, good_category, base_price, is_available_from_start, is_tradeable, is_money, has_overseas_penalty + ); + + return ret; + })(good_category_value); + })(root); lock_good_definitions(); @@ -139,7 +118,7 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager IndexedFlatMap& good_effects = modifier_manager.modifier_effect_cache.good_effects; - good_effects = std::move(decltype(ModifierEffectCache::good_effects){get_good_definitions()}); + good_effects = std::move(decltype(ModifierEffectCache::good_effects) { get_good_definitions() }); bool ret = true; @@ -159,18 +138,17 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager ModifierEffectCache::good_effects_t& this_good_effects = good_effects.at(good); const auto good_modifier = [&modifier_manager, &ret, &good_identifier]( - ModifierEffect const*& effect_cache, std::string_view name, ModifierEffect::format_t format, - std::string_view localisation_key, bool has_no_effect = false - ) -> void { + ModifierEffect const*& effect_cache, std::string_view name, + ModifierEffect::format_t format, std::string_view localisation_key, + bool has_no_effect = false + ) -> void { ret &= modifier_manager.register_technology_modifier_effect( - effect_cache, ModifierManager::get_flat_identifier(name, good_identifier), - format, localisation_key, has_no_effect + effect_cache, ModifierManager::get_flat_identifier(name, good_identifier), format, localisation_key, + has_no_effect ); }; - const auto make_production_localisation_suffix = [&good]( - std::string_view localisation_suffix - ) -> memory::string { + const auto make_production_localisation_suffix = [&good](std::string_view localisation_suffix) -> memory::string { return memory::fmt::format("${}$ ${}$", good, localisation_suffix); }; @@ -210,10 +188,7 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager this_good_effects.artisan_goods_throughput, "artisan_goods_throughput", FORMAT_x100_1DP_PC_POS, make_production_localisation_suffix("TECH_THROUGHPUT"), HAS_NO_EFFECT ); - good_modifier( - this_good_effects.rgo_size, "rgo_size", FORMAT_x100_2DP_PC_POS, - memory::fmt::format("{}_RGO_SIZE", good) - ); + good_modifier(this_good_effects.rgo_size, "rgo_size", FORMAT_x100_2DP_PC_POS, memory::fmt::format("{}_RGO_SIZE", good)); } return ret; diff --git a/src/openvic-simulation/economy/GoodDefinition.hpp b/src/openvic-simulation/economy/GoodDefinition.hpp index 64c45d291..4398ec96b 100644 --- a/src/openvic-simulation/economy/GoodDefinition.hpp +++ b/src/openvic-simulation/economy/GoodDefinition.hpp @@ -17,6 +17,7 @@ namespace OpenVic { private: memory::vector> SPAN_PROPERTY(good_definitions); + public: GoodCategory(std::string_view new_identifier); GoodCategory(GoodCategory&&) = default; diff --git a/src/openvic-simulation/economy/GoodInstance.cpp b/src/openvic-simulation/economy/GoodInstance.cpp index 34ab86a35..c5c401d8a 100644 --- a/src/openvic-simulation/economy/GoodInstance.cpp +++ b/src/openvic-simulation/economy/GoodInstance.cpp @@ -6,24 +6,21 @@ using namespace OpenVic; -GoodInstance::GoodInstance( - GoodDefinition const* new_good_definition, - GameRulesManager const* new_game_rules_manager -) : HasIdentifierAndColour { *new_good_definition }, - HasIndex { new_good_definition->index }, - GoodMarket { *new_game_rules_manager, *new_good_definition } - {} +GoodInstance::GoodInstance(GoodDefinition const* new_good_definition, GameRulesManager const* new_game_rules_manager) + : HasIdentifierAndColour { *new_good_definition }, HasIndex { new_good_definition->index }, + GoodMarket { *new_game_rules_manager, *new_good_definition } {} GoodInstanceManager::GoodInstanceManager( - GoodDefinitionManager const& new_good_definition_manager, - GameRulesManager const& game_rules_manager -) : good_definition_manager { new_good_definition_manager }, - good_instance_by_definition { - new_good_definition_manager.get_good_definitions(), - [game_rules_manager_ptr=&game_rules_manager](GoodDefinition const& good_definition) -> auto { - return std::make_tuple(&good_definition, game_rules_manager_ptr); - } - } { assert(new_good_definition_manager.good_definitions_are_locked()); } + GoodDefinitionManager const& new_good_definition_manager, GameRulesManager const& game_rules_manager +) + : good_definition_manager { new_good_definition_manager }, + good_instance_by_definition { new_good_definition_manager.get_good_definitions(), + [game_rules_manager_ptr = + &game_rules_manager](GoodDefinition const& good_definition) -> auto { + return std::make_tuple(&good_definition, game_rules_manager_ptr); + } } { + assert(new_good_definition_manager.good_definitions_are_locked()); +} bool GoodInstance::is_trading_good() const { return is_available && !good_definition.is_money; @@ -31,25 +28,17 @@ bool GoodInstance::is_trading_good() const { GoodInstance* GoodInstanceManager::get_good_instance_by_identifier(std::string_view identifier) { GoodDefinition const* good_definition = good_definition_manager.get_good_definition_by_identifier(identifier); - return good_definition == nullptr - ? nullptr - : &get_good_instance_by_definition(*good_definition); + return good_definition == nullptr ? nullptr : &get_good_instance_by_definition(*good_definition); } GoodInstance const* GoodInstanceManager::get_good_instance_by_identifier(std::string_view identifier) const { GoodDefinition const* good_definition = good_definition_manager.get_good_definition_by_identifier(identifier); - return good_definition == nullptr - ? nullptr - : &get_good_instance_by_definition(*good_definition); + return good_definition == nullptr ? nullptr : &get_good_instance_by_definition(*good_definition); } GoodInstance* GoodInstanceManager::get_good_instance_by_index(typename GoodInstance::index_t index) { - return good_instance_by_definition.contains_index(index) - ? &good_instance_by_definition.at_index(index) - : nullptr; + return good_instance_by_definition.contains_index(index) ? &good_instance_by_definition.at_index(index) : nullptr; } GoodInstance const* GoodInstanceManager::get_good_instance_by_index(typename GoodInstance::index_t index) const { - return good_instance_by_definition.contains_index(index) - ? &good_instance_by_definition.at_index(index) - : nullptr; + return good_instance_by_definition.contains_index(index) ? &good_instance_by_definition.at_index(index) : nullptr; } GoodInstance& GoodInstanceManager::get_good_instance_by_definition(GoodDefinition const& good_definition) { return good_instance_by_definition.at(good_definition); diff --git a/src/openvic-simulation/economy/GoodInstance.hpp b/src/openvic-simulation/economy/GoodInstance.hpp index b51194321..d7cd40aae 100644 --- a/src/openvic-simulation/economy/GoodInstance.hpp +++ b/src/openvic-simulation/economy/GoodInstance.hpp @@ -1,8 +1,8 @@ #pragma once #include "openvic-simulation/economy/trading/GoodMarket.hpp" -#include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" +#include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/TypedIndices.hpp" @@ -15,11 +15,8 @@ namespace OpenVic { friend struct GoodInstanceManager; public: - //pointers instead of references to allow construction via std::tuple - GoodInstance( - GoodDefinition const* new_good_definition, - GameRulesManager const* new_game_rules_manager - ); + // pointers instead of references to allow construction via std::tuple + GoodInstance(GoodDefinition const* new_good_definition, GameRulesManager const* new_game_rules_manager); GoodInstance(GoodInstance const&) = delete; GoodInstance& operator=(GoodInstance const&) = delete; GoodInstance(GoodInstance&&) = delete; @@ -37,8 +34,7 @@ namespace OpenVic { public: GoodInstanceManager( - GoodDefinitionManager const& new_good_definition_manager, - GameRulesManager const& game_rules_manager + GoodDefinitionManager const& new_good_definition_manager, GameRulesManager const& game_rules_manager ); constexpr forwardable_span get_good_instances() { diff --git a/src/openvic-simulation/economy/production/ArtisanalProducer.cpp b/src/openvic-simulation/economy/production/ArtisanalProducer.cpp index fef8535e2..2566284f5 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducer.cpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducer.cpp @@ -1,14 +1,13 @@ #include "ArtisanalProducer.hpp" -#include "ArtisanalProducerDeps.hpp" #include #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/random/RandomGenerator.hpp" #include "openvic-simulation/core/random/WeightedSampling.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/defines/EconomyDefines.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" @@ -22,31 +21,27 @@ #include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" +#include "ArtisanalProducerDeps.hpp" + using namespace OpenVic; -ArtisanalProducer::ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps) : ArtisanalProducer( - artisanal_producer_deps, - IndexedFlatMap { artisanal_producer_deps.good_keys }, - nullptr, - nullptr, - fixed_point_t::_0 -) { }; +ArtisanalProducer::ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps) + : ArtisanalProducer( + artisanal_producer_deps, IndexedFlatMap { artisanal_producer_deps.good_keys }, nullptr, + nullptr, fixed_point_t::_0 + ) {}; ArtisanalProducer::ArtisanalProducer( - ArtisanalProducerDeps const& artisanal_producer_deps, - IndexedFlatMap&& new_stockpile, - ProductionType const* const new_production_type, - GoodDefinition const* const new_last_produced_good, + ArtisanalProducerDeps const& artisanal_producer_deps, IndexedFlatMap&& new_stockpile, + ProductionType const* const new_production_type, GoodDefinition const* const new_last_produced_good, fixed_point_t new_current_production -) : economy_defines { artisanal_producer_deps.economy_defines }, - modifier_effect_cache { artisanal_producer_deps.modifier_effect_cache }, - stockpile { std::move(new_stockpile) }, - production_type_nullable { nullptr }, - last_produced_good { new_last_produced_good }, - current_production { new_current_production } - { - set_production_type(new_production_type); - } +) + : economy_defines { artisanal_producer_deps.economy_defines }, + modifier_effect_cache { artisanal_producer_deps.modifier_effect_cache }, stockpile { std::move(new_stockpile) }, + production_type_nullable { nullptr }, last_produced_good { new_last_produced_good }, + current_production { new_current_production } { + set_production_type(new_production_type); +} void ArtisanalProducer::set_production_type(ProductionType const* const new_production_type) { if (production_type_nullable == new_production_type) { @@ -64,17 +59,17 @@ void ArtisanalProducer::set_production_type(ProductionType const* const new_prod } void ArtisanalProducer::artisan_tick_handler::calculate_inputs( - IndexedFlatMap const& stockpile, - const bool should_report_input_demand + IndexedFlatMap const& stockpile, const bool should_report_input_demand ) { fixed_point_map_t const& input_goods = production_type.input_goods; - //throughput scalar, the minimum of stockpile / base_desired_quantity - //inputs_bought_fraction uses base_desired_quantity as population size is cancelled in the production and input calculations. + // throughput scalar, the minimum of stockpile / base_desired_quantity + // inputs_bought_fraction uses base_desired_quantity as population size is cancelled in the production and input + // calculations. const pop_size_t pop_size = pop.get_size(); fixed_point_t inputs_bought_numerator = type_safe::get(pop_size), - inputs_bought_denominator = type_safe::get(production_type.base_workforce_size), - inputs_bought_fraction_v = inputs_bought_numerator / inputs_bought_denominator; + inputs_bought_denominator = type_safe::get(production_type.base_workforce_size), + inputs_bought_fraction_v = inputs_bought_numerator / inputs_bought_denominator; distinct_goods_to_buy = 0; wants_more_mask.fill(false); @@ -83,17 +78,14 @@ void ArtisanalProducer::artisan_tick_handler::calculate_inputs( GoodDefinition const& input_good = *it.key(); const fixed_point_t base_desired_quantity = it.value(); const ptrdiff_t i = it - input_goods.begin(); - const fixed_point_t desired_quantity = demand_per_input[i] = base_desired_quantity * pop_size / production_type.base_workforce_size; + const fixed_point_t desired_quantity = demand_per_input[i] = + base_desired_quantity * pop_size / production_type.base_workforce_size; if (desired_quantity == 0) { continue; } if (should_report_input_demand && country_to_report_economy_nullable != nullptr) { - country_to_report_economy_nullable->report_input_demand( - production_type, - input_good, - desired_quantity - ); + country_to_report_economy_nullable->report_input_demand(production_type, input_good, desired_quantity); } const fixed_point_t stockpiled_quantity = stockpile.at(input_good); @@ -109,15 +101,11 @@ void ArtisanalProducer::artisan_tick_handler::calculate_inputs( distinct_goods_to_buy++; } - inputs_bought_fraction = Fraction { - inputs_bought_numerator, - inputs_bought_denominator - }; + inputs_bought_fraction = Fraction { inputs_bought_numerator, inputs_bought_denominator }; } void ArtisanalProducer::artisan_tick_handler::produce( - fixed_point_t& costs_of_production, - fixed_point_t& current_production, + fixed_point_t& costs_of_production, fixed_point_t& current_production, IndexedFlatMap& stockpile ) { fixed_point_t produce_left_to_sell = current_production = production_type.base_output_quantity * inputs_bought_fraction; @@ -138,16 +126,12 @@ void ArtisanalProducer::artisan_tick_handler::produce( const ptrdiff_t i = it - input_goods.begin(); fixed_point_t& good_stockpile = stockpile.at(input_good); - //Consume input good + // Consume input good fixed_point_t consumed_quantity = base_desired_quantity * inputs_bought_fraction; costs_of_production += consumed_quantity * market_instance.get_good_instance(input_good).get_price(); if (country_to_report_economy_nullable != nullptr) { - country_to_report_economy_nullable->report_input_consumption( - production_type, - input_good, - consumed_quantity - ); + country_to_report_economy_nullable->report_input_consumption(production_type, input_good, consumed_quantity); } if (input_good == production_type.output_good) { @@ -160,10 +144,7 @@ void ArtisanalProducer::artisan_tick_handler::produce( } } - good_stockpile = std::max( - fixed_point_t::_0, - good_stockpile - consumed_quantity - ); + good_stockpile = std::max(fixed_point_t::_0, good_stockpile - consumed_quantity); if (good_stockpile >= demand_per_input[i]) { wants_more_mask.set(input_good, false); @@ -176,21 +157,19 @@ void ArtisanalProducer::artisan_tick_handler::produce( void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( fixed_point_map_t& max_quantity_to_buy_per_good, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - IndexedFlatMap const& stockpile, - PopValuesFromProvince const& values_from_province + memory::vector& pop_max_quantity_to_buy_per_good, memory::vector& pop_money_to_spend_per_good, + IndexedFlatMap const& stockpile, PopValuesFromProvince const& values_from_province ) { - //executed once per pop while nothing else uses it. - const fixed_point_t total_cash_to_spend = pop.get_cash().get_copy_of_value() / values_from_province.get_max_cost_multiplier(); + // executed once per pop while nothing else uses it. + const fixed_point_t total_cash_to_spend = + pop.get_cash().get_copy_of_value() / values_from_province.get_max_cost_multiplier(); if (total_cash_to_spend <= 0 || distinct_goods_to_buy <= 0) { return; } - //Figure out the optimal amount of goods to buy based on their price, stockpiled quantiy & demand - fixed_point_t max_possible_satisfaction_numerator= 1, - max_possible_satisfaction_denominator= 1; + // Figure out the optimal amount of goods to buy based on their price, stockpiled quantiy & demand + fixed_point_t max_possible_satisfaction_numerator = 1, max_possible_satisfaction_denominator = 1; fixed_point_map_t const& input_goods = production_type.input_goods; bool at_or_below_optimum = false; @@ -209,11 +188,11 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( total_stockpile_value += max_price * stockpile.at(input_good); } - if ( total_demand_value == 0) { + if (total_demand_value == 0) { max_possible_satisfaction_numerator = 1; max_possible_satisfaction_denominator = 1; } else { - //epsilon is the minimum costs for a trade. + // epsilon is the minimum costs for a trade. const fixed_point_t flat_costs = fixed_point_t::epsilon * distinct_goods_to_buy; max_possible_satisfaction_numerator = total_stockpile_value + total_cash_to_spend - flat_costs; max_possible_satisfaction_denominator = total_demand_value + flat_costs; @@ -232,22 +211,20 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( const ptrdiff_t i = it - input_goods.begin(); const fixed_point_t optimal_quantity = fixed_point_t::mul_div( - demand_per_input[i], - max_possible_satisfaction_numerator, - max_possible_satisfaction_denominator + demand_per_input[i], max_possible_satisfaction_numerator, max_possible_satisfaction_denominator ); - + const fixed_point_t stockpiled_quantity = stockpile.at(input_good); if (stockpiled_quantity >= optimal_quantity) { at_or_below_optimum = false; wants_more = false; --distinct_goods_to_buy; - } + } } } fixed_point_t debug_cash_left = total_cash_to_spend; - //Place buy orders for each input + // Place buy orders for each input for (auto it = input_goods.begin(); it < input_goods.end(); it++) { GoodDefinition const& input_good = *it.key(); if (!wants_more_mask.at(input_good)) { @@ -259,15 +236,10 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( const fixed_point_t max_quantity_to_buy = good_demand - stockpiled_quantity; if (max_quantity_to_buy > 0) { - const fixed_point_t optimal_quantity = fixed_point_t::mul_div( - good_demand, - max_possible_satisfaction_numerator, - max_possible_satisfaction_denominator - ); - const fixed_point_t money_to_spend = market_instance.get_max_money_to_allocate_to_buy_quantity( - input_good, - optimal_quantity - stockpiled_quantity - ); + const fixed_point_t optimal_quantity = + fixed_point_t::mul_div(good_demand, max_possible_satisfaction_numerator, max_possible_satisfaction_denominator); + const fixed_point_t money_to_spend = + market_instance.get_max_money_to_allocate_to_buy_quantity(input_good, optimal_quantity - stockpiled_quantity); max_quantity_to_buy_per_good[&input_good] = max_quantity_to_buy; pop.allocate_cash_for_artisanal_spending(money_to_spend); const size_t index_in_all_goods = type_safe::get(input_good.index); @@ -283,15 +255,10 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( } void ArtisanalProducer::artisan_tick( - MarketInstance const& market_instance, - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator, - IndexedFlatMap& reusable_goods_mask, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - memory::vector& reusable_map_0, - memory::vector& reusable_map_1, + MarketInstance const& market_instance, Pop& pop, PopValuesFromProvince const& values_from_province, + RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, + memory::vector& pop_max_quantity_to_buy_per_good, memory::vector& pop_money_to_spend_per_good, + memory::vector& reusable_map_0, memory::vector& reusable_map_1, fixed_point_map_t& goods_to_sell ) { CountryInstance* const country_to_report_economy_nullable = pop.get_location().get_country_to_report_economy(); @@ -315,13 +282,9 @@ void ArtisanalProducer::artisan_tick( } } - ProductionType const* new_production_type_ptr = pick_production_type( - pop, - values_from_province, - random_number_generator - ); + ProductionType const* new_production_type_ptr = pick_production_type(pop, values_from_province, random_number_generator); - //if there is no valid production type, keep doing what we were doing, like in Vic2. + // if there is no valid production type, keep doing what we were doing, like in Vic2. if (new_production_type_ptr == nullptr) { new_production_type_ptr = old_production_type_ptr; } @@ -332,31 +295,26 @@ void ArtisanalProducer::artisan_tick( max_price_per_input.resize(input_goods.size(), 0); demand_per_input.resize(input_goods.size(), 0); - artisan_tick_handler tick_handler { - country_to_report_economy_nullable, - demand_per_input, - market_instance, - max_price_per_input, - pop, - old_production_type, - wants_more_mask - }; - + artisan_tick_handler tick_handler { country_to_report_economy_nullable, + demand_per_input, + market_instance, + max_price_per_input, + pop, + old_production_type, + wants_more_mask }; + const bool should_report_input_demand = old_production_type_ptr == new_production_type_ptr; tick_handler.calculate_inputs(stockpile, should_report_input_demand); tick_handler.produce(costs_of_production, current_production, stockpile); last_produced_good = &old_production_type.output_good; if (old_production_type_ptr == new_production_type_ptr) { tick_handler.allocate_money_for_inputs( - max_quantity_to_buy_per_good, - pop_max_quantity_to_buy_per_good, - pop_money_to_spend_per_good, - stockpile, + max_quantity_to_buy_per_good, pop_max_quantity_to_buy_per_good, pop_money_to_spend_per_good, stockpile, values_from_province ); } } - + if (new_production_type_ptr != old_production_type_ptr) { set_production_type(new_production_type_ptr); ProductionType const& new_production_type = *new_production_type_ptr; @@ -365,23 +323,18 @@ void ArtisanalProducer::artisan_tick( max_price_per_input.resize(input_goods.size(), 0); demand_per_input.resize(input_goods.size(), 0); - artisan_tick_handler tick_handler { - country_to_report_economy_nullable, - demand_per_input, - market_instance, - max_price_per_input, - pop, - new_production_type, - wants_more_mask - }; - + artisan_tick_handler tick_handler { country_to_report_economy_nullable, + demand_per_input, + market_instance, + max_price_per_input, + pop, + new_production_type, + wants_more_mask }; + constexpr bool should_report_input_demand = true; tick_handler.calculate_inputs(stockpile, should_report_input_demand); tick_handler.allocate_money_for_inputs( - max_quantity_to_buy_per_good, - pop_max_quantity_to_buy_per_good, - pop_money_to_spend_per_good, - stockpile, + max_quantity_to_buy_per_good, pop_max_quantity_to_buy_per_good, pop_money_to_spend_per_good, stockpile, values_from_province ); } @@ -401,10 +354,7 @@ void ArtisanalProducer::artisan_tick( fixed_point_t ArtisanalProducer::add_to_stockpile(GoodDefinition const& good, const fixed_point_t quantity) { if (OV_unlikely(quantity < 0)) { - spdlog::error_s( - "Attempted to add negative quantity {} of {} to artisan stockpile.", - quantity, good - ); + spdlog::error_s("Attempted to add negative quantity {} of {} to artisan stockpile.", quantity, good); return 0; } @@ -422,18 +372,15 @@ fixed_point_t ArtisanalProducer::add_to_stockpile(GoodDefinition const& good, co void ArtisanalProducer::subtract_from_stockpile(GoodDefinition const& good, const fixed_point_t sold_quantity) { if (OV_unlikely(sold_quantity < 0)) { - spdlog::error_s( - "Attempted to subtract negative quantity {} of {} to artisan stockpile.", - sold_quantity, good - ); + spdlog::error_s("Attempted to subtract negative quantity {} of {} to artisan stockpile.", sold_quantity, good); return; } fixed_point_t& stockpiled_quantity = stockpile.at(good); if (OV_unlikely(stockpiled_quantity < sold_quantity)) { spdlog::error_s( - "Attempted to subtract more {} of {} from artisan stockpile than it has {}.", - sold_quantity, good, stockpiled_quantity + "Attempted to subtract more {} of {} from artisan stockpile than it has {}.", sold_quantity, good, + stockpiled_quantity ); stockpiled_quantity = 0; @@ -444,9 +391,7 @@ void ArtisanalProducer::subtract_from_stockpile(GoodDefinition const& good, cons } std::optional ArtisanalProducer::estimate_production_type_score( - GoodInstanceManager const& good_instance_manager, - ProductionType const& production_type, - ProvinceInstance& location, + GoodInstanceManager const& good_instance_manager, ProductionType const& production_type, ProvinceInstance& location, const fixed_point_t max_cost_multiplier ) { if (production_type.template_type != ProductionType::template_type_t::ARTISAN) { @@ -469,38 +414,27 @@ std::optional ArtisanalProducer::estimate_production_type_score( estimated_costs *= max_cost_multiplier; const fixed_point_t estimated_revenue = production_type.base_output_quantity * output_good.get_price(); - return calculate_production_type_score( - estimated_revenue, - estimated_costs, - production_type.base_workforce_size - ); + return calculate_production_type_score(estimated_revenue, estimated_costs, production_type.base_workforce_size); } fixed_point_t ArtisanalProducer::calculate_production_type_score( - const fixed_point_t revenue, - const fixed_point_t costs, - const pop_size_t workforce + const fixed_point_t revenue, const fixed_point_t costs, const pop_size_t workforce ) { if (costs >= revenue) { return 0; } - //the score penalty at 0 margin + // the score penalty at 0 margin constexpr fixed_point_t k = fixed_point_t::_0_50; static_assert(0 <= k); static_assert(k <= 1); - return ( - k * fixed_point_t::mul_div(costs, costs, revenue) - -(1+k)*costs - + revenue - ).mul_div(Pop::size_denominator, workforce); //factor out pop size without making values too small + return (k * fixed_point_t::mul_div(costs, costs, revenue) - (1 + k) * costs + revenue) + .mul_div(Pop::size_denominator, workforce); // factor out pop size without making values too small } ProductionType const* ArtisanalProducer::pick_production_type( - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator + Pop& pop, PopValuesFromProvince const& values_from_province, RandomU32& random_number_generator ) const { bool should_pick_new_production_type; const auto ranked_artisanal_production_types = values_from_province.get_ranked_artisanal_production_types(); @@ -515,11 +449,7 @@ ProductionType const* ArtisanalProducer::pick_production_type( if (production_type_nullable == nullptr || (revenue <= costs)) { should_pick_new_production_type = true; } else if (base_chance_to_switch_while_profitable > 0) { - const fixed_point_t current_score = calculate_production_type_score( - revenue, - costs, - pop.get_size() - ); + const fixed_point_t current_score = calculate_production_type_score(revenue, costs, pop.get_size()); fixed_point_t relative_score = ranked_artisanal_production_types.empty() ? fixed_point_t::_1 : fixed_point_t::_0; assert(ranked_artisanal_production_types.size() < std::numeric_limits::max()); @@ -530,25 +460,23 @@ ProductionType const* ArtisanalProducer::pick_production_type( if (i == 0) { relative_score = fixed_point_t::_1; } else { - const fixed_point_t previous_score_estimate = ranked_artisanal_production_types[i-1].second; - relative_score = ( - (current_score - score_estimate) - / (previous_score_estimate - score_estimate) - + static_cast(ranked_artisanal_production_types.size() - i) - ) / static_cast(1 + ranked_artisanal_production_types.size()); + const fixed_point_t previous_score_estimate = ranked_artisanal_production_types[i - 1].second; + relative_score = ((current_score - score_estimate) / (previous_score_estimate - score_estimate) + + static_cast(ranked_artisanal_production_types.size() - i)) / + static_cast(1 + ranked_artisanal_production_types.size()); } break; } if (current_score == score_estimate) { - relative_score = fixed_point_t(static_cast(ranked_artisanal_production_types.size() - i)) - / static_cast(1 + ranked_artisanal_production_types.size()); + relative_score = fixed_point_t(static_cast(ranked_artisanal_production_types.size() - i)) / + static_cast(1 + ranked_artisanal_production_types.size()); } } - //picked so the line hits 0 at relative_score = 2/3 and the area under the curve equals 1 - //2/3 was picked as being in the top 1/3 of production types makes it very unlikely you'll profit from switching. - constexpr fixed_point_t slope = fixed_point_t{-9} / 2; + // picked so the line hits 0 at relative_score = 2/3 and the area under the curve equals 1 + // 2/3 was picked as being in the top 1/3 of production types makes it very unlikely you'll profit from switching. + constexpr fixed_point_t slope = fixed_point_t { -9 } / 2; constexpr fixed_point_t offset = 3; const fixed_point_t change_modifier_from_relative_score = std::max(fixed_point_t::_0, slope * relative_score + offset); @@ -559,11 +487,7 @@ ProductionType const* ArtisanalProducer::pick_production_type( constexpr fixed_point_t weights_sum = 1; const fixed_point_t keep_current_chance = weights_sum - switch_chance; const std::array weights { keep_current_chance, switch_chance }; - const size_t should_switch = sample_weighted_index( - random_number_generator(), - weights, - weights_sum - ); + const size_t should_switch = sample_weighted_index(random_number_generator(), weights, weights_sum); should_pick_new_production_type = should_switch == 1; } } @@ -571,23 +495,19 @@ ProductionType const* ArtisanalProducer::pick_production_type( if (!should_pick_new_production_type) { return production_type_nullable; } - + fixed_point_t weights_sum = 0; memory::vector weights {}; weights.reserve(ranked_artisanal_production_types.size()); for (auto const& [production_type, score_estimate] : ranked_artisanal_production_types) { - //TODO calculate actual scores including availability of goods + // TODO calculate actual scores including availability of goods const fixed_point_t weight = score_estimate * score_estimate; weights.push_back(weight); weights_sum += weight; } - const size_t sample_index = sample_weighted_index( - random_number_generator(), - weights, - weights_sum - ); + const size_t sample_index = sample_weighted_index(random_number_generator(), weights, weights_sum); assert(sample_index >= 0 && sample_index < ranked_artisanal_production_types.size()); return ranked_artisanal_production_types[sample_index].first; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ArtisanalProducer.hpp b/src/openvic-simulation/economy/production/ArtisanalProducer.hpp index fa06298f8..b2d48e2c3 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducer.hpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducer.hpp @@ -30,7 +30,7 @@ namespace OpenVic { ModifierEffectCache const& modifier_effect_cache; IndexedFlatMap stockpile; - //only used during day tick (from artisan_tick() until MarketInstance.execute_orders()) + // only used during day tick (from artisan_tick() until MarketInstance.execute_orders()) fixed_point_map_t max_quantity_to_buy_per_good; ProductionType const* PROPERTY(production_type_nullable); @@ -40,53 +40,39 @@ namespace OpenVic { void set_production_type(ProductionType const* const new_production_type); ProductionType const* pick_production_type( - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator + Pop& pop, PopValuesFromProvince const& values_from_province, RandomU32& random_number_generator ) const; - static fixed_point_t calculate_production_type_score( - const fixed_point_t revenue, - const fixed_point_t costs, - const pop_size_t workforce - ); + static fixed_point_t + calculate_production_type_score(const fixed_point_t revenue, const fixed_point_t costs, const pop_size_t workforce); public: ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps); ArtisanalProducer( - ArtisanalProducerDeps const& artisanal_producer_deps, - IndexedFlatMap&& new_stockpile, - ProductionType const* const new_production_type, - GoodDefinition const* const new_last_produced_good, + ArtisanalProducerDeps const& artisanal_producer_deps, IndexedFlatMap&& new_stockpile, + ProductionType const* const new_production_type, GoodDefinition const* const new_last_produced_good, const fixed_point_t new_current_production ); void artisan_tick( - MarketInstance const& market_instance, - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator, - IndexedFlatMap& reusable_goods_mask, + MarketInstance const& market_instance, Pop& pop, PopValuesFromProvince const& values_from_province, + RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - memory::vector& reusable_map_0, - memory::vector& reusable_map_1, - fixed_point_map_t& goods_to_sell + memory::vector& pop_money_to_spend_per_good, memory::vector& reusable_map_0, + memory::vector& reusable_map_1, fixed_point_map_t& goods_to_sell ); - //thread safe if called once per good and stockpile already has an entry. - //adds to stockpile up to max_quantity_to_buy and returns quantity added to stockpile + // thread safe if called once per good and stockpile already has an entry. + // adds to stockpile up to max_quantity_to_buy and returns quantity added to stockpile fixed_point_t add_to_stockpile(GoodDefinition const& good, const fixed_point_t quantity); void subtract_from_stockpile(GoodDefinition const& good, const fixed_point_t sold_quantity); - //optional to handle invalid + // optional to handle invalid static std::optional estimate_production_type_score( - GoodInstanceManager const& good_instance_manager, - ProductionType const& production_type, - ProvinceInstance& location, + GoodInstanceManager const& good_instance_manager, ProductionType const& production_type, ProvinceInstance& location, const fixed_point_t max_cost_multiplier ); - + private: struct artisan_tick_handler { private: @@ -103,27 +89,20 @@ namespace OpenVic { public: artisan_tick_handler( CountryInstance* const new_country_to_report_economy_nullable, - memory::vector& new_demand_per_input, - MarketInstance const& new_market_instance, - memory::vector& new_max_price_per_input, - Pop& new_pop, - ProductionType const& new_production_type, + memory::vector& new_demand_per_input, MarketInstance const& new_market_instance, + memory::vector& new_max_price_per_input, Pop& new_pop, ProductionType const& new_production_type, IndexedFlatMap& new_wants_more_mask - ) : country_to_report_economy_nullable { new_country_to_report_economy_nullable }, - demand_per_input { new_demand_per_input }, - market_instance { new_market_instance }, - max_price_per_input { new_max_price_per_input }, - pop { new_pop }, - production_type { new_production_type }, - wants_more_mask { new_wants_more_mask } {} + ) + : country_to_report_economy_nullable { new_country_to_report_economy_nullable }, + demand_per_input { new_demand_per_input }, market_instance { new_market_instance }, + max_price_per_input { new_max_price_per_input }, pop { new_pop }, production_type { new_production_type }, + wants_more_mask { new_wants_more_mask } {} void calculate_inputs( - IndexedFlatMap const& stockpile, - const bool should_report_input_demand + IndexedFlatMap const& stockpile, const bool should_report_input_demand ); void produce( - fixed_point_t& costs_of_production, - fixed_point_t& current_production, + fixed_point_t& costs_of_production, fixed_point_t& current_production, IndexedFlatMap& stockpile ); void allocate_money_for_inputs( diff --git a/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp b/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp index e949c7513..2780d5d49 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp @@ -12,4 +12,4 @@ namespace OpenVic { forwardable_span good_keys; ModifierEffectCache const& modifier_effect_cache; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/Employee.cpp b/src/openvic-simulation/economy/production/Employee.cpp index 5568563ad..71d5300d8 100644 --- a/src/openvic-simulation/economy/production/Employee.cpp +++ b/src/openvic-simulation/economy/production/Employee.cpp @@ -5,12 +5,9 @@ using namespace OpenVic; -Employee::Employee(Pop& new_pop, const pop_size_t new_size) - : pop { new_pop }, - size { new_size } - {} +Employee::Employee(Pop& new_pop, const pop_size_t new_size) : pop { new_pop }, size { new_size } {} fixed_point_t Employee::update_minimum_wage(CountryInstance& country_to_report_economy) { const fixed_point_t minimum_wage_base = country_to_report_economy.calculate_minimum_wage_base(pop.get_type()); return minimum_wage_cached = minimum_wage_base * size / Pop::size_denominator; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/Employee.hpp b/src/openvic-simulation/economy/production/Employee.hpp index 1d6208f6a..e4614d790 100644 --- a/src/openvic-simulation/economy/production/Employee.hpp +++ b/src/openvic-simulation/economy/production/Employee.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/population/PopSize.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { struct CountryInstance; @@ -12,8 +12,9 @@ namespace OpenVic { Pop& PROPERTY_MOD(pop); pop_size_t PROPERTY_RW(size); fixed_point_t PROPERTY_RW(minimum_wage_cached); + public: Employee(Pop& new_pop, const pop_size_t new_size); fixed_point_t update_minimum_wage(CountryInstance& country_to_report_economy); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/FactoryProducer.cpp b/src/openvic-simulation/economy/production/FactoryProducer.cpp index 333f67a9e..06331c8dc 100644 --- a/src/openvic-simulation/economy/production/FactoryProducer.cpp +++ b/src/openvic-simulation/economy/production/FactoryProducer.cpp @@ -3,42 +3,23 @@ using namespace OpenVic; FactoryProducer::FactoryProducer( - ProductionType const& new_production_type, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - ordered_map&& new_employees, - fixed_point_map_t&& new_stockpile, - fixed_point_t new_budget, - fixed_point_t new_balance_yesterday, - fixed_point_t new_received_investments_yesterday, - fixed_point_t new_market_spendings_yesterday, - fixed_point_t new_paychecks_yesterday, - uint32_t new_unprofitable_days, - uint32_t new_subsidised_days, - uint32_t new_days_without_input, - uint8_t new_hiring_priority, - uint8_t new_profit_history_current, - daily_profit_history_t&& new_daily_profit_history -) : production_type { new_production_type }, - size_multiplier { new_size_multiplier }, - revenue_yesterday { new_revenue_yesterday }, - output_quantity_yesterday { new_output_quantity_yesterday }, - unsold_quantity_yesterday { new_unsold_quantity_yesterday }, - employees { std::move(new_employees) }, - stockpile { std::move(new_stockpile) }, - budget { new_budget }, - balance_yesterday { new_balance_yesterday }, - received_investments_yesterday { new_received_investments_yesterday }, - market_spendings_yesterday { new_market_spendings_yesterday }, - paychecks_yesterday { new_paychecks_yesterday }, - unprofitable_days { new_unprofitable_days }, - subsidised_days { new_subsidised_days }, - days_without_input { new_days_without_input }, - hiring_priority { new_hiring_priority }, - profit_history_current { new_profit_history_current }, - daily_profit_history { std::move(new_daily_profit_history) } {} + ProductionType const& new_production_type, fixed_point_t new_size_multiplier, fixed_point_t new_revenue_yesterday, + fixed_point_t new_output_quantity_yesterday, fixed_point_t new_unsold_quantity_yesterday, + ordered_map&& new_employees, fixed_point_map_t&& new_stockpile, + fixed_point_t new_budget, fixed_point_t new_balance_yesterday, fixed_point_t new_received_investments_yesterday, + fixed_point_t new_market_spendings_yesterday, fixed_point_t new_paychecks_yesterday, uint32_t new_unprofitable_days, + uint32_t new_subsidised_days, uint32_t new_days_without_input, uint8_t new_hiring_priority, + uint8_t new_profit_history_current, daily_profit_history_t&& new_daily_profit_history +) + : production_type { new_production_type }, size_multiplier { new_size_multiplier }, + revenue_yesterday { new_revenue_yesterday }, output_quantity_yesterday { new_output_quantity_yesterday }, + unsold_quantity_yesterday { new_unsold_quantity_yesterday }, employees { std::move(new_employees) }, + stockpile { std::move(new_stockpile) }, budget { new_budget }, balance_yesterday { new_balance_yesterday }, + received_investments_yesterday { new_received_investments_yesterday }, + market_spendings_yesterday { new_market_spendings_yesterday }, paychecks_yesterday { new_paychecks_yesterday }, + unprofitable_days { new_unprofitable_days }, subsidised_days { new_subsidised_days }, + days_without_input { new_days_without_input }, hiring_priority { new_hiring_priority }, + profit_history_current { new_profit_history_current }, daily_profit_history { std::move(new_daily_profit_history) } {} FactoryProducer::FactoryProducer(ProductionType const& new_production_type, fixed_point_t new_size_multiplier) : FactoryProducer { new_production_type, new_size_multiplier, 0, 0, 0, {}, {}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {} } {} diff --git a/src/openvic-simulation/economy/production/FactoryProducer.hpp b/src/openvic-simulation/economy/production/FactoryProducer.hpp index 380419e9a..14caa87d7 100644 --- a/src/openvic-simulation/economy/production/FactoryProducer.hpp +++ b/src/openvic-simulation/economy/production/FactoryProducer.hpp @@ -2,10 +2,10 @@ #include +#include "openvic-simulation/population/PopSize.hpp" +#include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/economy/production/ProductionType.cpp b/src/openvic-simulation/economy/production/ProductionType.cpp index 9646c879f..592d3effa 100644 --- a/src/openvic-simulation/economy/production/ProductionType.cpp +++ b/src/openvic-simulation/economy/production/ProductionType.cpp @@ -14,34 +14,19 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; ProductionType::ProductionType( - GameRulesManager const& new_game_rules_manager, - const std::string_view new_identifier, - std::optional&& new_owner, - memory::vector&& new_jobs, - const template_type_t new_template_type, - const pop_size_t new_base_workforce_size, - fixed_point_map_t&& new_input_goods, - GoodDefinition const& new_output_good, - const fixed_point_t new_base_output_quantity, - memory::vector&& new_bonuses, - fixed_point_map_t&& new_maintenance_requirements, - const bool new_is_coastal, - const bool new_is_farm, + GameRulesManager const& new_game_rules_manager, const std::string_view new_identifier, std::optional&& new_owner, + memory::vector&& new_jobs, const template_type_t new_template_type, const pop_size_t new_base_workforce_size, + fixed_point_map_t&& new_input_goods, GoodDefinition const& new_output_good, + const fixed_point_t new_base_output_quantity, memory::vector&& new_bonuses, + fixed_point_map_t&& new_maintenance_requirements, const bool new_is_coastal, const bool new_is_farm, const bool new_is_mine -) : HasIdentifier { new_identifier }, - game_rules_manager { new_game_rules_manager }, - owner { std::move(new_owner) }, - jobs { std::move(new_jobs) }, - template_type { new_template_type }, - base_workforce_size { new_base_workforce_size }, - input_goods { std::move(new_input_goods) }, - output_good { new_output_good }, - base_output_quantity { new_base_output_quantity }, - bonuses { std::move(new_bonuses) }, - maintenance_requirements { std::move(new_maintenance_requirements) }, - is_coastal { new_is_coastal }, - _is_farm { new_is_farm }, - _is_mine { new_is_mine } {} +) + : HasIdentifier { new_identifier }, game_rules_manager { new_game_rules_manager }, owner { std::move(new_owner) }, + jobs { std::move(new_jobs) }, template_type { new_template_type }, base_workforce_size { new_base_workforce_size }, + input_goods { std::move(new_input_goods) }, output_good { new_output_good }, + base_output_quantity { new_base_output_quantity }, bonuses { std::move(new_bonuses) }, + maintenance_requirements { std::move(new_maintenance_requirements) }, is_coastal { new_is_coastal }, + _is_farm { new_is_farm }, _is_mine { new_is_mine } {} bool ProductionType::get_is_farm_for_tech() const { @@ -59,14 +44,14 @@ bool ProductionType::get_is_mine_for_non_tech() const { return !_is_farm; } -bool ProductionType::is_valid_for_artisan_in(ProvinceInstance& province) const{ +bool ProductionType::is_valid_for_artisan_in(ProvinceInstance& province) const { if (template_type != template_type_t::ARTISAN) { return false; } return !is_coastal || game_rules_manager.may_use_coastal_artisanal_production_types(province); } -bool ProductionType::is_valid_for_factory_in(State& state) const{ +bool ProductionType::is_valid_for_factory_in(State& state) const { if (template_type != template_type_t::FACTORY) { return false; } @@ -87,14 +72,8 @@ ProductionType const* ProductionTypeManager::get_good_to_rgo_production_type(Goo } node_callback_t ProductionTypeManager::_expect_job( - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - NodeTools::callback_t< - PopType const*, - Job::effect_t, - fixed_point_t, - fixed_point_t - > emplace_callback + GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, + NodeTools::callback_t emplace_callback ) { return [this, &good_definition_manager, &pop_manager, emplace_callback](ast::NodeCPtr node) mutable -> bool { using enum Job::effect_t; @@ -103,16 +82,15 @@ node_callback_t ProductionTypeManager::_expect_job( Job::effect_t effect_type { THROUGHPUT }; fixed_point_t effect_multiplier = 1, desired_workforce_share = 1; - static const string_map_t effect_map = { - { "input", INPUT }, { "output", OUTPUT }, { "throughput", THROUGHPUT } - }; + static const string_map_t effect_map = { { "input", INPUT }, + { "output", OUTPUT }, + { "throughput", THROUGHPUT } }; - bool ret = expect_dictionary_keys( - "poptype", ONE_EXACTLY, expect_identifier(assign_variable_callback(pop_type)), - "effect", ONE_EXACTLY, expect_identifier(expect_mapped_string(effect_map, assign_variable_callback(effect_type))), - "effect_multiplier", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(effect_multiplier)), - "amount", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(desired_workforce_share)) - )(node); + bool + ret = + expect_dictionary_keys("poptype", ONE_EXACTLY, expect_identifier(assign_variable_callback(pop_type)), "effect", ONE_EXACTLY, expect_identifier(expect_mapped_string(effect_map, assign_variable_callback(effect_type))), "effect_multiplier", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(effect_multiplier)), "amount", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(desired_workforce_share)))( + node + ); PopType const* const found_pop_type = pop_manager.get_pop_type_by_identifier(pop_type); return ret & emplace_callback(found_pop_type, effect_type, effect_multiplier, desired_workforce_share); @@ -125,32 +103,18 @@ node_callback_t ProductionTypeManager::_expect_job_list( ) { return [this, &good_definition_manager, &pop_manager, callback](ast::NodeCPtr node) mutable -> bool { memory::vector jobs; - bool ret = expect_list( - _expect_job( - good_definition_manager, - pop_manager, - vector_emplace_callback(jobs) - ) - )(node); + bool ret = expect_list(_expect_job(good_definition_manager, pop_manager, vector_emplace_callback(jobs)))(node); ret &= callback(std::move(jobs)); return ret; }; } bool ProductionTypeManager::add_production_type( - GameRulesManager const& game_rules_manager, - const std::string_view identifier, - std::optional&& owner_before_move, - memory::vector&& jobs, - const ProductionType::template_type_t template_type, - const pop_size_t base_workforce_size, - fixed_point_map_t&& input_goods, - GoodDefinition const* const output_good, - const fixed_point_t base_output_quantity, - memory::vector&& bonuses, - fixed_point_map_t&& maintenance_requirements, - const bool is_coastal, - const bool is_farm, + GameRulesManager const& game_rules_manager, const std::string_view identifier, std::optional&& owner_before_move, + memory::vector&& jobs, const ProductionType::template_type_t template_type, const pop_size_t base_workforce_size, + fixed_point_map_t&& input_goods, GoodDefinition const* const output_good, + const fixed_point_t base_output_quantity, memory::vector&& bonuses, + fixed_point_map_t&& maintenance_requirements, const bool is_coastal, const bool is_farm, const bool is_mine ) { if (identifier.empty()) { @@ -177,16 +141,13 @@ bool ProductionTypeManager::add_production_type( if (template_type == ARTISAN) { if (owner_before_move.has_value()) { - spdlog::warn_s( - "Artisanal production type {} should not have an owner - it is being ignored.", identifier - ); + spdlog::warn_s("Artisanal production type {} should not have an owner - it is being ignored.", identifier); owner_before_move.reset(); } if (!jobs.empty()) { spdlog::warn_s( - "Artisanal production type {} should not have employees - {} are being ignored.", - identifier, jobs.size() + "Artisanal production type {} should not have employees - {} are being ignored.", identifier, jobs.size() ); jobs.clear(); } @@ -208,40 +169,31 @@ bool ProductionTypeManager::add_production_type( for (size_t i = 0; i < jobs.size(); i++) { if (jobs[i].pop_type == nullptr) { - spdlog::error_s( - "Production type {} has invalid pop type in employees[{}].", - identifier, i - ); + spdlog::error_s("Production type {} has invalid pop type in employees[{}].", identifier, i); return false; } } } const bool ret = production_types.emplace_item( - identifier, - game_rules_manager, identifier, std::move(owner_before_move), std::move(jobs), template_type, base_workforce_size, std::move(input_goods), *output_good, - base_output_quantity, std::move(bonuses), std::move(maintenance_requirements), is_coastal, is_farm, is_mine + identifier, game_rules_manager, identifier, std::move(owner_before_move), std::move(jobs), template_type, + base_workforce_size, std::move(input_goods), *output_good, base_output_quantity, std::move(bonuses), + std::move(maintenance_requirements), is_coastal, is_farm, is_mine ); if (ret && (template_type == RGO)) { ProductionType const& production_type = production_types.back(); ProductionType const*& current_rgo_pt = good_to_rgo_production_type.at(*output_good); - if (current_rgo_pt == nullptr || ( - (is_farm && !is_mine) - && (!current_rgo_pt->_is_farm || current_rgo_pt->_is_mine) - )) { + if (current_rgo_pt == nullptr || ((is_farm && !is_mine) && (!current_rgo_pt->_is_farm || current_rgo_pt->_is_mine))) { // pure farms are preferred over alternatives. Use first pt otherwise. current_rgo_pt = &get_back_production_type(); } - //else ignore, we already have an rgo pt + // else ignore, we already have an rgo pt std::optional const& owner_after_move = production_type.owner; - if (rgo_owner_sprite <= 0 - && template_type == RGO - && owner_after_move.has_value() - && owner_after_move->pop_type != nullptr - ) { + if (rgo_owner_sprite <= 0 && template_type == RGO && owner_after_move.has_value() && + owner_after_move->pop_type != nullptr) { /* Set rgo owner sprite to that of the first RGO owner we find. */ rgo_owner_sprite = owner_after_move->pop_type->sprite; } @@ -251,10 +203,8 @@ bool ProductionTypeManager::add_production_type( } bool ProductionTypeManager::load_production_types_file( - GameRulesManager const& game_rules_manager, - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, ovdl::v2script::Parser const& parser ) { using namespace std::string_view_literals; auto template_symbol = parser.find_intern("template"sv); @@ -271,63 +221,53 @@ bool ProductionTypeManager::load_production_types_file( /* Pass #1: find and store template identifiers */ ordered_set templates; ordered_map template_target_map; - bool ret = expect_dictionary( - [this, &expected_types, &templates, &template_target_map, &template_symbol, &output_goods_symbol] - (std::string_view key, ast::NodeCPtr value) -> bool { + bool ret = + expect_dictionary([this, &expected_types, &templates, &template_target_map, &template_symbol, &output_goods_symbol](std::string_view key, ast::NodeCPtr value) -> bool { expected_types++; std::string_view template_id = ""; bool has_found_template = false; - const bool is_parsing_template_success = expect_key( - template_symbol, - expect_identifier(assign_variable_callback(template_id)), - &has_found_template - )(value); + const bool is_parsing_template_success = + expect_key(template_symbol, expect_identifier(assign_variable_callback(template_id)), &has_found_template)( + value + ); if (has_found_template) { OV_ERR_FAIL_COND_V_MSG( - !is_parsing_template_success, - false, - memory::fmt::format("Failed get template identifier for {}", key) + !is_parsing_template_success, false, memory::fmt::format("Failed get template identifier for {}", key) ); templates.emplace(template_id); template_target_map.emplace(key, template_id); } else { bool has_found_output_goods = false; - expect_key( - output_goods_symbol, - success_callback, - &has_found_output_goods - )(value); + expect_key(output_goods_symbol, success_callback, &has_found_output_goods)(value); if (!has_found_output_goods) { - //assume it's a template + // assume it's a template templates.emplace(key); } } return true; - } - )(parser.get_file_node()); + })(parser.get_file_node()); /* Pass #2: create and populate the template map */ ordered_map template_node_map; - ret &= expect_dictionary( - [this, &expected_types, &templates, &template_node_map](std::string_view key, ast::NodeCPtr value) -> bool { + ret &= + expect_dictionary([this, &expected_types, &templates, &template_node_map](std::string_view key, ast::NodeCPtr value) -> bool { if (templates.contains(key)) { template_node_map.emplace(key, value); expected_types--; } return true; - } - )(parser.get_file_node()); + })(parser.get_file_node()); /* Pass #3: actually load production types */ - good_to_rgo_production_type = std::move(decltype(good_to_rgo_production_type){good_definition_manager.get_good_definitions()}); + good_to_rgo_production_type = + std::move(decltype(good_to_rgo_production_type) { good_definition_manager.get_good_definitions() }); reserve_more_production_types(expected_types); - ret &= expect_dictionary( - [this, &game_rules_manager, &good_definition_manager, &pop_manager, &template_target_map, &template_node_map]( - std::string_view key, ast::NodeCPtr node) -> bool { + ret &= + expect_dictionary([this, &game_rules_manager, &good_definition_manager, &pop_manager, &template_target_map, &template_node_map](std::string_view key, ast::NodeCPtr node) -> bool { using enum ProductionType::template_type_t; if (template_node_map.contains(key)) { @@ -346,22 +286,23 @@ bool ProductionTypeManager::load_production_types_file( bool ret = true; - static const string_map_t template_type_map = { - { "factory", FACTORY }, { "rgo", RGO }, { "artisan", ARTISAN } - }; + static const string_map_t template_type_map = { { "factory", FACTORY }, + { "rgo", RGO }, + { "artisan", ARTISAN } }; auto parse_node = expect_dictionary_keys( "template", ZERO_OR_ONE, success_callback, /* Already parsed using expect_key in Pass #1 above. */ - "bonus", ZERO_OR_MORE, [&bonuses](ast::NodeCPtr bonus_node) -> bool { + "bonus", ZERO_OR_MORE, + [&bonuses](ast::NodeCPtr bonus_node) -> bool { using enum scope_type_t; ConditionScript trigger { STATE, NO_SCOPE, NO_SCOPE }; fixed_point_t bonus_value {}; - const bool ret = expect_dictionary_keys( - "trigger", ONE_EXACTLY, trigger.expect_script(), - "value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bonus_value)) - )(bonus_node); + const bool ret = + expect_dictionary_keys("trigger", ONE_EXACTLY, trigger.expect_script(), "value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bonus_value)))( + bonus_node + ); bonuses.emplace_back(std::move(trigger), bonus_value); @@ -370,19 +311,18 @@ bool ProductionTypeManager::load_production_types_file( "owner", ZERO_OR_ONE, _expect_job(good_definition_manager, pop_manager, emplace_opt_callback(owner)), "employees", ZERO_OR_ONE, _expect_job_list(good_definition_manager, pop_manager, move_variable_callback(jobs)), "type", ZERO_OR_ONE, - expect_identifier(expect_mapped_string(template_type_map, assign_variable_callback(template_type))), + expect_identifier(expect_mapped_string(template_type_map, assign_variable_callback(template_type))), "workforce", ZERO_OR_ONE, expect_strong_typedef(assign_variable_callback(base_workforce_size)), "input_goods", ZERO_OR_ONE, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(input_goods)), - "output_goods", ZERO_OR_ONE, - good_definition_manager.expect_good_definition_identifier(assign_variable_callback_pointer(output_good)), - "value", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(base_output_quantity)), - "efficiency", ZERO_OR_ONE, good_definition_manager.expect_good_definition_decimal_map( - move_variable_callback(maintenance_requirements) - ), - "is_coastal", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_coastal)), - "farm", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_farm)), - "mine", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_mine)) + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(input_goods)), "output_goods", + ZERO_OR_ONE, + good_definition_manager.expect_good_definition_identifier(assign_variable_callback_pointer(output_good)), + "value", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(base_output_quantity)), "efficiency", + ZERO_OR_ONE, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(maintenance_requirements)), + "is_coastal", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_coastal)), "farm", ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_farm)), "mine", ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_mine)) ); /* Check if this ProductionType has a template, and if so parse it. */ @@ -394,10 +334,7 @@ bool ProductionTypeManager::load_production_types_file( if (node_it != template_node_map.end()) { ret &= parse_node(node_it->second); } else { - spdlog::error_s( - "Missing template {} for production type {}!", - template_id, key - ); + spdlog::error_s("Missing template {} for production type {}!", template_id, key); ret = false; } } @@ -407,14 +344,13 @@ bool ProductionTypeManager::load_production_types_file( ret &= parse_node(node); ret &= add_production_type( - game_rules_manager, - key, std::move(owner), std::move(jobs), template_type, base_workforce_size, std::move(input_goods), output_good, - base_output_quantity, std::move(bonuses), std::move(maintenance_requirements), is_coastal, is_farm, is_mine + game_rules_manager, key, std::move(owner), std::move(jobs), template_type, base_workforce_size, + std::move(input_goods), output_good, base_output_quantity, std::move(bonuses), + std::move(maintenance_requirements), is_coastal, is_farm, is_mine ); return ret; - } - )(parser.get_file_node()); + })(parser.get_file_node()); production_types.lock(); diff --git a/src/openvic-simulation/economy/production/ProductionType.hpp b/src/openvic-simulation/economy/production/ProductionType.hpp index 170f26f1f..5dcfb09cc 100644 --- a/src/openvic-simulation/economy/production/ProductionType.hpp +++ b/src/openvic-simulation/economy/production/ProductionType.hpp @@ -2,12 +2,12 @@ #include +#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/scripts/ConditionScript.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/types/PopSprite.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -21,16 +21,13 @@ namespace OpenVic { const effect_t effect_type; const fixed_point_t effect_multiplier; const fixed_point_t amount; - + constexpr Job( - PopType const* const new_pop_type, - const effect_t new_effect_type, - const fixed_point_t new_effect_multiplier, + PopType const* const new_pop_type, const effect_t new_effect_type, const fixed_point_t new_effect_multiplier, const fixed_point_t new_amount - ) : pop_type { new_pop_type }, - effect_type { new_effect_type }, - effect_multiplier { new_effect_multiplier }, - amount { new_amount } {} + ) + : pop_type { new_pop_type }, effect_type { new_effect_type }, effect_multiplier { new_effect_multiplier }, + amount { new_amount } {} constexpr Job() : Job(nullptr, effect_t::THROUGHPUT, fixed_point_t::_0, fixed_point_t::_0) {}; }; @@ -68,20 +65,12 @@ namespace OpenVic { const fixed_point_t base_output_quantity; ProductionType( - GameRulesManager const& new_game_rules_manager, - const std::string_view new_identifier, - std::optional&& new_owner, - memory::vector&& new_jobs, - const template_type_t new_template_type, - const pop_size_t new_base_workforce_size, - fixed_point_map_t&& new_input_goods, - GoodDefinition const& new_output_good, - const fixed_point_t new_base_output_quantity, - memory::vector&& new_bonuses, - fixed_point_map_t&& new_maintenance_requirements, - const bool new_is_coastal, - const bool new_is_farm, - const bool new_is_mine + GameRulesManager const& new_game_rules_manager, const std::string_view new_identifier, + std::optional&& new_owner, memory::vector&& new_jobs, const template_type_t new_template_type, + const pop_size_t new_base_workforce_size, fixed_point_map_t&& new_input_goods, + GoodDefinition const& new_output_good, const fixed_point_t new_base_output_quantity, + memory::vector&& new_bonuses, fixed_point_map_t&& new_maintenance_requirements, + const bool new_is_coastal, const bool new_is_farm, const bool new_is_mine ); constexpr bool get_is_farm_for_non_tech() const { @@ -105,12 +94,7 @@ namespace OpenVic { NodeTools::node_callback_t _expect_job( GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, - NodeTools::callback_t< - PopType const*, - Job::effect_t, - fixed_point_t, - fixed_point_t - > emplace_callback + NodeTools::callback_t emplace_callback ); NodeTools::node_callback_t _expect_job_list( GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, @@ -122,29 +106,20 @@ namespace OpenVic { : good_to_rgo_production_type { decltype(good_to_rgo_production_type)::create_empty() } {} bool add_production_type( - GameRulesManager const& game_rules_manager, - const std::string_view identifier, - std::optional&& owner, - memory::vector&& jobs, - const ProductionType::template_type_t template_type, - const pop_size_t base_workforce_size, - fixed_point_map_t&& input_goods, - GoodDefinition const* const output_good, - const fixed_point_t base_output_quantity, + GameRulesManager const& game_rules_manager, const std::string_view identifier, std::optional&& owner, + memory::vector&& jobs, const ProductionType::template_type_t template_type, + const pop_size_t base_workforce_size, fixed_point_map_t&& input_goods, + GoodDefinition const* const output_good, const fixed_point_t base_output_quantity, memory::vector&& bonuses, - fixed_point_map_t&& maintenance_requirements, - const bool is_coastal, - const bool is_farm, + fixed_point_map_t&& maintenance_requirements, const bool is_coastal, const bool is_farm, const bool is_mine ); bool load_production_types_file( - GameRulesManager const& game_rules_manager, - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, ovdl::v2script::Parser const& parser ); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp index 2ac1e6dd3..f88e9ece3 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp @@ -1,5 +1,6 @@ #include "ResourceGatheringOperation.hpp" -#include "ResourceGatheringOperationDeps.hpp" + +#include #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" @@ -10,40 +11,31 @@ #include "openvic-simulation/map/State.hpp" #include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/population/PopType.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/population/PopSum.hpp" +#include "openvic-simulation/population/PopType.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -#include "openvic-simulation/utility/Logger.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Logger.hpp" -#include +#include "ResourceGatheringOperationDeps.hpp" using namespace OpenVic; ResourceGatheringOperation::ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps, - ProductionType const* new_production_type_nullable, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - memory::vector&& new_employees + ResourceGatheringOperationDeps const& rgo_deps, ProductionType const* new_production_type_nullable, + fixed_point_t new_size_multiplier, fixed_point_t new_revenue_yesterday, fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, memory::vector&& new_employees ) : market_instance { rgo_deps.market_instance }, modifier_effect_cache { rgo_deps.modifier_effect_cache }, production_type_nullable { new_production_type_nullable }, revenue_yesterday { new_revenue_yesterday }, output_quantity_yesterday { new_output_quantity_yesterday }, unsold_quantity_yesterday { new_unsold_quantity_yesterday }, - size_multiplier { new_size_multiplier }, employees { std::move(new_employees) }, employee_count_per_type_cache { rgo_deps.pop_type_keys } {} + size_multiplier { new_size_multiplier }, employees { std::move(new_employees) }, + employee_count_per_type_cache { rgo_deps.pop_type_keys } {} -ResourceGatheringOperation::ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps -) : ResourceGatheringOperation { - rgo_deps, - nullptr, 0, - 0, 0, - 0, {} -} {} +ResourceGatheringOperation::ResourceGatheringOperation(ResourceGatheringOperationDeps const& rgo_deps) + : ResourceGatheringOperation { rgo_deps, nullptr, 0, 0, 0, 0, {} } {} pop_size_t ResourceGatheringOperation::get_employee_count_per_type_cache(PopType const& key) const { return employee_count_per_type_cache.at(key); @@ -68,7 +60,7 @@ void ResourceGatheringOperation::initialise_rgo_size_multiplier() { ProductionType const& production_type = *production_type_nullable; std::span jobs = production_type.get_jobs(); - pop_sum_t total_worker_count_in_province = 0; //not counting equivalents + pop_sum_t total_worker_count_in_province = 0; // not counting equivalents for (Job const& job : jobs) { total_worker_count_in_province += location.get_population_by_type(*job.pop_type); } @@ -78,18 +70,15 @@ void ResourceGatheringOperation::initialise_rgo_size_multiplier() { if (size_modifier == 0) { size_multiplier = 0; } else { - size_multiplier = ( - ( - fixed_point_t::from_fraction( - total_worker_count_in_province, - base_workforce_size - ) / size_modifier - ).ceil() - * fixed_point_t::_1_50 - ).floor(); + size_multiplier = + ((fixed_point_t::from_fraction(total_worker_count_in_province, base_workforce_size) / size_modifier) + .ceil() * + fixed_point_t::_1_50) + .floor(); } - max_employee_count_cache = (size_modifier * size_multiplier * base_workforce_size).floor>(); + max_employee_count_cache = + (size_modifier * size_multiplier * base_workforce_size).floor>(); } fixed_point_t ResourceGatheringOperation::calculate_size_modifier() const { @@ -116,9 +105,8 @@ fixed_point_t ResourceGatheringOperation::calculate_size_modifier() const { size_modifier += location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_size_local()); } - size_modifier += location.get_modifier_effect_value( - *modifier_effect_cache.get_good_effects(production_type.output_good).get_rgo_size() - ); + size_modifier += + location.get_modifier_effect_value(*modifier_effect_cache.get_good_effects(production_type.output_good).get_rgo_size()); return size_modifier > 0 ? size_modifier : fixed_point_t::_0; } @@ -133,7 +121,7 @@ void ResourceGatheringOperation::rgo_tick(memory::vector& reusabl ProductionType const& production_type = *production_type_nullable; std::span jobs = production_type.get_jobs(); - total_worker_count_in_province_cache = 0; //not counting equivalents + total_worker_count_in_province_cache = 0; // not counting equivalents for (Job const& job : jobs) { total_worker_count_in_province_cache += location.get_population_by_type(*job.pop_type); } @@ -161,7 +149,7 @@ void ResourceGatheringOperation::rgo_tick(memory::vector& reusabl production_type.output_good, country_to_report_economy_nullable == nullptr ? std::nullopt - : std::optional{country_to_report_economy_nullable->index}, + : std::optional { country_to_report_economy_nullable->index }, output_quantity_yesterday, this, after_sell, @@ -171,7 +159,9 @@ void ResourceGatheringOperation::rgo_tick(memory::vector& reusabl } } -void ResourceGatheringOperation::after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { +void ResourceGatheringOperation::after_sell( + void* actor, SellResult const& sell_result, memory::vector& reusable_vector +) { ResourceGatheringOperation& rgo = *static_cast(actor); rgo.revenue_yesterday = sell_result.money_gained; rgo.pay_employees(reusable_vector); @@ -181,7 +171,7 @@ void ResourceGatheringOperation::hire() { pop_sum_t const& available_worker_count = total_worker_count_in_province_cache; total_employees_count_cache = 0; total_paid_employees_count_cache = 0; - employees.clear(); //TODO implement Victoria 2 hiring logic + employees.clear(); // TODO implement Victoria 2 hiring logic employee_count_per_type_cache.fill(0); if (production_type_nullable == nullptr) { return; @@ -189,25 +179,30 @@ void ResourceGatheringOperation::hire() { ProvinceInstance& location = *location_ptr; ProductionType const& production_type = *production_type_nullable; - if (max_employee_count_cache <= 0) { return; } - if (available_worker_count <= 0) { return; } + if (max_employee_count_cache <= 0) { + return; + } + if (available_worker_count <= 0) { + return; + } fixed_point_t proportion_to_hire; if (max_employee_count_cache >= available_worker_count) { - //hire everyone + // hire everyone proportion_to_hire = 1; } else { - //hire all pops proportionally + // hire all pops proportionally proportion_to_hire = fixed_point_t::from_fraction(max_employee_count_cache, available_worker_count); } std::span jobs = production_type.get_jobs(); - for (Pop& pop : location.get_mutable_pops()){ + for (Pop& pop : location.get_mutable_pops()) { PopType const& pop_type = pop.get_type(); for (Job const& job : jobs) { PopType const* const job_pop_type = job.pop_type; if (job_pop_type && *job_pop_type == pop_type) { - const pop_size_t pop_size_to_hire = (proportion_to_hire * pop.get_size()).floor>(); + const pop_size_t pop_size_to_hire = + (proportion_to_hire * pop.get_size()).floor>(); if (pop_size_to_hire <= 0) { continue; } @@ -227,7 +222,7 @@ void ResourceGatheringOperation::hire() { fixed_point_t ResourceGatheringOperation::produce() { const fixed_point_t size_modifier = calculate_size_modifier(); - if (size_modifier == 0){ + if (size_modifier == 0) { return 0; } @@ -255,33 +250,26 @@ fixed_point_t ResourceGatheringOperation::produce() { if (total_owner_count_in_state_cache > 0) { switch (owner_job.effect_type) { - case Job::effect_t::OUTPUT: - output_multiplier += owner_job.effect_multiplier.mul_div( - total_owner_count_in_state_cache, - state_population - ); - break; - case Job::effect_t::THROUGHPUT: - throughput_multiplier += owner_job.effect_multiplier.mul_div( - total_owner_count_in_state_cache, - state_population - ); - break; - default: - spdlog::error_s("Invalid job effect in RGO {}", production_type); - break; + case Job::effect_t::OUTPUT: + output_multiplier += owner_job.effect_multiplier.mul_div(total_owner_count_in_state_cache, state_population); + break; + case Job::effect_t::THROUGHPUT: + throughput_multiplier += + owner_job.effect_multiplier.mul_div(total_owner_count_in_state_cache, state_population); + break; + default: spdlog::error_s("Invalid job effect in RGO {}", production_type); break; } } } // TODO - work out how best to avoid repeated lookups of the same effects, // e.g. by caching total non-local effect values at the CountryInstance level - throughput_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_tech()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_country()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_throughput()); - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_country()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_output()); + throughput_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_tech()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_country()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_throughput()); + output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_country()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_output()); if (production_type.get_is_farm_for_tech()) { const fixed_point_t farm_rgo_throughput_and_output = @@ -291,8 +279,8 @@ fixed_point_t ResourceGatheringOperation::produce() { } if (production_type.get_is_farm_for_non_tech()) { - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_global()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_local()); + output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_global()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_local()); } if (production_type.get_is_mine_for_tech()) { @@ -303,8 +291,8 @@ fixed_point_t ResourceGatheringOperation::produce() { } if (production_type.get_is_mine_for_non_tech()) { - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_global()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_local()); + output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_global()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_local()); } auto const& good_effects = modifier_effect_cache.get_good_effects(production_type.output_good); @@ -322,31 +310,23 @@ fixed_point_t ResourceGatheringOperation::produce() { const fixed_point_t effect_multiplier = job.effect_multiplier; const fixed_point_t amount = job.amount; - const fixed_point_t effect = effect_multiplier != fixed_point_t::_1 - && fixed_point_t::from_fraction(employees_of_type, max_employee_count_cache) > amount - ? effect_multiplier * amount //special Vic2 logic + const fixed_point_t effect = effect_multiplier != fixed_point_t::_1 && + fixed_point_t::from_fraction(employees_of_type, max_employee_count_cache) > amount + ? effect_multiplier * amount // special Vic2 logic : effect_multiplier.mul_div(employees_of_type, max_employee_count_cache); switch (job.effect_type) { - case Job::effect_t::OUTPUT: - output_from_workers += effect; - break; - case Job::effect_t::THROUGHPUT: - throughput_from_workers += effect; - break; - default: - spdlog::error_s("Invalid job effect in RGO {}", production_type); - break; + case Job::effect_t::OUTPUT: output_from_workers += effect; break; + case Job::effect_t::THROUGHPUT: throughput_from_workers += effect; break; + default: spdlog::error_s("Invalid job effect in RGO {}", production_type); break; } } } - //if province is overseas multiply by (1 + overseas penalty) + // if province is overseas multiply by (1 + overseas penalty) - return production_type.base_output_quantity - * size_modifier * size_multiplier - * throughput_multiplier * throughput_from_workers - * output_multiplier * output_from_workers; + return production_type.base_output_quantity * size_modifier * size_multiplier * throughput_multiplier * + throughput_from_workers * output_multiplier * output_from_workers; } void ResourceGatheringOperation::pay_employees(memory::vector& reusable_vector) { @@ -377,12 +357,8 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re if (revenue <= total_minimum_wage) { for (Employee& employee : employees) { const fixed_point_t income_for_this_pop = std::max( - fixed_point_t::mul_div( - revenue, - employee.get_minimum_wage_cached(), - total_minimum_wage - ), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + fixed_point_t::mul_div(revenue, employee.get_minimum_wage_cached(), total_minimum_wage), + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); Pop& employee_pop = employee.get_pop(); employee_pop.add_rgo_worker_income(income_for_this_pop); @@ -391,10 +367,8 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re } else { fixed_point_t revenue_left = revenue; if (total_owner_count_in_state_cache > 0) { - const fixed_point_t upper_limit = std::min( - fixed_point_t::_0_50, - fixed_point_t::_1 - total_minimum_wage / revenue_left - ); + const fixed_point_t upper_limit = + std::min(fixed_point_t::_0_50, fixed_point_t::_1 - total_minimum_wage / revenue_left); const fixed_point_t owner_share = std::min( fixed_point_t::from_fraction(2 * total_owner_count_in_state_cache, total_worker_count_in_province_cache), upper_limit @@ -403,7 +377,7 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re for (Pop& owner_pop : *owner_pops_cache_nullable) { const fixed_point_t income_for_this_pop = std::max( revenue_left * owner_share.mul_div(owner_pop.get_size(), total_owner_count_in_state_cache), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); owner_pop.add_rgo_owner_income(income_for_this_pop); total_owner_income_cache += income_for_this_pop; @@ -412,8 +386,8 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re } if (total_paid_employees_count_cache == 0) { - //scenario slaves only - //Money is removed from system in Victoria 2. + // scenario slaves only + // Money is removed from system in Victoria 2. } else { memory::vector& incomes = reusable_vector; incomes.resize(employees.size()); @@ -427,7 +401,7 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re if (employee_pop_type.is_slave) { continue; } - + const fixed_point_t minimum_wage = employee.get_minimum_wage_cached(); if (minimum_wage > 0 && incomes[i] == minimum_wage) { continue; @@ -436,14 +410,14 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re const pop_size_t employee_size = employee.get_size(); const fixed_point_t income_for_this_pop = std::max( revenue_left.mul_div(employee_size, count_workers_to_be_paid), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); if (income_for_this_pop < minimum_wage) { incomes[i] = minimum_wage; revenue_left -= minimum_wage; count_workers_to_be_paid -= employee_size; - i = -1; //Restart loop and skip minimum incomes. This is required to spread the remaining revenue again. + i = -1; // Restart loop and skip minimum incomes. This is required to spread the remaining revenue again. } else { incomes[i] = income_for_this_pop; } @@ -462,4 +436,4 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re reusable_vector.clear(); } } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp b/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp index 29adf0b94..5e68767e8 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp @@ -3,12 +3,12 @@ #include #include "openvic-simulation/economy/production/Employee.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/population/PopSum.hpp" -#include "openvic-simulation/utility/Getters.hpp" +#include "openvic-simulation/types/IndexedFlatMap.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { struct MarketInstance; @@ -50,13 +50,9 @@ namespace OpenVic { public: ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps, - ProductionType const* new_production_type_nullable, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - memory::vector&& new_employees + ResourceGatheringOperationDeps const& rgo_deps, ProductionType const* new_production_type_nullable, + fixed_point_t new_size_multiplier, fixed_point_t new_revenue_yesterday, fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, memory::vector&& new_employees ); ResourceGatheringOperation(ResourceGatheringOperationDeps const& rgo_deps); @@ -69,4 +65,4 @@ namespace OpenVic { static constexpr size_t VECTORS_FOR_RGO_TICK = 1; void rgo_tick(memory::vector& reusable_vector); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp b/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp index eb03bb457..979585c62 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp @@ -12,4 +12,4 @@ namespace OpenVic { ModifierEffectCache const& modifier_effect_cache; forwardable_span pop_type_keys; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/BuyResult.hpp b/src/openvic-simulation/economy/trading/BuyResult.hpp index a3bcf4c24..f31be506f 100644 --- a/src/openvic-simulation/economy/trading/BuyResult.hpp +++ b/src/openvic-simulation/economy/trading/BuyResult.hpp @@ -13,17 +13,14 @@ namespace OpenVic { const fixed_point_t money_spent_on_imports; constexpr BuyResult( - GoodDefinition const& new_good_definition, - const fixed_point_t new_quantity_bought, - const fixed_point_t new_money_spent_total, - const fixed_point_t new_money_spent_on_imports - ) : good_definition { new_good_definition }, - quantity_bought { new_quantity_bought }, - money_spent_total { new_money_spent_total }, - money_spent_on_imports { new_money_spent_on_imports } {} + GoodDefinition const& new_good_definition, const fixed_point_t new_quantity_bought, + const fixed_point_t new_money_spent_total, const fixed_point_t new_money_spent_on_imports + ) + : good_definition { new_good_definition }, quantity_bought { new_quantity_bought }, + money_spent_total { new_money_spent_total }, money_spent_on_imports { new_money_spent_on_imports } {} static constexpr BuyResult no_purchase_result(GoodDefinition const& good_definition) { return { good_definition, 0, 0, 0 }; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp b/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp index 79afa18fb..56da37b00 100644 --- a/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp +++ b/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp @@ -8,7 +8,7 @@ namespace OpenVic { struct GoodBuyUpToOrder { using actor_t = void*; - using callback_t = void(*)(const actor_t, BuyResult const&); + using callback_t = void (*)(const actor_t, BuyResult const&); private: const actor_t actor; @@ -20,23 +20,17 @@ namespace OpenVic { const fixed_point_t money_to_spend; constexpr GoodBuyUpToOrder( - const std::optional new_country_index_optional, - const fixed_point_t new_max_quantity, - const fixed_point_t new_money_to_spend, - const actor_t new_actor, - const callback_t new_after_trade - ) : country_index_optional { new_country_index_optional }, - max_quantity { new_max_quantity }, - money_to_spend { new_money_to_spend }, - actor { new_actor }, - after_trade { new_after_trade } - {} + const std::optional new_country_index_optional, const fixed_point_t new_max_quantity, + const fixed_point_t new_money_to_spend, const actor_t new_actor, const callback_t new_after_trade + ) + : country_index_optional { new_country_index_optional }, max_quantity { new_max_quantity }, + money_to_spend { new_money_to_spend }, actor { new_actor }, after_trade { new_after_trade } {} constexpr void call_after_trade(BuyResult const& buy_result) const { after_trade(actor, buy_result); } - //highest price per unit at which the buyer can afford max_quantity + // highest price per unit at which the buyer can afford max_quantity constexpr fixed_point_t get_affordable_price() const { return money_to_spend / max_quantity; } @@ -47,24 +41,15 @@ namespace OpenVic { GoodDefinition const& good; constexpr BuyUpToOrder( - GoodDefinition const& new_good, - const std::optional new_country_index_optional, - const fixed_point_t new_max_quantity, - const fixed_point_t new_money_to_spend, - const actor_t new_actor, + GoodDefinition const& new_good, const std::optional new_country_index_optional, + const fixed_point_t new_max_quantity, const fixed_point_t new_money_to_spend, const actor_t new_actor, const callback_t new_after_trade - ) : GoodBuyUpToOrder { - new_country_index_optional, - new_max_quantity, - new_money_to_spend, - new_actor, - new_after_trade - }, - good { new_good } - {} + ) + : GoodBuyUpToOrder { new_country_index_optional, new_max_quantity, new_money_to_spend, new_actor, new_after_trade }, + good { new_good } {} - constexpr void call_after_trade(BuyResult const& buy_result) const { - GoodBuyUpToOrder::call_after_trade(buy_result); - } + constexpr void call_after_trade(BuyResult const& buy_result) const { + GoodBuyUpToOrder::call_after_trade(buy_result); + } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/GoodMarket.cpp b/src/openvic-simulation/economy/trading/GoodMarket.cpp index e140d8475..a08ae935d 100644 --- a/src/openvic-simulation/economy/trading/GoodMarket.cpp +++ b/src/openvic-simulation/economy/trading/GoodMarket.cpp @@ -1,4 +1,5 @@ #include "GoodMarket.hpp" + #include #include "openvic-simulation/economy/GoodDefinition.hpp" @@ -12,45 +13,29 @@ using namespace OpenVic; static constexpr size_t MONTHS_OF_PRICE_HISTORY = 36; GoodMarket::GoodMarket(GameRulesManager const& new_game_rules_manager, GoodDefinition const& new_good_definition) - : game_rules_manager { new_game_rules_manager }, - good_definition { new_good_definition }, - price { new_good_definition.base_price }, - is_available { new_good_definition.is_available_from_start }, - price_history { MONTHS_OF_PRICE_HISTORY, new_good_definition.base_price } - { - on_use_exponential_price_changes_changed(); - update_next_price_limits(); - } + : game_rules_manager { new_game_rules_manager }, good_definition { new_good_definition }, + price { new_good_definition.base_price }, is_available { new_good_definition.is_available_from_start }, + price_history { MONTHS_OF_PRICE_HISTORY, new_good_definition.base_price } { + on_use_exponential_price_changes_changed(); + update_next_price_limits(); +} void GoodMarket::on_use_exponential_price_changes_changed() { if (game_rules_manager.get_use_exponential_price_changes()) { absolute_maximum_price = fixed_point_t::usable_max; absolute_minimum_price = fixed_point_t::epsilon << exponential_price_change_shift; } else { - absolute_maximum_price = std::min( - good_definition.base_price * 5, - fixed_point_t::usable_max - ); - absolute_minimum_price = std::max( - good_definition.base_price * 22 / 100, - fixed_point_t::epsilon - ); + absolute_maximum_price = std::min(good_definition.base_price * 5, fixed_point_t::usable_max); + absolute_minimum_price = std::max(good_definition.base_price * 22 / 100, fixed_point_t::epsilon); } } void GoodMarket::update_next_price_limits() { - const fixed_point_t max_price_change = game_rules_manager.get_use_exponential_price_changes() - ? price >> exponential_price_change_shift - : fixed_point_t::_0_01; - - max_next_price = std::min( - absolute_maximum_price, - price + max_price_change - ); - min_next_price = std::max( - absolute_minimum_price, - price - max_price_change - ); + const fixed_point_t max_price_change = + game_rules_manager.get_use_exponential_price_changes() ? price >> exponential_price_change_shift : fixed_point_t::_0_01; + + max_next_price = std::min(absolute_maximum_price, price + max_price_change); + min_next_price = std::max(absolute_minimum_price, price - max_price_change); price_inverse = fixed_point_t::_1 / price; } @@ -68,18 +53,11 @@ void GoodMarket::add_market_sell_order(GoodMarketSellOrder&& market_sell_order) void GoodMarket::execute_orders( TypedSpan reusable_country_map_0, TypedSpan reusable_country_map_1, - std::span< - memory::vector, - VECTORS_FOR_EXECUTE_ORDERS - > reusable_vectors + std::span, VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors ) { if (!is_available) { - //price remains the same - price_change_yesterday - = quantity_traded_yesterday - = total_demand_yesterday - = total_supply_yesterday - = 0; + // price remains the same + price_change_yesterday = quantity_traded_yesterday = total_demand_yesterday = total_supply_yesterday = 0; for (GoodBuyUpToOrder const& buy_up_to_order : buy_up_to_orders) { buy_up_to_order.call_after_trade(BuyResult::no_purchase_result(good_definition)); @@ -92,10 +70,9 @@ void GoodMarket::execute_orders( } fixed_point_t new_price; - //MarketInstance ensured only orders with quantity > 0 are added. - //So running total > 0 unless orders are empty. - fixed_point_t demand_sum = 0, - supply_sum = 0; + // MarketInstance ensured only orders with quantity > 0 are added. + // So running total > 0 unless orders are empty. + fixed_point_t demand_sum = 0, supply_sum = 0; if (market_sell_orders.empty()) { quantity_traded_yesterday = 0; fixed_point_t max_affordable_price = price; @@ -112,7 +89,7 @@ void GoodMarket::execute_orders( if (game_rules_manager.get_use_optimal_pricing()) { new_price = std::min(max_next_price, max_affordable_price); } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 if (demand_sum > 0) { new_price = max_next_price; } else { @@ -134,7 +111,7 @@ void GoodMarket::execute_orders( quantity_bought_per_order.resize(buy_up_to_orders.size()); purchasing_power_per_order.resize(buy_up_to_orders.size()); - fixed_point_t money_left_to_spend_sum = 0; //sum of money_to_spend for all buyers that can't afford their max_quantity + fixed_point_t money_left_to_spend_sum = 0; // sum of money_to_spend for all buyers that can't afford their max_quantity fixed_point_t max_quantity_to_buy_sum = 0; fixed_point_t purchasing_power_sum = 0; for (size_t i = 0; i < buy_up_to_orders.size(); i++) { @@ -145,7 +122,7 @@ void GoodMarket::execute_orders( if (game_rules_manager.get_use_optimal_pricing()) { const fixed_point_t affordable_price = buy_up_to_order.get_affordable_price(); if (affordable_price > min_next_price) { - //no point selling lower as it would not attract more buyers + // no point selling lower as it would not attract more buyers min_next_price = affordable_price; } } @@ -172,11 +149,11 @@ void GoodMarket::execute_orders( fixed_point_t remaining_supply = supply_sum; const bool is_selling_for_max_price = max_quantity_to_buy_sum >= supply_sum; if (is_selling_for_max_price) { - //sell for max_next_price + // sell for max_next_price if (game_rules_manager.get_use_optimal_pricing()) { new_price = max_next_price; } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 new_price = max_next_price; } @@ -193,15 +170,12 @@ void GoodMarket::execute_orders( const std::optional country_index_optional = buy_up_to_order.country_index_optional; if (country_index_optional.has_value()) { - //subtract as it might be updated below + // subtract as it might be updated below actual_bought_per_country[country_index_optional.value()] -= distributed_supply; } - distributed_supply = fixed_point_t::mul_div( - remaining_supply, - purchasing_power_per_order[i], - purchasing_power_sum - ); + distributed_supply = + fixed_point_t::mul_div(remaining_supply, purchasing_power_per_order[i], purchasing_power_sum); if (distributed_supply >= max_quantity) { someone_bought_max_quantity = true; @@ -220,23 +194,18 @@ void GoodMarket::execute_orders( } } while (someone_bought_max_quantity); - execute_buy_orders( - new_price, - actual_bought_per_country, - supply_per_country, - quantity_bought_per_order - ); + execute_buy_orders(new_price, actual_bought_per_country, supply_per_country, quantity_bought_per_order); } else { - //sell below max_next_price + // sell below max_next_price if (game_rules_manager.get_use_optimal_pricing()) { new_price = price; - //drop price while remaining_supply > 0 && new_price > min_next_price + // drop price while remaining_supply > 0 && new_price > min_next_price while (remaining_supply > 0) { const fixed_point_t possible_price = money_left_to_spend_sum / remaining_supply; if (possible_price >= new_price) { - //use previous new_price + // use previous new_price break; } @@ -261,7 +230,7 @@ void GoodMarket::execute_orders( } } } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 if (supply_sum > demand_sum) { new_price = min_next_price; } else { @@ -269,16 +238,12 @@ void GoodMarket::execute_orders( } } - //figure out how much every buyer bought + // figure out how much every buyer bought for (size_t i = 0; i < buy_up_to_orders.size(); i++) { GoodBuyUpToOrder const& buy_up_to_order = buy_up_to_orders[i]; - const fixed_point_t quantity_bought - = quantity_bought_per_order[i] - = std::min( - buy_up_to_order.max_quantity, - buy_up_to_order.money_to_spend / new_price - ); + const fixed_point_t quantity_bought = quantity_bought_per_order[i] = + std::min(buy_up_to_order.max_quantity, buy_up_to_order.money_to_spend / new_price); const std::optional country_index_optional = buy_up_to_order.country_index_optional; if (country_index_optional.has_value()) { @@ -286,21 +251,16 @@ void GoodMarket::execute_orders( } } - execute_buy_orders( - new_price, - actual_bought_per_country, - supply_per_country, - quantity_bought_per_order - ); + execute_buy_orders(new_price, actual_bought_per_country, supply_per_country, quantity_bought_per_order); } for (auto& reusable_vector : reusable_vectors) { reusable_vector.clear(); } - //figure out how much of each order was sold + // figure out how much of each order was sold if (quantity_traded_yesterday == supply_sum) { - //everything was sold + // everything was sold for (GoodMarketSellOrder const& market_sell_order : market_sell_orders) { const fixed_point_t quantity_sold = market_sell_order.quantity; fixed_point_t money_gained; @@ -309,20 +269,13 @@ void GoodMarket::execute_orders( } else { money_gained = std::max( quantity_sold * new_price, - fixed_point_t::epsilon //round up + fixed_point_t::epsilon // round up ); } - market_sell_order.call_after_trade( - { - good_definition, - quantity_sold, - money_gained - }, - reusable_vectors[0] - ); + market_sell_order.call_after_trade({ good_definition, quantity_sold, money_gained }, reusable_vectors[0]); } } else { - //quantity is evenly divided after taking domestic buyers into account + // quantity is evenly divided after taking domestic buyers into account fixed_point_t total_quantity_traded_domestically = 0; for (country_index_t country_index(0); country_index < actual_bought_per_country.size(); ++country_index) { const fixed_point_t actual_bought = actual_bought_per_country[country_index]; @@ -331,7 +284,8 @@ void GoodMarket::execute_orders( total_quantity_traded_domestically += traded_domestically; } - const fixed_point_t total_quantity_traded_as_export = quantity_traded_yesterday - total_quantity_traded_domestically; + const fixed_point_t total_quantity_traded_as_export = + quantity_traded_yesterday - total_quantity_traded_domestically; const fixed_point_t total_quantity_offered_as_export = supply_sum - total_quantity_traded_domestically; for (GoodMarketSellOrder const& market_sell_order : market_sell_orders) { const fixed_point_t quantity_offered = market_sell_order.quantity; @@ -349,17 +303,14 @@ void GoodMarket::execute_orders( quantity_sold_domestically = total_bought_domestically >= total_domestic_supply ? quantity_offered : fixed_point_t::mul_div( - quantity_offered, - total_bought_domestically, - total_domestic_supply //> 0 as we're selling - ); + quantity_offered, total_bought_domestically, + total_domestic_supply //> 0 as we're selling + ); quantity_offered_as_export = quantity_offered - quantity_sold_domestically; } const fixed_point_t fair_share_of_exports = fixed_point_t::mul_div( - quantity_offered_as_export, - total_quantity_traded_as_export, - total_quantity_offered_as_export + quantity_offered_as_export, total_quantity_traded_as_export, total_quantity_offered_as_export ); const fixed_point_t quantity_sold = quantity_sold_domestically + fair_share_of_exports; @@ -369,17 +320,10 @@ void GoodMarket::execute_orders( } else { money_gained = std::max( quantity_sold * new_price, - fixed_point_t::epsilon //round up + fixed_point_t::epsilon // round up ); } - market_sell_order.call_after_trade( - { - good_definition, - quantity_sold, - money_gained - }, - reusable_vectors[0] - ); + market_sell_order.call_after_trade({ good_definition, quantity_sold, money_gained }, reusable_vectors[0]); } } @@ -401,10 +345,8 @@ void GoodMarket::execute_orders( } void GoodMarket::execute_buy_orders( - const fixed_point_t new_price, - TypedSpan actual_bought_per_country, - TypedSpan supply_per_country, - std::span quantity_bought_per_order + const fixed_point_t new_price, TypedSpan actual_bought_per_country, + TypedSpan supply_per_country, std::span quantity_bought_per_order ) { quantity_traded_yesterday = 0; for (size_t i = 0; i < buy_up_to_orders.size(); i++) { @@ -417,43 +359,35 @@ void GoodMarket::execute_buy_orders( quantity_traded_yesterday += quantity_bought; const fixed_point_t money_spent_total = std::max( quantity_bought * new_price, - fixed_point_t::epsilon //we know from purchasing power that you can afford it. + fixed_point_t::epsilon // we know from purchasing power that you can afford it. ); fixed_point_t money_spent_on_imports; const std::optional country_index_optional = buy_up_to_order.country_index_optional; if (!country_index_optional.has_value()) { - //could be trade between native Americans and tribal Africa, so it's all imported + // could be trade between native Americans and tribal Africa, so it's all imported money_spent_on_imports = money_spent_total; } else { const country_index_t country_index = country_index_optional.value(); - //must be > 0, since quantity_bought > 0 + // must be > 0, since quantity_bought > 0 const fixed_point_t actual_bought_in_my_country = actual_bought_per_country[country_index]; const fixed_point_t supply_in_my_country = supply_per_country[country_index]; if (supply_in_my_country >= actual_bought_in_my_country) { - //no imports + // no imports money_spent_on_imports = 0; } else { - const fixed_point_t money_spent_domestically = fixed_point_t::mul_div( - money_spent_total, - supply_in_my_country, - actual_bought_in_my_country - ); + const fixed_point_t money_spent_domestically = + fixed_point_t::mul_div(money_spent_total, supply_in_my_country, actual_bought_in_my_country); money_spent_on_imports = money_spent_total - money_spent_domestically; } } - buy_up_to_order.call_after_trade({ - good_definition, - quantity_bought, - money_spent_total, - money_spent_on_imports - }); + buy_up_to_order.call_after_trade({ good_definition, quantity_bought, money_spent_total, money_spent_on_imports }); } } } void GoodMarket::record_price_history() { price_history.push_back(price); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/GoodMarket.hpp b/src/openvic-simulation/economy/trading/GoodMarket.hpp index 37d420b9f..b6ec1ae93 100644 --- a/src/openvic-simulation/economy/trading/GoodMarket.hpp +++ b/src/openvic-simulation/economy/trading/GoodMarket.hpp @@ -5,10 +5,10 @@ #include "openvic-simulation/economy/trading/BuyUpToOrder.hpp" #include "openvic-simulation/economy/trading/MarketSellOrder.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/TypedSpan.hpp" #include "openvic-simulation/types/ValueHistory.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -24,13 +24,12 @@ namespace OpenVic { fixed_point_t absolute_maximum_price; fixed_point_t absolute_minimum_price; - //only used during day tick (from actors placing order until execute_orders()) + // only used during day tick (from actors placing order until execute_orders()) memory::vector buy_up_to_orders; memory::vector market_sell_orders; void execute_buy_orders( - const fixed_point_t new_price, - TypedSpan actual_bought_per_country, + const fixed_point_t new_price, TypedSpan actual_bought_per_country, TypedSpan supply_per_country, std::span quantity_bought_per_order ); @@ -50,6 +49,7 @@ namespace OpenVic { ValueHistory PROPERTY(price_history); void update_next_price_limits(); + public: GoodDefinition const& good_definition; @@ -59,21 +59,18 @@ namespace OpenVic { GoodMarket(GoodMarket&&) = delete; GoodMarket& operator=(GoodMarket&&) = delete; - //thread safe + // thread safe void add_buy_up_to_order(GoodBuyUpToOrder&& buy_up_to_order); void add_market_sell_order(GoodMarketSellOrder&& market_sell_order); - //not thread safe + // not thread safe static constexpr size_t VECTORS_FOR_EXECUTE_ORDERS = 2; void execute_orders( TypedSpan reusable_country_map_0, TypedSpan reusable_country_map_1, - std::span< - memory::vector, - VECTORS_FOR_EXECUTE_ORDERS - > reusable_vectors + std::span, VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors ); void on_use_exponential_price_changes_changed(); void record_price_history(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/MarketInstance.cpp b/src/openvic-simulation/economy/trading/MarketInstance.cpp index 3dde889c2..288de3d22 100644 --- a/src/openvic-simulation/economy/trading/MarketInstance.cpp +++ b/src/openvic-simulation/economy/trading/MarketInstance.cpp @@ -1,5 +1,6 @@ #include "MarketInstance.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/defines/CountryDefines.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/economy/GoodInstance.hpp" @@ -8,7 +9,6 @@ #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/ThreadPool.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; @@ -24,9 +24,11 @@ fixed_point_t MarketInstance::get_min_next_price(GoodDefinition const& good_defi return good_instance_manager.get_good_instance_by_definition(good_definition).get_min_next_price(); } -fixed_point_t MarketInstance::get_max_money_to_allocate_to_buy_quantity(GoodDefinition const& good_definition, const fixed_point_t quantity) const { - //round up so money_to_spend >= max_next_price * max_quantity_to_buy; - //always add epsilon as money_to_spend == max_next_price * max_quantity_to_buy is rare and this is cheaper for performance. +fixed_point_t MarketInstance::get_max_money_to_allocate_to_buy_quantity( + GoodDefinition const& good_definition, const fixed_point_t quantity +) const { + // round up so money_to_spend >= max_next_price * max_quantity_to_buy; + // always add epsilon as money_to_spend == max_next_price * max_quantity_to_buy is rare and this is cheaper for performance. return quantity * get_max_next_price(good_definition) + fixed_point_t::epsilon; } @@ -37,10 +39,7 @@ GoodInstance const& MarketInstance::get_good_instance(GoodDefinition const& good void MarketInstance::place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order) { GoodDefinition const& good = buy_up_to_order.good; if (OV_unlikely(buy_up_to_order.max_quantity <= 0)) { - spdlog::error_s( - "Received BuyUpToOrder for {} with max quantity {}", - good, buy_up_to_order.max_quantity - ); + spdlog::error_s("Received BuyUpToOrder for {} with max quantity {}", good, buy_up_to_order.max_quantity); buy_up_to_order.call_after_trade(BuyResult::no_purchase_result(good)); return; } @@ -49,26 +48,21 @@ void MarketInstance::place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order) { good_instance.add_buy_up_to_order(std::move(buy_up_to_order)); } -void MarketInstance::place_market_sell_order(MarketSellOrder&& market_sell_order, memory::vector& reusable_vector) { +void MarketInstance::place_market_sell_order( + MarketSellOrder&& market_sell_order, memory::vector& reusable_vector +) { GoodDefinition const& good = market_sell_order.good; const fixed_point_t quantity = market_sell_order.quantity; if (OV_unlikely(quantity <= 0)) { - spdlog::error_s( - "Received MarketSellOrder for {} with quantity {}", - good, quantity - ); + spdlog::error_s("Received MarketSellOrder for {} with quantity {}", good, quantity); market_sell_order.call_after_trade(SellResult::no_sales_result(good), reusable_vector); return; } if (good.is_money) { market_sell_order.call_after_trade( - { - market_sell_order.good, - quantity, - quantity * country_defines.get_gold_to_worker_pay_rate() * good.base_price - }, + { market_sell_order.good, quantity, quantity * country_defines.get_gold_to_worker_pay_rate() * good.base_price }, reusable_vector ); return; diff --git a/src/openvic-simulation/economy/trading/MarketInstance.hpp b/src/openvic-simulation/economy/trading/MarketInstance.hpp index 57d4c527a..a36dd920d 100644 --- a/src/openvic-simulation/economy/trading/MarketInstance.hpp +++ b/src/openvic-simulation/economy/trading/MarketInstance.hpp @@ -17,19 +17,20 @@ namespace OpenVic { ThreadPool& thread_pool; CountryDefines const& country_defines; GoodInstanceManager& good_instance_manager; + public: constexpr MarketInstance( - ThreadPool& new_thread_pool, - CountryDefines const& new_country_defines, + ThreadPool& new_thread_pool, CountryDefines const& new_country_defines, GoodInstanceManager& new_good_instance_manager - ) : thread_pool { new_thread_pool }, - country_defines { new_country_defines }, - good_instance_manager { new_good_instance_manager } {} + ) + : thread_pool { new_thread_pool }, country_defines { new_country_defines }, + good_instance_manager { new_good_instance_manager } {} bool get_is_available(GoodDefinition const& good_definition) const; fixed_point_t get_max_next_price(GoodDefinition const& good_definition) const; fixed_point_t get_min_next_price(GoodDefinition const& good_definition) const; - fixed_point_t get_max_money_to_allocate_to_buy_quantity(GoodDefinition const& good_definition, const fixed_point_t quantity) const; + fixed_point_t + get_max_money_to_allocate_to_buy_quantity(GoodDefinition const& good_definition, const fixed_point_t quantity) const; GoodInstance const& get_good_instance(GoodDefinition const& good_definition) const; void place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order); void place_market_sell_order(MarketSellOrder&& market_sell_order, memory::vector& reusable_vector); diff --git a/src/openvic-simulation/economy/trading/MarketSellOrder.hpp b/src/openvic-simulation/economy/trading/MarketSellOrder.hpp index 975c18aa7..228ae9a68 100644 --- a/src/openvic-simulation/economy/trading/MarketSellOrder.hpp +++ b/src/openvic-simulation/economy/trading/MarketSellOrder.hpp @@ -22,15 +22,11 @@ namespace OpenVic { const fixed_point_t quantity; constexpr GoodMarketSellOrder( - const std::optional new_country_index_optional, - const fixed_point_t new_quantity, - const actor_t new_actor, - const callback_t new_after_trade - ) : country_index_optional { new_country_index_optional }, - quantity { new_quantity }, - actor { new_actor }, - after_trade { new_after_trade } - {} + const std::optional new_country_index_optional, const fixed_point_t new_quantity, + const actor_t new_actor, const callback_t new_after_trade + ) + : country_index_optional { new_country_index_optional }, quantity { new_quantity }, actor { new_actor }, + after_trade { new_after_trade } {} constexpr void call_after_trade(SellResult const& sell_result, memory::vector& reusable_vector) const { after_trade(actor, sell_result, reusable_vector); @@ -42,18 +38,9 @@ namespace OpenVic { GoodDefinition const& good; constexpr MarketSellOrder( - GoodDefinition const& new_good, - const std::optional new_country_index_optional, - const fixed_point_t new_quantity, - const actor_t new_actor, - const callback_t new_after_trade - ) : GoodMarketSellOrder { - new_country_index_optional, - new_quantity, - new_actor, - new_after_trade - }, - good { new_good } - {} + GoodDefinition const& new_good, const std::optional new_country_index_optional, + const fixed_point_t new_quantity, const actor_t new_actor, const callback_t new_after_trade + ) + : GoodMarketSellOrder { new_country_index_optional, new_quantity, new_actor, new_after_trade }, good { new_good } {} }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/SellResult.hpp b/src/openvic-simulation/economy/trading/SellResult.hpp index 26000015d..13ce479fd 100644 --- a/src/openvic-simulation/economy/trading/SellResult.hpp +++ b/src/openvic-simulation/economy/trading/SellResult.hpp @@ -12,15 +12,13 @@ namespace OpenVic { const fixed_point_t money_gained; constexpr SellResult( - GoodDefinition const& new_good_definition, - const fixed_point_t new_quantity_sold, + GoodDefinition const& new_good_definition, const fixed_point_t new_quantity_sold, const fixed_point_t new_money_gained - ) : good_definition { new_good_definition }, - quantity_sold { new_quantity_sold }, - money_gained { new_money_gained } {} + ) + : good_definition { new_good_definition }, quantity_sold { new_quantity_sold }, money_gained { new_money_gained } {} static constexpr SellResult no_sales_result(GoodDefinition const& good_definition) { return { good_definition, 0, 0 }; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/Bookmark.cpp b/src/openvic-simulation/history/Bookmark.cpp index d2fb7c6bc..853b668a5 100644 --- a/src/openvic-simulation/history/Bookmark.cpp +++ b/src/openvic-simulation/history/Bookmark.cpp @@ -13,31 +13,23 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Bookmark::Bookmark( - index_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, + index_t new_index, std::string_view new_name, std::string_view new_description, Date new_date, fvec2_t new_initial_camera_position -) : HasIdentifier { std::to_string(type_safe::get(new_index)) }, - HasIndex { new_index }, - name { new_name }, - description { new_description }, - date { new_date }, - initial_camera_position { new_initial_camera_position } {} +) + : HasIdentifier { std::to_string(type_safe::get(new_index)) }, HasIndex { new_index }, name { new_name }, + description { new_description }, date { new_date }, initial_camera_position { new_initial_camera_position } {} bool BookmarkManager::add_bookmark( std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position ) { return bookmarks.emplace_item( - name, - Bookmark::index_t { bookmarks.size() }, name, description, date, initial_camera_position + name, Bookmark::index_t { bookmarks.size() }, name, description, date, initial_camera_position ); } bool BookmarkManager::load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - bookmarks, - [this, map_height](std::string_view key, ast::NodeCPtr value) -> bool { + const bool ret = + expect_dictionary_reserve_length(bookmarks, [this, map_height](std::string_view key, ast::NodeCPtr value) -> bool { if (key != "bookmark") { spdlog::error_s("Invalid bookmark declaration {}", key); return false; @@ -58,8 +50,7 @@ bool BookmarkManager::load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr ret &= add_bookmark(name, description, date, initial_camera_position); return ret; - } - )(root); + })(root); lock_bookmarks(); return ret; diff --git a/src/openvic-simulation/history/Bookmark.hpp b/src/openvic-simulation/history/Bookmark.hpp index 4584d628e..3e9a94b5c 100644 --- a/src/openvic-simulation/history/Bookmark.hpp +++ b/src/openvic-simulation/history/Bookmark.hpp @@ -21,10 +21,7 @@ namespace OpenVic { const fvec2_t initial_camera_position; Bookmark( - index_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, + index_t new_index, std::string_view new_name, std::string_view new_description, Date new_date, fvec2_t new_initial_camera_position ); Bookmark(Bookmark&&) = default; @@ -35,9 +32,7 @@ namespace OpenVic { IdentifierRegistry IDENTIFIER_REGISTRY(bookmark); public: - bool add_bookmark( - std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position - ); + bool add_bookmark(std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position); bool load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr root); Date get_last_bookmark_date() const; @@ -51,4 +46,4 @@ struct fmt::formatter : formatter { format_context::iterator format(Bookmark const&, format_context& ctx) const { return ctx.out(); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/history/CountryHistory.cpp b/src/openvic-simulation/history/CountryHistory.cpp index 8a523256e..017b8699a 100644 --- a/src/openvic-simulation/history/CountryHistory.cpp +++ b/src/openvic-simulation/history/CountryHistory.cpp @@ -1,20 +1,22 @@ #include "CountryHistory.hpp" -#include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/core/FormatValidate.hpp" +#include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/politics/Government.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; CountryHistoryEntry::CountryHistoryEntry( - CountryDefinition const& new_country, Date new_date, decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, + CountryDefinition const& new_country, Date new_date, + decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys -) : HistoryEntry { new_date }, country { new_country }, upper_house_proportion_by_ideology { ideology_keys }, - flag_overrides_by_government_type { government_type_keys } {} +) + : HistoryEntry { new_date }, country { new_country }, upper_house_proportion_by_ideology { ideology_keys }, + flag_overrides_by_government_type { government_type_keys } {} fixed_point_t CountryHistoryEntry::get_upper_house_proportion_by_ideology(Ideology const& key) const { return upper_house_proportion_by_ideology.at(key); @@ -27,7 +29,8 @@ GovernmentType const* CountryHistoryEntry::get_flag_overrides_by_government_type CountryHistoryMap::CountryHistoryMap( CountryDefinition const& new_country, decltype(ideology_keys) new_ideology_keys, decltype(government_type_keys) new_government_type_keys -) : country { new_country }, ideology_keys { new_ideology_keys }, government_type_keys { new_government_type_keys } {} +) + : country { new_country }, ideology_keys { new_ideology_keys }, government_type_keys { new_government_type_keys } {} memory::unique_ptr CountryHistoryMap::_make_entry(Date date) const { return memory::make_unique(country, date, ideology_keys, government_type_keys); @@ -65,8 +68,8 @@ bool CountryHistoryMap::_load_history_entry( } else if (it->second == add) { // Desired culture instruction already exists spdlog::warn_s( - "Duplicate attempt to {} accepted culture {} {} country history of {}", - add ? "add" : "remove", add ? "to" : "from", culture, entry.country + "Duplicate attempt to {} accepted culture {} {} country history of {}", add ? "add" : "remove", + add ? "to" : "from", culture, entry.country ); return true; } else { @@ -74,11 +77,7 @@ bool CountryHistoryMap::_load_history_entry( entry.accepted_cultures.erase(it); spdlog::warn_s( "Attempted to {} accepted culture {} {} country history of {} after previously {} it", - add ? "add" : "remove", - culture, - add ? "to" : "from", - entry.country, - add ? "removing" : "adding" + add ? "add" : "remove", culture, add ? "to" : "from", entry.country, add ? "removing" : "adding" ); return true; } diff --git a/src/openvic-simulation/history/CountryHistory.hpp b/src/openvic-simulation/history/CountryHistory.hpp index 72ac07278..e6d3bf020 100644 --- a/src/openvic-simulation/history/CountryHistory.hpp +++ b/src/openvic-simulation/history/CountryHistory.hpp @@ -3,11 +3,11 @@ #include #include "openvic-simulation/history/HistoryMap.hpp" +#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -29,6 +29,7 @@ namespace OpenVic { struct CountryHistoryEntry : HistoryEntry { friend struct CountryHistoryMap; + private: std::optional PROPERTY(primary_culture); ordered_map PROPERTY(accepted_cultures); @@ -64,7 +65,8 @@ namespace OpenVic { CountryDefinition const& country; CountryHistoryEntry( - CountryDefinition const& new_country, const Date new_date, decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, + CountryDefinition const& new_country, const Date new_date, + decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys ); }; @@ -114,4 +116,4 @@ namespace OpenVic { decltype(CountryHistoryMap::government_type_keys) government_type_keys, ast::NodeCPtr root ); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/DiplomaticHistory.cpp b/src/openvic-simulation/history/DiplomaticHistory.cpp index 916bf2e9f..3e3253dfe 100644 --- a/src/openvic-simulation/history/DiplomaticHistory.cpp +++ b/src/openvic-simulation/history/DiplomaticHistory.cpp @@ -1,8 +1,8 @@ #include "DiplomaticHistory.hpp" #include "openvic-simulation/DefinitionManager.hpp" -#include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/history/DiplomaticHistory.hpp" +#include "openvic-simulation/utility/Containers.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; diff --git a/src/openvic-simulation/history/DiplomaticHistory.hpp b/src/openvic-simulation/history/DiplomaticHistory.hpp index 6acd8a14e..5cf3d0ef7 100644 --- a/src/openvic-simulation/history/DiplomaticHistory.hpp +++ b/src/openvic-simulation/history/DiplomaticHistory.hpp @@ -23,10 +23,8 @@ namespace OpenVic { bool locked = false; template - static memory::vector> filter_by_date( - std::span items, - const Date date - ) { + static memory::vector> + filter_by_date(std::span items, const Date date) { memory::vector> ret; for (HistoryType const& item : items) { if (item.period.is_date_in_period(date)) { @@ -51,7 +49,7 @@ namespace OpenVic { [[nodiscard]] memory::vector> get_reparations(Date date) const { return filter_by_date(reparations, date); } - [[nodiscard]] memory::vector> get_subjects(Date date) const{ + [[nodiscard]] memory::vector> get_subjects(Date date) const { return filter_by_date(subjects, date); } /* Returns all wars that begin before date. NOTE: Some wargoals may be added or countries may join after date, diff --git a/src/openvic-simulation/history/HistoryManager.hpp b/src/openvic-simulation/history/HistoryManager.hpp index 80be9647a..e36ed7bd1 100644 --- a/src/openvic-simulation/history/HistoryManager.hpp +++ b/src/openvic-simulation/history/HistoryManager.hpp @@ -14,6 +14,7 @@ namespace OpenVic { CountryHistoryManager PROPERTY_REF(country_manager); ProvinceHistoryManager PROPERTY_REF(province_manager); DiplomaticHistoryManager PROPERTY_REF(diplomacy_manager); + public: HistoryManager(DefinitionManager const& definition_manager) : province_manager { definition_manager } {} }; diff --git a/src/openvic-simulation/history/HistoryMap.hpp b/src/openvic-simulation/history/HistoryMap.hpp index 828a7032e..cb81302fb 100644 --- a/src/openvic-simulation/history/HistoryMap.hpp +++ b/src/openvic-simulation/history/HistoryMap.hpp @@ -13,6 +13,7 @@ namespace OpenVic { struct HistoryEntry { protected: constexpr HistoryEntry(const Date new_date) : date { new_date } {} + public: const Date date; }; @@ -32,10 +33,8 @@ namespace OpenVic { private: ordered_map> PROPERTY(entries); - bool _try_load_history_entry( - DefinitionManager const& definition_manager, Args... args, Date date, ast::NodeCPtr root - ) { - entry_type *const entry = _get_or_make_entry(definition_manager, date); + bool _try_load_history_entry(DefinitionManager const& definition_manager, Args... args, Date date, ast::NodeCPtr root) { + entry_type* const entry = _get_or_make_entry(definition_manager, date); if (entry != nullptr) { return _load_history_entry(definition_manager, args..., *entry, root); } else { @@ -59,18 +58,13 @@ namespace OpenVic { } bool _load_history_sub_entry_callback( - DefinitionManager const& definition_manager, - Args... args, - Date date, - ast::NodeCPtr root, - NodeTools::template_key_map_t const& key_map, - std::string_view key, - ast::NodeCPtr value + DefinitionManager const& definition_manager, Args... args, Date date, ast::NodeCPtr root, + NodeTools::template_key_map_t const& key_map, std::string_view key, ast::NodeCPtr value ) { /* Date blocks (loaded into the corresponding HistoryEntry) */ Date::from_chars_result result; const Date sub_date { Date::from_string(key, &result) }; - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { if (sub_date < date) { spdlog::warn_s("History entry {} defined before parent entry date {}", sub_date, date); } @@ -84,8 +78,10 @@ namespace OpenVic { return false; } } - - return NodeTools::map_key_value_invalid_callback>(key_map, key, value); + + return NodeTools::map_key_value_invalid_callback>( + key_map, key, value + ); } /* Returns history entry at specific date, if date doesn't have an entry creates one, if that fails returns nullptr. */ diff --git a/src/openvic-simulation/history/ProvinceHistory.cpp b/src/openvic-simulation/history/ProvinceHistory.cpp index 099fc2e07..1b5aff88b 100644 --- a/src/openvic-simulation/history/ProvinceHistory.cpp +++ b/src/openvic-simulation/history/ProvinceHistory.cpp @@ -2,35 +2,29 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" -#include "openvic-simulation/utility/Logger.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Logger.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; ProvinceHistoryEntry::ProvinceHistoryEntry( - BuildingTypeManager const& building_type_manager, - ProvinceDefinition const& new_province, - Date new_date -) : HistoryEntry { new_date }, - province { new_province }, - _province_building_levels( - building_type_manager.get_province_building_types().size(), - building_level_t(0) - ), - province_building_levels(_province_building_levels) -{} - -ProvinceHistoryMap::ProvinceHistoryMap(ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager) - : province { new_province }, - building_type_manager { new_building_type_manager } - {} + BuildingTypeManager const& building_type_manager, ProvinceDefinition const& new_province, Date new_date +) + : HistoryEntry { new_date }, province { new_province }, + _province_building_levels(building_type_manager.get_province_building_types().size(), building_level_t(0)), + province_building_levels(_province_building_levels) {} + +ProvinceHistoryMap::ProvinceHistoryMap( + ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager +) + : province { new_province }, building_type_manager { new_building_type_manager } {} memory::unique_ptr ProvinceHistoryMap::_make_entry(Date date) const { return memory::make_unique(building_type_manager, province, date); @@ -47,9 +41,7 @@ bool ProvinceHistoryMap::_load_history_entry( TerrainTypeManager const& terrain_type_manager = definition_manager.get_map_definition().get_terrain_type_manager(); using enum colony_status_t; - static const string_map_t colony_status_map { - { "0", STATE }, { "1", PROTECTORATE }, { "2", COLONY } - }; + static const string_map_t colony_status_map { { "0", STATE }, { "1", PROTECTORATE }, { "2", COLONY } }; const auto set_core_instruction = [&entry](bool add) { return [&entry, add](CountryDefinition const& country) -> bool { @@ -61,11 +53,8 @@ bool ProvinceHistoryMap::_load_history_entry( } else if (it->second == add) { // Desired core instruction already exists spdlog::warn_s( - "Duplicate attempt to {} core of country {} {} province history of {}", - add ? "add" : "remove", - country, - add ? "to" : "from", - entry.province + "Duplicate attempt to {} core of country {} {} province history of {}", add ? "add" : "remove", country, + add ? "to" : "from", entry.province ); return true; } else { @@ -73,11 +62,7 @@ bool ProvinceHistoryMap::_load_history_entry( entry.cores.erase(it); spdlog::warn_s( "Attempted to {} core of country {} {} province history of {} after previously {} it", - add ? "add" : "remove", - country, - add ? "to" : "from", - entry.province, - add ? "removing" : "adding" + add ? "add" : "remove", country, add ? "to" : "from", entry.province, add ? "removing" : "adding" ); return true; } @@ -277,14 +262,9 @@ ProvinceHistoryMap const* ProvinceHistoryManager::get_province_history(ProvinceD ProvinceHistoryMap* ProvinceHistoryManager::_get_or_make_province_history(ProvinceDefinition const& province) { decltype(province_histories)::iterator it = province_histories.find(&province); if (it == province_histories.end()) { - const std::pair result = - province_histories.emplace( - &province, - ProvinceHistoryMap { - province, - definition_manager.get_economy_manager().get_building_type_manager() - } - ); + const std::pair result = province_histories.emplace( + &province, ProvinceHistoryMap { province, definition_manager.get_economy_manager().get_building_type_manager() } + ); if (result.second) { it = result.first; } else { @@ -299,10 +279,7 @@ bool ProvinceHistoryManager::load_province_history_file( DefinitionManager const& definition_manager, ProvinceDefinition const& province, ast::NodeCPtr root ) { if (locked) { - spdlog::error_s( - "Attempted to load province history file for {} after province history registry was locked!", - province - ); + spdlog::error_s("Attempted to load province history file for {} after province history registry was locked!", province); return false; } @@ -315,20 +292,18 @@ bool ProvinceHistoryManager::load_province_history_file( } bool ProvinceHistoryEntry::_load_province_pop_history( - DefinitionManager const& definition_manager, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, ast::NodeCPtr root, bool* non_integer_size ) { PopManager const& pop_manager = definition_manager.get_pop_manager(); RebelManager const& rebel_manager = definition_manager.get_politics_manager().get_rebel_manager(); - return pop_manager.expect_pop_type_dictionary_reserve_length( - pops, - [this, &pop_manager, &rebel_manager, non_integer_size](PopType const& pop_type, ast::NodeCPtr pop_node) -> bool { + return pop_manager + .expect_pop_type_dictionary_reserve_length(pops, [this, &pop_manager, &rebel_manager, non_integer_size](PopType const& pop_type, ast::NodeCPtr pop_node) -> bool { return pop_manager.load_pop_bases_into_vector(rebel_manager, pops, pop_type, pop_node, non_integer_size); - } - )(root); + })(root); } bool ProvinceHistoryMap::_load_province_pop_history( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ) { ProvinceHistoryEntry* entry = _get_or_make_entry(definition_manager, date); if (entry != nullptr) { @@ -339,20 +314,19 @@ bool ProvinceHistoryMap::_load_province_pop_history( } bool ProvinceHistoryManager::load_pop_history_file( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ) { if (locked) { spdlog::error_s("Attempted to load pop history file after province history registry was locked!"); return false; } - return definition_manager.get_map_definition().expect_province_definition_dictionary( - [this, &definition_manager, date, non_integer_size](ProvinceDefinition const& province, ast::NodeCPtr node) -> bool { + return definition_manager.get_map_definition() + .expect_province_definition_dictionary([this, &definition_manager, date, non_integer_size](ProvinceDefinition const& province, ast::NodeCPtr node) -> bool { ProvinceHistoryMap* province_history = _get_or_make_province_history(province); if (province_history != nullptr) { return province_history->_load_province_pop_history(definition_manager, date, node, non_integer_size); } else { return false; } - } - )(root); + })(root); } diff --git a/src/openvic-simulation/history/ProvinceHistory.hpp b/src/openvic-simulation/history/ProvinceHistory.hpp index 37b7c27a8..dadb3331a 100644 --- a/src/openvic-simulation/history/ProvinceHistory.hpp +++ b/src/openvic-simulation/history/ProvinceHistory.hpp @@ -2,18 +2,18 @@ #include +#include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/economy/BuildingType.hpp" #include "openvic-simulation/history/HistoryMap.hpp" +#include "openvic-simulation/map/LifeRating.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/types/ColonyStatus.hpp" #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/FixedVector.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/types/TypedSpan.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -#include "openvic-simulation/map/LifeRating.hpp" +#include "openvic-simulation/types/TypedSpan.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/Getters.hpp" @@ -30,10 +30,9 @@ namespace OpenVic { friend struct ProvinceHistoryMap; ProvinceHistoryEntry( - BuildingTypeManager const& building_type_manager, - ProvinceDefinition const& new_province, - Date new_date + BuildingTypeManager const& building_type_manager, ProvinceDefinition const& new_province, Date new_date ); + private: std::optional PROPERTY(owner); std::optional PROPERTY(controller); @@ -45,18 +44,20 @@ namespace OpenVic { std::optional PROPERTY(terrain_type); memory::FixedVector _province_building_levels; TypedSpan province_building_levels; + public: constexpr TypedSpan get_province_building_levels() const { return province_building_levels; } + private: ordered_map PROPERTY(state_buildings); fixed_point_map_t PROPERTY(party_loyalties); memory::vector SPAN_PROPERTY(pops); - bool _load_province_pop_history( - DefinitionManager const& definition_manager, ast::NodeCPtr root, bool *non_integer_size - ); + bool + _load_province_pop_history(DefinitionManager const& definition_manager, ast::NodeCPtr root, bool* non_integer_size); + public: ProvinceDefinition const& province; }; @@ -74,8 +75,9 @@ namespace OpenVic { ProvinceHistoryMap(ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager); memory::unique_ptr _make_entry(Date date) const override; - bool _load_history_entry(DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root) - override; + bool _load_history_entry( + DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root + ) override; private: bool _load_province_pop_history( @@ -94,7 +96,8 @@ namespace OpenVic { ProvinceHistoryMap* _get_or_make_province_history(ProvinceDefinition const& province); public: - ProvinceHistoryManager(DefinitionManager const& new_definition_manager) : definition_manager { new_definition_manager } {}; + ProvinceHistoryManager(DefinitionManager const& new_definition_manager) + : definition_manager { new_definition_manager } {}; void reserve_more_province_histories(size_t size); void lock_province_histories(MapDefinition const& map_definition, bool detailed_errors); diff --git a/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp b/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp index 353246f48..5a08a1f51 100644 --- a/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp @@ -13,10 +13,9 @@ namespace OpenVic { const Period period; constexpr AllianceHistory( - CountryDefinition const& new_first, - CountryDefinition const& new_second, - const Period new_period - ) : first { new_first }, second { new_second }, period { new_period } {} + CountryDefinition const& new_first, CountryDefinition const& new_second, const Period new_period + ) + : first { new_first }, second { new_second }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp b/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp index dd1afdfc3..7b9a4d93d 100644 --- a/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp @@ -13,10 +13,9 @@ namespace OpenVic { const Period period; constexpr ReparationsHistory( - CountryDefinition const& new_receiver, - CountryDefinition const& new_sender, - const Period new_period - ) : receiver { new_receiver }, sender { new_sender }, period { new_period } {} + CountryDefinition const& new_receiver, CountryDefinition const& new_sender, const Period new_period + ) + : receiver { new_receiver }, sender { new_sender }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp b/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp index 70f8fd726..98e34bb9d 100644 --- a/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp @@ -8,22 +8,17 @@ namespace OpenVic { struct CountryDefinition; struct SubjectHistory { public: - enum struct type_t : uint8_t { - VASSAL, - UNION, - SUBSTATE - }; + enum struct type_t : uint8_t { VASSAL, UNION, SUBSTATE }; CountryDefinition const& overlord; CountryDefinition const& subject; const type_t subject_type; const Period period; constexpr SubjectHistory( - CountryDefinition const& new_overlord, - CountryDefinition const& new_subject, - const type_t new_subject_type, + CountryDefinition const& new_overlord, CountryDefinition const& new_subject, const type_t new_subject_type, const Period new_period - ) : overlord { new_overlord }, subject { new_subject }, subject_type { new_subject_type }, period { new_period } {} + ) + : overlord { new_overlord }, subject { new_subject }, subject_type { new_subject_type }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/WarHistory.cpp b/src/openvic-simulation/history/diplomacy/WarHistory.cpp index c9f363371..42be38f3f 100644 --- a/src/openvic-simulation/history/diplomacy/WarHistory.cpp +++ b/src/openvic-simulation/history/diplomacy/WarHistory.cpp @@ -3,9 +3,8 @@ using namespace OpenVic; WarHistory::WarHistory( - std::string_view new_war_name, - memory::vector&& new_attackers, - memory::vector&& new_defenders, - memory::vector&& new_wargoals -) : war_name { new_war_name }, attackers { std::move(new_attackers) }, defenders { std::move(new_defenders) }, - wargoals { std::move(new_wargoals) } {} \ No newline at end of file + std::string_view new_war_name, memory::vector&& new_attackers, + memory::vector&& new_defenders, memory::vector&& new_wargoals +) + : war_name { new_war_name }, attackers { std::move(new_attackers) }, defenders { std::move(new_defenders) }, + wargoals { std::move(new_wargoals) } {} diff --git a/src/openvic-simulation/history/diplomacy/WarHistory.hpp b/src/openvic-simulation/history/diplomacy/WarHistory.hpp index 30bc8939a..722135cc4 100644 --- a/src/openvic-simulation/history/diplomacy/WarHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/WarHistory.hpp @@ -12,11 +12,11 @@ namespace OpenVic { struct CountryDefinition; struct ProvinceDefinition; struct WargoalType; - + struct WarHistory { friend struct DiplomaticHistoryManager; - struct added_wargoal_t { + struct added_wargoal_t { public: const Date date_added; CountryDefinition const& actor; @@ -26,20 +26,14 @@ namespace OpenVic { // TODO - could these just be nullptr when unset rather than using optionals? const std::optional third_party; const std::optional target; - + constexpr added_wargoal_t( - const Date new_date_added, - CountryDefinition const& new_actor, - CountryDefinition const& new_receiver, - WargoalType const& new_wargoal, - std::optional new_third_party, + const Date new_date_added, CountryDefinition const& new_actor, CountryDefinition const& new_receiver, + WargoalType const& new_wargoal, std::optional new_third_party, std::optional new_target - ) : date_added { new_date_added }, - actor { new_actor }, - receiver { new_receiver }, - wargoal { new_wargoal }, - third_party { new_third_party }, - target { new_target } {} + ) + : date_added { new_date_added }, actor { new_actor }, receiver { new_receiver }, wargoal { new_wargoal }, + third_party { new_third_party }, target { new_target } {} }; static_assert(std::is_trivially_move_constructible_v); @@ -50,7 +44,7 @@ namespace OpenVic { public: CountryDefinition const& country; - + constexpr war_participant_t(CountryDefinition const& new_country, const Period new_period) : country { new_country }, period { new_period } {} }; @@ -69,4 +63,4 @@ namespace OpenVic { memory::vector SPAN_PROPERTY(defenders); memory::vector SPAN_PROPERTY(wargoals); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXObject.cpp b/src/openvic-simulation/interface/GFXObject.cpp index c889bfbd3..833b34cf7 100644 --- a/src/openvic-simulation/interface/GFXObject.cpp +++ b/src/openvic-simulation/interface/GFXObject.cpp @@ -7,7 +7,8 @@ using namespace OpenVic; using namespace OpenVic::GFX; using namespace OpenVic::NodeTools; -node_callback_t Object::expect_objects(length_callback_t length_callback, callback_t&&> callback) { +node_callback_t +Object::expect_objects(length_callback_t length_callback, callback_t&&> callback) { return expect_dictionary_keys_and_length( length_callback, @@ -17,43 +18,31 @@ node_callback_t Object::expect_objects(length_callback_t length_callback, callba "arrowType", ZERO_OR_MORE, _expect_instance(callback), /* battlearrow.gfx */ - "battlearrow", ZERO_OR_MORE, _expect_instance(callback), - "mapinfo", ZERO_OR_MORE, _expect_instance(callback), + "battlearrow", ZERO_OR_MORE, _expect_instance(callback), "mapinfo", ZERO_OR_MORE, + _expect_instance(callback), /* mapitems.gfx */ - "projectionType", ZERO_OR_MORE, _expect_instance(callback), - "progressbar3dType", ZERO_OR_MORE, _expect_instance(callback), - "billboardType", ZERO_OR_MORE, _expect_instance(callback), - "unitstatsBillboardType", ZERO_OR_MORE, success_callback, + "projectionType", ZERO_OR_MORE, _expect_instance(callback), "progressbar3dType", ZERO_OR_MORE, + _expect_instance(callback), "billboardType", ZERO_OR_MORE, + _expect_instance(callback), "unitstatsBillboardType", ZERO_OR_MORE, success_callback, /* core.gfx */ "animatedmaptext", ZERO_OR_MORE, _expect_instance(callback), - "flagType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback, - "size", ONE_EXACTLY, success_callback - ), - "provinceType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "provinceWaterType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "mapTextType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "meshType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback, - "xfile", ONE_EXACTLY, success_callback - ) + "flagType", ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback, "size", ONE_EXACTLY, success_callback), "provinceType", + ZERO_OR_MORE, expect_dictionary_keys("name", ONE_EXACTLY, success_callback), "provinceWaterType", ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback), "mapTextType", ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback), "meshType", ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback, "xfile", ONE_EXACTLY, success_callback) ); } Actor::Attachment::Attachment(std::string_view new_actor_name, std::string_view new_attach_node, attach_id_t new_attach_id) - : actor_name { new_actor_name }, attach_node { new_attach_node }, attach_id { new_attach_id } {} + : actor_name { new_actor_name }, attach_node { new_attach_node }, attach_id { new_attach_id } {} Actor::Animation::Animation(std::string_view new_file, fixed_point_t new_scroll_time) - : file { new_file }, scroll_time { new_scroll_time } {} + : file { new_file }, scroll_time { new_scroll_time } {} Actor::Actor() {} @@ -68,16 +57,15 @@ bool Actor::_set_animation(std::string_view name, std::string_view file, fixed_p animation = &attack_animation; } else { spdlog::error_s( - "Unknown animation type \"{}\" for actor {} (with file {} and scroll time {})", - name, get_name(), file, scroll_time + "Unknown animation type \"{}\" for actor {} (with file {} and scroll time {})", name, get_name(), file, scroll_time ); return false; } if (animation->has_value()) { spdlog::error_s( - "Duplicate {} animation for actor {}: {} with scroll time {} (already set to {} with scroll time {})", - name, get_name(), file, scroll_time, (*animation)->file, (*animation)->scroll_time + "Duplicate {} animation for actor {}: {} with scroll time {} (already set to {} with scroll time {})", name, + get_name(), file, scroll_time, (*animation)->file, (*animation)->scroll_time ); return false; } @@ -97,25 +85,27 @@ bool Actor::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { using namespace std::string_view_literals; static const auto bind_set_animation = [](Actor* self, std::string_view name) { - return [self, name](std::string_view file){ return self->_set_animation(name, file, 0); }; + return [self, name](std::string_view file) { + return self->_set_animation(name, file, 0); + }; }; // Default max vanilla attachments is 1, 3 is the max I've seen in mods attachments.reserve(1); - ret &= add_key_map_entries(key_map, - "actorfile", ONE_EXACTLY, expect_string(assign_variable_callback_string(model_file)), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), + ret &= add_key_map_entries( + key_map, "actorfile", ONE_EXACTLY, expect_string(assign_variable_callback_string(model_file)), "scale", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(scale)), - "attach", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { + "attach", ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { std::string_view actor_name {}, attach_node {}; Attachment::attach_id_t attach_id = 0; - if (!expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(actor_name)), - "node", ONE_EXACTLY, expect_string(assign_variable_callback(attach_node)), - "attachId", ONE_EXACTLY, expect_uint(assign_variable_callback(attach_id)) - )(node)) { + if (!expect_dictionary_keys< + StringMapCaseInsensitive>("name", ONE_EXACTLY, expect_string(assign_variable_callback(actor_name)), "node", ONE_EXACTLY, expect_string(assign_variable_callback(attach_node)), "attachId", ONE_EXACTLY, expect_uint(assign_variable_callback(attach_id)))( + node + )) { spdlog::error_s("Failed to load attachment for actor {}", get_name()); return false; } @@ -124,18 +114,17 @@ bool Actor::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { return true; }, - "idle", ZERO_OR_ONE, expect_string(bind_set_animation(this, "idle"sv)), - "move", ZERO_OR_ONE, expect_string(bind_set_animation(this, "move"sv)), - "attack", ZERO_OR_ONE, expect_string(bind_set_animation(this, "attack"sv)), - "animation", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { + "idle", ZERO_OR_ONE, expect_string(bind_set_animation(this, "idle"sv)), "move", ZERO_OR_ONE, + expect_string(bind_set_animation(this, "move"sv)), "attack", ZERO_OR_ONE, + expect_string(bind_set_animation(this, "attack"sv)), "animation", ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { std::string_view name {}, file {}; fixed_point_t scroll_time = 0; - if (!expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), - "file", ONE_EXACTLY, expect_string(assign_variable_callback(file)), - "defaultAnimationTime", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scroll_time)) - )(node)) { + if (!expect_dictionary_keys< + StringMapCaseInsensitive>("name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), "file", ONE_EXACTLY, expect_string(assign_variable_callback(file)), "defaultAnimationTime", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scroll_time)))( + node + )) { spdlog::error_s("Failed to load animation for actor {}", get_name()); return false; } @@ -153,17 +142,17 @@ ArrowType::ArrowType() {} bool ArrowType::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(size)), - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "bodytexture", ONE_EXACTLY, expect_string(assign_variable_callback_string(body_texture_file)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "endAt", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(end_at)), - "height", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(height)), - "type", ONE_EXACTLY, expect_int64(assign_variable_callback(arrow_type)), - "heading", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(heading)), - "effect", ONE_EXACTLY, expect_string(assign_variable_callback_string(effect_file)) + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(size)), "textureFile", ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_file)), "bodytexture", ONE_EXACTLY, + expect_string(assign_variable_callback_string(body_texture_file)), "color", ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), "colortwo", ONE_EXACTLY, + expect_colour(assign_variable_callback(progress_colour)), "endAt", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(end_at)), "height", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(height)), "type", ONE_EXACTLY, + expect_int64(assign_variable_callback(arrow_type)), "heading", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(heading)), "effect", ONE_EXACTLY, + expect_string(assign_variable_callback_string(effect_file)) ); return ret; @@ -175,17 +164,17 @@ BattleArrow::BattleArrow() {} bool BattleArrow::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_body)), - "textureFile1", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_head)), - "start", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(start)), - "stop", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(stop)), - "x", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(dims.x)), - "y", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(dims.y)), - "font", ONE_EXACTLY, expect_string(assign_variable_callback_string(font)), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), - "nofade", ZERO_OR_ONE, expect_bool(assign_variable_callback(no_fade)), - "textureloop", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(texture_loop)) + ret &= add_key_map_entries( + key_map, "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_body)), "textureFile1", + ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_head)), "start", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(start)), "stop", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(stop)), "x", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(dims.x)), "y", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(dims.y)), "font", ONE_EXACTLY, + expect_string(assign_variable_callback_string(font)), "scale", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(scale)), "nofade", ZERO_OR_ONE, + expect_bool(assign_variable_callback(no_fade)), "textureloop", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(texture_loop)) ); return ret; @@ -196,9 +185,9 @@ MapInfo::MapInfo() {} bool MapInfo::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)) + ret &= add_key_map_entries( + key_map, "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), "scale", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)) ); return ret; @@ -207,25 +196,25 @@ bool MapInfo::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { /* MapItems.gfx */ Projection::Projection() {} -//TODO: Verify... -// whether pulseSpeed is fixedpoint_t or int -// pulseSpeed doesn't seem to do anything, so assume fixed_point_t since its a speed -//fadeout could be int, expect_int_bool, or fixed_point_t -//fadeout seems not to do anything +// TODO: Verify... +// whether pulseSpeed is fixedpoint_t or int +// pulseSpeed doesn't seem to do anything, so assume fixed_point_t since its a speed +// fadeout could be int, expect_int_bool, or fixed_point_t +// fadeout seems not to do anything bool Projection::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "size", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(size)), - "spin", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spin)), - "pulsating", ONE_EXACTLY, expect_bool(assign_variable_callback(pulsating)), - "pulseLowest", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pulse_lowest)), - "pulseSpeed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pulse_speed)), - "additative", ONE_EXACTLY, expect_bool(assign_variable_callback(additative)), - "expanding", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(expanding)), - "duration", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(duration)), - "fadeout", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(fadeout)) + ret &= add_key_map_entries( + key_map, "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), "size", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(size)), "spin", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spin)), "pulsating", ONE_EXACTLY, + expect_bool(assign_variable_callback(pulsating)), "pulseLowest", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pulse_lowest)), "pulseSpeed", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pulse_speed)), "additative", ONE_EXACTLY, + expect_bool(assign_variable_callback(additative)), "expanding", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(expanding)), "duration", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(duration)), "fadeout", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(fadeout)) ); return ret; @@ -237,13 +226,13 @@ Billboard::Billboard() {} bool Billboard::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "texturefile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "noOfFrames", ZERO_OR_ONE, expect_uint((callback_t)[this](frame_t frames_read) -> bool { + ret &= add_key_map_entries( + key_map, "texturefile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), "noOfFrames", + ZERO_OR_ONE, expect_uint((callback_t)[this](frame_t frames_read) -> bool { if (frames_read < 1) { spdlog::error_s( - "Billboard {} had an invalid number of frames {}, setting number of frames to 1", - this->get_name(), frames_read + "Billboard {} had an invalid number of frames {}, setting number of frames to 1", this->get_name(), + frames_read ); no_of_frames = 1; return false; @@ -251,10 +240,8 @@ bool Billboard::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { no_of_frames = frames_read; return true; }), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), - "font_size", ZERO_OR_ONE, success_callback, - "offset2", ZERO_OR_ONE, success_callback, - "font", ZERO_OR_ONE, success_callback + "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), "font_size", ZERO_OR_ONE, success_callback, + "offset2", ZERO_OR_ONE, success_callback, "font", ZERO_OR_ONE, success_callback ); return ret; @@ -265,10 +252,9 @@ ProgressBar3d::ProgressBar3d() {} bool ProgressBar3d::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), + ret &= add_key_map_entries( + key_map, "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), "colortwo", ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), "effectFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(effect_file)) ); @@ -282,19 +268,19 @@ AnimatedMapText::AnimatedMapText() {} bool AnimatedMapText::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "speed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(speed)), - "position", ZERO_OR_ONE, expect_fvec3(assign_variable_callback(position)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)), - "textblock", ONE_EXACTLY, expect_dictionary_keys( - "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "font", ONE_EXACTLY, expect_string(assign_variable_callback_string(font)), - "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(text_position)), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "format", ONE_EXACTLY, expect_text_format(assign_variable_callback(format)) + ret &= add_key_map_entries( + key_map, "speed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(speed)), "position", ZERO_OR_ONE, + expect_fvec3(assign_variable_callback(position)), "scale", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)), "textblock", ONE_EXACTLY, + expect_dictionary_keys( + "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text)), "color", ONE_EXACTLY, + expect_colour(assign_variable_callback(colour)), "font", ONE_EXACTLY, + expect_string(assign_variable_callback_string(font)), "position", ONE_EXACTLY, + expect_fvec2(assign_variable_callback(text_position)), "size", ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), "format", ONE_EXACTLY, + expect_text_format(assign_variable_callback(format)) ) ); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXObject.hpp b/src/openvic-simulation/interface/GFXObject.hpp index 03dcfd926..b3a34135e 100644 --- a/src/openvic-simulation/interface/GFXObject.hpp +++ b/src/openvic-simulation/interface/GFXObject.hpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/interface/LoadBase.hpp" #include "openvic-simulation/core/ui/TextFormat.hpp" +#include "openvic-simulation/interface/LoadBase.hpp" #include "openvic-simulation/types/Vector.hpp" #include "openvic-simulation/utility/Containers.hpp" @@ -77,20 +77,20 @@ namespace OpenVic::GFX { /* arrows.gfx */ class ArrowType final : public Object { - //Named<> already handles the name property + // Named<> already handles the name property fixed_point_t PROPERTY(size, 5); - //texture_file is unused, body_texture_file determines the appearance of the arrow - memory::string PROPERTY(texture_file); //unused + // texture_file is unused, body_texture_file determines the appearance of the arrow + memory::string PROPERTY(texture_file); // unused memory::string PROPERTY(body_texture_file); - //colours dont appear to be used - //TODO: Verify these property names for color and colortwo are correct + // colours dont appear to be used + // TODO: Verify these property names for color and colortwo are correct colour_t PROPERTY(back_colour); colour_t PROPERTY(progress_colour); - fixed_point_t PROPERTY(end_at, 1); //how should float be repd? >> fixed_point handles it + fixed_point_t PROPERTY(end_at, 1); // how should float be repd? >> fixed_point handles it fixed_point_t PROPERTY(height, 1); - uint64_t PROPERTY(arrow_type, 0); //TODO: what does this do? - fixed_point_t PROPERTY(heading, 1); //also float + uint64_t PROPERTY(arrow_type, 0); // TODO: what does this do? + fixed_point_t PROPERTY(heading, 1); // also float memory::string PROPERTY(effect_file); @@ -111,10 +111,10 @@ namespace OpenVic::GFX { memory::string PROPERTY(texture_arrow_body); memory::string PROPERTY(texture_arrow_head); - fixed_point_t PROPERTY(start, 1); //labelled 'body start width' in file - fixed_point_t PROPERTY(stop, 1); //labelled 'body end width' in file + fixed_point_t PROPERTY(start, 1); // labelled 'body start width' in file + fixed_point_t PROPERTY(stop, 1); // labelled 'body end width' in file - fvec2_t PROPERTY(dims, { 1, 1 }); //x,y labelled 'arrow length','arrow height' in file + fvec2_t PROPERTY(dims, { 1, 1 }); // x,y labelled 'arrow length','arrow height' in file memory::string PROPERTY(font); fixed_point_t PROPERTY(scale, 1); bool PROPERTY(no_fade, false); @@ -149,7 +149,7 @@ namespace OpenVic::GFX { /* mapitems.gfx */ class Projection final : public Object { memory::string PROPERTY(texture_file); - //TODO: pulseSpeed, fadeout be ints or fixed points? assume fixed_point_t to start + // TODO: pulseSpeed, fadeout be ints or fixed points? assume fixed_point_t to start fixed_point_t PROPERTY(size, 1); fixed_point_t PROPERTY(spin, 1); bool PROPERTY(pulsating, false); @@ -157,8 +157,8 @@ namespace OpenVic::GFX { fixed_point_t PROPERTY(pulse_speed, 1); bool PROPERTY(additative, false); fixed_point_t PROPERTY(expanding, 1); - fixed_point_t PROPERTY(duration, 0); //0 means it stays indefinitely (also the default value) - fixed_point_t PROPERTY(fadeout, 0); //appears to have no effect + fixed_point_t PROPERTY(duration, 0); // 0 means it stays indefinitely (also the default value) + fixed_point_t PROPERTY(fadeout, 0); // appears to have no effect protected: bool _fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) override; @@ -211,7 +211,7 @@ namespace OpenVic::GFX { using enum text_format_t; private: - //textblock + // textblock memory::string PROPERTY(text); colour_t PROPERTY(colour); memory::string PROPERTY(font); @@ -220,7 +220,7 @@ namespace OpenVic::GFX { fvec2_t PROPERTY(size); text_format_t PROPERTY(format, text_format_t::left); - //end textblock + // end textblock fixed_point_t PROPERTY(speed, 1); fixed_point_t PROPERTY(scale, 1); @@ -237,4 +237,4 @@ namespace OpenVic::GFX { OV_DETAIL_GET_TYPE }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXSprite.cpp b/src/openvic-simulation/interface/GFXSprite.cpp index c488d0439..099ed0f03 100644 --- a/src/openvic-simulation/interface/GFXSprite.cpp +++ b/src/openvic-simulation/interface/GFXSprite.cpp @@ -7,24 +7,24 @@ using namespace OpenVic::NodeTools; Font::Font( std::string_view new_identifier, colour_argb_t new_colour, std::string_view new_fontname, std::string_view new_charset, uint32_t new_height, colour_codes_t&& new_colour_codes -) : HasIdentifierAndAlphaColour { new_identifier, new_colour, false }, fontname { new_fontname }, charset { new_charset }, - height { new_height }, colour_codes { std::move(new_colour_codes) } {} +) + : HasIdentifierAndAlphaColour { new_identifier, new_colour, false }, fontname { new_fontname }, charset { new_charset }, + height { new_height }, colour_codes { std::move(new_colour_codes) } {} -node_callback_t Sprite::expect_sprites(length_callback_t length_callback, callback_t&&> callback) { +node_callback_t +Sprite::expect_sprites(length_callback_t length_callback, callback_t&&> callback) { return expect_dictionary_keys_and_length( - length_callback, - "spriteType", ZERO_OR_MORE, _expect_instance(callback), - "progressbartype", ZERO_OR_MORE, _expect_instance(callback), - "PieChartType", ZERO_OR_MORE, _expect_instance(callback), - "LineChartType", ZERO_OR_MORE, _expect_instance(callback), - "textSpriteType", ZERO_OR_MORE, _expect_instance(callback), - "maskedShieldType", ZERO_OR_MORE, _expect_instance(callback), - "tileSpriteType", ZERO_OR_MORE, _expect_instance(callback), - "corneredTileSpriteType", ZERO_OR_MORE, _expect_instance(callback), + length_callback, "spriteType", ZERO_OR_MORE, _expect_instance(callback), "progressbartype", + ZERO_OR_MORE, _expect_instance(callback), "PieChartType", ZERO_OR_MORE, + _expect_instance(callback), "LineChartType", ZERO_OR_MORE, + _expect_instance(callback), "textSpriteType", ZERO_OR_MORE, + _expect_instance(callback), "maskedShieldType", ZERO_OR_MORE, + _expect_instance(callback), "tileSpriteType", ZERO_OR_MORE, + _expect_instance(callback), "corneredTileSpriteType", ZERO_OR_MORE, + _expect_instance(callback), /* Each only has one vanilla instance which isn't used anywhere. */ - "BarChartType", ZERO_OR_MORE, success_callback, - "scrollingSprite", ZERO_OR_MORE, success_callback + "BarChartType", ZERO_OR_MORE, success_callback, "scrollingSprite", ZERO_OR_MORE, success_callback ); } @@ -32,12 +32,11 @@ TextureSprite::TextureSprite() {} bool TextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "texturefile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), + ret &= add_key_map_entries( + key_map, "texturefile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), - "norefcount", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "loadType", ZERO_OR_ONE, success_callback + "norefcount", ZERO_OR_ONE, success_callback, "allwaystransparent", ZERO_OR_ONE, success_callback, "loadType", + ZERO_OR_ONE, success_callback ); return ret; } @@ -46,12 +45,11 @@ IconTextureSprite::IconTextureSprite() {} bool IconTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "noOfFrames", ZERO_OR_ONE, expect_uint(assign_variable_callback(no_of_frames)), + ret &= add_key_map_entries( + key_map, "noOfFrames", ZERO_OR_ONE, expect_uint(assign_variable_callback(no_of_frames)), - "effectFile", ZERO_OR_ONE, success_callback, - "transparencecheck", ZERO_OR_ONE, success_callback, - "clicksound", ZERO_OR_ONE, success_callback + "effectFile", ZERO_OR_ONE, success_callback, "transparencecheck", ZERO_OR_ONE, success_callback, "clicksound", + ZERO_OR_ONE, success_callback ); return ret; } @@ -60,9 +58,7 @@ TileTextureSprite::TileTextureSprite() {} bool TileTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)) - ); + ret &= add_key_map_entries(key_map, "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size))); return ret; } @@ -70,9 +66,9 @@ CorneredTileTextureSprite::CorneredTileTextureSprite() {} bool CorneredTileTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - "borderSize", ONE_EXACTLY, expect_ivec2(assign_variable_callback(border_size)) + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), "borderSize", ONE_EXACTLY, + expect_ivec2(assign_variable_callback(border_size)) ); return ret; } @@ -81,17 +77,15 @@ ProgressBar::ProgressBar() {} bool ProgressBar::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "textureFile1", ZERO_OR_ONE, expect_string(assign_variable_callback_string(progress_texture_file)), - "textureFile2", ZERO_OR_ONE, expect_string(assign_variable_callback_string(back_texture_file)), - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - - "effectFile", ONE_EXACTLY, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "loadType", ZERO_OR_ONE, success_callback, - "horizontal", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), "colortwo", ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), "textureFile1", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(progress_texture_file)), "textureFile2", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(back_texture_file)), "size", ONE_EXACTLY, + expect_ivec2(assign_variable_callback(size)), + + "effectFile", ONE_EXACTLY, success_callback, "allwaystransparent", ZERO_OR_ONE, success_callback, "loadType", + ZERO_OR_ONE, success_callback, "horizontal", ZERO_OR_ONE, success_callback ); return ret; } @@ -108,9 +102,9 @@ LineChart::LineChart() {} bool LineChart::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - "linewidth", ONE_EXACTLY, expect_uint(assign_variable_callback(linewidth)), + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), "linewidth", ONE_EXACTLY, + expect_uint(assign_variable_callback(linewidth)), "allwaystransparent", ZERO_OR_ONE, success_callback ); @@ -121,13 +115,12 @@ MaskedFlag::MaskedFlag() {} bool MaskedFlag::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile1", ONE_EXACTLY, expect_string(assign_variable_callback_string(overlay_file)), - "textureFile2", ONE_EXACTLY, expect_string(assign_variable_callback_string(mask_file)), + ret &= add_key_map_entries( + key_map, "textureFile1", ONE_EXACTLY, expect_string(assign_variable_callback_string(overlay_file)), "textureFile2", + ONE_EXACTLY, expect_string(assign_variable_callback_string(mask_file)), - "effectFile", ONE_EXACTLY, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "flipv", ZERO_OR_ONE, success_callback + "effectFile", ONE_EXACTLY, success_callback, "allwaystransparent", ZERO_OR_ONE, success_callback, "flipv", ZERO_OR_ONE, + success_callback ); return ret; } diff --git a/src/openvic-simulation/interface/GUI.cpp b/src/openvic-simulation/interface/GUI.cpp index 1e9dffbdf..5e699fc61 100644 --- a/src/openvic-simulation/interface/GUI.cpp +++ b/src/openvic-simulation/interface/GUI.cpp @@ -14,9 +14,7 @@ Position::Position() {} bool Position::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Named::_fill_key_map(key_map); - ret &= add_key_map_entry(key_map, - "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(position)) - ); + ret &= add_key_map_entry(key_map, "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(position))); return ret; } @@ -25,14 +23,13 @@ Element::Element() {} bool Element::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Named::_fill_key_map(key_map, ui_manager); using enum orientation_t; - static const string_map_t orientation_map = { - { "UPPER_LEFT", UPPER_LEFT }, { "LOWER_LEFT", LOWER_LEFT }, - { "LOWER_RIGHT", LOWER_RIGHT }, { "UPPER_RIGHT", UPPER_RIGHT }, - { "CENTER", CENTER }, { "CENTER_UP", CENTER_UP }, { "CENTER_DOWN", CENTER_DOWN } - }; - ret &= add_key_map_entries(key_map, - "position", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(position)), - "orientation", ZERO_OR_ONE, expect_identifier_or_string(expect_mapped_string( + static const string_map_t orientation_map = { { "UPPER_LEFT", UPPER_LEFT }, { "LOWER_LEFT", LOWER_LEFT }, + { "LOWER_RIGHT", LOWER_RIGHT }, { "UPPER_RIGHT", UPPER_RIGHT }, + { "CENTER", CENTER }, { "CENTER_UP", CENTER_UP }, + { "CENTER_DOWN", CENTER_DOWN } }; + ret &= add_key_map_entries( + key_map, "position", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(position)), "orientation", ZERO_OR_ONE, + expect_identifier_or_string(expect_mapped_string( orientation_map, assign_variable_callback(orientation), true /* Warn if the key here is invalid, leaving the default orientation UPPER_LEFT unchanged. */ )) @@ -41,32 +38,37 @@ bool Element::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIMa } bool Element::_fill_elements_key_map( - NodeTools::case_insensitive_key_map_t& key_map, callback_t&&> callback, UIManager const& ui_manager + NodeTools::case_insensitive_key_map_t& key_map, callback_t&&> callback, + UIManager const& ui_manager ) { bool ret = true; - ret &= add_key_map_entries(key_map, - "iconType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "shieldtype", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "guiButtonType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "checkboxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "textBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "instantTextBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "OverlappingElementsBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "listboxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "editBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "scrollbarType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "windowType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "eu3dialogtype", ZERO_OR_MORE, _expect_instance(callback, ui_manager) + ret &= add_key_map_entries( + key_map, "iconType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), "shieldtype", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "guiButtonType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "checkboxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "textBoxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "instantTextBoxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "OverlappingElementsBoxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "listboxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "editBoxType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "scrollbarType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "windowType", ZERO_OR_MORE, + _expect_instance(callback, ui_manager), "eu3dialogtype", ZERO_OR_MORE, + _expect_instance(callback, ui_manager) ); return ret; } bool Scene::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { - bool ret = Element::_fill_elements_key_map(key_map, [this](memory::unique_base_ptr&& element) -> bool { - return scene_elements.emplace_via_move(std::move(element)); - }, ui_manager); - ret &= add_key_map_entry(key_map, - "positionType", ZERO_OR_MORE, Position::_expect_value([this](Position&& position) -> bool { + bool ret = Element::_fill_elements_key_map( + key_map, + [this](memory::unique_base_ptr&& element) -> bool { + return scene_elements.emplace_via_move(std::move(element)); + }, + ui_manager + ); + ret &= add_key_map_entry( + key_map, "positionType", ZERO_OR_MORE, Position::_expect_value([this](Position&& position) -> bool { return scene_positions.emplace_via_move(std::move(position)); }) ); @@ -76,30 +78,35 @@ bool Scene::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIMana node_callback_t Scene::expect_scene( std::string_view scene_name, callback_t&&> callback, UIManager const& ui_manager ) { - return _expect_instance([scene_name, callback](memory::unique_base_ptr&& scene) mutable -> bool { - scene->_set_name(scene_name); - return callback(std::move(scene)); - }, ui_manager); + return _expect_instance( + [scene_name, callback](memory::unique_base_ptr&& scene) mutable -> bool { + scene->_set_name(scene_name); + return callback(std::move(scene)); + }, + ui_manager + ); } Window::Window() {} bool Window::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { - bool ret = Element::_fill_elements_key_map(key_map, [this](memory::unique_base_ptr&& element) -> bool { - return window_elements.emplace_via_move(std::move(element), duplicate_warning_callback); - }, ui_manager); + bool ret = Element::_fill_elements_key_map( + key_map, + [this](memory::unique_base_ptr&& element) -> bool { + return window_elements.emplace_via_move(std::move(element), duplicate_warning_callback); + }, + ui_manager + ); ret &= Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "moveable", ZERO_OR_ONE, expect_int_bool(assign_variable_callback(moveable)), - "fullScreen", ZERO_OR_ONE, expect_bool(assign_variable_callback(fullscreen)), - "backGround", ZERO_OR_ONE, expect_string(assign_variable_callback_string(background), true), + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), "moveable", ZERO_OR_ONE, + expect_int_bool(assign_variable_callback(moveable)), "fullScreen", ZERO_OR_ONE, + expect_bool(assign_variable_callback(fullscreen)), "backGround", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(background), true), "dontRender", ZERO_OR_ONE, success_callback, // always empty string? - "horizontalBorder", ZERO_OR_ONE, success_callback, - "verticalBorder", ZERO_OR_ONE, success_callback, - "upsound", ZERO_OR_ONE, success_callback, - "downsound", ZERO_OR_ONE, success_callback + "horizontalBorder", ZERO_OR_ONE, success_callback, "verticalBorder", ZERO_OR_ONE, success_callback, "upsound", + ZERO_OR_ONE, success_callback, "downsound", ZERO_OR_ONE, success_callback ); return ret; } @@ -108,14 +115,15 @@ Icon::Icon() {} bool Icon::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, + ret &= add_key_map_entries( + key_map, // TODO - make these share a ONE_EXACTLY count - "spriteType", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), - "buttonMesh", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), + "spriteType", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), "buttonMesh", + ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), - "frame", ZERO_OR_ONE, expect_uint(assign_variable_callback(frame)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)), - "rotation", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(rotation)) + "frame", ZERO_OR_ONE, expect_uint(assign_variable_callback(frame)), "scale", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)), "rotation", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(rotation)) ); return ret; } @@ -125,21 +133,19 @@ BaseButton::BaseButton() {} bool BaseButton::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); // look up sprite registry for texture sprite with name... - ret &= add_key_map_entries(key_map, + ret &= add_key_map_entries( + key_map, // TODO - make these share a ONE_EXACTLY count - "quadTextureSprite", ZERO_OR_ONE, - ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite), true), - "spriteType", ZERO_OR_ONE, - ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), + "quadTextureSprite", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite), true), + "spriteType", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), "buttonText", ZERO_OR_ONE, expect_string(assign_variable_callback_string(text), true), /* Some buttons have multiple fonts listed with the last one being used. */ - "buttonFont", ZERO_OR_MORE, ui_manager.expect_font_string(assign_variable_callback_pointer(font), true), - "shortcut", ZERO_OR_ONE, expect_string(assign_variable_callback_string(shortcut), true), + "buttonFont", ZERO_OR_MORE, ui_manager.expect_font_string(assign_variable_callback_pointer(font), true), "shortcut", + ZERO_OR_ONE, expect_string(assign_variable_callback_string(shortcut), true), - "tooltip", ZERO_OR_ONE, success_callback, - "tooltipText", ZERO_OR_ONE, success_callback, - "delayedTooltipText", ZERO_OR_ONE, success_callback + "tooltip", ZERO_OR_ONE, success_callback, "tooltipText", ZERO_OR_ONE, success_callback, "delayedTooltipText", + ZERO_OR_ONE, success_callback ); return ret; } @@ -148,12 +154,15 @@ Button::Button() {} bool Button::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = BaseButton::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(size)), - "rotation", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(rotation)), + ret &= add_key_map_entries( + key_map, "size", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(size)), "rotation", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(rotation)), "format", ZERO_OR_ONE, success_callback, /* Is always left from what I've seen. */ - "clicksound", ZERO_OR_ONE, ui_manager.definition_manager.get_sound_effect_manager().expect_sound_effect_identifier_or_string(assign_variable_callback_pointer(clicksound), true, true), + "clicksound", ZERO_OR_ONE, + ui_manager.definition_manager.get_sound_effect_manager().expect_sound_effect_identifier_or_string( + assign_variable_callback_pointer(clicksound), true, true + ), "parent", ZERO_OR_ONE, success_callback /* Links buttons to a scrollbar, not needed thanks to contextual info. */ ); return ret; @@ -168,9 +177,7 @@ AlignedElement::AlignedElement() {} bool AlignedElement::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "format", ZERO_OR_ONE, expect_text_format(assign_variable_callback(format)) - ); + ret &= add_key_map_entries(key_map, "format", ZERO_OR_ONE, expect_text_format(assign_variable_callback(format))); return ret; } @@ -178,16 +185,15 @@ Text::Text() {} bool Text::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = AlignedElement::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "text", ZERO_OR_ONE, expect_string(assign_variable_callback_string(text), true), - "font", ONE_EXACTLY, ui_manager.expect_font_string(assign_variable_callback_pointer(font)), - "maxWidth", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(max_size.x)), - "maxHeight", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(max_size.y)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(border_size)), - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file), true), - - "fixedsize", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, "text", ZERO_OR_ONE, expect_string(assign_variable_callback_string(text), true), "font", ONE_EXACTLY, + ui_manager.expect_font_string(assign_variable_callback_pointer(font)), "maxWidth", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(max_size.x)), "maxHeight", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(max_size.y)), "borderSize", ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(border_size)), "textureFile", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file), true), + + "fixedsize", ZERO_OR_ONE, success_callback, "allwaystransparent", ZERO_OR_ONE, success_callback ); return ret; } @@ -196,9 +202,9 @@ OverlappingElementsBox::OverlappingElementsBox() {} bool OverlappingElementsBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = AlignedElement::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "spacing", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spacing)) + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), "spacing", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spacing)) ); return ret; } @@ -207,17 +213,15 @@ ListBox::ListBox() {} bool ListBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "offset", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(scrollbar_offset)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(items_offset)), - "spacing", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(spacing)), - "scrollbartype", ZERO_OR_ONE, expect_string(assign_variable_callback_string(scrollbar_name)), - - "backGround", ZERO_OR_ONE, success_callback, - "horizontal", ZERO_OR_ONE, success_callback, - "priority", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), "offset", ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(scrollbar_offset)), "borderSize", ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(items_offset)), "spacing", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(spacing)), "scrollbartype", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(scrollbar_name)), + + "backGround", ZERO_OR_ONE, success_callback, "horizontal", ZERO_OR_ONE, success_callback, "priority", ZERO_OR_ONE, + success_callback, "allwaystransparent", ZERO_OR_ONE, success_callback ); return ret; } @@ -226,12 +230,12 @@ TextEditBox::TextEditBox() {} bool TextEditBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text), true), - "font", ONE_EXACTLY, ui_manager.expect_font_string(assign_variable_callback_pointer(font)), - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file), true), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "borderSize", ONE_EXACTLY, expect_fvec2(assign_variable_callback(border_size)) + ret &= add_key_map_entries( + key_map, "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text), true), "font", ONE_EXACTLY, + ui_manager.expect_font_string(assign_variable_callback_pointer(font)), "textureFile", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file), true), "size", ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), "borderSize", ONE_EXACTLY, + expect_fvec2(assign_variable_callback(border_size)) ); return ret; } @@ -245,26 +249,26 @@ bool Scrollbar::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UI const auto add_element = [this](memory::unique_base_ptr&& element) -> bool { return scrollbar_elements.emplace_via_move(std::move(element)); }; - ret &= add_key_map_entries(key_map, - "slider", ONE_EXACTLY, expect_string(assign_variable_callback_string(slider_button_name)), - "track", ONE_EXACTLY, expect_string(assign_variable_callback_string(track_button_name)), - "leftbutton", ONE_EXACTLY, expect_string(assign_variable_callback_string(less_button_name)), - "rightbutton", ONE_EXACTLY, expect_string(assign_variable_callback_string(more_button_name)), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(border_size)), - "minValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_value)), - "maxValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_value)), - "stepSize", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(step_size)), - "startValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(start_value)), - "horizontal", ONE_EXACTLY, expect_int_bool(assign_variable_callback(horizontal)), - "useRangeLimit", ZERO_OR_ONE, expect_bool(assign_variable_callback(range_limited)), - "rangeLimitMin", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(range_limit_min)), - "rangeLimitMax", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(range_limit_max)), - "rangeLimitMinIcon", ZERO_OR_ONE, expect_string(assign_variable_callback_string(range_limit_min_icon_name)), - "rangeLimitMaxIcon", ZERO_OR_ONE, expect_string(assign_variable_callback_string(range_limit_max_icon_name)), - - "guiButtonType", ONE_OR_MORE, _expect_instance(add_element, ui_manager), - "iconType", ZERO_OR_MORE, _expect_instance(add_element, ui_manager), + ret &= add_key_map_entries( + key_map, "slider", ONE_EXACTLY, expect_string(assign_variable_callback_string(slider_button_name)), "track", + ONE_EXACTLY, expect_string(assign_variable_callback_string(track_button_name)), "leftbutton", ONE_EXACTLY, + expect_string(assign_variable_callback_string(less_button_name)), "rightbutton", ONE_EXACTLY, + expect_string(assign_variable_callback_string(more_button_name)), "size", ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), "borderSize", ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(border_size)), "minValue", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(min_value)), "maxValue", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_value)), "stepSize", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(step_size)), "startValue", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(start_value)), "horizontal", ONE_EXACTLY, + expect_int_bool(assign_variable_callback(horizontal)), "useRangeLimit", ZERO_OR_ONE, + expect_bool(assign_variable_callback(range_limited)), "rangeLimitMin", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(range_limit_min)), "rangeLimitMax", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(range_limit_max)), "rangeLimitMinIcon", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(range_limit_min_icon_name)), "rangeLimitMaxIcon", ZERO_OR_ONE, + expect_string(assign_variable_callback_string(range_limit_max_icon_name)), + + "guiButtonType", ONE_OR_MORE, _expect_instance(add_element, ui_manager), "iconType", ZERO_OR_MORE, + _expect_instance(add_element, ui_manager), "priority", ZERO_OR_ONE, success_callback ); @@ -280,16 +284,13 @@ T const* Scrollbar::get_element(std::string_view name, std::string_view type) co return cast_element; } else { spdlog::error_s( - "GUI Scrollbar {} {} element {} has wrong type: {} (expected {})", - get_name(), type, name, element->get_type(), T::get_type_static() + "GUI Scrollbar {} {} element {} has wrong type: {} (expected {})", get_name(), type, name, element->get_type(), + T::get_type_static() ); return nullptr; } } else { - spdlog::error_s( - "GUI Scrollbar {} has no {} element named {}!", - get_name(), type, name - ); + spdlog::error_s("GUI Scrollbar {} has no {} element named {}!", get_name(), type, name); return nullptr; } } diff --git a/src/openvic-simulation/interface/GUI.hpp b/src/openvic-simulation/interface/GUI.hpp index 200912b0b..9126be5dd 100644 --- a/src/openvic-simulation/interface/GUI.hpp +++ b/src/openvic-simulation/interface/GUI.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/interface/GFXSprite.hpp" #include "openvic-simulation/core/ui/TextFormat.hpp" +#include "openvic-simulation/interface/GFXSprite.hpp" #include "openvic-simulation/misc/SoundEffect.hpp" namespace OpenVic { @@ -29,9 +29,7 @@ namespace OpenVic::GUI { friend class Scene; public: - enum class orientation_t { - UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT, UPPER_RIGHT, CENTER, CENTER_UP, CENTER_DOWN - }; + enum class orientation_t { UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT, UPPER_RIGHT, CENTER, CENTER_UP, CENTER_DOWN }; private: fvec2_t PROPERTY(position); @@ -71,9 +69,9 @@ namespace OpenVic::GUI { OV_DETAIL_GET_TYPE static NodeTools::node_callback_t expect_scene( - std::string_view scene_name, NodeTools::callback_t&&> callback, UIManager const& ui_manager + std::string_view scene_name, NodeTools::callback_t&&> callback, + UIManager const& ui_manager ); - }; class Window final : public Element { @@ -268,7 +266,7 @@ namespace OpenVic::GUI { fixed_point_t PROPERTY(start_value); bool PROPERTY_CUSTOM_PREFIX(horizontal, is, false) - bool PROPERTY_CUSTOM_PREFIX(range_limited, is, false); + bool PROPERTY_CUSTOM_PREFIX(range_limited, is, false); fixed_point_t PROPERTY(range_limit_min); fixed_point_t PROPERTY(range_limit_max); memory::string PROPERTY(range_limit_min_icon_name); diff --git a/src/openvic-simulation/interface/LoadBase.hpp b/src/openvic-simulation/interface/LoadBase.hpp index e787ef501..c5f3455e1 100644 --- a/src/openvic-simulation/interface/LoadBase.hpp +++ b/src/openvic-simulation/interface/LoadBase.hpp @@ -24,9 +24,7 @@ namespace OpenVic { } template> T> - static NodeTools::node_callback_t _expect_value( - NodeTools::callback_t callback, Context... context - ) { + static NodeTools::node_callback_t _expect_value(NodeTools::callback_t callback, Context... context) { return [callback, &context...](ast::NodeCPtr node) mutable -> bool { T value {}; bool ret = value.load(node, context...); @@ -36,9 +34,8 @@ namespace OpenVic { } template> T, std::derived_from U> - static NodeTools::node_callback_t _expect_instance( - NodeTools::callback_t&&> callback, Context... context - ) { + static NodeTools::node_callback_t + _expect_instance(NodeTools::callback_t&&> callback, Context... context) { return [callback, &context...](ast::NodeCPtr node) mutable -> bool { memory::unique_base_ptr instance { memory::make_unique() }; bool ret = instance->load(node, context...); diff --git a/src/openvic-simulation/interface/UI.cpp b/src/openvic-simulation/interface/UI.cpp index de6a29427..19b9030f2 100644 --- a/src/openvic-simulation/interface/UI.cpp +++ b/src/openvic-simulation/interface/UI.cpp @@ -21,10 +21,7 @@ bool UIManager::add_font( return false; } if (colour.alpha == colour_argb_t::colour_traits::null) { - spdlog::error_s( - "Invalid colour for font {} - completely transparent! ({})", - identifier, colour - ); + spdlog::error_s("Invalid colour for font {} - completely transparent! ({})", identifier, colour); return false; } if (fontname.empty()) { @@ -32,9 +29,7 @@ bool UIManager::add_font( return false; } const bool ret = fonts.emplace_item( - identifier, - duplicate_warning_callback, - identifier, colour, fontname, charset, height, std::move(colour_codes) + identifier, duplicate_warning_callback, identifier, colour, fontname, charset, height, std::move(colour_codes) ); if (universal_colour_codes.empty() && ret) { @@ -78,19 +73,13 @@ bool UIManager::_load_font(ast::NodeCPtr node) { } NodeCallback auto UIManager::_load_fonts(std::string_view font_key) { - return expect_dictionary_reserve_length( - fonts, - [this, font_key](std::string_view key, ast::NodeCPtr node) -> bool { - if (key != font_key) { - spdlog::error_s( - "Invalid key: \"{}\" (expected {})", - key, font_key - ); - return false; - } - return _load_font(node); + return expect_dictionary_reserve_length(fonts, [this, font_key](std::string_view key, ast::NodeCPtr node) -> bool { + if (key != font_key) { + spdlog::error_s("Invalid key: \"{}\" (expected {})", key, font_key); + return false; } - ); + return _load_font(node); + }); } void UIManager::lock_gfx_registries() { diff --git a/src/openvic-simulation/interface/UI.hpp b/src/openvic-simulation/interface/UI.hpp index 33a776427..91a5c95c7 100644 --- a/src/openvic-simulation/interface/UI.hpp +++ b/src/openvic-simulation/interface/UI.hpp @@ -13,7 +13,7 @@ namespace OpenVic { NamedBaseInstanceRegistry IDENTIFIER_REGISTRY(object); NamedBaseInstanceRegistry IDENTIFIER_REGISTRY(scene); - + bool _load_font(ast::NodeCPtr node); NodeTools::NodeCallback auto _load_fonts(std::string_view font_key); diff --git a/src/openvic-simulation/map/Crime.cpp b/src/openvic-simulation/map/Crime.cpp index 45375d9ff..6502d74db 100644 --- a/src/openvic-simulation/map/Crime.cpp +++ b/src/openvic-simulation/map/Crime.cpp @@ -7,15 +7,12 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Crime::Crime( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - icon_t new_icon, - ConditionScript&& new_trigger, - bool new_default_active -) : HasIndex { new_index }, - TriggeredModifier { new_identifier, std::move(new_values), modifier_type_t::CRIME, new_icon, std::move(new_trigger) }, - is_default_active { new_default_active } {} + index_t new_index, std::string_view new_identifier, ModifierValue&& new_values, icon_t new_icon, + ConditionScript&& new_trigger, bool new_default_active +) + : HasIndex { new_index }, + TriggeredModifier { new_identifier, std::move(new_values), modifier_type_t::CRIME, new_icon, std::move(new_trigger) }, + is_default_active { new_default_active } {} bool CrimeManager::add_crime_modifier( std::string_view identifier, ModifierValue&& values, IconModifier::icon_t icon, ConditionScript&& trigger, @@ -27,16 +24,14 @@ bool CrimeManager::add_crime_modifier( } return crime_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - Crime::index_t { get_crime_modifier_count() }, identifier, std::move(values), icon, std::move(trigger), default_active + identifier, duplicate_warning_callback, Crime::index_t { get_crime_modifier_count() }, identifier, std::move(values), + icon, std::move(trigger), default_active ); } bool CrimeManager::load_crime_modifiers(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - crime_modifiers, - [this, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { + const bool ret = + expect_dictionary_reserve_length(crime_modifiers, [this, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { using enum scope_type_t; ModifierValue modifier_value; @@ -54,8 +49,7 @@ bool CrimeManager::load_crime_modifiers(ModifierManager const& modifier_manager, ret &= add_crime_modifier(key, std::move(modifier_value), icon, std::move(trigger), default_active); return ret; - } - )(root); + })(root); lock_crime_modifiers(); diff --git a/src/openvic-simulation/map/Crime.hpp b/src/openvic-simulation/map/Crime.hpp index b4430feeb..7cd573167 100644 --- a/src/openvic-simulation/map/Crime.hpp +++ b/src/openvic-simulation/map/Crime.hpp @@ -9,16 +9,13 @@ namespace OpenVic { struct Crime final : HasIndex, TriggeredModifier { friend struct CrimeManager; + public: bool is_default_active; Crime( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - icon_t new_icon, - ConditionScript&& new_trigger, - bool new_default_active + index_t new_index, std::string_view new_identifier, ModifierValue&& new_values, icon_t new_icon, + ConditionScript&& new_trigger, bool new_default_active ); Crime(Crime&&) = default; }; diff --git a/src/openvic-simulation/map/MapDefinition.cpp b/src/openvic-simulation/map/MapDefinition.cpp index a50ae778b..54fcf7a5d 100644 --- a/src/openvic-simulation/map/MapDefinition.cpp +++ b/src/openvic-simulation/map/MapDefinition.cpp @@ -1,9 +1,9 @@ #include "MapDefinition.hpp" +#include #include #include #include -#include #include #include #include @@ -17,7 +17,10 @@ #include +#include "openvic-simulation/core/FormatValidate.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/io/BMP.hpp" +#include "openvic-simulation/core/string/CharConv.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" @@ -25,11 +28,8 @@ #include "openvic-simulation/types/OrderedContainersMath.hpp" #include "openvic-simulation/types/TypedSpan.hpp" #include "openvic-simulation/types/Vector.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" -#include "openvic-simulation/utility/Logger.hpp" -#include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Logger.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -37,12 +37,12 @@ using namespace OpenVic::NodeTools; MapDefinition::MapDefinition() {} ProvinceDefinition* MapDefinition::get_province_definition_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) { return province_definitions.get_item_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } ProvinceDefinition const* MapDefinition::get_province_definition_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const { return province_definitions.get_item_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } @@ -50,14 +50,14 @@ ProvinceDefinition const* MapDefinition::get_province_definition_from_number( RiverSegment::RiverSegment(uint8_t new_size, memory::vector&& new_points) : size { new_size }, points { std::move(new_points) } {} -//1 entry reserved for null province +// 1 entry reserved for null province static constexpr province_index_t MAX_PROVINCE_COUNT = std::numeric_limits().max() - 1; bool MapDefinition::add_province_definition(std::string_view identifier, colour_t colour) { if (province_definitions.size() >= type_safe::get(max_provinces)) { spdlog::error_s( - "The map's province list is full - maximum number of provinces is {} (this can be at most {})", - max_provinces, MAX_PROVINCE_COUNT + "The map's province list is full - maximum number of provinces is {} (this can be at most {})", max_provinces, + MAX_PROVINCE_COUNT ); return false; } @@ -66,10 +66,10 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ return false; } // Victoria 2 CTDs on non-numeric province numbers - if (!ranges::all_of(identifier, [](char c) -> bool { return std::isdigit(c); })) { - spdlog::error_s( - "Invalid province identifier: {} (can only contain numeric characters)", identifier - ); + if (!ranges::all_of(identifier, [](char c) -> bool { + return std::isdigit(c); + })) { + spdlog::error_s("Invalid province identifier: {} (can only contain numeric characters)", identifier); return false; } if (colour.is_null()) { @@ -79,16 +79,13 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ const ProvinceDefinition::province_number_t province_number = get_province_number_from_colour(colour); if (province_number != ProvinceDefinition::NULL_PROVINCE_NUMBER) { spdlog::error_s( - "Duplicate province colours: {} and {}", - get_province_definition_from_number(province_number)->to_string(), identifier + "Duplicate province colours: {} and {}", get_province_definition_from_number(province_number)->to_string(), + identifier ); return false; } - if (!province_definitions.emplace_item( - identifier, - identifier, colour, province_index_t(get_province_definition_count()) - )) { + if (!province_definitions.emplace_item(identifier, identifier, colour, province_index_t(get_province_definition_count()))) { return false; } @@ -97,18 +94,14 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ return true; } -ProvinceDefinition::distance_t MapDefinition::calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to -) const { +ProvinceDefinition::distance_t +MapDefinition::calculate_distance_between(ProvinceDefinition const& from, ProvinceDefinition const& to) const { const fvec2_t to_pos = to.get_unit_position(); const fvec2_t from_pos = from.get_unit_position(); const fixed_point_t min_x = std::min( (to_pos.x - from_pos.x).abs(), - std::min( - (to_pos.x - from_pos.x + get_width()).abs(), - (to_pos.x - from_pos.x - get_width()).abs() - ) + std::min((to_pos.x - from_pos.x + get_width()).abs(), (to_pos.x - from_pos.x - get_width()).abs()) ); return fvec2_t { min_x, to_pos.y - from_pos.y }.length_squared().sqrt(); @@ -198,10 +191,7 @@ bool MapDefinition::add_special_adjacency( adjacency_t::data_t data ) { if (from == to) { - spdlog::error_s( - "Trying to add {} adjacency from province {} to itself!", - adjacency_t::get_type_name(type), from - ); + spdlog::error_s("Trying to add {} adjacency from province {} to itself!", adjacency_t::get_type_name(type), from); return false; } @@ -212,20 +202,14 @@ bool MapDefinition::add_special_adjacency( case LAND: case STRAIT: if (from.is_water() || to.is_water()) { - spdlog::error_s( - "{} adjacency from {} to {} has water endpoint(s)!", - adjacency_t::get_type_name(type), from, to - ); + spdlog::error_s("{} adjacency from {} to {} has water endpoint(s)!", adjacency_t::get_type_name(type), from, to); return false; } break; case WATER: case CANAL: if (!from.is_water() || !to.is_water()) { - spdlog::error_s( - "{} adjacency from {} to {} has land endpoint(s)!", - adjacency_t::get_type_name(type), from, to - ); + spdlog::error_s("{} adjacency from {} to {} has land endpoint(s)!", adjacency_t::get_type_name(type), from, to); return false; } break; @@ -241,9 +225,7 @@ bool MapDefinition::add_special_adjacency( * - land-water = delete existing coastal adjacency, preventing armies and navies from moving between the provinces * - water-water = delete existing water adjacency, preventing navies from moving between the provinces */ break; - default: - spdlog::error_s("Invalid adjacency type {}", static_cast(type)); - return false; + default: spdlog::error_s("Invalid adjacency type {}", static_cast(type)); return false; } /* Check through province */ @@ -251,19 +233,15 @@ bool MapDefinition::add_special_adjacency( const bool water_expected = type == STRAIT; if (through == nullptr || through->is_water() != water_expected) { spdlog::error_s( - "{} adjacency from {} to {} has a {} through province {}", - adjacency_t::get_type_name(type), - from, - to, - through == nullptr ? "null" : (water_expected ? "land" : "water"), - ovfmt::validate(through) + "{} adjacency from {} to {} has a {} through province {}", adjacency_t::get_type_name(type), from, to, + through == nullptr ? "null" : (water_expected ? "land" : "water"), ovfmt::validate(through) ); return false; } } else if (through != nullptr) { spdlog::warn_s( - "{} adjacency from {} to {} has a non-null through province {}", - adjacency_t::get_type_name(type), from, to, *through + "{} adjacency from {} to {} has a non-null through province {}", adjacency_t::get_type_name(type), from, to, + *through ); through = nullptr; } @@ -271,27 +249,23 @@ bool MapDefinition::add_special_adjacency( /* Check canal data */ if (data != adjacency_t::DEFAULT_DATA && type != CANAL) { spdlog::warn_s( - "{} adjacency from {} to {} has invalid data {}", - adjacency_t::get_type_name(type), from, to, static_cast(data) + "{} adjacency from {} to {} has invalid data {}", adjacency_t::get_type_name(type), from, to, + static_cast(data) ); data = adjacency_t::DEFAULT_DATA; } const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); - const auto add_adjacency = [this, distance, type, through, data]( - ProvinceDefinition& from, ProvinceDefinition const& to - ) -> bool { - const memory::vector::iterator existing_adjacency = std::find_if( - from.adjacencies.begin(), from.adjacencies.end(), - [&to](adjacency_t const& adj) -> bool { return adj.get_to() == to; } - ); + const auto add_adjacency = [this, distance, type, through, + data](ProvinceDefinition& from, ProvinceDefinition const& to) -> bool { + const memory::vector::iterator existing_adjacency = + std::find_if(from.adjacencies.begin(), from.adjacencies.end(), [&to](adjacency_t const& adj) -> bool { + return adj.get_to() == to; + }); if (existing_adjacency != from.adjacencies.end()) { if (type == existing_adjacency->get_type()) { - spdlog::warn_s( - "Adjacency from {} to {} already has type {}!", - from, to, adjacency_t::get_type_name(type) - ); + spdlog::warn_s("Adjacency from {} to {} already has type {}!", from, to, adjacency_t::get_type_name(type)); if (type != STRAIT && type != CANAL) { /* Straits and canals might change through or data, otherwise we can exit early */ return true; @@ -305,14 +279,13 @@ bool MapDefinition::add_special_adjacency( } else { if (type != STRAIT && type != CANAL) { spdlog::error_s( - "Provinces {} and {} already have an existing {} adjacency, cannot create a {} adjacency!", - from, to, adjacency_t::get_type_name(existing_adjacency->get_type()), adjacency_t::get_type_name(type) + "Provinces {} and {} already have an existing {} adjacency, cannot create a {} adjacency!", from, to, + adjacency_t::get_type_name(existing_adjacency->get_type()), adjacency_t::get_type_name(type) ); return false; } - if ( - type != existing_adjacency->get_type() && existing_adjacency->get_type() != (type == CANAL ? WATER : LAND) - ) { + if (type != existing_adjacency->get_type() && + existing_adjacency->get_type() != (type == CANAL ? WATER : LAND)) { spdlog::error_s( "Cannot convert {} adjacency from {} to {} to type {}!", adjacency_t::get_type_name(existing_adjacency->get_type()), from, to, adjacency_t::get_type_name(type) @@ -337,10 +310,7 @@ bool MapDefinition::add_special_adjacency( } return true; } else if (type == IMPASSABLE) { - spdlog::warn_s( - "Provinces {} and {} do not have an existing adjacency to make impassable!", - from, to - ); + spdlog::warn_s("Provinces {} and {} do not have an existing adjacency to make impassable!", from, to); return true; } else { from.adjacencies.emplace_back(to, distance, type, through, data); @@ -388,8 +358,7 @@ bool MapDefinition::set_water_province(std::string_view identifier) { } province.water = true; path_map_sea.try_add_point( - province.get_province_number(), - path_map_land.get_point_position(province.get_province_number()) + province.get_province_number(), path_map_land.get_point_position(province.get_province_number()) ); return true; } @@ -422,9 +391,7 @@ size_t MapDefinition::get_water_province_count() const { } bool MapDefinition::add_region( - std::string_view identifier, - memory::vector>&& provinces, - colour_t colour + std::string_view identifier, memory::vector>&& provinces, colour_t colour ) { if (identifier.empty()) { spdlog::error_s("Invalid region identifier - empty!"); @@ -440,9 +407,7 @@ bool MapDefinition::add_region( if (OV_unlikely(province_definition.has_region())) { spdlog::warn_s( "Province {} is assigned to multiple regions, including {} and {}. First defined region wins.", - province_definition, - *province_definition.get_region(), - identifier + province_definition, *province_definition.get_region(), identifier ); valid_provinces_count--; } @@ -450,10 +415,7 @@ bool MapDefinition::add_region( is_meta |= province_definition.is_water(); } - if (!regions.emplace_item( - identifier, - identifier, colour, is_meta - )) { + if (!regions.emplace_item(identifier, identifier, colour, is_meta)) { return false; } @@ -506,17 +468,12 @@ ProvinceDefinition const* MapDefinition::get_province_definition_at(ivec2_t pos) bool MapDefinition::set_max_provinces(province_index_t new_max_provinces) { if (new_max_provinces <= province_index_t(0)) { - spdlog::error_s( - "Trying to set max province count to an invalid value {} (must be greater than 0)", - new_max_provinces - ); + spdlog::error_s("Trying to set max province count to an invalid value {} (must be greater than 0)", new_max_provinces); return false; } if (new_max_provinces > MAX_PROVINCE_COUNT) { spdlog::error_s( - "Trying to set max province count to an invalid value {} (must <= {})", - new_max_provinces, - MAX_PROVINCE_COUNT + "Trying to set max province count to an invalid value {} (must <= {})", new_max_provinces, MAX_PROVINCE_COUNT ); return false; } @@ -558,7 +515,7 @@ static bool _parse_province_colour(colour_t& colour, std::array lines) LineObject const& header = lines.front(); if (!_validate_province_definitions_header(header)) { spdlog::error_s( - "Non-standard province definition file header - make sure this is not a province definition: {}", - header + "Non-standard province definition file header - make sure this is not a province definition: {}", header ); } @@ -594,11 +550,10 @@ bool MapDefinition::load_province_definitions(std::span lines) const std::string_view identifier = line.get_value_for(0); if (!identifier.empty()) { colour_t colour = colour_t::null(); - if (!_parse_province_colour(colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) })) { - spdlog::error_s( - "Error reading colour in province definition: {}", - line - ); + if (!_parse_province_colour( + colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) } + )) { + spdlog::error_s("Error reading colour in province definition: {}", line); ret = false; } ret &= add_province_definition(identifier, colour); @@ -607,7 +562,9 @@ bool MapDefinition::load_province_definitions(std::span lines) } ProvinceDefinition const& definition = province_definitions.back(); - ret &= path_map_land.try_add_point(definition.get_province_number(), { definition.centre.x.round(), definition.centre.y.round() }); + ret &= path_map_land.try_add_point( + definition.get_province_number(), { definition.centre.x.round(), definition.centre.y.round() } + ); if (!ret) { spdlog::error_s("Province {} could not be added to " _OV_STR(path_map_land), identifier); } @@ -624,40 +581,35 @@ bool MapDefinition::load_province_definitions(std::span lines) } bool MapDefinition::load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root) { - return expect_province_definition_dictionary( - [this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { - return province.load_positions(*this, building_type_manager, node); - } - )(root); + return expect_province_definition_dictionary([this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { + return province.load_positions(*this, building_type_manager, node); + })(root); } bool MapDefinition::load_region_colours(ast::NodeCPtr root, memory::vector& colours) { - return expect_dictionary_reserve_length( - colours, - [&colours](std::string_view key, ast::NodeCPtr value) -> bool { - if (key != "color") { - spdlog::error_s("Invalid key in region colours: \"{}\"", key); - return false; - } - return expect_colour(vector_callback(colours))(value); + return expect_dictionary_reserve_length(colours, [&colours](std::string_view key, ast::NodeCPtr value) -> bool { + if (key != "color") { + spdlog::error_s("Invalid key in region colours: \"{}\"", key); + return false; + } + return expect_colour(vector_callback(colours))(value); })(root); } bool MapDefinition::load_region_file(ast::NodeCPtr root, std::span colours) { - const bool ret = expect_dictionary_reserve_length( - regions, - [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { + const bool ret = + expect_dictionary_reserve_length(regions, [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { memory::vector> provinces; - bool ret = expect_list_reserve_length( - provinces, expect_province_definition_identifier(vector_emplace_callback(provinces)) - )(region_node); + bool ret = + expect_list_reserve_length(provinces, expect_province_definition_identifier(vector_emplace_callback(provinces)))( + region_node + ); ret &= add_region(region_identifier, std::move(provinces), colours[regions.size() % colours.size()]); return ret; - } - )(root); + })(root); lock_regions(); @@ -701,15 +653,17 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) thread_local memory::vector points; points.emplace_back(segment.point); - uint8_t size = river_data[segment.point.x + segment.point.y * rivers_bmp.get_width()] - 1; // determine river size by colour + uint8_t size = + river_data[segment.point.x + segment.point.y * rivers_bmp.get_width()] - 1; // determine river size by colour bool river_complete = false; size_t recursion_limit = 0; - while(true) { + while (true) { ++recursion_limit; if (recursion_limit == RIVER_RECURSION_LIMIT) { spdlog::error_s( - "River segment starting @ ({}, {}) exceeded length limit of 4096 pixels. Check for misplaced pixel or circular river.", + "River segment starting @ ({}, {}) exceeded length limit of 4096 pixels. Check for misplaced pixel or " + "circular river.", points.front().x, points.front().y ); break; @@ -729,12 +683,12 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) direction_t old_direction; direction_t new_direction; }; - static constexpr std::array neighbours = {{ - { {0, -1}, UP, DOWN }, // Down - { {1, 0}, LEFT, RIGHT }, // Right - { {0, 1}, DOWN, UP }, // Up - { {-1, 0}, RIGHT, LEFT }, // Left - }}; + static constexpr std::array neighbours = { { + { { 0, -1 }, UP, DOWN }, // Down + { { 1, 0 }, LEFT, RIGHT }, // Right + { { 0, 1 }, DOWN, UP }, // Up + { { -1, 0 }, RIGHT, LEFT }, // Left + } }; for (const auto& neighbour : neighbours) { ivec2_t neighbour_pos = { segment.point.x + neighbour.offset.x, segment.point.y + neighbour.offset.y }; @@ -778,7 +732,8 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) // simplify points to only include first, last, and corners const auto is_corner_point = [](ivec2_t previous, ivec2_t current, ivec2_t next) -> bool { - return ((current.x - previous.x) * (next.y - current.y)) != ((current.y - previous.y) * (next.x - current.x)); //slope is fun! + return ((current.x - previous.x) * (next.y - current.y)) != + ((current.y - previous.y) * (next.x - current.x)); // slope is fun! }; memory::vector simplified_points; simplified_points.emplace_back(points.front()); @@ -795,7 +750,9 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) } } -bool MapDefinition::load_map_images(fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors) { +bool MapDefinition::load_map_images( + fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors +) { if (!province_definitions_are_locked()) { spdlog::error_s("Province index image cannot be generated until after provinces are locked!"); return false; @@ -815,8 +772,7 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (province_bmp.get_bits_per_pixel() != expected_province_bpp) { spdlog::error_s( - "Invalid province BMP bits per pixel: {} (expected {})", - province_bmp.get_bits_per_pixel(), expected_province_bpp + "Invalid province BMP bits per pixel: {} (expected {})", province_bmp.get_bits_per_pixel(), expected_province_bpp ); return false; } @@ -828,8 +784,8 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (terrain_bmp.get_bits_per_pixel() != expected_terrain_rivers_bpp) { spdlog::error_s( - "Invalid terrain BMP bits per pixel: {} (expected {})", - terrain_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp + "Invalid terrain BMP bits per pixel: {} (expected {})", terrain_bmp.get_bits_per_pixel(), + expected_terrain_rivers_bpp ); return false; } @@ -841,22 +797,17 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (rivers_bmp.get_bits_per_pixel() != expected_terrain_rivers_bpp) { spdlog::error_s( - "Invalid rivers BMP bits per pixel: {} (expected {})", - rivers_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp + "Invalid rivers BMP bits per pixel: {} (expected {})", rivers_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp ); return false; } - if (province_bmp.get_width() != terrain_bmp.get_width() || - province_bmp.get_height() != terrain_bmp.get_height() || - province_bmp.get_width() != rivers_bmp.get_width() || - province_bmp.get_height() != rivers_bmp.get_height() - ) { + if (province_bmp.get_width() != terrain_bmp.get_width() || province_bmp.get_height() != terrain_bmp.get_height() || + province_bmp.get_width() != rivers_bmp.get_width() || province_bmp.get_height() != rivers_bmp.get_height()) { spdlog::error_s( - "Mismatched map BMP dims: provinces:{}x{}, terrain: {}x{}, rivers: {}x{}", - province_bmp.get_width(), province_bmp.get_height(), - terrain_bmp.get_width(), terrain_bmp.get_height(), - rivers_bmp.get_width(), rivers_bmp.get_height() + "Mismatched map BMP dims: provinces:{}x{}, terrain: {}x{}, rivers: {}x{}", province_bmp.get_width(), + province_bmp.get_height(), terrain_bmp.get_width(), terrain_bmp.get_height(), rivers_bmp.get_width(), + rivers_bmp.get_height() ); return false; } @@ -869,23 +820,22 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons uint8_t const* terrain_data = terrain_bmp.get_pixel_data().data(); memory::FixedVector> _terrain_type_pixels_list( - province_definitions.size(), - [](const size_t i) { return fixed_point_map_t{}; } + province_definitions.size(), [](const size_t i) { + return fixed_point_map_t {}; + } ); TypedSpan> terrain_type_pixels_list { _terrain_type_pixels_list }; bool ret = true; ordered_set unrecognised_province_colours; - memory::FixedVector _pixels_per_province( - province_definitions.size(), - [](const size_t i) { return fixed_point_t::_0; } - ); + memory::FixedVector _pixels_per_province(province_definitions.size(), [](const size_t i) { + return fixed_point_t::_0; + }); TypedSpan pixels_per_province { _pixels_per_province }; - memory::FixedVector _pixel_position_sum_per_province( - province_definitions.size(), - [](const size_t i) { return fvec2_t{}; } - ); + memory::FixedVector _pixel_position_sum_per_province(province_definitions.size(), [](const size_t i) { + return fvec2_t {}; + }); TypedSpan pixel_position_sum_per_province { _pixel_position_sum_per_province }; for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { @@ -912,13 +862,11 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons province_number = get_province_number_from_colour(province_colour); - if (province_number == ProvinceDefinition::NULL_PROVINCE_NUMBER && !unrecognised_province_colours.contains(province_colour)) { + if (province_number == ProvinceDefinition::NULL_PROVINCE_NUMBER && + !unrecognised_province_colours.contains(province_colour)) { unrecognised_province_colours.insert(province_colour); if (detailed_errors) { - spdlog::warn_s( - "Unrecognised province colour {} at {}", - province_colour, pos - ); + spdlog::warn_s("Unrecognised province colour {} at {}", province_colour, pos); } } @@ -1088,7 +1036,7 @@ bool MapDefinition::generate_and_load_province_adjacencies(std::span std::numeric_limits::max()) { spdlog::error_s("Invalid adjacency data: \"{}\"", data_str); ret = false; @@ -1106,54 +1054,41 @@ bool MapDefinition::generate_and_load_province_adjacencies(std::span bool { - if (identifier.empty()) { - spdlog::error_s("Invalid climate identifier - empty!"); - return false; - } + bool ret = expect_dictionary_reserve_length(climates, [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + if (identifier.empty()) { + spdlog::error_s("Invalid climate identifier - empty!"); + return false; + } - bool ret = true; - Climate* cur_climate = climates.get_item_by_identifier(identifier); - if (cur_climate == nullptr) { - ModifierValue values; + bool ret = true; + Climate* cur_climate = climates.get_item_by_identifier(identifier); + if (cur_climate == nullptr) { + ModifierValue values; - ret &= NodeTools::expect_dictionary( - modifier_manager.expect_base_province_modifier(values) - )(node); + ret &= NodeTools::expect_dictionary(modifier_manager.expect_base_province_modifier(values))(node); - ret &= climates.emplace_item( - identifier, - identifier, std::move(values), Modifier::modifier_type_t::CLIMATE - ); - } else { - ret &= expect_list_reserve_length(*cur_climate, expect_province_definition_identifier( - [this, cur_climate, &identifier](ProvinceDefinition& province) { - if (province.climate != cur_climate) { - cur_climate->add_province(province); - if (province.climate != nullptr) { - Climate* old_climate = climates.get_item_by_identifier(province.climate->get_identifier()); - old_climate->remove_province(province); - spdlog::warn_s( - "Province with id {} found in multiple climates: {} and {}", - province, identifier, *old_climate - ); - } - province.climate = cur_climate; - } else { + ret &= climates.emplace_item(identifier, identifier, std::move(values), Modifier::modifier_type_t::CLIMATE); + } else { + ret &= + expect_list_reserve_length(*cur_climate, expect_province_definition_identifier([this, cur_climate, &identifier](ProvinceDefinition& province) { + if (province.climate != cur_climate) { + cur_climate->add_province(province); + if (province.climate != nullptr) { + Climate* old_climate = climates.get_item_by_identifier(province.climate->get_identifier()); + old_climate->remove_province(province); spdlog::warn_s( - "Province with id {} defined twice in climate {}", - province, identifier + "Province with id {} found in multiple climates: {} and {}", province, identifier, *old_climate ); } - return true; + province.climate = cur_climate; + } else { + spdlog::warn_s("Province with id {} defined twice in climate {}", province, identifier); } - ))(node); - } - return ret; + return true; + }))(node); } - )(root); + return ret; + })(root); for (Climate& climate : climates.get_items()) { climate.lock(); @@ -1165,10 +1100,8 @@ bool MapDefinition::load_climate_file(ModifierManager const& modifier_manager, a } bool MapDefinition::load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - bool ret = expect_dictionary_reserve_length( - continents, - [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { - + bool ret = + expect_dictionary_reserve_length(continents, [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { if (identifier.empty()) { spdlog::error_s("Invalid continent identifier - empty!"); return false; @@ -1176,24 +1109,21 @@ bool MapDefinition::load_continent_file(ModifierManager const& modifier_manager, ModifierValue values; memory::vector> prov_list; + auto prov_list_emplace_func = [&prov_list](ProvinceDefinition const& province) -> bool { + if (province.continent == nullptr) { + prov_list.emplace_back(province); + } else { + spdlog::warn_s("Province {} found in multiple continents", province); + } + return true; + }; + bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_base_province_modifier(values), - "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier( - [&prov_list](ProvinceDefinition const& province) -> bool { - if (province.continent == nullptr) { - prov_list.emplace_back(province); - } else { - spdlog::warn_s("Province {} found in multiple continents", province); - } - return true; - } - )) + modifier_manager.expect_base_province_modifier(values), // + "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier(prov_list_emplace_func)) )(node); - if (!continents.emplace_item( - identifier, - identifier, std::move(values), Modifier::modifier_type_t::CONTINENT - )) { + if (!continents.emplace_item(identifier, identifier, std::move(values), Modifier::modifier_type_t::CONTINENT)) { return false; } @@ -1206,8 +1136,7 @@ bool MapDefinition::load_continent_file(ModifierManager const& modifier_manager, } return ret; - } - )(root); + })(root); lock_continents(); diff --git a/src/openvic-simulation/map/MapDefinition.hpp b/src/openvic-simulation/map/MapDefinition.hpp index c52099ac4..8dc94da27 100644 --- a/src/openvic-simulation/map/MapDefinition.hpp +++ b/src/openvic-simulation/map/MapDefinition.hpp @@ -78,25 +78,25 @@ namespace OpenVic { } IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(province_definition); - ProvinceDefinition* get_province_definition_from_number( - const ProvinceDefinition::province_number_t province_number - ); + ProvinceDefinition* get_province_definition_from_number(const ProvinceDefinition::province_number_t province_number); public: MapDefinition(); - ProvinceDefinition const* get_province_definition_from_number( - const ProvinceDefinition::province_number_t province_number - ) const; + ProvinceDefinition const* + get_province_definition_from_number(const ProvinceDefinition::province_number_t province_number) const; - inline constexpr int32_t get_width() const { return dims.x; } - inline constexpr int32_t get_height() const { return dims.y; } + inline constexpr int32_t get_width() const { + return dims.x; + } + inline constexpr int32_t get_height() const { + return dims.y; + } bool add_province_definition(std::string_view identifier, colour_t colour); - ProvinceDefinition::distance_t calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to - ) const; + ProvinceDefinition::distance_t + calculate_distance_between(ProvinceDefinition const& from, ProvinceDefinition const& to) const; bool add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to); bool add_special_adjacency( ProvinceDefinition& from, ProvinceDefinition& to, ProvinceDefinition::adjacency_t::type_t type, @@ -116,9 +116,9 @@ namespace OpenVic { ProvinceDefinition* get_province_definition_at(ivec2_t pos); /* This provides a safe way to remove the const qualifier of a ProvinceDefinition const&, via a non-const Map. - * It looks up the ProvinceDefinition& using the ProvinceDefinition const&'s index. Requiring a non-const Map ensures that this - * function can only be used where the ProvinceDefinition& could already be accessed by other means, such as the - * index method, preventing misleading code, or in the worst case undefined behaviour. */ + * It looks up the ProvinceDefinition& using the ProvinceDefinition const&'s index. Requiring a non-const Map ensures + * that this function can only be used where the ProvinceDefinition& could already be accessed by other means, such as + * the index method, preventing misleading code, or in the worst case undefined behaviour. */ constexpr ProvinceDefinition& get_mutable_province_definition(ProvinceDefinition const& province) { return *province_definitions.get_item_by_index(province.index); } @@ -128,8 +128,7 @@ namespace OpenVic { bool set_max_provinces(ProvinceDefinition::index_t new_max_provinces); bool add_region( - std::string_view identifier, - memory::vector>&& provinces, + std::string_view identifier, memory::vector>&& provinces, colour_t colour ); @@ -138,7 +137,9 @@ namespace OpenVic { bool load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root); static bool load_region_colours(ast::NodeCPtr root, memory::vector& colours); bool load_region_file(ast::NodeCPtr root, std::span colours); - bool load_map_images(fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors); + bool load_map_images( + fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors + ); bool generate_and_load_province_adjacencies(std::span additional_adjacencies); bool load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); bool load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/map/MapInstance.cpp b/src/openvic-simulation/map/MapInstance.cpp index 4b864e85b..6b79fe8ad 100644 --- a/src/openvic-simulation/map/MapInstance.cpp +++ b/src/openvic-simulation/map/MapInstance.cpp @@ -13,46 +13,32 @@ using namespace OpenVic; MapInstance::MapInstance( - MapDefinition const& new_map_definition, - ProvinceInstanceDeps const& province_instance_deps, - ThreadPool& new_thread_pool -) : map_definition { new_map_definition }, - thread_pool { new_thread_pool }, - land_pathing { new_map_definition, *this }, - sea_pathing { new_map_definition, *this }, - province_instance_by_definition( - new_map_definition.get_province_definitions(), - [&province_instance_deps]( - ProvinceDefinition const& province_definition - ) -> auto { - return std::make_tuple( - std::ref(province_definition), - std::ref(province_instance_deps) - ); - } - ) { assert(new_map_definition.province_definitions_are_locked()); } + MapDefinition const& new_map_definition, ProvinceInstanceDeps const& province_instance_deps, ThreadPool& new_thread_pool +) + : map_definition { new_map_definition }, thread_pool { new_thread_pool }, land_pathing { new_map_definition, *this }, + sea_pathing { new_map_definition, *this }, + province_instance_by_definition( + new_map_definition.get_province_definitions(), + [&province_instance_deps](ProvinceDefinition const& province_definition) -> auto { + return std::make_tuple(std::ref(province_definition), std::ref(province_instance_deps)); + } + ) { + assert(new_map_definition.province_definitions_are_locked()); +} ProvinceInstance* MapInstance::get_province_instance_by_identifier(std::string_view identifier) { ProvinceDefinition const* province_definition = map_definition.get_province_definition_by_identifier(identifier); - return province_definition == nullptr - ? nullptr - : &get_province_instance_by_definition(*province_definition); + return province_definition == nullptr ? nullptr : &get_province_instance_by_definition(*province_definition); } ProvinceInstance const* MapInstance::get_province_instance_by_identifier(std::string_view identifier) const { ProvinceDefinition const* province_definition = map_definition.get_province_definition_by_identifier(identifier); - return province_definition == nullptr - ? nullptr - : &get_province_instance_by_definition(*province_definition); + return province_definition == nullptr ? nullptr : &get_province_instance_by_definition(*province_definition); } ProvinceInstance* MapInstance::get_province_instance_by_index(typename ProvinceInstance::index_t index) { - return province_instance_by_definition.contains_index(index) - ? &province_instance_by_definition.at_index(index) - : nullptr; + return province_instance_by_definition.contains_index(index) ? &province_instance_by_definition.at_index(index) : nullptr; } ProvinceInstance const* MapInstance::get_province_instance_by_index(typename ProvinceInstance::index_t index) const { - return province_instance_by_definition.contains_index(index) - ? &province_instance_by_definition.at_index(index) - : nullptr; + return province_instance_by_definition.contains_index(index) ? &province_instance_by_definition.at_index(index) : nullptr; } ProvinceInstance& MapInstance::get_province_instance_by_definition(ProvinceDefinition const& province_definition) { return province_instance_by_definition.at(province_definition); @@ -62,12 +48,12 @@ ProvinceInstance const& MapInstance::get_province_instance_by_definition(Provinc } ProvinceInstance* MapInstance::get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) { return get_province_instance_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } ProvinceInstance const* MapInstance::get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const { return get_province_instance_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } @@ -81,12 +67,8 @@ bool MapInstance::is_canal_enabled(canal_index_t canal_index) const { } bool MapInstance::apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, - const Date date, - CountryInstanceManager& country_manager, - IssueManager const& issue_manager, - MilitaryDefines const& military_defines, - PopDeps const& pop_deps + ProvinceHistoryManager const& history_manager, const Date date, CountryInstanceManager& country_manager, + IssueManager const& issue_manager, MilitaryDefines const& military_defines, PopDeps const& pop_deps ) { bool ret = true; @@ -121,13 +103,10 @@ bool MapInstance::apply_history_to_provinces( if (pop_history_entry == nullptr) { spdlog::warn_s("No pop history entry for province {} for date {}", province, date); } else { - ret &= province.add_pop_vec( - pop_history_entry->get_pops(), - pop_deps - ); + ret &= province.add_pop_vec(pop_history_entry->get_pops(), pop_deps); province.setup_pop_test_values(issue_manager); - //update pops so OOB can use up to date max_supported_regiments + // update pops so OOB can use up to date max_supported_regiments province._update_pops(military_defines); } @@ -165,12 +144,12 @@ void MapInstance::update_gamestate(InstanceManager const& instance_manager) { void MapInstance::map_tick() { thread_pool.process_province_ticks(); - //state tick - //after province tick as province tick sets pop employment to 0 - //state tick will update pop employment via factories + // state tick + // after province tick as province tick sets pop employment to 0 + // state tick will update pop employment via factories } void MapInstance::initialise_for_new_game(InstanceManager const& instance_manager) { update_gamestate(instance_manager); thread_pool.process_province_initialise_for_new_game(); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/MapInstance.hpp b/src/openvic-simulation/map/MapInstance.hpp index 4fc8b1446..4e2e7499e 100644 --- a/src/openvic-simulation/map/MapInstance.hpp +++ b/src/openvic-simulation/map/MapInstance.hpp @@ -43,8 +43,7 @@ namespace OpenVic { public: MapInstance( - MapDefinition const& new_map_definition, - ProvinceInstanceDeps const& province_instance_deps, + MapDefinition const& new_map_definition, ProvinceInstanceDeps const& province_instance_deps, ThreadPool& new_thread_pool ); @@ -64,23 +63,18 @@ namespace OpenVic { ProvinceInstance* get_province_instance_by_index(typename ProvinceInstance::index_t index); ProvinceInstance const* get_province_instance_by_index(typename ProvinceInstance::index_t index) const; ProvinceInstance& get_province_instance_by_definition(ProvinceDefinition const& province_definition); - ProvinceInstance* get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number - ); + ProvinceInstance* + get_province_instance_from_number(decltype(std::declval().get_province_number()) province_number); ProvinceInstance const* get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const; void enable_canal(canal_index_t canal_index); bool is_canal_enabled(canal_index_t canal_index) const; bool apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, - const Date date, - CountryInstanceManager& country_manager, - IssueManager const& issue_manager, - MilitaryDefines const& military_defines, - PopDeps const& pop_deps + ProvinceHistoryManager const& history_manager, const Date date, CountryInstanceManager& country_manager, + IssueManager const& issue_manager, MilitaryDefines const& military_defines, PopDeps const& pop_deps ); void update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache); diff --git a/src/openvic-simulation/map/Mapmode.cpp b/src/openvic-simulation/map/Mapmode.cpp index 6100d3137..cb114ef28 100644 --- a/src/openvic-simulation/map/Mapmode.cpp +++ b/src/openvic-simulation/map/Mapmode.cpp @@ -20,37 +20,29 @@ using namespace OpenVic; using namespace OpenVic::colour_literals; Mapmode::Mapmode( - std::string_view new_identifier, - index_t new_index, - colour_func_t new_colour_func, - std::string_view new_localisation_key, + std::string_view new_identifier, index_t new_index, colour_func_t new_colour_func, std::string_view new_localisation_key, bool new_is_parchment_mapmode_allowed -) : HasIdentifier { new_identifier }, - HasIndex { new_index }, - colour_func { std::move(new_colour_func) }, - localisation_key { new_localisation_key.empty() ? new_identifier : new_localisation_key }, - is_parchment_mapmode_allowed { new_is_parchment_mapmode_allowed } {} - -const Mapmode Mapmode::ERROR_MAPMODE { - "mapmode_error", index_t { std::numeric_limits::max() }, []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> base_stripe_t { - return { 0xFFFF0000_argb, colour_argb_t::null() }; - } -}; +) + : HasIdentifier { new_identifier }, HasIndex { new_index }, colour_func { std::move(new_colour_func) }, + localisation_key { new_localisation_key.empty() ? new_identifier : new_localisation_key }, + is_parchment_mapmode_allowed { new_is_parchment_mapmode_allowed } {} + +const Mapmode Mapmode::ERROR_MAPMODE { "mapmode_error", index_t { std::numeric_limits::max() }, + [](MapInstance const& map_instance, ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> base_stripe_t { + return { 0xFFFF0000_argb, colour_argb_t::null() }; + } }; Mapmode::base_stripe_t Mapmode::get_base_stripe_colours( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province ) const { return colour_func ? colour_func(map_instance, province, player_country, selected_province) : colour_argb_t::null(); } bool MapmodeManager::add_mapmode( - std::string_view identifier, - Mapmode::colour_func_t colour_func, - std::string_view localisation_key, + std::string_view identifier, Mapmode::colour_func_t colour_func, std::string_view localisation_key, bool parchment_mapmode_allowed ) { if (identifier.empty()) { @@ -62,15 +54,14 @@ bool MapmodeManager::add_mapmode( return false; } return mapmodes.emplace_item( - identifier, - identifier, Mapmode::index_t { get_mapmode_count() }, colour_func, localisation_key, parchment_mapmode_allowed + identifier, identifier, Mapmode::index_t { get_mapmode_count() }, colour_func, localisation_key, + parchment_mapmode_allowed ); } bool MapmodeManager::generate_mapmode_colours( - MapInstance const& map_instance, Mapmode const* mapmode, - CountryInstance const* player_country, ProvinceInstance const* selected_province, - uint8_t* target + MapInstance const& map_instance, Mapmode const* mapmode, CountryInstance const* player_country, + ProvinceInstance const* selected_province, uint8_t* target ) const { if (target == nullptr) { spdlog::error_s("Mapmode colour target pointer is null!"); @@ -80,9 +71,7 @@ bool MapmodeManager::generate_mapmode_colours( bool ret = true; if (mapmode == nullptr) { mapmode = &Mapmode::ERROR_MAPMODE; - spdlog::error_s( - "Trying to generate mapmode colours using null mapmode! Defaulting to \"{}\"", *mapmode - ); + spdlog::error_s("Trying to generate mapmode colours using null mapmode! Defaulting to \"{}\"", *mapmode); ret = false; } @@ -91,9 +80,8 @@ bool MapmodeManager::generate_mapmode_colours( target_stripes[ProvinceDefinition::NULL_PROVINCE_NUMBER] = colour_argb_t::null(); for (ProvinceInstance const& province : map_instance.get_province_instances()) { - target_stripes[province.province_definition.get_province_number()] = mapmode->get_base_stripe_colours( - map_instance, province, player_country, selected_province - ); + target_stripes[province.province_definition.get_province_number()] = + mapmode->get_base_stripe_colours(map_instance, province, player_country, selected_province); } return ret; @@ -108,11 +96,11 @@ static constexpr colour_argb_t DEFAULT_COLOUR_GREY = (0x7F7F7F_argb).with_alpha( template requires(std::same_as || std::same_as) -static constexpr auto get_colour_mapmode(T const*(P::*get_item)() const) { +static constexpr auto get_colour_mapmode(T const* (P::*get_item)() const) { return [get_item]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.province_definition; T const* item = ([&province, &province_definition]() -> P const& { @@ -135,13 +123,12 @@ static constexpr auto get_colour_mapmode(T const*(P::*get_item)() const) { template requires(std::same_as || std::same_as) -static constexpr auto get_colour_mapmode( - BASE_T const*(P::*get_base_item)() const, STRIPE_T const*(P::*get_stripe_item)() const -) { +static constexpr auto +get_colour_mapmode(BASE_T const* (P::*get_base_item)() const, STRIPE_T const* (P::*get_stripe_item)() const) { return [get_base_item, get_stripe_item]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.province_definition; P const& p = [&province, &province_definition]() -> P const& { @@ -169,9 +156,7 @@ static constexpr auto get_colour_mapmode( } template -static constexpr Mapmode::base_stripe_t shaded_mapmode( - ordered_map const& map -) { +static constexpr Mapmode::base_stripe_t shaded_mapmode(ordered_map const& map) { const auto largest = get_largest_two_items(map); if (largest.first != map.end()) { const colour_argb_t base_colour = colour_argb_t { largest.first->first->get_colour(), ALPHA_VALUE }; @@ -188,11 +173,11 @@ static constexpr Mapmode::base_stripe_t shaded_mapmode( } template -static constexpr auto shaded_mapmode(ordered_map const&(ProvinceInstance::*get_map)() const) { +static constexpr auto shaded_mapmode(ordered_map const& (ProvinceInstance::*get_map)() const) { return [get_map]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { return shaded_mapmode((province.*get_map)()); }; } @@ -211,18 +196,16 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin // The order of mapmodes matches their numbering, but is different from the order in which their buttons appear ret &= add_mapmode( "mapmode_terrain", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { return colour_argb_t::null(); }, "MAPMODE_1", false // Parchment mapmode not allowed ); - ret &= add_mapmode("mapmode_political", get_colour_mapmode( - &ProvinceInstance::get_owner, &ProvinceInstance::get_controller - ), "MAPMODE_2"); + ret &= add_mapmode( + "mapmode_political", get_colour_mapmode(&ProvinceInstance::get_owner, &ProvinceInstance::get_controller), "MAPMODE_2" + ); ret &= add_mapmode("mapmode_militancy", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_3"); ret &= add_mapmode("mapmode_diplomatic", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_4"); ret &= add_mapmode("mapmode_region", get_colour_mapmode(&ProvinceDefinition::get_region), "MAPMODE_5"); @@ -231,27 +214,28 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin spdlog::error_s("Cannot setup infrastructure mapmode because infrastructure_building_type is null."); ret = false; } else if (!infrastructure_building_type_ptr->province_building_index.has_value()) { - spdlog::error_s("Cannot setup infrastructure mapmode because infrastructure_building_type has no province_building_index."); + spdlog::error_s( + "Cannot setup infrastructure mapmode because infrastructure_building_type has no province_building_index." + ); ret = false; } else { ret &= add_mapmode( "mapmode_infrastructure", [&building_type_manager, infrastructure_building_type_ptr]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province ) -> Mapmode::base_stripe_t { BuildingType const& infrastructure_building_type = *infrastructure_building_type_ptr; - BuildingInstance const& infrastructure = province.get_buildings()[infrastructure_building_type.province_building_index.value()]; + BuildingInstance const& infrastructure = + province.get_buildings()[infrastructure_building_type.province_building_index.value()]; const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( - type_safe::get(infrastructure.get_level()), type_safe::get(infrastructure_building_type.max_level) + 1, 0.5f, 1.0f + type_safe::get(infrastructure.get_level()), type_safe::get(infrastructure_building_type.max_level) + 1, + 0.5f, 1.0f ); switch (infrastructure.get_expansion_state()) { - case BuildingInstance::ExpansionState::CannotExpand: - return colour_argb_t { val, 0, 0, ALPHA_VALUE }; - case BuildingInstance::ExpansionState::CanExpand: - return colour_argb_t { 0, 0, val, ALPHA_VALUE }; - default: - return colour_argb_t { 0, val, 0, ALPHA_VALUE }; + case BuildingInstance::ExpansionState::CannotExpand: return colour_argb_t { val, 0, 0, ALPHA_VALUE }; + case BuildingInstance::ExpansionState::CanExpand: return colour_argb_t { 0, 0, val, ALPHA_VALUE }; + default: return colour_argb_t { 0, val, 0, ALPHA_VALUE }; } return colour_argb_t::null(); }, @@ -265,16 +249,15 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin ret &= add_mapmode("mapmode_rgo", get_colour_mapmode(&ProvinceInstance::get_rgo_good), "MAPMODE_11"); ret &= add_mapmode( "mapmode_population", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { // TODO - explore non-linear scaling to have more variation among non-massive provinces // TODO - when selecting a province, only show the population of provinces controlled (or owned?) // by the same country, relative to the most populous province in that set of provinces if (!province.province_definition.is_water()) { const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( - type_safe::get(province.get_total_population()), type_safe::get(map_instance.get_highest_province_population()) + 1, 0.1f, 1.0f + type_safe::get(province.get_total_population()), + type_safe::get(map_instance.get_highest_province_population()) + 1, 0.1f, 1.0f ); return colour_argb_t { 0, val, 0, ALPHA_VALUE }; } else { @@ -283,7 +266,9 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin }, "MAPMODE_12" ); - ret &= add_mapmode("mapmode_culture", shaded_mapmode(&ProvinceInstance::get_population_by_culture), "MAPMODE_13"); + ret &= add_mapmode( + "mapmode_culture", shaded_mapmode(&ProvinceInstance::get_population_by_culture), "MAPMODE_13" + ); ret &= add_mapmode("mapmode_sphere", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_14"); ret &= add_mapmode("mapmode_supply", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_15"); ret &= add_mapmode("mapmode_party_loyalty", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_16"); @@ -294,10 +279,8 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin ret &= add_mapmode("mapmode_crisis", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_21"); ret &= add_mapmode( "mapmode_naval", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.province_definition; if (province_definition.has_port()) { @@ -319,18 +302,16 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin if constexpr (false) { ret &= add_mapmode( "mapmode_province", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { return colour_argb_t { province.province_definition.get_colour(), ALPHA_VALUE }; } ); ret &= add_mapmode( "mapmode_index", [&map_definition]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province ) -> Mapmode::base_stripe_t { const colour_argb_t::value_type f = colour_argb_t::colour_traits::component_from_fraction( province.province_definition.get_province_number(), map_definition.get_province_definition_count() + 1 @@ -338,14 +319,13 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin return colour_argb_t::fill_as(f).with_alpha(ALPHA_VALUE); } ); - ret &= add_mapmode("mapmode_religion", shaded_mapmode(&ProvinceInstance::get_population_by_religion)); + ret &= + add_mapmode("mapmode_religion", shaded_mapmode(&ProvinceInstance::get_population_by_religion)); ret &= add_mapmode("mapmode_terrain_type", get_colour_mapmode(&ProvinceInstance::get_terrain_type)); ret &= add_mapmode( "mapmode_adjacencies", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + [](MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { if (selected_province != nullptr) { ProvinceDefinition const& selected_province_definition = selected_province->province_definition; @@ -363,13 +343,13 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin colour_argb_t::integer_type base_int; switch (adj->get_type()) { using enum ProvinceDefinition::adjacency_t::type_t; - case LAND: base_int = 0x00FF00; break; - case WATER: base_int = 0x0000FF; break; - case COASTAL: base_int = 0xF9D199; break; + case LAND: base_int = 0x00FF00; break; + case WATER: base_int = 0x0000FF; break; + case COASTAL: base_int = 0xF9D199; break; case IMPASSABLE: base_int = 0x8B4513; break; - case STRAIT: base_int = 0x00FFFF; break; - case CANAL: base_int = 0x888888; break; - default: base_int = 0xFF0000; break; + case STRAIT: base_int = 0x00FFFF; break; + case CANAL: base_int = 0x888888; break; + default: base_int = 0xFF0000; break; } base = colour_argb_t::from_integer(base_int).with_alpha(ALPHA_VALUE); stripe = base; diff --git a/src/openvic-simulation/map/Mapmode.hpp b/src/openvic-simulation/map/Mapmode.hpp index 3baadb9ec..0607cbbee 100644 --- a/src/openvic-simulation/map/Mapmode.hpp +++ b/src/openvic-simulation/map/Mapmode.hpp @@ -1,13 +1,13 @@ #pragma once +#include + #include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -#include - namespace OpenVic { struct BuildingTypeManager; struct MapmodeManager; @@ -27,8 +27,7 @@ namespace OpenVic { constexpr base_stripe_t(colour_argb_t both) : base_stripe_t { both, both } {} }; using colour_func_t = fu2::function< - base_stripe_t(MapInstance const&, ProvinceInstance const&, CountryInstance const*, ProvinceInstance const*) const - >; + base_stripe_t(MapInstance const&, ProvinceInstance const&, CountryInstance const*, ProvinceInstance const*) const>; private: // Not const so they don't have to be copied when the Mapmode is moved @@ -40,17 +39,14 @@ namespace OpenVic { const bool is_parchment_mapmode_allowed; Mapmode( - std::string_view new_identifier, - index_t new_index, - colour_func_t new_colour_func, - std::string_view new_localisation_key = {}, - bool new_is_parchment_mapmode_allowed = true + std::string_view new_identifier, index_t new_index, colour_func_t new_colour_func, + std::string_view new_localisation_key = {}, bool new_is_parchment_mapmode_allowed = true ); Mapmode(Mapmode&&) = default; base_stripe_t get_base_stripe_colours( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, ProvinceInstance const& province, CountryInstance const* player_country, + ProvinceInstance const* selected_province ) const; }; @@ -62,9 +58,7 @@ namespace OpenVic { constexpr MapmodeManager() {}; bool add_mapmode( - std::string_view identifier, - Mapmode::colour_func_t colour_func, - std::string_view localisation_key = {}, + std::string_view identifier, Mapmode::colour_func_t colour_func, std::string_view localisation_key = {}, bool parchment_mapmode_allowed = true ); @@ -74,9 +68,8 @@ namespace OpenVic { * together adjacently, so each province's entry is 8 bytes long. * The list contains all provinces indexed by their number + index 0 for the "null province". */ bool generate_mapmode_colours( - MapInstance const& map_instance, Mapmode const* mapmode, - CountryInstance const* player_country, ProvinceInstance const* selected_province, - uint8_t* target + MapInstance const& map_instance, Mapmode const* mapmode, CountryInstance const* player_country, + ProvinceInstance const* selected_province, uint8_t* target ) const; bool setup_mapmodes(MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager); diff --git a/src/openvic-simulation/map/ProvinceDefinition.cpp b/src/openvic-simulation/map/ProvinceDefinition.cpp index 78f9b2751..fefa0f477 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.cpp +++ b/src/openvic-simulation/map/ProvinceDefinition.cpp @@ -10,12 +10,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -ProvinceDefinition::ProvinceDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index -) : HasIdentifierAndColour { new_identifier, new_colour, true }, - HasIndex { new_index } {} +ProvinceDefinition::ProvinceDefinition(std::string_view new_identifier, colour_t new_colour, index_t new_index) + : HasIdentifierAndColour { new_identifier, new_colour, true }, HasIndex { new_index } {} memory::string ProvinceDefinition::to_string() const { return memory::fmt::format("(#{}, {}, 0x{})", get_province_number(), get_identifier(), get_colour()); @@ -126,20 +122,21 @@ fixed_point_t ProvinceDefinition::get_building_rotation(BuildingType const* buil std::string_view ProvinceDefinition::adjacency_t::get_type_name(type_t type) { switch (type) { - case type_t::LAND: return "Land"; - case type_t::WATER: return "Water"; - case type_t::COASTAL: return "Coastal"; + case type_t::LAND: return "Land"; + case type_t::WATER: return "Water"; + case type_t::COASTAL: return "Coastal"; case type_t::IMPASSABLE: return "Impassable"; - case type_t::STRAIT: return "Strait"; - case type_t::CANAL: return "Canal"; - default: return "Invalid Adjacency Type"; + case type_t::STRAIT: return "Strait"; + case type_t::CANAL: return "Canal"; + default: return "Invalid Adjacency Type"; } } ProvinceDefinition::adjacency_t const* ProvinceDefinition::get_adjacency_to(ProvinceDefinition const& province) const { - const memory::vector::const_iterator it = std::find_if(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { return adj.get_to() == province; } - ); + const memory::vector::const_iterator it = + std::find_if(adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_to() == province; + }); if (it != adjacencies.end()) { return &*it; } else { @@ -148,14 +145,13 @@ ProvinceDefinition::adjacency_t const* ProvinceDefinition::get_adjacency_to(Prov } bool ProvinceDefinition::is_adjacent_to(ProvinceDefinition const& province) const { - return std::any_of(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { return adj.get_to() == province; } - ); + return std::any_of(adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_to() == province; + }); } -memory::vector> ProvinceDefinition::get_adjacencies_going_through( - ProvinceDefinition const& province -) const { +memory::vector> +ProvinceDefinition::get_adjacencies_going_through(ProvinceDefinition const& province) const { memory::vector> ret; for (adjacency_t const& adj : adjacencies) { if (adj.get_through() != nullptr && *adj.get_through() == province) { @@ -166,11 +162,9 @@ memory::vector> Pr } bool ProvinceDefinition::has_adjacency_going_through(ProvinceDefinition const& province) const { - return std::any_of(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { - return adj.get_through() != nullptr && *adj.get_through() == province; - } - ); + return std::any_of(adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_through() != nullptr && *adj.get_through() == province; + }); } fvec2_t ProvinceDefinition::get_unit_position() const { diff --git a/src/openvic-simulation/map/ProvinceDefinition.hpp b/src/openvic-simulation/map/ProvinceDefinition.hpp index 2a644fee3..49da91ee4 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.hpp +++ b/src/openvic-simulation/map/ProvinceDefinition.hpp @@ -6,13 +6,13 @@ #include #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/Vector.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -40,12 +40,12 @@ namespace OpenVic { static constexpr data_t DEFAULT_DATA = 0; enum struct type_t : uint8_t { - LAND, /* Between two land provinces */ - WATER, /* Between two water provinces */ - COASTAL, /* Between a land province and a water province */ + LAND, /* Between two land provinces */ + WATER, /* Between two water provinces */ + COASTAL, /* Between a land province and a water province */ IMPASSABLE, /* Between two land provinces (non-traversable) */ - STRAIT, /* Between two land provinces with a water through province */ - CANAL /* Between two water provinces with a land through province */ + STRAIT, /* Between two land provinces with a water through province */ + CANAL /* Between two water provinces with a land through province */ }; /* Type display name used for logging */ @@ -61,16 +61,10 @@ namespace OpenVic { public: constexpr adjacency_t( - ProvinceDefinition const& new_to, - const distance_t new_distance, - const type_t new_type, - ProvinceDefinition const* const new_through, - const data_t new_data - ) : to { new_to }, - through { new_through }, - distance { new_distance }, - type { new_type }, - data { new_data } {} + ProvinceDefinition const& new_to, const distance_t new_distance, const type_t new_type, + ProvinceDefinition const* const new_through, const data_t new_data + ) + : to { new_to }, through { new_through }, distance { new_distance }, type { new_type }, data { new_data } {} adjacency_t(adjacency_t const&) = delete; adjacency_t(adjacency_t&&) = default; @@ -151,7 +145,8 @@ namespace OpenVic { adjacency_t const* get_adjacency_to(ProvinceDefinition const& province) const; bool is_adjacent_to(ProvinceDefinition const& province) const; - memory::vector> get_adjacencies_going_through(ProvinceDefinition const& province) const; + memory::vector> + get_adjacencies_going_through(ProvinceDefinition const& province) const; bool has_adjacency_going_through(ProvinceDefinition const& province) const; fvec2_t get_unit_position() const; diff --git a/src/openvic-simulation/map/ProvinceInstance.cpp b/src/openvic-simulation/map/ProvinceInstance.cpp index e7bc0bd60..0f9f5256a 100644 --- a/src/openvic-simulation/map/ProvinceInstance.cpp +++ b/src/openvic-simulation/map/ProvinceInstance.cpp @@ -1,50 +1,43 @@ #include "ProvinceInstance.hpp" -#include "ProvinceInstanceDeps.hpp" #include +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/defines/MilitaryDefines.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/economy/BuildingInstance.hpp" #include "openvic-simulation/economy/BuildingType.hpp" #include "openvic-simulation/economy/production/Employee.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" -#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/modifier/StaticModifierCache.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "ProvinceInstanceDeps.hpp" + using namespace OpenVic; ProvinceInstance::ProvinceInstance( - ProvinceDefinition const& new_province_definition, - ProvinceInstanceDeps const& province_instance_deps -) : HasIdentifierAndColour { new_province_definition }, - HasIndex { new_province_definition.index }, - FlagStrings { "province" }, - PopsAggregate { - province_instance_deps.stratas, - province_instance_deps.pop_types, - province_instance_deps.ideologies - }, - province_definition { new_province_definition }, - game_rules_manager { province_instance_deps.game_rules_manager }, - terrain_type { new_province_definition.get_default_terrain_type() }, - rgo { province_instance_deps.rgo_deps }, - pops_cache_by_type { province_instance_deps.pop_types }, - _buildings( - new_province_definition.is_water() - ? 0 - : province_instance_deps.building_type_manager.get_province_building_types().size(), - [&province_instance_deps](const size_t i) -> BuildingType const& { - return province_instance_deps.building_type_manager.get_province_building_types()[i]; - } - ), - buildings(_buildings) -{ + ProvinceDefinition const& new_province_definition, ProvinceInstanceDeps const& province_instance_deps +) + : HasIdentifierAndColour { new_province_definition }, HasIndex { new_province_definition.index }, + FlagStrings { "province" }, + PopsAggregate { province_instance_deps.stratas, province_instance_deps.pop_types, province_instance_deps.ideologies }, + province_definition { new_province_definition }, game_rules_manager { province_instance_deps.game_rules_manager }, + terrain_type { new_province_definition.get_default_terrain_type() }, rgo { province_instance_deps.rgo_deps }, + pops_cache_by_type { province_instance_deps.pop_types }, + _buildings( + new_province_definition.is_water() + ? 0 + : province_instance_deps.building_type_manager.get_province_building_types().size(), + [&province_instance_deps](const size_t i) -> BuildingType const& { + return province_instance_deps.building_type_manager.get_province_building_types()[i]; + } + ), + buildings(_buildings) { modifier_sum.set_this_source(this); rgo.setup_location_ptr(*this); } @@ -76,12 +69,11 @@ bool ProvinceInstance::set_rgo_production_type_nullable(ProductionType const* rg ProductionType const& rgo_production_type = *rgo_production_type_nullable; if (rgo_production_type.template_type != ProductionType::template_type_t::RGO) { spdlog::error_s( - "Tried setting province {} rgo to {} which is not of template_type RGO.", - *this, rgo_production_type + "Tried setting province {} rgo to {} which is not of template_type RGO.", *this, rgo_production_type ); is_valid_operation = false; } - is_valid_operation&=convert_rgo_worker_pops_to_equivalent(rgo_production_type); + is_valid_operation &= convert_rgo_worker_pops_to_equivalent(rgo_production_type); } rgo.set_production_type_nullable(rgo_production_type_nullable); @@ -110,9 +102,7 @@ bool ProvinceInstance::set_owner(CountryInstance* new_owner) { if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::Owner) { country_to_report_economy = new_owner; } else if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::NeitherWhenOccupied) { - country_to_report_economy = is_occupied() - ? nullptr - : owner; + country_to_report_economy = is_occupied() ? nullptr : owner; } } @@ -140,9 +130,7 @@ bool ProvinceInstance::set_controller(CountryInstance* new_controller) { if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::Controller) { country_to_report_economy = new_controller; } else if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::NeitherWhenOccupied) { - country_to_report_economy = is_occupied() - ? nullptr - : owner; + country_to_report_economy = is_occupied() ? nullptr : owner; } } @@ -153,10 +141,7 @@ bool ProvinceInstance::add_core(CountryInstance& new_core, bool warn) { if (cores.emplace(&new_core).second) { return new_core.add_core_province(*this); } else if (warn) { - spdlog::warn_s( - "Attempted to add core \"{}\" to province {}: already exists!", - new_core, *this - ); + spdlog::warn_s("Attempted to add core \"{}\" to province {}: already exists!", new_core, *this); } return true; } @@ -165,36 +150,22 @@ bool ProvinceInstance::remove_core(CountryInstance& core_to_remove, bool warn) { if (cores.erase(&core_to_remove) > 0) { return core_to_remove.remove_core_province(*this); } else if (warn) { - spdlog::warn_s( - "Attempted to remove core \"{}\" from province {}: does not exist!", - core_to_remove, *this - ); + spdlog::warn_s("Attempted to remove core \"{}\" from province {}: does not exist!", core_to_remove, *this); } return true; } bool ProvinceInstance::expand_building( - ModifierEffectCache const& modifier_effect_cache, - const province_building_index_t index, - CountryInstance& actor + ModifierEffectCache const& modifier_effect_cache, const province_building_index_t index, CountryInstance& actor ) { return buildings[index].expand(modifier_effect_cache, actor, *this); } -bool ProvinceInstance::add_pop_vec( - std::span pop_vec, - PopDeps const& pop_deps -) { +bool ProvinceInstance::add_pop_vec(std::span pop_vec, PopDeps const& pop_deps) { if (!province_definition.is_water()) { reserve_more(pops, pop_vec.size()); for (PopBase const& pop : pop_vec) { - pops.emplace( - *this, - pop, - get_supporter_equivalents_by_ideology().get_keys(), - pop_deps, - ++last_pop_id - ); + pops.emplace(*this, pop, get_supporter_equivalents_by_ideology().get_keys(), pop_deps, ++last_pop_id); } return true; } else { @@ -221,10 +192,11 @@ void ProvinceInstance::_update_pops(MilitaryDefines const& military_defines) { using enum colony_status_t; - const fixed_point_t pop_size_per_regiment_multiplier = - colony_status == PROTECTORATE ? military_defines.get_pop_size_per_regiment_protectorate_multiplier() + const fixed_point_t pop_size_per_regiment_multiplier = colony_status == PROTECTORATE + ? military_defines.get_pop_size_per_regiment_protectorate_multiplier() : colony_status == COLONY ? military_defines.get_pop_size_per_regiment_colony_multiplier() - : is_owner_core() ? fixed_point_t::_1 : military_defines.get_pop_size_per_regiment_non_core_multiplier(); + : is_owner_core() ? fixed_point_t::_1 + : military_defines.get_pop_size_per_regiment_non_core_multiplier(); for (Pop& pop : pops) { pops_cache_by_type.at(pop.get_type()).push_back(pop); @@ -325,7 +297,7 @@ bool ProvinceInstance::convert_rgo_worker_pops_to_equivalent(ProductionType cons if (job_pop_type != old_pop_type) { PopType const* const equivalent_ptr = old_pop_type.get_equivalent(); if (equivalent_ptr != nullptr && job_pop_type == *equivalent_ptr) { - is_valid_operation&=pop.convert_to_equivalent(); + is_valid_operation &= pop.convert_to_equivalent(); } } } @@ -373,14 +345,9 @@ void ProvinceInstance::update_gamestate(InstanceManager const& instance_manager) } void ProvinceInstance::province_tick( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, + const Date today, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ) { if (is_occupied()) { ++occupation_duration; @@ -389,12 +356,7 @@ void ProvinceInstance::province_tick( if (!pops.empty()) { reusable_pop_values.update_pop_values_from_province(*this); for (Pop& pop : pops) { - pop.pop_tick( - reusable_pop_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + pop.pop_tick(reusable_pop_values, random_number_generator, reusable_goods_mask, reusable_vectors); } } @@ -408,38 +370,31 @@ bool ProvinceInstance::add_unit_instance_group(UnitInstanceGroup& group) { using enum unit_branch_t; switch (group.branch) { - case LAND: - armies.emplace_back(static_cast(group)); - return true; - case NAVAL: - navies.emplace_back(static_cast(group)); - return true; + case LAND: armies.emplace_back(static_cast(group)); return true; + case NAVAL: navies.emplace_back(static_cast(group)); return true; default: spdlog::error_s( - "Trying to add unit group \"{}\" with invalid branch {} to province {}", - group.get_name(), static_cast(group.branch), *this + "Trying to add unit group \"{}\" with invalid branch {} to province {}", group.get_name(), + static_cast(group.branch), *this ); return false; } } bool ProvinceInstance::remove_unit_instance_group(UnitInstanceGroup const& group) { - const auto remove_from_vector = [this, &group]( - memory::vector>>& unit_instance_groups - ) -> bool { - auto it = std::find( - unit_instance_groups.begin(), - unit_instance_groups.end(), - group - ); + const auto remove_from_vector = + [this, &group]( + memory::vector>>& unit_instance_groups + ) -> bool { + auto it = std::find(unit_instance_groups.begin(), unit_instance_groups.end(), group); if (it != unit_instance_groups.end()) { unit_instance_groups.erase(it); return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from province {}", - get_branched_unit_group_name(Branch), group.get_name(), *this + "Trying to remove non-existent {} \"{}\" from province {}", get_branched_unit_group_name(Branch), + group.get_name(), *this ); return false; } @@ -448,14 +403,12 @@ bool ProvinceInstance::remove_unit_instance_group(UnitInstanceGroup const& group using enum unit_branch_t; switch (group.branch) { - case LAND: - return remove_from_vector(armies); - case NAVAL: - return remove_from_vector(navies); + case LAND: return remove_from_vector(armies); + case NAVAL: return remove_from_vector(navies); default: spdlog::error_s( - "Trying to remove unit group \"{}\" with invalid branch {} from province {}", - group.get_name(), static_cast(group.branch), *this + "Trying to remove unit group \"{}\" with invalid branch {} from province {}", group.get_name(), + static_cast(group.branch), *this ); return false; } @@ -504,23 +457,12 @@ bool ProvinceInstance::apply_history_to_province(ProvinceHistoryEntry const& ent } void ProvinceInstance::initialise_for_new_game( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, + const Date today, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ) { initialise_rgo(); - province_tick( - today, - reusable_pop_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + province_tick(today, reusable_pop_values, random_number_generator, reusable_goods_mask, reusable_vectors); } void ProvinceInstance::initialise_rgo() { @@ -538,7 +480,8 @@ memory::colony& ProvinceInstance::get_mutable_pops() { } template -std::conditional_t, Pop const*, Pop*> ProvinceInstance::_find_pop_by_id(T& self, const pop_id_in_province_t pop_id) { +std::conditional_t, Pop const*, Pop*> +ProvinceInstance::_find_pop_by_id(T& self, const pop_id_in_province_t pop_id) { if (pop_id.is_null()) { return nullptr; } @@ -551,5 +494,9 @@ std::conditional_t, Pop const*, Pop*> ProvinceInstance::_find return nullptr; } -Pop* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) { return _find_pop_by_id(*this, pop_id); } -Pop const* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) const { return _find_pop_by_id(*this, pop_id); } \ No newline at end of file +Pop* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) { + return _find_pop_by_id(*this, pop_id); +} +Pop const* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) const { + return _find_pop_by_id(*this, pop_id); +} diff --git a/src/openvic-simulation/map/ProvinceInstance.hpp b/src/openvic-simulation/map/ProvinceInstance.hpp index f280155c7..4a982c21b 100644 --- a/src/openvic-simulation/map/ProvinceInstance.hpp +++ b/src/openvic-simulation/map/ProvinceInstance.hpp @@ -14,11 +14,11 @@ #include "openvic-simulation/population/PopIdInProvince.hpp" #include "openvic-simulation/population/PopsAggregate.hpp" #include "openvic-simulation/types/ColonyStatus.hpp" +#include "openvic-simulation/types/FixedVector.hpp" #include "openvic-simulation/types/FlagStrings.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/types/FixedVector.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/TypedSpan.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" @@ -51,25 +51,17 @@ namespace OpenVic { struct TerrainType; struct UnitInstanceGroup; - //HasIndex index_t must match ProvinceDefinition's index_t - struct ProvinceInstance - : HasIdentifierAndColour, - HasIndex, - FlagStrings, - PopsAggregate { + // HasIndex index_t must match ProvinceDefinition's index_t + struct ProvinceInstance : HasIdentifierAndColour, HasIndex, FlagStrings, PopsAggregate { friend struct MapInstance; static constexpr std::string_view get_colony_status_string(colony_status_t colony_status) { using enum colony_status_t; switch (colony_status) { - case STATE: - return "state"; - case PROTECTORATE: - return "protectorate"; - case COLONY: - return "colony"; - default: - return "unknown colony status"; + case STATE: return "state"; + case PROTECTORATE: return "protectorate"; + case COLONY: return "colony"; + default: return "unknown colony status"; } } @@ -102,10 +94,12 @@ namespace OpenVic { ResourceGatheringOperation PROPERTY(rgo); memory::FixedVector _buildings; TypedSpan buildings; + public: constexpr TypedSpan get_buildings() const { return buildings; } + private: memory::vector> SPAN_PROPERTY(armies); memory::vector> SPAN_PROPERTY(navies); @@ -118,20 +112,18 @@ namespace OpenVic { OV_UNIT_BRANCHED_GETTER_CONST(get_unit_instance_groups, armies, navies); private: - pop_id_in_province_t last_pop_id{0}; + pop_id_in_province_t last_pop_id { 0 }; memory::colony PROPERTY(pops); // TODO - replace with a more easily vectorisable container? void _update_pops(MilitaryDefines const& military_defines); bool convert_rgo_worker_pops_to_equivalent(ProductionType const& production_type); void initialise_rgo(); OV_IFLATMAP_PROPERTY(PopType, memory::vector>, pops_cache_by_type); + public: ProvinceDefinition const& province_definition; - ProvinceInstance( - ProvinceDefinition const& new_province_definition, - ProvinceInstanceDeps const& province_instance_deps - ); + ProvinceInstance(ProvinceDefinition const& new_province_definition, ProvinceInstanceDeps const& province_instance_deps); ProvinceInstance(ProvinceInstance const&) = delete; ProvinceInstance& operator=(ProvinceInstance const&) = delete; ProvinceInstance(ProvinceInstance&&) = delete; @@ -172,15 +164,10 @@ namespace OpenVic { return !is_occupied(); } bool expand_building( - ModifierEffectCache const& modifier_effect_cache, - const province_building_index_t index, - CountryInstance& actor + ModifierEffectCache const& modifier_effect_cache, const province_building_index_t index, CountryInstance& actor ); - bool add_pop_vec( - std::span pop_vec, - PopDeps const& pop_deps - ); + bool add_pop_vec(std::span pop_vec, PopDeps const& pop_deps); size_t get_pop_count() const; void update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache); @@ -199,29 +186,17 @@ namespace OpenVic { } } void update_gamestate(InstanceManager const& instance_manager); - static constexpr size_t VECTORS_FOR_PROVINCE_TICK = std::max( - ResourceGatheringOperation::VECTORS_FOR_RGO_TICK, - Pop::VECTORS_FOR_POP_TICK - ); + static constexpr size_t VECTORS_FOR_PROVINCE_TICK = + std::max(ResourceGatheringOperation::VECTORS_FOR_RGO_TICK, Pop::VECTORS_FOR_POP_TICK); void province_tick( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, + const Date today, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ); void initialise_for_new_game( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, + const Date today, PopValuesFromProvince& reusable_pop_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ); bool add_unit_instance_group(UnitInstanceGroup& group); @@ -231,11 +206,14 @@ namespace OpenVic { void setup_pop_test_values(IssueManager const& issue_manager); memory::colony& get_mutable_pops(); + private: template - static std::conditional_t, Pop const*, Pop*> _find_pop_by_id(T& self, const pop_id_in_province_t pop_id); + static std::conditional_t, Pop const*, Pop*> + _find_pop_by_id(T& self, const pop_id_in_province_t pop_id); + public: Pop* find_pop_by_id(const pop_id_in_province_t pop_id); Pop const* find_pop_by_id(const pop_id_in_province_t pop_id) const; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/ProvinceInstanceDeps.hpp b/src/openvic-simulation/map/ProvinceInstanceDeps.hpp index 6c8ff6335..f38f3c3ba 100644 --- a/src/openvic-simulation/map/ProvinceInstanceDeps.hpp +++ b/src/openvic-simulation/map/ProvinceInstanceDeps.hpp @@ -18,4 +18,4 @@ namespace OpenVic { ResourceGatheringOperationDeps const& rgo_deps; forwardable_span stratas; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/State.cpp b/src/openvic-simulation/map/State.cpp index 6fa3b5847..87d14edbf 100644 --- a/src/openvic-simulation/map/State.cpp +++ b/src/openvic-simulation/map/State.cpp @@ -14,36 +14,25 @@ using namespace OpenVic; State::State( - StateSet const& new_state_set, - ProvinceInstance* new_capital, - memory::vector>&& new_provinces, - colony_status_t new_colony_status, - forwardable_span strata_keys, - forwardable_span pop_type_keys, + StateSet const& new_state_set, ProvinceInstance* new_capital, + memory::vector>&& new_provinces, colony_status_t new_colony_status, + forwardable_span strata_keys, forwardable_span pop_type_keys, forwardable_span ideology_keys -) : PopsAggregate { strata_keys, pop_type_keys, ideology_keys }, - state_set { new_state_set }, - capital { new_capital }, - provinces { std::move(new_provinces) }, - colony_status { new_colony_status }, - pops_cache_by_type { pop_type_keys } -{ +) + : PopsAggregate { strata_keys, pop_type_keys, ideology_keys }, state_set { new_state_set }, capital { new_capital }, + provinces { std::move(new_provinces) }, colony_status { new_colony_status }, pops_cache_by_type { pop_type_keys } { _update_country(); } memory::string State::get_identifier() const { return memory::fmt::format( - "{}_{}_{}", - state_set.region, - ovfmt::validate(get_owner(), "NoCountry"), + "{}_{}_{}", state_set.region, ovfmt::validate(get_owner(), "NoCountry"), ProvinceInstance::get_colony_status_string(colony_status) ); } CountryInstance* State::get_owner() const { - return capital == nullptr - ? static_cast(nullptr) - : capital->get_owner(); + return capital == nullptr ? static_cast(nullptr) : capital->get_owner(); } memory::vector> const& State::get_pops_cache_by_type(PopType const& pop_type) const { @@ -64,11 +53,7 @@ void State::update_gamestate() { for (auto const& [pop_type, province_pops_of_type] : province.get_pops_cache_by_type()) { memory::vector>& state_pops_of_type = pops_cache_by_type.at(pop_type); - state_pops_of_type.insert( - state_pops_of_type.end(), - province_pops_of_type.begin(), - province_pops_of_type.end() - ); + state_pops_of_type.insert(state_pops_of_type.end(), province_pops_of_type.begin(), province_pops_of_type.end()); } } @@ -97,10 +82,10 @@ void State::update_gamestate() { void State::_update_country() { CountryInstance* const owner_ptr = get_owner(); - if (owner_ptr == previous_country_ptr) { + if (owner_ptr == previous_country_ptr) { return; } - + update_parties_for_votes(owner_ptr); if (previous_country_ptr != nullptr) { previous_country_ptr->remove_state(*this); @@ -131,13 +116,15 @@ void StateSet::update_gamestate() { } bool StateManager::add_state_set( - MapInstance& map_instance, Region const& region, - forwardable_span strata_keys, - forwardable_span pop_type_keys, - forwardable_span ideology_keys + MapInstance& map_instance, Region const& region, forwardable_span strata_keys, + forwardable_span pop_type_keys, forwardable_span ideology_keys ) { - OV_ERR_FAIL_COND_V_MSG(region.is_meta, false, memory::fmt::format("Cannot use meta region \"{}\" as state template!", region)); - OV_ERR_FAIL_COND_V_MSG(region.empty(), false, memory::fmt::format("Cannot use empty region \"{}\" as state template!", region)); + OV_ERR_FAIL_COND_V_MSG( + region.is_meta, false, memory::fmt::format("Cannot use meta region \"{}\" as state template!", region) + ); + OV_ERR_FAIL_COND_V_MSG( + region.empty(), false, memory::fmt::format("Cannot use empty region \"{}\" as state template!", region) + ); memory::vector>> temp_provinces; @@ -173,9 +160,7 @@ bool StateManager::add_state_set( State& state = *state_set.states.emplace( /* TODO: capital province logic */ - state_set, &capital, - std::move(provinces), capital.get_colony_status(), - strata_keys, pop_type_keys, ideology_keys + state_set, &capital, std::move(provinces), capital.get_colony_status(), strata_keys, pop_type_keys, ideology_keys ); for (ProvinceInstance& province : state.get_provinces()) { @@ -187,11 +172,8 @@ bool StateManager::add_state_set( } bool StateManager::generate_states( - MapDefinition const& map_definition, - MapInstance& map_instance, - forwardable_span strata_keys, - forwardable_span pop_type_keys, - forwardable_span ideology_keys + MapDefinition const& map_definition, MapInstance& map_instance, forwardable_span strata_keys, + forwardable_span pop_type_keys, forwardable_span ideology_keys ) { state_sets.clear(); state_sets.reserve(map_definition.get_region_count()); @@ -226,4 +208,4 @@ void StateManager::update_gamestate() { fmt::format_context::iterator fmt::formatter::format(State const& state, fmt::format_context& ctx) const { return formatter::format(state.get_identifier(), ctx); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/State.hpp b/src/openvic-simulation/map/State.hpp index 038c11b04..0bf5c57d3 100644 --- a/src/openvic-simulation/map/State.hpp +++ b/src/openvic-simulation/map/State.hpp @@ -2,14 +2,15 @@ #include -#include #include +#include + +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/population/PopsAggregate.hpp" #include "openvic-simulation/types/ColonyStatus.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -31,7 +32,7 @@ namespace OpenVic { friend struct StateManager; private: - CountryInstance* previous_country_ptr = nullptr; + CountryInstance* previous_country_ptr = nullptr; ProvinceInstance* PROPERTY_PTR(capital); memory::vector> SPAN_PROPERTY(provinces); @@ -47,12 +48,9 @@ namespace OpenVic { StateSet const& state_set; State( - StateSet const& new_state_set, - ProvinceInstance* new_capital, - memory::vector>&& new_provinces, - colony_status_t new_colony_status, - forwardable_span strata_keys, - forwardable_span pop_type_keys, + StateSet const& new_state_set, ProvinceInstance* new_capital, + memory::vector>&& new_provinces, colony_status_t new_colony_status, + forwardable_span strata_keys, forwardable_span pop_type_keys, forwardable_span ideology_keys ); State(State&&) = delete; @@ -98,10 +96,8 @@ namespace OpenVic { memory::vector SPAN_PROPERTY(state_sets); bool add_state_set( - MapInstance& map_instance, Region const& region, - forwardable_span strata_keys, - forwardable_span pop_type_keys, - forwardable_span ideology_keys + MapInstance& map_instance, Region const& region, forwardable_span strata_keys, + forwardable_span pop_type_keys, forwardable_span ideology_keys ); public: @@ -109,11 +105,8 @@ namespace OpenVic { * After this function, the `regions` property is unmanaged and must be carefully updated and * validated by functions that modify it. */ bool generate_states( - MapDefinition const& map_definition, - MapInstance& map_instance, - forwardable_span strata_keys, - forwardable_span pop_type_keys, - forwardable_span ideology_keys + MapDefinition const& map_definition, MapInstance& map_instance, forwardable_span strata_keys, + forwardable_span pop_type_keys, forwardable_span ideology_keys ); void reset(); diff --git a/src/openvic-simulation/map/TerrainType.cpp b/src/openvic-simulation/map/TerrainType.cpp index 510c232a3..f407b6f2c 100644 --- a/src/openvic-simulation/map/TerrainType.cpp +++ b/src/openvic-simulation/map/TerrainType.cpp @@ -2,50 +2,37 @@ #include +#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/utility/Containers.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; TerrainType::TerrainType( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_modifier, - fixed_point_t new_movement_cost, - fixed_point_t new_defence_bonus, - fixed_point_t new_combat_width_percentage_change, + index_t new_index, std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_modifier, + fixed_point_t new_movement_cost, fixed_point_t new_defence_bonus, fixed_point_t new_combat_width_percentage_change, bool new_is_water -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(new_modifier), modifier_type_t::TERRAIN }, - HasColour { new_colour, false }, - movement_cost { new_movement_cost }, - defence_bonus { new_defence_bonus }, - combat_width_percentage_change { new_combat_width_percentage_change }, - is_water { new_is_water } {} +) + : HasIndex { new_index }, Modifier { new_identifier, std::move(new_modifier), modifier_type_t::TERRAIN }, + HasColour { new_colour, false }, movement_cost { new_movement_cost }, defence_bonus { new_defence_bonus }, + combat_width_percentage_change { new_combat_width_percentage_change }, is_water { new_is_water } {} TerrainTypeMapping::TerrainTypeMapping( - std::string_view new_identifier, - TerrainType const& new_type, - memory::vector&& new_terrain_indices, - index_t new_priority, - bool new_has_texture -) : HasIdentifier { new_identifier }, - type { new_type }, - terrain_indices { std::move(new_terrain_indices) }, - priority { new_priority }, - has_texture { new_has_texture } {} + std::string_view new_identifier, TerrainType const& new_type, memory::vector&& new_terrain_indices, + index_t new_priority, bool new_has_texture +) + : HasIdentifier { new_identifier }, type { new_type }, terrain_indices { std::move(new_terrain_indices) }, + priority { new_priority }, has_texture { new_has_texture } {} bool TerrainTypeManager::generate_modifiers(ModifierManager& modifier_manager) const { using enum ModifierEffect::format_t; IndexedFlatMap& unit_terrain_effects = modifier_manager.modifier_effect_cache.unit_terrain_effects; - unit_terrain_effects = std::move(decltype(ModifierEffectCache::unit_terrain_effects){get_terrain_types()}); + unit_terrain_effects = std::move(decltype(ModifierEffectCache::unit_terrain_effects) { get_terrain_types() }); bool ret = true; for (TerrainType const& terrain_type : get_terrain_types()) { @@ -72,13 +59,8 @@ bool TerrainTypeManager::generate_modifiers(ModifierManager& modifier_manager) c } bool TerrainTypeManager::add_terrain_type( - std::string_view identifier, - colour_t colour, - ModifierValue&& values, - fixed_point_t movement_cost, - fixed_point_t defence_bonus, - fixed_point_t combat_width_percentage_change, - bool is_water + std::string_view identifier, colour_t colour, ModifierValue&& values, fixed_point_t movement_cost, + fixed_point_t defence_bonus, fixed_point_t combat_width_percentage_change, bool is_water ) { if (identifier.empty()) { spdlog::error_s("Invalid terrain type identifier - empty!"); @@ -86,26 +68,19 @@ bool TerrainTypeManager::add_terrain_type( } if (movement_cost < 0) { - spdlog::error_s( - "Invalid movement cost for terrain type \"{}\": {} (cannot be negative!)", - identifier, movement_cost - ); + spdlog::error_s("Invalid movement cost for terrain type \"{}\": {} (cannot be negative!)", identifier, movement_cost); return false; } return terrain_types.emplace_item( - identifier, - TerrainType::index_t { get_terrain_type_count() }, identifier, - colour, std::move(values), movement_cost, defence_bonus, combat_width_percentage_change, is_water + identifier, TerrainType::index_t { get_terrain_type_count() }, identifier, colour, std::move(values), movement_cost, + defence_bonus, combat_width_percentage_change, is_water ); } bool TerrainTypeManager::add_terrain_type_mapping( - std::string_view identifier, - TerrainType const* type, - memory::vector&& terrain_indices, - TerrainTypeMapping::index_t priority, - bool has_texture + std::string_view identifier, TerrainType const* type, memory::vector&& terrain_indices, + TerrainTypeMapping::index_t priority, bool has_texture ) { if (!terrain_types_are_locked()) { spdlog::error_s("Cannot register terrain type mappings until terrain types are locked!"); @@ -131,51 +106,47 @@ bool TerrainTypeManager::add_terrain_type_mapping( terrain_type_mappings_map.emplace(idx, terrain_type_mappings.size()); } else { spdlog::error_s( - "Terrain index {} cannot map to {} as it already maps to {}", - static_cast(idx), identifier, ovfmt::validate(terrain_type_mappings.get_item_by_index(it->second)) + "Terrain index {} cannot map to {} as it already maps to {}", static_cast(idx), identifier, + ovfmt::validate(terrain_type_mappings.get_item_by_index(it->second)) ); ret = false; } } - ret &= terrain_type_mappings.emplace_item( - identifier, - identifier, *type, std::move(terrain_indices), priority, has_texture - ); + ret &= terrain_type_mappings.emplace_item(identifier, identifier, *type, std::move(terrain_indices), priority, has_texture); return ret; } node_callback_t TerrainTypeManager::_load_terrain_type_categories(ModifierManager const& modifier_manager) { - return [this, &modifier_manager](ast::NodeCPtr root) -> bool { - const bool ret = expect_dictionary_reserve_length(terrain_types, - [this, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_node) -> bool { - ModifierValue values; - fixed_point_t movement_cost, defence_bonus, combat_width_percentage_change; - colour_t colour = colour_t::null(); - bool is_water = false; - - bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_terrain_modifier(values), - "movement_cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_cost)), - "defence", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(defence_bonus)), - "combat_width", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(combat_width_percentage_change)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "is_water", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_water)) - )(type_node); - - ret &= add_terrain_type( - type_key, colour, std::move(values), movement_cost, defence_bonus, combat_width_percentage_change, is_water - ); - - return ret; - } - )(root); - - lock_terrain_types(); - - return ret; - }; + return + [this, &modifier_manager](ast::NodeCPtr root) -> bool { + const bool ret = + expect_dictionary_reserve_length(terrain_types, [this, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_node) -> bool { + ModifierValue values; + fixed_point_t movement_cost, defence_bonus, combat_width_percentage_change; + colour_t colour = colour_t::null(); + bool is_water = false; + + bool + ret = + NodeTools:: + expect_dictionary_keys_and_default(modifier_manager.expect_terrain_modifier(values), "movement_cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_cost)), "defence", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(defence_bonus)), "combat_width", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(combat_width_percentage_change)), "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), "is_water", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_water)))( + type_node + ); + + ret &= add_terrain_type( + type_key, colour, std::move(values), movement_cost, defence_bonus, combat_width_percentage_change, + is_water + ); + + return ret; + })(root); + + lock_terrain_types(); + + return ret; + }; } bool TerrainTypeManager::_load_terrain_type_mapping(std::string_view mapping_key, ast::NodeCPtr mapping_value) { diff --git a/src/openvic-simulation/map/TerrainType.hpp b/src/openvic-simulation/map/TerrainType.hpp index 802eef402..59eef10c9 100644 --- a/src/openvic-simulation/map/TerrainType.hpp +++ b/src/openvic-simulation/map/TerrainType.hpp @@ -21,13 +21,8 @@ namespace OpenVic { const bool is_water; TerrainType( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_modifier, - fixed_point_t new_movement_cost, - fixed_point_t new_defence_bonus, - fixed_point_t new_combat_width_percentage_change, + index_t new_index, std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_modifier, + fixed_point_t new_movement_cost, fixed_point_t new_defence_bonus, fixed_point_t new_combat_width_percentage_change, bool new_is_water ); TerrainType(TerrainType&&) = default; @@ -45,11 +40,8 @@ namespace OpenVic { const bool has_texture; TerrainTypeMapping( - std::string_view new_identifier, - TerrainType const& new_type, - memory::vector&& new_terrain_indices, - index_t new_priority, - bool new_has_texture + std::string_view new_identifier, TerrainType const& new_type, memory::vector&& new_terrain_indices, + index_t new_priority, bool new_has_texture ); TerrainTypeMapping(TerrainTypeMapping&&) = default; }; @@ -69,21 +61,13 @@ namespace OpenVic { public: bool add_terrain_type( - std::string_view identifier, - colour_t colour, - ModifierValue&& values, - fixed_point_t movement_cost, - fixed_point_t defence_bonus, - fixed_point_t combat_width_percentage_change, - bool is_water + std::string_view identifier, colour_t colour, ModifierValue&& values, fixed_point_t movement_cost, + fixed_point_t defence_bonus, fixed_point_t combat_width_percentage_change, bool is_water ); bool add_terrain_type_mapping( - std::string_view identifier, - TerrainType const* type, - memory::vector&& terrain_indices, - TerrainTypeMapping::index_t priority, - bool has_texture + std::string_view identifier, TerrainType const* type, memory::vector&& terrain_indices, + TerrainTypeMapping::index_t priority, bool has_texture ); TerrainTypeMapping const* get_terrain_type_mapping_for(TerrainTypeMapping::index_t idx) const; diff --git a/src/openvic-simulation/military/CombatWidth.hpp b/src/openvic-simulation/military/CombatWidth.hpp index c1ed14326..23a13e73a 100644 --- a/src/openvic-simulation/military/CombatWidth.hpp +++ b/src/openvic-simulation/military/CombatWidth.hpp @@ -9,11 +9,11 @@ namespace OpenVic { struct combat_width_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } @@ -23,4 +23,4 @@ struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(OpenVic::combat_width_t const& value, fmt::format_context& ctx) const { return fmt::formatter::format(type_safe::get(value), ctx); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/military/Deployment.cpp b/src/openvic-simulation/military/Deployment.cpp index 6959d7b54..988357297 100644 --- a/src/openvic-simulation/military/Deployment.cpp +++ b/src/openvic-simulation/military/Deployment.cpp @@ -2,9 +2,9 @@ #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/map/MapDefinition.hpp" -#include "openvic-simulation/military/MilitaryManager.hpp" #include "openvic-simulation/military/Leader.hpp" #include "openvic-simulation/military/LeaderTrait.hpp" +#include "openvic-simulation/military/MilitaryManager.hpp" #include "openvic-simulation/military/UnitType.hpp" #include "openvic-simulation/utility/Containers.hpp" @@ -13,7 +13,8 @@ using namespace OpenVic::NodeTools; UnitDeployment::UnitDeployment( std::string_view new_name, RegimentType const& new_type, ProvinceDefinition const* new_home -) : name { new_name }, type { new_type }, home { new_home } {} +) + : name { new_name }, type { new_type }, home { new_home } {} UnitDeployment::UnitDeployment(std::string_view new_name, ShipType const& new_type) : name { new_name }, type { new_type } {} @@ -22,13 +23,15 @@ template UnitDeploymentGroup::UnitDeploymentGroup( std::string_view new_name, ProvinceDefinition const& new_location, memory::vector<_Unit>&& new_units, std::optional new_leader_index -) : name { new_name }, location { new_location }, units { std::move(new_units) }, leader_index { new_leader_index } {} +) + : name { new_name }, location { new_location }, units { std::move(new_units) }, leader_index { new_leader_index } {} Deployment::Deployment( std::string_view new_path, memory::vector&& new_armies, memory::vector&& new_navies, memory::vector&& new_leaders -) : HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, - leaders { std::move(new_leaders) } {} +) + : HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, + leaders { std::move(new_leaders) } {} bool DeploymentManager::add_deployment( std::string_view path, memory::vector&& armies, memory::vector&& navies, @@ -39,19 +42,12 @@ bool DeploymentManager::add_deployment( return false; } - return deployments.emplace_item( - path, - path, std::move(armies), std::move(navies), std::move(leaders) - ); + return deployments.emplace_item(path, path, std::move(armies), std::move(navies), std::move(leaders)); } bool DeploymentManager::load_oob_file( - Dataloader const& dataloader, - MapDefinition const& map_definition, - MilitaryManager const& military_manager, - std::string_view history_path, - Deployment const*& deployment, - bool fail_on_missing + Dataloader const& dataloader, MapDefinition const& map_definition, MilitaryManager const& military_manager, + std::string_view history_path, Deployment const*& deployment, bool fail_on_missing ) { deployment = get_deployment_by_identifier(history_path); if (deployment != nullptr) { @@ -65,8 +61,7 @@ bool DeploymentManager::load_oob_file( static constexpr std::string_view oob_directory = "history/units/"; - const fs::path lookedup_path = - dataloader.lookup_file(append_string_views(oob_directory, history_path), false); + const fs::path lookedup_path = dataloader.lookup_file(append_string_views(oob_directory, history_path), false); if (lookedup_path.empty()) { missing_oob_files.emplace(history_path); @@ -96,7 +91,8 @@ bool DeploymentManager::load_oob_file( using enum unit_branch_t; - const auto leader_callback = [&map_definition, &military_manager, &general_count, &admiral_count](ast::NodeCPtr node) -> bool { + const auto leader_callback = [&map_definition, &military_manager, &general_count, + &admiral_count](ast::NodeCPtr node) -> bool { std::string_view leader_name {}; unit_branch_t leader_branch = INVALID_BRANCH; Date leader_date {}; @@ -127,26 +123,18 @@ bool DeploymentManager::load_oob_file( // Default cases for leader personality and background match vic2 behaviour of ignoring invalid traits. if (leader_personality != nullptr && !leader_personality->is_personality_trait()) { spdlog::warn_s( - "Leader {} has personality \"{}\" which is not a personality trait!", - leader_name, *leader_personality + "Leader {} has personality \"{}\" which is not a personality trait!", leader_name, *leader_personality ); leader_personality = nullptr; } if (leader_background != nullptr && !leader_background->is_background_trait()) { - spdlog::warn_s( - "Leader {} has background \"{}\" which is not a background trait!", - leader_name, *leader_background - ); + spdlog::warn_s("Leader {} has background \"{}\" which is not a background trait!", leader_name, *leader_background); leader_background = nullptr; } switch (leader_branch) { - case LAND: - ++general_count; - break; - case NAVAL: - ++admiral_count; - break; + case LAND: ++general_count; break; + case NAVAL: ++admiral_count; break; default: spdlog::error_s("Invalid branch {} for leader {}", static_cast(leader_branch), leader_name); return false; @@ -267,12 +255,9 @@ bool DeploymentManager::load_oob_file( if (general_count + admiral_count != leaders.size()) { spdlog::error_s( - "Mismatch in sum (#{}) of general (#{}) and admiral (#{}) counts when compared to loaded leader count (#{}) for OOB file {}", - general_count + admiral_count, - general_count, - admiral_count, - leaders.size(), - history_path + "Mismatch in sum (#{}) of general (#{}) and admiral (#{}) counts when compared to loaded leader count (#{}) for " + "OOB file {}", + general_count + admiral_count, general_count, admiral_count, leaders.size(), history_path ); return false; } diff --git a/src/openvic-simulation/military/Deployment.hpp b/src/openvic-simulation/military/Deployment.hpp index c3c1a073b..64fac54b9 100644 --- a/src/openvic-simulation/military/Deployment.hpp +++ b/src/openvic-simulation/military/Deployment.hpp @@ -85,9 +85,7 @@ namespace OpenVic { public: Deployment( - std::string_view new_path, - memory::vector&& new_armies, - memory::vector&& new_navies, + std::string_view new_path, memory::vector&& new_armies, memory::vector&& new_navies, memory::vector&& new_leaders ); Deployment(Deployment&&) = default; @@ -102,19 +100,13 @@ namespace OpenVic { public: bool add_deployment( - std::string_view path, - memory::vector&& armies, - memory::vector&& navies, + std::string_view path, memory::vector&& armies, memory::vector&& navies, memory::vector&& leaders ); bool load_oob_file( - Dataloader const& dataloader, - MapDefinition const& map_definition, - MilitaryManager const& military_manager, - std::string_view history_path, - Deployment const*& deployment, - bool fail_on_missing + Dataloader const& dataloader, MapDefinition const& map_definition, MilitaryManager const& military_manager, + std::string_view history_path, Deployment const*& deployment, bool fail_on_missing ); size_t get_missing_oob_file_count() const; diff --git a/src/openvic-simulation/military/Leader.cpp b/src/openvic-simulation/military/Leader.cpp index 41361dff3..b57e1813e 100644 --- a/src/openvic-simulation/military/Leader.cpp +++ b/src/openvic-simulation/military/Leader.cpp @@ -3,20 +3,11 @@ using namespace OpenVic; LeaderBase::LeaderBase( - std::string_view new_name, - unit_branch_t new_branch, - Date new_date, - LeaderTrait const* new_personality, - LeaderTrait const* new_background, - fixed_point_t new_prestige, - std::string_view new_picture -) : name { new_name }, - branch { new_branch }, - date { new_date }, - personality { new_personality }, - background { new_background }, - prestige { new_prestige }, - picture { new_picture } {} + std::string_view new_name, unit_branch_t new_branch, Date new_date, LeaderTrait const* new_personality, + LeaderTrait const* new_background, fixed_point_t new_prestige, std::string_view new_picture +) + : name { new_name }, branch { new_branch }, date { new_date }, personality { new_personality }, + background { new_background }, prestige { new_prestige }, picture { new_picture } {} void LeaderBase::set_picture(std::string_view new_picture) { picture = new_picture; diff --git a/src/openvic-simulation/military/Leader.hpp b/src/openvic-simulation/military/Leader.hpp index 25c4245cf..8a5ae6843 100644 --- a/src/openvic-simulation/military/Leader.hpp +++ b/src/openvic-simulation/military/Leader.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/types/Date.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/UniqueId.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -52,6 +52,7 @@ namespace OpenVic { private: UnitInstanceGroup* PROPERTY_PTR(unit_instance_group, nullptr); bool PROPERTY_RW(can_be_used, true); + public: const unique_id_t unique_id; diff --git a/src/openvic-simulation/military/UnitInstance.cpp b/src/openvic-simulation/military/UnitInstance.cpp index 99ee5c9f6..65ae00aa0 100644 --- a/src/openvic-simulation/military/UnitInstance.cpp +++ b/src/openvic-simulation/military/UnitInstance.cpp @@ -2,33 +2,22 @@ using namespace OpenVic; -UnitInstance::UnitInstance( - unique_id_t new_unique_id, - std::string_view new_name, - UnitType const& new_unit_type -) : unique_id { new_unique_id }, - name { new_name }, - unit_type { new_unit_type }, - organisation { new_unit_type.default_organisation }, - max_organisation { organisation }, - strength { new_unit_type.max_strength } {} +UnitInstance::UnitInstance(unique_id_t new_unique_id, std::string_view new_name, UnitType const& new_unit_type) + : unique_id { new_unique_id }, name { new_name }, unit_type { new_unit_type }, + organisation { new_unit_type.default_organisation }, max_organisation { organisation }, + strength { new_unit_type.max_strength } {} void UnitInstance::set_name(std::string_view new_name) { name = new_name; } UnitInstanceBranched::UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - RegimentType const& new_regiment_type, - Pop* new_pop, + unique_id_t new_unique_id, std::string_view new_name, RegimentType const& new_regiment_type, Pop* new_pop, bool new_mobilised -) : UnitInstance { new_unique_id, new_name, new_regiment_type }, - pop { new_pop }, - mobilised { new_mobilised } {} +) + : UnitInstance { new_unique_id, new_name, new_regiment_type }, pop { new_pop }, mobilised { new_mobilised } {} UnitInstanceBranched::UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - ShipType const& new_ship_type -) : UnitInstance { new_unique_id, new_name, new_ship_type } {} + unique_id_t new_unique_id, std::string_view new_name, ShipType const& new_ship_type +) + : UnitInstance { new_unique_id, new_name, new_ship_type } {} diff --git a/src/openvic-simulation/military/UnitInstance.hpp b/src/openvic-simulation/military/UnitInstance.hpp index 9b3a57d6d..067d26ea6 100644 --- a/src/openvic-simulation/military/UnitInstance.hpp +++ b/src/openvic-simulation/military/UnitInstance.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/military/UnitType.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/UniqueId.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -18,11 +18,7 @@ namespace OpenVic { fixed_point_t PROPERTY(strength); protected: - UnitInstance( - unique_id_t new_unique_id, - std::string_view new_name, - UnitType const& new_unit_type - ); + UnitInstance(unique_id_t new_unique_id, std::string_view new_name, UnitType const& new_unit_type); public: const unique_id_t unique_id; @@ -56,10 +52,7 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(mobilised, is); UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - RegimentType const& new_regiment_type, - Pop* new_pop, + unique_id_t new_unique_id, std::string_view new_name, RegimentType const& new_regiment_type, Pop* new_pop, bool new_mobilised ); @@ -76,11 +69,7 @@ namespace OpenVic { friend struct UnitInstanceManager; private: - UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - ShipType const& new_ship_type - ); + UnitInstanceBranched(unique_id_t new_unique_id, std::string_view new_name, ShipType const& new_ship_type); public: UnitInstanceBranched(UnitInstanceBranched&&) = default; diff --git a/src/openvic-simulation/military/UnitInstanceGroup.cpp b/src/openvic-simulation/military/UnitInstanceGroup.cpp index 6bb28d70f..357403b59 100644 --- a/src/openvic-simulation/military/UnitInstanceGroup.cpp +++ b/src/openvic-simulation/military/UnitInstanceGroup.cpp @@ -20,18 +20,13 @@ using namespace OpenVic; using enum unit_branch_t; UnitInstanceGroup::UnitInstanceGroup( - unique_id_t new_unique_id, - unit_branch_t new_branch, - std::string_view new_name, - CountryInstance& new_country, + unique_id_t new_unique_id, unit_branch_t new_branch, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location -) : unique_id { new_unique_id }, - branch { new_branch }, - name { new_name }, - country { new_country }, - location { new_location } { - new_country.add_unit_instance_group(*this); - } +) + : unique_id { new_unique_id }, branch { new_branch }, name { new_name }, country { new_country }, + location { new_location } { + new_country.add_unit_instance_group(*this); +} void UnitInstanceGroup::update_gamestate() { total_organisation = 0; @@ -47,9 +42,7 @@ void UnitInstanceGroup::update_gamestate() { } } -void UnitInstanceGroup::tick() { - -} +void UnitInstanceGroup::tick() {} size_t UnitInstanceGroup::get_unit_count() const { return units.size(); @@ -78,10 +71,9 @@ UnitType const* UnitInstanceGroup::get_display_unit_type() const { } return get_largest_item_tie_break( - weighted_unit_types, - [](UnitType const* lhs, UnitType const* rhs) -> bool { - return lhs->weighted_value < rhs->weighted_value; - } + weighted_unit_types, [](UnitType const* lhs, UnitType const* rhs) -> bool { + return lhs->weighted_value < rhs->weighted_value; + } )->first; } @@ -91,8 +83,8 @@ bool UnitInstanceGroup::add_unit(UnitInstance& unit) { return true; } else { spdlog::error_s( - "Trying to add {} unit \"{}\" to {} unit group \"{}\"", - get_branch_name(unit.get_branch()), unit.get_name(), get_branch_name(branch), get_name() + "Trying to add {} unit \"{}\" to {} unit group \"{}\"", get_branch_name(unit.get_branch()), unit.get_name(), + get_branch_name(branch), get_name() ); return false; } @@ -105,10 +97,7 @@ bool UnitInstanceGroup::remove_unit(UnitInstance const& unit) { units.erase(it); return true; } else { - spdlog::error_s( - "Trying to remove non-existent unit \"{}\" from unit group \"{}\"", - unit.get_name(), get_name() - ); + spdlog::error_s("Trying to remove non-existent unit \"{}\" from unit group \"{}\"", unit.get_name(), get_name()); return false; } } @@ -150,8 +139,7 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { leader->unit_instance_group = nullptr; } else { spdlog::error_s( - "Mismatch between leader and unit instance group: group {} has leader {} but the leader has group {}", - name, + "Mismatch between leader and unit instance group: group {} has leader {} but the leader has group {}", name, leader->get_name(), leader->get_unit_instance_group() != nullptr ? leader->get_unit_instance_group()->get_name() : "NULL" ); @@ -164,8 +152,8 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { if (new_leader != nullptr) { if (OV_unlikely(new_leader->branch != branch)) { spdlog::error_s( - "Trying to assign {} leader \"{}\" to {} unit group \"{}\"", - get_branch_name(new_leader->branch), new_leader->get_name(), get_branch_name(branch), name + "Trying to assign {} leader \"{}\" to {} unit group \"{}\"", get_branch_name(new_leader->branch), + new_leader->get_name(), get_branch_name(branch), name ); return false; } @@ -173,12 +161,8 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { if (OV_unlikely(new_leader->country != country)) { spdlog::error_s( "Trying to assign {} \"{}\" of country \"{}\" to {} \"{}\" of country \"{}\"", - get_branched_leader_name(new_leader->branch), - new_leader->get_name(), - new_leader->country, - get_branched_unit_group_name(branch), - name, - country + get_branched_leader_name(new_leader->branch), new_leader->get_name(), new_leader->country, + get_branched_unit_group_name(branch), name, country ); return false; } @@ -188,8 +172,8 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { ret &= new_leader->unit_instance_group->set_leader(nullptr); } else { spdlog::error_s( - "{} {} already leads {} {}!", - get_branched_leader_name(new_leader->branch), new_leader->get_name(),get_branched_unit_group_name(branch), name + "{} {} already leads {} {}!", get_branched_leader_name(new_leader->branch), new_leader->get_name(), + get_branched_unit_group_name(branch), name ); ret = false; } @@ -239,11 +223,9 @@ bool UnitInstanceGroup::is_in_combat() const { } UnitInstanceGroupBranched::UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location -) : UnitInstanceGroup { new_unique_id, LAND, new_name, new_country, new_location } {} + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location +) + : UnitInstanceGroup { new_unique_id, LAND, new_name, new_country, new_location } {} void UnitInstanceGroupBranched::update_gamestate() { UnitInstanceGroup::update_gamestate(); @@ -254,11 +236,9 @@ void UnitInstanceGroupBranched::tick() { } UnitInstanceGroupBranched::UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location -) : UnitInstanceGroup { new_unique_id, NAVAL, new_name, new_country, new_location } {} + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location +) + : UnitInstanceGroup { new_unique_id, NAVAL, new_name, new_country, new_location } {} void UnitInstanceGroupBranched::update_gamestate() { UnitInstanceGroup::update_gamestate(); @@ -296,7 +276,7 @@ Pop* UnitInstanceManager::recruit_pop_in(ProvinceInstance& province, const bool } } - //fallback to understrength pops + // fallback to understrength pops if (is_rebel) { for (auto& pop : province.get_mutable_pops()) { if (pop.get_rebel_type() != nullptr && pop.try_recruit_understrength()) { @@ -319,9 +299,7 @@ Pop* UnitInstanceManager::recruit_pop_in(ProvinceInstance& province, const bool template UnitInstanceBranched& UnitInstanceManager::generate_unit_instance( - UnitDeployment const& unit_deployment, - MapInstance& map_instance, - const bool is_rebel + UnitDeployment const& unit_deployment, MapInstance& map_instance, const bool is_rebel ) { UnitInstanceBranched& unit_instance = *get_unit_instances().insert( [this, &unit_deployment, &map_instance, is_rebel]() -> UnitInstanceBranched { @@ -329,25 +307,16 @@ UnitInstanceBranched& UnitInstanceManager::generate_unit_instance( RegimentDeployment const& regiment_deployment = unit_deployment; ProvinceInstance& province = map_instance.get_province_instance_by_definition(*regiment_deployment.get_home()); Pop* const pop_ptr = recruit_pop_in(province, is_rebel); - if (pop_ptr == nullptr) { + if (pop_ptr == nullptr) { spdlog::warn_s( - "Regiment {} in province {} lacks backing pop.", regiment_deployment.get_name(), province.get_identifier() + "Regiment {} in province {} lacks backing pop.", regiment_deployment.get_name(), + province.get_identifier() ); } - return { - unique_id_counter++, - unit_deployment.get_name(), - unit_deployment.type, - pop_ptr, - false - }; + return { unique_id_counter++, unit_deployment.get_name(), unit_deployment.type, pop_ptr, false }; } else if constexpr (Branch == NAVAL) { - return { - unique_id_counter++, - unit_deployment.get_name(), - unit_deployment.type - }; + return { unique_id_counter++, unit_deployment.get_name(), unit_deployment.type }; } }() ); @@ -363,27 +332,20 @@ bool UnitInstanceManager::generate_unit_instance_group( ) { if (unit_deployment_group.get_units().empty()) { spdlog::error_s( - "Trying to generate unit group \"{}\" with no units for country \"{}\"", - unit_deployment_group.get_name(), country + "Trying to generate unit group \"{}\" with no units for country \"{}\"", unit_deployment_group.get_name(), country ); return false; } - + ProvinceInstance& location = map_instance.get_province_instance_by_definition(unit_deployment_group.get_location()); - UnitInstanceGroupBranched& unit_instance_group = *get_unit_instance_groups().emplace( - unique_id_counter++, - unit_deployment_group.get_name(), - country, - location - ); + UnitInstanceGroupBranched& unit_instance_group = + *get_unit_instance_groups().emplace(unique_id_counter++, unit_deployment_group.get_name(), country, location); unit_instance_group_map.emplace(unit_instance_group.unique_id, unit_instance_group); bool ret = true; for (UnitDeployment const& unit_deployment : unit_deployment_group.get_units()) { - ret &= unit_instance_group.add_unit( - generate_unit_instance(unit_deployment, map_instance, country.is_rebel_country()) - ); + ret &= unit_instance_group.add_unit(generate_unit_instance(unit_deployment, map_instance, country.is_rebel_country())); } ret &= unit_instance_group.set_country(country); @@ -398,8 +360,8 @@ bool UnitInstanceManager::generate_unit_instance_group( ret &= unit_instance_group.set_leader(&it->get()); } else { spdlog::error_s( - "Invalid leader index {} for unit group \"{}\" for country \"{}\"", - *unit_deployment_group.get_leader_index(), unit_deployment_group.get_name(), country + "Invalid leader index {} for unit group \"{}\" for country \"{}\"", *unit_deployment_group.get_leader_index(), + unit_deployment_group.get_name(), country ); ret = false; } @@ -410,28 +372,23 @@ bool UnitInstanceManager::generate_unit_instance_group( template void UnitInstanceManager::generate_leader(CountryInstance& country, T&& leader_base) { - LeaderInstance& leader_instance = *leaders.emplace( - unique_id_counter++, - std::forward(leader_base), - country - ); + LeaderInstance& leader_instance = *leaders.emplace(unique_id_counter++, std::forward(leader_base), country); leader_instance_map.emplace(leader_instance.unique_id, leader_instance); country.add_leader(leader_instance); if (leader_instance.get_picture().empty() && country.get_primary_culture() != nullptr) { - leader_instance.set_picture(culture_manager.get_leader_picture_name( - country.get_primary_culture()->group.get_leader(), leader_instance.branch - )); + leader_instance.set_picture( + culture_manager.get_leader_picture_name(country.get_primary_culture()->group.get_leader(), leader_instance.branch) + ); } } UnitInstanceManager::UnitInstanceManager( - CultureManager const& new_culture_manager, - LeaderTraitManager const& new_leader_trait_manager, + CultureManager const& new_culture_manager, LeaderTraitManager const& new_leader_trait_manager, MilitaryDefines const& new_military_defines -) : culture_manager { new_culture_manager }, - leader_trait_manager { new_leader_trait_manager }, - military_defines { new_military_defines } {} +) + : culture_manager { new_culture_manager }, leader_trait_manager { new_leader_trait_manager }, + military_defines { new_military_defines } {} bool UnitInstanceManager::generate_deployment( MapInstance& map_instance, CountryInstance& country, Deployment const& deployment @@ -503,20 +460,14 @@ UnitInstanceGroup* UnitInstanceManager::get_unit_instance_group_by_unique_id(uni } bool UnitInstanceManager::create_leader( - CountryInstance& country, - unit_branch_t branch, - Date creation_date, - std::string_view name, - LeaderTrait const* personality, + CountryInstance& country, unit_branch_t branch, Date creation_date, std::string_view name, LeaderTrait const* personality, LeaderTrait const* background ) { const fixed_point_t leader_creation_cost = military_defines.get_leader_recruit_cost(); if (country.get_leadership_point_stockpile() < leader_creation_cost) { spdlog::error_s( - "Country \"{}\" does not have enough leadership points ({}) to create a {} (cost: {})", - country, - country.get_leadership_point_stockpile().to_string(2), - get_branched_leader_name(branch), + "Country \"{}\" does not have enough leadership points ({}) to create a {} (cost: {})", country, + country.get_leadership_point_stockpile().to_string(2), get_branched_leader_name(branch), leader_creation_cost.to_string(2) ); return false; @@ -555,30 +506,28 @@ bool UnitInstanceManager::create_leader( // TODO - use "noTrait" or "noPersonality" or "noBackground" if either is nullptr if (personality == nullptr && !leader_trait_manager.get_personality_traits().empty()) { - personality = leader_trait_manager.get_personality_traits()[ - item_selection_counter++ % leader_trait_manager.get_personality_traits().size() - ]; + personality = + leader_trait_manager + .get_personality_traits()[item_selection_counter++ % leader_trait_manager.get_personality_traits().size()]; } if (background == nullptr && !leader_trait_manager.get_background_traits().empty()) { - background = leader_trait_manager.get_background_traits()[ - item_selection_counter++ % leader_trait_manager.get_background_traits().size() - ]; + background = + leader_trait_manager + .get_background_traits()[item_selection_counter++ % leader_trait_manager.get_background_traits().size()]; } // TODO - make starting prestige a random proportion of the maximum random prestige const fixed_point_t starting_prestige = military_defines.get_leader_max_random_prestige() * static_cast(item_selection_counter++ % 11) / 10; - generate_leader(country, LeaderBase{ - name, - branch, - creation_date, - personality, - background, - starting_prestige, - {} // No picture, will be set up by generate_leader - }); + generate_leader( + country, + LeaderBase { + name, branch, creation_date, personality, background, starting_prestige, {} // No picture, will be set up by + // generate_leader + } + ); return true; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/military/UnitInstanceGroup.hpp b/src/openvic-simulation/military/UnitInstanceGroup.hpp index cbd94049d..9069830ff 100644 --- a/src/openvic-simulation/military/UnitInstanceGroup.hpp +++ b/src/openvic-simulation/military/UnitInstanceGroup.hpp @@ -6,14 +6,13 @@ #include #include "openvic-simulation/military/Leader.hpp" +#include "openvic-simulation/military/UnitBranchedGetterMacro.hpp" //below other imports that undef the macros #include "openvic-simulation/military/UnitInstance.hpp" #include "openvic-simulation/military/UnitType.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" -#include "openvic-simulation/utility/Getters.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" - -#include "openvic-simulation/military/UnitBranchedGetterMacro.hpp" //below other imports that undef the macros +#include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { struct ProvinceInstance; @@ -43,10 +42,7 @@ namespace OpenVic { protected: UnitInstanceGroup( - unique_id_t new_unique_id, - unit_branch_t new_branch, - std::string_view new_name, - CountryInstance& new_country, + unique_id_t new_unique_id, unit_branch_t new_branch, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ); @@ -103,10 +99,7 @@ namespace OpenVic { public: UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ); UnitInstanceGroupBranched(UnitInstanceGroupBranched&&) = default; @@ -115,10 +108,12 @@ namespace OpenVic { // TODO - do these work fine when units is empty? std::span> get_regiment_instances() { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } std::span> get_regiment_instances() const { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } }; @@ -129,10 +124,7 @@ namespace OpenVic { public: UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ); UnitInstanceGroupBranched(UnitInstanceGroupBranched&&) = default; @@ -143,7 +135,8 @@ namespace OpenVic { return { reinterpret_cast const*>(get_units().data()), get_units().size() }; } std::span> get_ship_instances() const { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } fixed_point_t get_total_consumed_supply() const; @@ -192,11 +185,8 @@ namespace OpenVic { Pop* recruit_pop_in(ProvinceInstance& province, const bool is_rebel) const; template - UnitInstanceBranched& generate_unit_instance( - UnitDeployment const& unit_deployment, - MapInstance& map_instance, - const bool is_rebel - ); + UnitInstanceBranched& + generate_unit_instance(UnitDeployment const& unit_deployment, MapInstance& map_instance, const bool is_rebel); template bool generate_unit_instance_group( MapInstance& map_instance, CountryInstance& country, UnitDeploymentGroup const& unit_deployment_group @@ -206,8 +196,7 @@ namespace OpenVic { public: UnitInstanceManager( - CultureManager const& new_culture_manager, - LeaderTraitManager const& new_leader_trait_manager, + CultureManager const& new_culture_manager, LeaderTraitManager const& new_leader_trait_manager, MilitaryDefines const& new_military_defines ); @@ -225,12 +214,8 @@ namespace OpenVic { // leadership points will be checked and, if there are enough, have the leader creation cost subtracted from them. // If the country does not have enough leadership points, the function will return false and no leader will be created. bool create_leader( - CountryInstance& country, - unit_branch_t branch, - Date creation_date, - std::string_view name = {}, - LeaderTrait const* personality = nullptr, - LeaderTrait const* background = nullptr + CountryInstance& country, unit_branch_t branch, Date creation_date, std::string_view name = {}, + LeaderTrait const* personality = nullptr, LeaderTrait const* background = nullptr ); }; } diff --git a/src/openvic-simulation/military/UnitType.cpp b/src/openvic-simulation/military/UnitType.cpp index fd3a597ef..083444374 100644 --- a/src/openvic-simulation/military/UnitType.cpp +++ b/src/openvic-simulation/military/UnitType.cpp @@ -4,6 +4,7 @@ #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/map/TerrainType.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" + #include "modifier/ModifierEffectCache.hpp" #include "types/UnitBranchType.hpp" @@ -13,73 +14,47 @@ using namespace OpenVic::NodeTools; using enum unit_branch_t; using enum UnitType::unit_category_t; -UnitType::UnitType( - std::string_view new_identifier, unit_branch_t new_branch, unit_type_args_t& unit_args -) : HasIdentifier { new_identifier }, - branch { new_branch }, - icon { unit_args.icon }, - sprite { unit_args.sprite }, - starts_unlocked { unit_args.starts_unlocked }, - unit_category { unit_args.unit_category }, - has_floating_flag { unit_args.floating_flag }, - priority { unit_args.priority }, - max_strength { unit_args.max_strength }, - default_organisation { unit_args.default_organisation }, - maximum_speed { unit_args.maximum_speed }, - weighted_value { unit_args.weighted_value }, - move_sound { unit_args.move_sound }, - select_sound { unit_args.select_sound }, - build_time { unit_args.build_time }, - build_cost { std::move(unit_args.build_cost) }, - supply_consumption { unit_args.supply_consumption }, - supply_cost { std::move(unit_args.supply_cost) } { +UnitType::UnitType(std::string_view new_identifier, unit_branch_t new_branch, unit_type_args_t& unit_args) + : HasIdentifier { new_identifier }, branch { new_branch }, icon { unit_args.icon }, sprite { unit_args.sprite }, + starts_unlocked { unit_args.starts_unlocked }, unit_category { unit_args.unit_category }, + has_floating_flag { unit_args.floating_flag }, priority { unit_args.priority }, max_strength { unit_args.max_strength }, + default_organisation { unit_args.default_organisation }, maximum_speed { unit_args.maximum_speed }, + weighted_value { unit_args.weighted_value }, move_sound { unit_args.move_sound }, select_sound { unit_args.select_sound }, + build_time { unit_args.build_time }, build_cost { std::move(unit_args.build_cost) }, + supply_consumption { unit_args.supply_consumption }, supply_cost { std::move(unit_args.supply_cost) } { using enum Modifier::modifier_type_t; for (auto [terrain, modifier_value] : mutable_iterator(unit_args.terrain_modifier_values)) { - terrain_modifiers.emplace(terrain, Modifier { - memory::fmt::format("{} {}", new_identifier, *terrain), std::move(modifier_value), - UNIT_TERRAIN - }); + terrain_modifiers.emplace( + terrain, + Modifier { memory::fmt::format("{} {}", new_identifier, *terrain), std::move(modifier_value), UNIT_TERRAIN } + ); } } UnitTypeBranched::UnitTypeBranched( - index_t new_index, std::string_view new_identifier, - unit_type_args_t& unit_args, regiment_type_args_t const& regiment_type_args -) : UnitType { new_identifier, LAND, unit_args }, - HasIndex { new_index }, - allowed_cultures { regiment_type_args.allowed_cultures }, - sprite_override { regiment_type_args.sprite_override }, - sprite_mount { regiment_type_args.sprite_mount }, - sprite_mount_attach_node { regiment_type_args.sprite_mount_attach_node }, - reconnaissance { regiment_type_args.reconnaissance }, - attack { regiment_type_args.attack }, - defence { regiment_type_args.defence }, - discipline { regiment_type_args.discipline }, - support { regiment_type_args.support }, - maneuver { regiment_type_args.maneuver }, - siege { regiment_type_args.siege } {} + index_t new_index, std::string_view new_identifier, unit_type_args_t& unit_args, + regiment_type_args_t const& regiment_type_args +) + : UnitType { new_identifier, LAND, unit_args }, HasIndex { new_index }, + allowed_cultures { regiment_type_args.allowed_cultures }, sprite_override { regiment_type_args.sprite_override }, + sprite_mount { regiment_type_args.sprite_mount }, + sprite_mount_attach_node { regiment_type_args.sprite_mount_attach_node }, + reconnaissance { regiment_type_args.reconnaissance }, attack { regiment_type_args.attack }, + defence { regiment_type_args.defence }, discipline { regiment_type_args.discipline }, + support { regiment_type_args.support }, maneuver { regiment_type_args.maneuver }, siege { regiment_type_args.siege } {} UnitTypeBranched::UnitTypeBranched( - index_t new_index, std::string_view new_identifier, - unit_type_args_t& unit_args, ship_type_args_t const& ship_type_args -) : UnitType { new_identifier, NAVAL, unit_args }, - HasIndex { new_index }, - naval_icon { ship_type_args.naval_icon }, - can_sail { ship_type_args.sail }, - is_transport { ship_type_args.transport }, - is_capital { ship_type_args.capital }, - colonial_points { ship_type_args.colonial_points }, - can_build_overseas { ship_type_args.build_overseas }, - min_port_level { ship_type_args.min_port_level }, - limit_per_port { ship_type_args.limit_per_port }, - supply_consumption_score { ship_type_args.supply_consumption_score }, - hull { ship_type_args.hull }, - gun_power { ship_type_args.gun_power }, - fire_range { ship_type_args.fire_range }, - evasion { ship_type_args.evasion }, - torpedo_attack { ship_type_args.torpedo_attack } {} + index_t new_index, std::string_view new_identifier, unit_type_args_t& unit_args, ship_type_args_t const& ship_type_args +) + : UnitType { new_identifier, NAVAL, unit_args }, HasIndex { new_index }, naval_icon { ship_type_args.naval_icon }, + can_sail { ship_type_args.sail }, is_transport { ship_type_args.transport }, is_capital { ship_type_args.capital }, + colonial_points { ship_type_args.colonial_points }, can_build_overseas { ship_type_args.build_overseas }, + min_port_level { ship_type_args.min_port_level }, limit_per_port { ship_type_args.limit_per_port }, + supply_consumption_score { ship_type_args.supply_consumption_score }, hull { ship_type_args.hull }, + gun_power { ship_type_args.gun_power }, fire_range { ship_type_args.fire_range }, evasion { ship_type_args.evasion }, + torpedo_attack { ship_type_args.torpedo_attack } {} void UnitTypeManager::reserve_all_unit_types(size_t size) { reserve_more_unit_types(size); @@ -100,10 +75,7 @@ static bool _check_shared_parameters(std::string_view identifier, UnitType::unit } if (unit_args.icon < 0) { - spdlog::error_s( - "Invalid icon for unit {} - {} (must be >= 0)", - identifier, unit_args.icon - ); + spdlog::error_s("Invalid icon for unit {} - {} (must be >= 0)", identifier, unit_args.icon); return false; } @@ -118,7 +90,8 @@ static bool _check_shared_parameters(std::string_view identifier, UnitType::unit } bool UnitTypeManager::add_regiment_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, RegimentType::regiment_type_args_t const& regiment_type_args + std::string_view identifier, UnitType::unit_type_args_t& unit_args, + RegimentType::regiment_type_args_t const& regiment_type_args ) { if (!_check_shared_parameters(identifier, unit_args)) { return false; @@ -132,9 +105,7 @@ bool UnitTypeManager::add_regiment_type( } bool ret = regiment_types.emplace_item( - identifier, - RegimentType::index_t { get_regiment_type_count() }, identifier, - unit_args, std::move(regiment_type_args) + identifier, RegimentType::index_t { get_regiment_type_count() }, identifier, unit_args, std::move(regiment_type_args) ); if (ret) { // Cannot use get_back_regiment_type() as we need non-const but don't want to generate all non-const functions. @@ -164,11 +135,8 @@ bool UnitTypeManager::add_ship_type( return false; } - bool ret = ship_types.emplace_item( - identifier, - ShipType::index_t { get_ship_type_count() }, identifier, - unit_args, ship_type_args - ); + bool ret = + ship_types.emplace_item(identifier, ShipType::index_t { get_ship_type_count() }, identifier, unit_args, ship_type_args); if (ret) { // Cannot use get_back_ship_type() as we need non-const but don't want to generate all non-const functions. ret &= unit_types.emplace_via_copy(&ship_types.back()); @@ -186,10 +154,7 @@ bool UnitTypeManager::load_unit_type_file( spdlog::error_s("type could not be interned."); } - return expect_dictionary([this, &good_definition_manager, &terrain_type_manager, &modifier_manager, &type_symbol]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - + return expect_dictionary([this, &good_definition_manager, &terrain_type_manager, &modifier_manager, &type_symbol](std::string_view key, ast::NodeCPtr value) -> bool { unit_branch_t branch = INVALID_BRANCH; bool ret = expect_key(type_symbol, expect_branch_identifier(assign_variable_callback(branch)))(value); @@ -204,50 +169,44 @@ bool UnitTypeManager::load_unit_type_file( UnitType::unit_type_args_t unit_args {}; static const string_map_t unit_type_map { - { "infantry", INFANTRY }, - { "cavalry", CAVALRY }, - { "support", SUPPORT }, - { "special", SPECIAL }, - { "big_ship", BIG_SHIP }, - { "light_ship", LIGHT_SHIP }, - { "transport", TRANSPORT } + { "infantry", INFANTRY }, { "cavalry", CAVALRY }, { "support", SUPPORT }, { "special", SPECIAL }, + { "big_ship", BIG_SHIP }, { "light_ship", LIGHT_SHIP }, { "transport", TRANSPORT } }; key_map_t key_map {}; /* Shared dictionary entries */ - ret &= add_key_map_entries(key_map, - "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.icon)), - "type", ONE_EXACTLY, success_callback, /* Already loaded above using expect_key */ - "sprite", ONE_EXACTLY, expect_identifier(assign_variable_callback(unit_args.sprite)), - "active", ZERO_OR_ONE, expect_bool(assign_variable_callback(unit_args.starts_unlocked)), - "unit_type", ONE_EXACTLY, - expect_identifier(expect_mapped_string(unit_type_map, assign_variable_callback(unit_args.unit_category))), - "floating_flag", ONE_EXACTLY, expect_bool(assign_variable_callback(unit_args.floating_flag)), - "priority", ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.priority)), - "max_strength", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.max_strength)), - "default_organisation", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.default_organisation)), - "maximum_speed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.maximum_speed)), - "weighted_value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.weighted_value)), - "move_sound", ZERO_OR_ONE, expect_identifier(assign_variable_callback(unit_args.move_sound)), - "select_sound", ZERO_OR_ONE, expect_identifier(assign_variable_callback(unit_args.select_sound)), - "build_time", ONE_EXACTLY, expect_days(assign_variable_callback(unit_args.build_time)), - "build_cost", ONE_EXACTLY, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.build_cost)), + ret &= add_key_map_entries( + key_map, "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.icon)), "type", ONE_EXACTLY, + success_callback, /* Already loaded above using expect_key */ + "sprite", ONE_EXACTLY, expect_identifier(assign_variable_callback(unit_args.sprite)), "active", ZERO_OR_ONE, + expect_bool(assign_variable_callback(unit_args.starts_unlocked)), "unit_type", ONE_EXACTLY, + expect_identifier(expect_mapped_string(unit_type_map, assign_variable_callback(unit_args.unit_category))), + "floating_flag", ONE_EXACTLY, expect_bool(assign_variable_callback(unit_args.floating_flag)), "priority", + ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.priority)), "max_strength", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.max_strength)), "default_organisation", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.default_organisation)), "maximum_speed", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.maximum_speed)), "weighted_value", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.weighted_value)), "move_sound", ZERO_OR_ONE, + expect_identifier(assign_variable_callback(unit_args.move_sound)), "select_sound", ZERO_OR_ONE, + expect_identifier(assign_variable_callback(unit_args.select_sound)), "build_time", ONE_EXACTLY, + expect_days(assign_variable_callback(unit_args.build_time)), "build_cost", ONE_EXACTLY, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.build_cost)), "supply_consumption", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.supply_consumption)), "supply_cost", ONE_EXACTLY, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.supply_cost)) + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.supply_cost)) ); auto add_terrain_modifier_value = [&unit_args, &terrain_type_manager, &modifier_manager]( - std::string_view default_key, ast::NodeCPtr default_value - ) -> bool { + std::string_view default_key, ast::NodeCPtr default_value + ) -> bool { TerrainType const* terrain_type = terrain_type_manager.get_terrain_type_by_identifier(default_key); if (terrain_type != nullptr) { ModifierValue& modifier_value = unit_args.terrain_modifier_values[terrain_type]; - return expect_dictionary( - modifier_manager.expect_unit_terrain_modifier(modifier_value, terrain_type->get_identifier()) - )(default_value); + return expect_dictionary(modifier_manager + .expect_unit_terrain_modifier(modifier_value, terrain_type->get_identifier()))( + default_value + ); } return key_value_invalid_callback(default_key, default_value); @@ -259,20 +218,20 @@ bool UnitTypeManager::load_unit_type_file( bool is_restricted_to_primary_culture = false; bool is_restricted_to_accepted_cultures = false; - ret &= add_key_map_entries(key_map, - "primary_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_restricted_to_primary_culture)), - "accepted_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_restricted_to_accepted_cultures)), - "sprite_override", ZERO_OR_ONE, expect_identifier(assign_variable_callback(regiment_type_args.sprite_override)), - "sprite_mount", ZERO_OR_ONE, expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount)), - "sprite_mount_attach_node", ZERO_OR_ONE, - expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount_attach_node)), + ret &= add_key_map_entries( + key_map, "primary_culture", ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_restricted_to_primary_culture)), "accepted_culture", ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_restricted_to_accepted_cultures)), "sprite_override", ZERO_OR_ONE, + expect_identifier(assign_variable_callback(regiment_type_args.sprite_override)), "sprite_mount", ZERO_OR_ONE, + expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount)), "sprite_mount_attach_node", + ZERO_OR_ONE, expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount_attach_node)), "reconnaissance", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.reconnaissance)), - "attack", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.attack)), - "defence", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.defence)), - "discipline", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.discipline)), - "support", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.support)), - "maneuver", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.maneuver)), - "siege", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(regiment_type_args.siege)) + "attack", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.attack)), "defence", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.defence)), "discipline", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.discipline)), "support", + ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.support)), "maneuver", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.maneuver)), "siege", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(regiment_type_args.siege)) ); if (is_restricted_to_accepted_cultures) { @@ -292,22 +251,21 @@ bool UnitTypeManager::load_unit_type_file( case NAVAL: { ShipType::ship_type_args_t ship_type_args {}; - ret &= add_key_map_entries(key_map, - "naval_icon", ONE_EXACTLY, expect_uint(assign_variable_callback(ship_type_args.naval_icon)), - "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.sail)), - "transport", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.transport)), - "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.capital)), - "colonial_points", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(ship_type_args.colonial_points)), - "can_build_overseas", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.build_overseas)), - "min_port_level", ONE_EXACTLY, expect_uint(assign_variable_callback(ship_type_args.min_port_level)), - "limit_per_port", ONE_EXACTLY, expect_int(assign_variable_callback(ship_type_args.limit_per_port)), - "supply_consumption_score", ZERO_OR_ONE, - expect_fixed_point(assign_variable_callback(ship_type_args.supply_consumption_score)), - "hull", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.hull)), - "gun_power", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.gun_power)), - "fire_range", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.fire_range)), - "evasion", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.evasion)), - "torpedo_attack", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(ship_type_args.torpedo_attack)) + ret &= add_key_map_entries( + key_map, "naval_icon", ONE_EXACTLY, expect_uint(assign_variable_callback(ship_type_args.naval_icon)), "sail", + ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.sail)), "transport", ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.transport)), "capital", ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.capital)), "colonial_points", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.colonial_points)), "can_build_overseas", ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.build_overseas)), "min_port_level", ONE_EXACTLY, + expect_uint(assign_variable_callback(ship_type_args.min_port_level)), "limit_per_port", ONE_EXACTLY, + expect_int(assign_variable_callback(ship_type_args.limit_per_port)), "supply_consumption_score", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.supply_consumption_score)), "hull", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.hull)), "gun_power", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.gun_power)), "fire_range", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.fire_range)), "evasion", ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.evasion)), "torpedo_attack", ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.torpedo_attack)) ); ret &= expect_dictionary_key_map_and_default(key_map, add_terrain_modifier_value)(value); @@ -328,14 +286,15 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons bool ret = true; const auto generate_stat_modifiers = [&modifier_manager, &ret]( - std::derived_from auto unit_type_effects, std::string_view identifier - ) -> void { + std::derived_from auto unit_type_effects, + std::string_view identifier + ) -> void { using enum ModifierEffect::format_t; const auto stat_modifier = [&modifier_manager, &ret, &identifier]( - ModifierEffect const*& effect_cache, std::string_view suffix, - ModifierEffect::format_t format, std::string_view localisation_key - ) -> void { + ModifierEffect const*& effect_cache, std::string_view suffix, + ModifierEffect::format_t format, std::string_view localisation_key + ) -> void { ret &= modifier_manager.register_technology_modifier_effect( effect_cache, ModifierManager::get_flat_identifier(identifier, suffix), format, memory::fmt::format("${}$: ${}$", identifier, localisation_key) @@ -361,17 +320,15 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons stat_modifier(unit_type_effects.maneuver, "maneuver", FORMAT_x1_0DP_POS, "Maneuver"); } stat_modifier(unit_type_effects.maximum_speed, "maximum_speed", FORMAT_x1_2DP_SPEED_POS, "MAXIMUM_SPEED"); - if constexpr(std::same_as) { + if constexpr (std::same_as) { stat_modifier(unit_type_effects.gun_power, "gun_power", FORMAT_x1_2DP_POS, "GUN_POWER"); stat_modifier(unit_type_effects.torpedo_attack, "torpedo_attack", FORMAT_x1_2DP_POS, "TORPEDO_ATTACK"); stat_modifier(unit_type_effects.hull, "hull", FORMAT_x1_2DP_POS, "HULL"); stat_modifier(unit_type_effects.fire_range, "fire_range", FORMAT_x100_0DP_POS, "FIRE_RANGE"); stat_modifier(unit_type_effects.evasion, "evasion", FORMAT_x100_0DP_PC_POS, "EVASION"); } - stat_modifier( - unit_type_effects.supply_consumption, "supply_consumption", FORMAT_x100_0DP_PC_NEG, "SUPPLY_CONSUMPTION" - ); - if constexpr(std::same_as) { + stat_modifier(unit_type_effects.supply_consumption, "supply_consumption", FORMAT_x100_0DP_PC_NEG, "SUPPLY_CONSUMPTION"); + if constexpr (std::same_as) { stat_modifier( unit_type_effects.supply_consumption_score, "supply_consumption_score", FORMAT_x1_0DP_NEG, "SUPPLY_LOAD" ); @@ -385,7 +342,7 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons IndexedFlatMap& regiment_type_effects = modifier_manager.modifier_effect_cache.regiment_type_effects; - regiment_type_effects = std::move(decltype(ModifierEffectCache::regiment_type_effects){get_regiment_types()}); + regiment_type_effects = std::move(decltype(ModifierEffectCache::regiment_type_effects) { get_regiment_types() }); for (RegimentType const& regiment_type : get_regiment_types()) { generate_stat_modifiers(regiment_type_effects.at(regiment_type), regiment_type.get_identifier()); @@ -396,7 +353,7 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons IndexedFlatMap& ship_type_effects = modifier_manager.modifier_effect_cache.ship_type_effects; - ship_type_effects = std::move(decltype(ModifierEffectCache::ship_type_effects){get_ship_types()}); + ship_type_effects = std::move(decltype(ModifierEffectCache::ship_type_effects) { get_ship_types() }); for (ShipType const& ship_type : get_ship_types()) { generate_stat_modifiers(ship_type_effects.at(ship_type), ship_type.get_identifier()); diff --git a/src/openvic-simulation/military/UnitType.hpp b/src/openvic-simulation/military/UnitType.hpp index 65dda9dca..17bbf5176 100644 --- a/src/openvic-simulation/military/UnitType.hpp +++ b/src/openvic-simulation/military/UnitType.hpp @@ -12,9 +12,9 @@ #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { struct TerrainType; @@ -27,7 +27,14 @@ namespace OpenVic { using terrain_modifiers_t = ordered_map; enum struct unit_category_t : uint8_t { - INVALID_UNIT_CATEGORY, INFANTRY, CAVALRY, SUPPORT, SPECIAL, BIG_SHIP, LIGHT_SHIP, TRANSPORT + INVALID_UNIT_CATEGORY, + INFANTRY, + CAVALRY, + SUPPORT, + SPECIAL, + BIG_SHIP, + LIGHT_SHIP, + TRANSPORT }; struct unit_type_args_t { @@ -40,7 +47,7 @@ namespace OpenVic { bool starts_unlocked = true, floating_flag = false; uint32_t priority = 0; fixed_point_t max_strength = 0, default_organisation = 0, maximum_speed = 0, weighted_value = 0, - supply_consumption = 0; + supply_consumption = 0; Timespan build_time; fixed_point_map_t build_cost, supply_cost; terrain_modifier_values_t terrain_modifier_values; @@ -82,9 +89,8 @@ namespace OpenVic { template<> struct UnitTypeBranched : UnitType, HasIndex { - static constexpr regiment_allowed_cultures_t allowed_cultures_get_most_permissive( - regiment_allowed_cultures_t lhs, regiment_allowed_cultures_t rhs - ) { + static constexpr regiment_allowed_cultures_t + allowed_cultures_get_most_permissive(regiment_allowed_cultures_t lhs, regiment_allowed_cultures_t rhs) { return std::min(lhs, rhs); } @@ -93,8 +99,7 @@ namespace OpenVic { std::string_view sprite_override, sprite_mount, sprite_mount_attach_node; // TODO - represent these as modifier effects, so that they can be combined with tech, inventions, // leader bonuses, etc. and applied to unit instances all in one go (same for ShipTypes below) - fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, - siege = 0; + fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, siege = 0; constexpr regiment_type_args_t() {}; regiment_type_args_t(regiment_type_args_t&&) = default; @@ -116,8 +121,8 @@ namespace OpenVic { const fixed_point_t siege; UnitTypeBranched( - index_t new_index, std::string_view new_identifier, - unit_type_args_t& unit_args, regiment_type_args_t const& regiment_type_args + index_t new_index, std::string_view new_identifier, unit_type_args_t& unit_args, + regiment_type_args_t const& regiment_type_args ); UnitTypeBranched(UnitTypeBranched&&) = default; }; @@ -130,7 +135,7 @@ namespace OpenVic { uint32_t min_port_level = 0; int32_t limit_per_port = 0; fixed_point_t colonial_points = 0, supply_consumption_score = 0, hull = 0, gun_power = 0, fire_range = 0, - evasion = 0, torpedo_attack = 0; + evasion = 0, torpedo_attack = 0; constexpr ship_type_args_t() {}; ship_type_args_t(ship_type_args_t&&) = default; @@ -155,8 +160,8 @@ namespace OpenVic { const fixed_point_t torpedo_attack; UnitTypeBranched( - index_t new_index, std::string_view new_identifier, - unit_type_args_t& unit_args, ship_type_args_t const& ship_type_args + index_t new_index, std::string_view new_identifier, unit_type_args_t& unit_args, + ship_type_args_t const& ship_type_args ); UnitTypeBranched(UnitTypeBranched&&) = default; }; @@ -176,17 +181,12 @@ namespace OpenVic { RegimentType::regiment_type_args_t const& regiment_type_args ); bool add_ship_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, - ShipType::ship_type_args_t const& ship_type_args + std::string_view identifier, UnitType::unit_type_args_t& unit_args, ShipType::ship_type_args_t const& ship_type_args ); - static NodeTools::Callback auto expect_branch_str( - NodeTools::Callback auto callback - ) { + static NodeTools::Callback auto expect_branch_str(NodeTools::Callback auto callback) { using enum unit_branch_t; - static const string_map_t branch_map { - { "land", LAND }, { "naval", NAVAL }, { "sea", NAVAL } - }; + static const string_map_t branch_map { { "land", LAND }, { "naval", NAVAL }, { "sea", NAVAL } }; return NodeTools::expect_mapped_string(branch_map, callback); } static NodeTools::NodeCallback auto expect_branch_identifier(NodeTools::Callback auto callback) { diff --git a/src/openvic-simulation/military/Wargoal.cpp b/src/openvic-simulation/military/Wargoal.cpp index 3f5afeaa7..3c6585ef6 100644 --- a/src/openvic-simulation/military/Wargoal.cpp +++ b/src/openvic-simulation/military/Wargoal.cpp @@ -1,32 +1,33 @@ #include "Wargoal.hpp" -#include - #include +#include + #include "openvic-simulation/dataloader/NodeTools.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; WargoalType::WargoalType( - std::string_view new_identifier, std::string_view new_war_name, Timespan new_available_length, - Timespan new_truce_length, sprite_t new_sprite_index, bool new_triggered_only, bool new_civil_war, - bool new_constructing, bool new_crisis, bool new_great_war_obligatory, bool new_mutual, - bool new_all_allowed_states, bool new_always, peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, - ConditionScript&& new_can_use, ConditionScript&& new_is_valid, ConditionScript&& new_allowed_states, - ConditionScript&& new_allowed_substate_regions, ConditionScript&& new_allowed_states_in_crisis, - ConditionScript&& new_allowed_countries, EffectScript&& new_on_add, EffectScript&& new_on_po_accepted -) : HasIdentifier { new_identifier }, war_name { new_war_name }, available_length { new_available_length }, - truce_length { new_truce_length }, sprite_index { new_sprite_index }, is_triggered_only { new_triggered_only }, - is_civil_war { new_civil_war }, constructing { new_constructing }, crisis { new_crisis }, - is_great_war_obligatory { new_great_war_obligatory }, is_mutual { new_mutual }, all_allowed_states { new_all_allowed_states }, - always { new_always }, modifiers { std::move(new_modifiers) }, peace_options { new_peace_options }, - can_use { std::move(new_can_use) }, is_valid { std::move(new_is_valid) }, allowed_states { std::move(new_allowed_states) }, - allowed_substate_regions { std::move(new_allowed_substate_regions) }, - allowed_states_in_crisis { std::move(new_allowed_states_in_crisis) }, - allowed_countries { std::move(new_allowed_countries) }, on_add { std::move(new_on_add) }, - on_po_accepted { std::move(new_on_po_accepted) } {} + std::string_view new_identifier, std::string_view new_war_name, Timespan new_available_length, Timespan new_truce_length, + sprite_t new_sprite_index, bool new_triggered_only, bool new_civil_war, bool new_constructing, bool new_crisis, + bool new_great_war_obligatory, bool new_mutual, bool new_all_allowed_states, bool new_always, + peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, ConditionScript&& new_can_use, + ConditionScript&& new_is_valid, ConditionScript&& new_allowed_states, ConditionScript&& new_allowed_substate_regions, + ConditionScript&& new_allowed_states_in_crisis, ConditionScript&& new_allowed_countries, EffectScript&& new_on_add, + EffectScript&& new_on_po_accepted +) + : HasIdentifier { new_identifier }, war_name { new_war_name }, available_length { new_available_length }, + truce_length { new_truce_length }, sprite_index { new_sprite_index }, is_triggered_only { new_triggered_only }, + is_civil_war { new_civil_war }, constructing { new_constructing }, crisis { new_crisis }, + is_great_war_obligatory { new_great_war_obligatory }, is_mutual { new_mutual }, + all_allowed_states { new_all_allowed_states }, always { new_always }, modifiers { std::move(new_modifiers) }, + peace_options { new_peace_options }, can_use { std::move(new_can_use) }, is_valid { std::move(new_is_valid) }, + allowed_states { std::move(new_allowed_states) }, allowed_substate_regions { std::move(new_allowed_substate_regions) }, + allowed_states_in_crisis { std::move(new_allowed_states_in_crisis) }, + allowed_countries { std::move(new_allowed_countries) }, on_add { std::move(new_on_add) }, + on_po_accepted { std::move(new_on_po_accepted) } {} bool WargoalType::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -42,12 +43,11 @@ bool WargoalType::parse_scripts(DefinitionManager const& definition_manager) { } bool WargoalTypeManager::add_wargoal_type( - std::string_view identifier, std::string_view war_name, Timespan available_length, - Timespan truce_length, WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, - bool constructing, bool crisis, bool great_war_obligatory, bool mutual, bool all_allowed_states, - bool always, WargoalType::peace_modifiers_t&& modifiers, WargoalType::peace_options_t peace_options, - ConditionScript&& can_use, ConditionScript&& is_valid, ConditionScript&& allowed_states, - ConditionScript&& allowed_substate_regions, ConditionScript&& allowed_states_in_crisis, + std::string_view identifier, std::string_view war_name, Timespan available_length, Timespan truce_length, + WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, bool constructing, bool crisis, + bool great_war_obligatory, bool mutual, bool all_allowed_states, bool always, WargoalType::peace_modifiers_t&& modifiers, + WargoalType::peace_options_t peace_options, ConditionScript&& can_use, ConditionScript&& is_valid, + ConditionScript&& allowed_states, ConditionScript&& allowed_substate_regions, ConditionScript&& allowed_states_in_crisis, ConditionScript&& allowed_countries, EffectScript&& on_add, EffectScript&& on_po_accepted ) { if (identifier.empty()) { @@ -65,10 +65,9 @@ bool WargoalTypeManager::add_wargoal_type( } return wargoal_types.emplace_item( - identifier, - identifier, war_name, available_length, truce_length, sprite_index, triggered_only, civil_war, constructing, crisis, - great_war_obligatory, mutual, all_allowed_states, always, std::move(modifiers), peace_options, std::move(can_use), - std::move(is_valid), std::move(allowed_states), std::move(allowed_substate_regions), + identifier, identifier, war_name, available_length, truce_length, sprite_index, triggered_only, civil_war, constructing, + crisis, great_war_obligatory, mutual, all_allowed_states, always, std::move(modifiers), peace_options, + std::move(can_use), std::move(is_valid), std::move(allowed_states), std::move(allowed_substate_regions), std::move(allowed_states_in_crisis), std::move(allowed_countries), std::move(on_add), std::move(on_po_accepted) ); } @@ -80,9 +79,8 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) spdlog::error_s("peace_order could not be interned."); } - bool ret = expect_dictionary_reserve_length( - wargoal_types, - [this, &peace_order_symbol](std::string_view identifier, ast::NodeCPtr value) -> bool { + bool ret = + expect_dictionary_reserve_length(wargoal_types, [this, &peace_order_symbol](std::string_view identifier, ast::NodeCPtr value) -> bool { // If peace_order_symbol is false, we know there is no peace_order string in the parser if (peace_order_symbol && identifier == peace_order_symbol.c_str()) { return true; @@ -95,7 +93,7 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) Timespan available {}, truce {}; WargoalType::sprite_t sprite_index = 0; bool triggered_only = false, civil_war = false, constructing = true, crisis = true, great_war_obligatory = false, - mutual = false, all_allowed_states = false, always = false; + mutual = false, all_allowed_states = false, always = false; WargoalType::peace_options_t peace_options = NO_PEACE_OPTIONS; WargoalType::peace_modifiers_t modifiers; ConditionScript can_use { COUNTRY, COUNTRY, COUNTRY }; @@ -104,7 +102,7 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) ConditionScript allowed_substate_regions { STATE, COUNTRY, COUNTRY }; ConditionScript allowed_states_in_crisis { STATE, COUNTRY, COUNTRY }; ConditionScript allowed_countries { COUNTRY, COUNTRY, COUNTRY }; - EffectScript on_add, on_po_accepted; //country as default scope for both + EffectScript on_add, on_po_accepted; // country as default scope for both const auto expect_peace_option = [&peace_options](WargoalType::peace_options_t peace_option) -> node_callback_t { return expect_bool([&peace_options, peace_option](bool val) -> bool { @@ -202,8 +200,7 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) std::move(allowed_states_in_crisis), std::move(allowed_countries), std::move(on_add), std::move(on_po_accepted) ); return ret; - } - )(parser.get_file_node()); + })(parser.get_file_node()); /* load order in which CBs are prioritised by AI */ ret &= expect_key( diff --git a/src/openvic-simulation/military/Wargoal.hpp b/src/openvic-simulation/military/Wargoal.hpp index 4cb2fc775..c91e799a5 100644 --- a/src/openvic-simulation/military/Wargoal.hpp +++ b/src/openvic-simulation/military/Wargoal.hpp @@ -4,12 +4,12 @@ #include +#include "openvic-simulation/core/template/EnumBitfield.hpp" #include "openvic-simulation/scripts/ConditionScript.hpp" #include "openvic-simulation/scripts/EffectScript.hpp" -#include "openvic-simulation/core/template/EnumBitfield.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { struct WargoalTypeManager; @@ -37,23 +37,23 @@ namespace OpenVic { using peace_modifiers_t = fixed_point_map_t; enum class peace_options_t : uint32_t { - NO_PEACE_OPTIONS = 0, - PO_ANNEX = 1 << 0, - PO_DEMAND_STATE = 1 << 1, - PO_COLONY = 1 << 2, - PO_ADD_TO_SPHERE = 1 << 3, - PO_DISARMAMENT = 1 << 4, - PO_REMOVE_FORTS = 1 << 5, + NO_PEACE_OPTIONS = 0, + PO_ANNEX = 1 << 0, + PO_DEMAND_STATE = 1 << 1, + PO_COLONY = 1 << 2, + PO_ADD_TO_SPHERE = 1 << 3, + PO_DISARMAMENT = 1 << 4, + PO_REMOVE_FORTS = 1 << 5, PO_REMOVE_NAVAL_BASES = 1 << 6, - PO_REPARATIONS = 1 << 7, - PO_REPAY_DEBT = 1 << 8, - PO_REMOVE_PRESTIGE = 1 << 9, - PO_MAKE_PUPPET = 1 << 10, - PO_RELEASE_PUPPET = 1 << 11, - PO_STATUS_QUO = 1 << 12, - PO_INSTALL_COMMUNISM = 1 << 13, - PO_REMOVE_COMMUNISM = 1 << 14, - PO_REMOVE_CORES = 1 << 15, // only usable with ANNEX, DEMAND_STATE, or TRANSFER_PROVINCES + PO_REPARATIONS = 1 << 7, + PO_REPAY_DEBT = 1 << 8, + PO_REMOVE_PRESTIGE = 1 << 9, + PO_MAKE_PUPPET = 1 << 10, + PO_RELEASE_PUPPET = 1 << 11, + PO_STATUS_QUO = 1 << 12, + PO_INSTALL_COMMUNISM = 1 << 13, + PO_REMOVE_COMMUNISM = 1 << 14, + PO_REMOVE_CORES = 1 << 15, // only usable with ANNEX, DEMAND_STATE, or TRANSFER_PROVINCES PO_TRANSFER_PROVINCES = 1 << 16, PO_CLEAR_UNION_SPHERE = 1 << 17 }; @@ -89,8 +89,8 @@ namespace OpenVic { WargoalType( std::string_view new_identifier, std::string_view new_war_name, Timespan new_available_length, Timespan new_truce_length, sprite_t new_sprite_index, bool new_triggered_only, bool new_civil_war, - bool new_constructing, bool new_crisis, bool new_great_war_obligatory, bool new_mutual, - bool new_all_allowed_states, bool new_always, peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, + bool new_constructing, bool new_crisis, bool new_great_war_obligatory, bool new_mutual, bool new_all_allowed_states, + bool new_always, peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, ConditionScript&& new_can_use, ConditionScript&& new_is_valid, ConditionScript&& new_allowed_states, ConditionScript&& new_allowed_substate_regions, ConditionScript&& new_allowed_states_in_crisis, ConditionScript&& new_allowed_countries, EffectScript&& new_on_add, EffectScript&& new_on_po_accepted @@ -98,7 +98,8 @@ namespace OpenVic { WargoalType(WargoalType&&) = default; }; - template<> struct enable_bitfield : std::true_type{}; + template<> + struct enable_bitfield : std::true_type {}; struct WargoalTypeManager { private: @@ -107,13 +108,13 @@ namespace OpenVic { public: bool add_wargoal_type( - std::string_view identifier, std::string_view war_name, Timespan available_length, - Timespan truce_length, WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, - bool constructing, bool crisis, bool great_war_obligatory, bool mutual, bool all_allowed_states, - bool always, WargoalType::peace_modifiers_t&& modifiers, WargoalType::peace_options_t peace_options, - ConditionScript&& can_use, ConditionScript&& is_valid, ConditionScript&& allowed_states, - ConditionScript&& allowed_substate_regions, ConditionScript&& allowed_states_in_crisis, - ConditionScript&& allowed_countries, EffectScript&& on_add, EffectScript&& on_po_accepted + std::string_view identifier, std::string_view war_name, Timespan available_length, Timespan truce_length, + WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, bool constructing, bool crisis, + bool great_war_obligatory, bool mutual, bool all_allowed_states, bool always, + WargoalType::peace_modifiers_t&& modifiers, WargoalType::peace_options_t peace_options, ConditionScript&& can_use, + ConditionScript&& is_valid, ConditionScript&& allowed_states, ConditionScript&& allowed_substate_regions, + ConditionScript&& allowed_states_in_crisis, ConditionScript&& allowed_countries, EffectScript&& on_add, + EffectScript&& on_po_accepted ); bool load_wargoal_file(ovdl::v2script::Parser const& parser); diff --git a/src/openvic-simulation/misc/Decision.cpp b/src/openvic-simulation/misc/Decision.cpp index c09d994cf..fbafe485c 100644 --- a/src/openvic-simulation/misc/Decision.cpp +++ b/src/openvic-simulation/misc/Decision.cpp @@ -8,10 +8,11 @@ Decision::Decision( std::string_view new_news_desc_long, std::string_view new_news_desc_medium, std::string_view new_news_desc_short, std::string_view new_picture, ConditionScript&& new_potential, ConditionScript&& new_allow, ConditionalWeightFactorMul&& new_ai_will_do, EffectScript&& new_effect -) : HasIdentifier { new_identifier }, has_alert { new_alert }, is_news { new_news }, news_title { new_news_title }, - news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, - news_desc_short { new_news_desc_short }, picture { new_picture }, potential { std::move(new_potential) }, - allow { std::move(new_allow) }, ai_will_do { std::move(new_ai_will_do) }, effect { std::move(new_effect) } {} +) + : HasIdentifier { new_identifier }, has_alert { new_alert }, is_news { new_news }, news_title { new_news_title }, + news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, news_desc_short { new_news_desc_short }, + picture { new_picture }, potential { std::move(new_potential) }, allow { std::move(new_allow) }, + ai_will_do { std::move(new_ai_will_do) }, effect { std::move(new_effect) } {} bool Decision::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -45,28 +46,23 @@ bool DecisionManager::add_decision( } return decisions.emplace_item( - identifier, - duplicate_warning_callback, - identifier, alert, news, news_title, news_desc_long, news_desc_medium, news_desc_short, picture, std::move(potential), - std::move(allow), std::move(ai_will_do), std::move(effect) + identifier, duplicate_warning_callback, identifier, alert, news, news_title, news_desc_long, news_desc_medium, + news_desc_short, picture, std::move(potential), std::move(allow), std::move(ai_will_do), std::move(effect) ); } bool DecisionManager::load_decision_file(ast::NodeCPtr root) { - return expect_dictionary_keys( - "political_decisions", ZERO_OR_ONE, expect_dictionary_reserve_length( - decisions, - [this](std::string_view identifier, ast::NodeCPtr node) -> bool { - using enum scope_type_t; + return expect_dictionary_keys("political_decisions", ZERO_OR_ONE, expect_dictionary_reserve_length(decisions, [this](std::string_view identifier, ast::NodeCPtr node) -> bool { + using enum scope_type_t; - bool alert = true, news = false; - std::string_view news_title, news_desc_long, news_desc_medium, news_desc_short, picture; - ConditionScript potential { COUNTRY, COUNTRY, NO_SCOPE }; - ConditionScript allow { COUNTRY, COUNTRY, NO_SCOPE }; - ConditionalWeightFactorMul ai_will_do { COUNTRY, COUNTRY, NO_SCOPE }; - EffectScript effect; + bool alert = true, news = false; + std::string_view news_title, news_desc_long, news_desc_medium, news_desc_short, picture; + ConditionScript potential { COUNTRY, COUNTRY, NO_SCOPE }; + ConditionScript allow { COUNTRY, COUNTRY, NO_SCOPE }; + ConditionalWeightFactorMul ai_will_do { COUNTRY, COUNTRY, NO_SCOPE }; + EffectScript effect; - bool ret = expect_dictionary_keys( + bool ret = expect_dictionary_keys( "alert", ZERO_OR_ONE, expect_bool(assign_variable_callback(alert)), "news", ZERO_OR_ONE, expect_bool(assign_variable_callback(news)), "news_title", ZERO_OR_ONE, expect_string(assign_variable_callback(news_title)), @@ -80,15 +76,14 @@ bool DecisionManager::load_decision_file(ast::NodeCPtr root) { "ai_will_do", ZERO_OR_ONE, ai_will_do.expect_conditional_weight() )(node); - ret &= add_decision( - identifier, alert, news, news_title, news_desc_long, news_desc_medium, news_desc_short, picture, - std::move(potential), std::move(allow), std::move(ai_will_do), std::move(effect) - ); + ret &= add_decision( + identifier, alert, news, news_title, news_desc_long, news_desc_medium, + news_desc_short, picture, std::move(potential), std::move(allow), + std::move(ai_will_do), std::move(effect) + ); - return ret; - } - ) - )(root); + return ret; + }))(root); } bool DecisionManager::parse_scripts(DefinitionManager const& definition_manager) { diff --git a/src/openvic-simulation/misc/Decision.hpp b/src/openvic-simulation/misc/Decision.hpp index c545cf0a4..ea0a34b67 100644 --- a/src/openvic-simulation/misc/Decision.hpp +++ b/src/openvic-simulation/misc/Decision.hpp @@ -44,8 +44,7 @@ namespace OpenVic { bool add_decision( std::string_view identifier, bool alert, bool news, std::string_view news_title, std::string_view news_desc_long, std::string_view news_desc_medium, std::string_view news_desc_short, std::string_view picture, - ConditionScript&& potential, ConditionScript&& allow, ConditionalWeightFactorMul&& ai_will_do, - EffectScript&& effect + ConditionScript&& potential, ConditionScript&& allow, ConditionalWeightFactorMul&& ai_will_do, EffectScript&& effect ); bool load_decision_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/misc/Event.cpp b/src/openvic-simulation/misc/Event.cpp index 1ea77109f..a605af0c1 100644 --- a/src/openvic-simulation/misc/Event.cpp +++ b/src/openvic-simulation/misc/Event.cpp @@ -14,7 +14,8 @@ using namespace OpenVic::NodeTools; Event::EventOption::EventOption( std::string_view new_name, EffectScript&& new_effect, ConditionalWeightFactorMul&& new_ai_chance -) : name { new_name }, effect { std::move(new_effect) }, ai_chance { std::move(new_ai_chance) } {} +) + : name { new_name }, effect { std::move(new_effect) }, ai_chance { std::move(new_ai_chance) } {} bool Event::EventOption::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -24,19 +25,20 @@ bool Event::EventOption::parse_scripts(DefinitionManager const& definition_manag } Event::Event( - std::string_view new_identifier, std::string_view new_title, std::string_view new_description, - std::string_view new_image, event_type_t new_type, bool new_triggered_only, bool new_major, bool new_fire_only_once, - bool new_allows_multiple_instances, bool new_news, std::string_view new_news_title, std::string_view new_news_desc_long, - std::string_view new_news_desc_medium, std::string_view new_news_desc_short, bool new_election, - const issue_group_t new_election_issue_group, ConditionScript&& new_trigger, ConditionalWeightTime&& new_mean_time_to_happen, - EffectScript&& new_immediate, memory::vector&& new_options -) : HasIdentifier { new_identifier }, title { new_title }, description { new_description }, image { new_image }, - type { new_type }, is_triggered_only { new_triggered_only }, is_major { new_major }, fire_only_once { new_fire_only_once }, - allows_multiple_instances { new_allows_multiple_instances }, is_news { new_news }, news_title { new_news_title }, - news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, news_desc_short { new_news_desc_short }, - election { new_election }, election_issue_group { new_election_issue_group }, trigger { std::move(new_trigger) }, - mean_time_to_happen { std::move(new_mean_time_to_happen) }, immediate { std::move(new_immediate) }, - options { std::move(new_options) } {} + std::string_view new_identifier, std::string_view new_title, std::string_view new_description, std::string_view new_image, + event_type_t new_type, bool new_triggered_only, bool new_major, bool new_fire_only_once, bool new_allows_multiple_instances, + bool new_news, std::string_view new_news_title, std::string_view new_news_desc_long, std::string_view new_news_desc_medium, + std::string_view new_news_desc_short, bool new_election, const issue_group_t new_election_issue_group, + ConditionScript&& new_trigger, ConditionalWeightTime&& new_mean_time_to_happen, EffectScript&& new_immediate, + memory::vector&& new_options +) + : HasIdentifier { new_identifier }, title { new_title }, description { new_description }, image { new_image }, + type { new_type }, is_triggered_only { new_triggered_only }, is_major { new_major }, + fire_only_once { new_fire_only_once }, allows_multiple_instances { new_allows_multiple_instances }, is_news { new_news }, + news_title { new_news_title }, news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, + news_desc_short { new_news_desc_short }, election { new_election }, election_issue_group { new_election_issue_group }, + trigger { std::move(new_trigger) }, mean_time_to_happen { std::move(new_mean_time_to_happen) }, + immediate { std::move(new_immediate) }, options { std::move(new_options) } {} bool Event::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -81,26 +83,22 @@ bool EventManager::register_event( if (election && std::holds_alternative(election_issue_group)) { spdlog::warn_s("Event with ID {} is an election event but has no issue group!", identifier); } else if (!election) { - std::visit([identifier](auto&& arg) { - using T = std::decay_t; // Get the clean type - - if constexpr (std::is_same_v>) { - spdlog::warn_s( - "Event with ID {} is not an election event but has party policy group {}!", - identifier, arg - ); - } else if constexpr (std::is_same_v>) { - spdlog::warn_s( - "Event with ID {} is not an election event but has reform group {}!", - identifier, arg - ); - } else if constexpr (!std::is_same_v){ - spdlog::error_s( - "Event with ID {} is not an election event but has unknown issue group {}!", - identifier, arg - ); - } - }, election_issue_group); + std::visit( + [identifier](auto&& arg) { + using T = std::decay_t; // Get the clean type + + if constexpr (std::is_same_v>) { + spdlog::warn_s("Event with ID {} is not an election event but has party policy group {}!", identifier, arg); + } else if constexpr (std::is_same_v>) { + spdlog::warn_s("Event with ID {} is not an election event but has reform group {}!", identifier, arg); + } else if constexpr (!std::is_same_v) { + spdlog::error_s( + "Event with ID {} is not an election event but has unknown issue group {}!", identifier, arg + ); + } + }, + election_issue_group + ); } if (news) { if (news_desc_long.empty() || news_desc_medium.empty() || news_desc_short.empty()) { @@ -123,11 +121,10 @@ bool EventManager::register_event( // TODO - error if is_triggered_only with triggers or MTTH defined return events.emplace_item( - identifier, - duplicate_warning_callback, - identifier, title, description, image, type, triggered_only, major, fire_only_once, allows_multiple_instances, news, - news_title, news_desc_long, news_desc_medium, news_desc_short, election, election_issue_group, std::move(trigger), - std::move(mean_time_to_happen), std::move(immediate), std::move(options) + identifier, duplicate_warning_callback, identifier, title, description, image, type, triggered_only, major, + fire_only_once, allows_multiple_instances, news, news_title, news_desc_long, news_desc_medium, news_desc_short, + election, election_issue_group, std::move(trigger), std::move(mean_time_to_happen), std::move(immediate), + std::move(options) ); } @@ -137,48 +134,42 @@ bool EventManager::add_on_action(std::string_view identifier, OnAction::weight_m return false; } - return on_actions.emplace_item( - identifier, - identifier, std::move(weighted_events) - ); + return on_actions.emplace_item(identifier, identifier, std::move(weighted_events)); } bool EventManager::load_event_file(IssueManager const& issue_manager, ast::NodeCPtr root) { - return expect_dictionary_reserve_length( - events, - [this, &issue_manager](std::string_view key, ast::NodeCPtr value) -> bool { - using enum scope_type_t; - - Event::event_type_t type; - scope_type_t initial_scope; - - if (key == "country_event") { - type = Event::event_type_t::COUNTRY; - initial_scope = COUNTRY; - } else if (key == "province_event") { - type = Event::event_type_t::PROVINCE; - initial_scope = PROVINCE; - } else { - spdlog::error_s("Invalid event type: {}", key); - return false; - } - - std::string_view identifier, title, description, image, news_title, news_desc_long, news_desc_medium, - news_desc_short; - bool triggered_only = false, major = false, fire_only_once = false, allows_multiple_instances = false, - news = false, election = false; - issue_group_t election_issue_group; - ConditionScript trigger { initial_scope, COUNTRY, NO_SCOPE }; - ConditionalWeightTime mean_time_to_happen { initial_scope, COUNTRY, NO_SCOPE }; - EffectScript immediate; - - // Ensures that if ever multithreaded, only one vector is used per thread - // Else acts like static - thread_local memory::vector options; - // Default max vanilla options is 5 - options.reserve(2); - - bool ret = expect_dictionary_keys( + return expect_dictionary_reserve_length(events, [this, &issue_manager](std::string_view key, ast::NodeCPtr value) -> bool { + using enum scope_type_t; + + Event::event_type_t type; + scope_type_t initial_scope; + + if (key == "country_event") { + type = Event::event_type_t::COUNTRY; + initial_scope = COUNTRY; + } else if (key == "province_event") { + type = Event::event_type_t::PROVINCE; + initial_scope = PROVINCE; + } else { + spdlog::error_s("Invalid event type: {}", key); + return false; + } + + std::string_view identifier, title, description, image, news_title, news_desc_long, news_desc_medium, news_desc_short; + bool triggered_only = false, major = false, fire_only_once = false, allows_multiple_instances = false, news = false, + election = false; + issue_group_t election_issue_group; + ConditionScript trigger { initial_scope, COUNTRY, NO_SCOPE }; + ConditionalWeightTime mean_time_to_happen { initial_scope, COUNTRY, NO_SCOPE }; + EffectScript immediate; + + // Ensures that if ever multithreaded, only one vector is used per thread + // Else acts like static + thread_local memory::vector options; + // Default max vanilla options is 5 + options.reserve(2); + + bool ret = expect_dictionary_keys( "id", ONE_EXACTLY, expect_identifier(assign_variable_callback(identifier)), "title", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(title)), "desc", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(description)), @@ -219,26 +210,24 @@ bool EventManager::load_event_file(IssueManager const& issue_manager, ast::NodeC "immediate", ZERO_OR_MORE, immediate.expect_script() )(value); - ret &= register_event( - identifier, title, description, image, type, triggered_only, major, fire_only_once, allows_multiple_instances, - news, news_title, news_desc_long, news_desc_medium, news_desc_short, election, election_issue_group, - std::move(trigger), std::move(mean_time_to_happen), std::move(immediate), std::move(options) - ); - return ret; - } - )(root); + ret &= register_event( + identifier, title, description, image, type, triggered_only, major, fire_only_once, allows_multiple_instances, news, + news_title, news_desc_long, news_desc_medium, news_desc_short, election, election_issue_group, std::move(trigger), + std::move(mean_time_to_happen), std::move(immediate), std::move(options) + ); + return ret; + })(root); } bool EventManager::load_on_action_file(ast::NodeCPtr root) { bool ret = expect_dictionary([this](std::string_view identifier, ast::NodeCPtr node) -> bool { OnAction::weight_map_t weighted_events; - bool ret = expect_dictionary_reserve_length( - weighted_events, - [this, &identifier, &weighted_events](std::string_view weight_str, ast::NodeCPtr event_node) -> bool { + bool ret = + expect_dictionary_reserve_length(weighted_events, [this, &identifier, &weighted_events](std::string_view weight_str, ast::NodeCPtr event_node) -> bool { bool ret = false; uint64_t weight; std::from_chars_result result = string_to_uint64(weight_str, weight); - ret = result.ec == std::errc{}; + ret = result.ec == std::errc {}; if (!ret) { spdlog::error_s("Invalid weight {} on action {}", weight_str, identifier); return ret; @@ -249,16 +238,18 @@ bool EventManager::load_on_action_file(ast::NodeCPtr root) { if (event != nullptr) { ret &= map_callback(weighted_events, event)(weight); - } else if (ast::FlatValue const* event_name = dryad::node_try_cast(event_node); event_name && event_name->value()) { + } else if ( + ast::FlatValue const* event_name = dryad::node_try_cast(event_node); + event_name && event_name->value() + ) { spdlog::warn_s( - "Non-existing event {} loaded on action {} with weight {}!", - event_name->value().view(), identifier, weight + "Non-existing event {} loaded on action {} with weight {}!", event_name->value().view(), identifier, + weight ); } return ret; - } - )(node); + })(node); ret &= add_on_action(identifier, std::move(weighted_events)); return ret; })(root); diff --git a/src/openvic-simulation/misc/Event.hpp b/src/openvic-simulation/misc/Event.hpp index f72f1b55b..41e4c1f0b 100644 --- a/src/openvic-simulation/misc/Event.hpp +++ b/src/openvic-simulation/misc/Event.hpp @@ -65,8 +65,8 @@ namespace OpenVic { Event( std::string_view new_identifier, std::string_view new_title, std::string_view new_description, - std::string_view new_image, event_type_t new_type, bool new_triggered_only, bool new_major, - bool new_fire_only_once, bool new_allows_multiple_instances, bool new_news, std::string_view new_news_title, + std::string_view new_image, event_type_t new_type, bool new_triggered_only, bool new_major, bool new_fire_only_once, + bool new_allows_multiple_instances, bool new_news, std::string_view new_news_title, std::string_view new_news_desc_long, std::string_view new_news_desc_medium, std::string_view new_news_desc_short, bool new_election, const issue_group_t new_election_issue_group, ConditionScript&& new_trigger, ConditionalWeightTime&& new_mean_time_to_happen, EffectScript&& new_immediate, @@ -98,8 +98,9 @@ namespace OpenVic { std::string_view identifier, std::string_view title, std::string_view description, std::string_view image, Event::event_type_t type, bool triggered_only, bool major, bool fire_only_once, bool allows_multiple_instances, bool news, std::string_view news_title, std::string_view news_desc_long, std::string_view news_desc_medium, - std::string_view news_desc_short, bool election, const issue_group_t election_issue_group, ConditionScript&& trigger, - ConditionalWeightTime&& mean_time_to_happen, EffectScript&& immediate, memory::vector&& options + std::string_view news_desc_short, bool election, const issue_group_t election_issue_group, + ConditionScript&& trigger, ConditionalWeightTime&& mean_time_to_happen, EffectScript&& immediate, + memory::vector&& options ); bool add_on_action(std::string_view identifier, OnAction::weight_map_t&& new_weighted_events); diff --git a/src/openvic-simulation/misc/GameAction.cpp b/src/openvic-simulation/misc/GameAction.cpp index 87dbca5b0..dca73b444 100644 --- a/src/openvic-simulation/misc/GameAction.cpp +++ b/src/openvic-simulation/misc/GameAction.cpp @@ -1,35 +1,35 @@ #include "GameAction.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/InstanceManager.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" using namespace OpenVic; -bool GameActionManager::VariantVisitor::operator() (none_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(none_argument_t const& argument) const { return false; } // Core -bool GameActionManager::VariantVisitor::operator() (tick_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(tick_argument_t const& argument) const { instance_manager.tick(); return true; } -bool GameActionManager::VariantVisitor::operator() (set_pause_argument_t const& new_is_paused) const { +bool GameActionManager::VariantVisitor::operator()(set_pause_argument_t const& new_is_paused) const { const bool old_pause = instance_manager.get_simulation_clock().is_paused(); instance_manager.get_simulation_clock().set_paused(type_safe::get(new_is_paused)); return old_pause != instance_manager.get_simulation_clock().is_paused(); } -bool GameActionManager::VariantVisitor::operator() (set_speed_argument_t const& new_speed) const { +bool GameActionManager::VariantVisitor::operator()(set_speed_argument_t const& new_speed) const { const SimulationClock::speed_t old_speed = instance_manager.get_simulation_clock().get_simulation_speed(); instance_manager.get_simulation_clock().set_simulation_speed(type_safe::get(new_speed)); return old_speed != instance_manager.get_simulation_clock().get_simulation_speed(); } -bool GameActionManager::VariantVisitor::operator() (set_ai_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_ai_argument_t const& argument) const { const auto [country_index, new_is_ai] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -44,7 +44,7 @@ bool GameActionManager::VariantVisitor::operator() (set_ai_argument_t const& arg } // Production -bool GameActionManager::VariantVisitor::operator() (expand_province_building_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(expand_province_building_argument_t const& argument) const { const auto [country_index, province_index, province_building_index] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -52,7 +52,7 @@ bool GameActionManager::VariantVisitor::operator() (expand_province_building_arg spdlog::error_s("GAME_ACTION_EXPAND_PROVINCE_BUILDING called with invalid country index: {}", country_index); return false; } - + ProvinceInstance* province = instance_manager.get_map_instance().get_province_instance_by_index(province_index); if (OV_unlikely(province == nullptr)) { @@ -61,14 +61,13 @@ bool GameActionManager::VariantVisitor::operator() (expand_province_building_arg } return province->expand_building( - instance_manager.definition_manager.get_modifier_manager().get_modifier_effect_cache(), - province_building_index, + instance_manager.definition_manager.get_modifier_manager().get_modifier_effect_cache(), province_building_index, *country ); } // Budget -bool GameActionManager::VariantVisitor::operator() (set_strata_tax_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_strata_tax_argument_t const& argument) const { const auto [country_index, strata_index, tax_rate] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -88,7 +87,7 @@ bool GameActionManager::VariantVisitor::operator() (set_strata_tax_argument_t co return false; } -bool GameActionManager::VariantVisitor::operator() (set_army_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_army_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -101,7 +100,7 @@ bool GameActionManager::VariantVisitor::operator() (set_army_spending_argument_t return false; } -bool GameActionManager::VariantVisitor::operator() (set_navy_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_navy_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -114,7 +113,7 @@ bool GameActionManager::VariantVisitor::operator() (set_navy_spending_argument_t return false; } -bool GameActionManager::VariantVisitor::operator() (set_construction_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_construction_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -127,7 +126,7 @@ bool GameActionManager::VariantVisitor::operator() (set_construction_spending_ar return false; } -bool GameActionManager::VariantVisitor::operator() (set_education_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_education_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -140,7 +139,7 @@ bool GameActionManager::VariantVisitor::operator() (set_education_spending_argum return false; } -bool GameActionManager::VariantVisitor::operator() (set_administration_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_administration_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -153,7 +152,7 @@ bool GameActionManager::VariantVisitor::operator() (set_administration_spending_ return false; } -bool GameActionManager::VariantVisitor::operator() (set_social_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_social_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -166,7 +165,7 @@ bool GameActionManager::VariantVisitor::operator() (set_social_spending_argument return false; } -bool GameActionManager::VariantVisitor::operator() (set_military_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_military_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -179,7 +178,7 @@ bool GameActionManager::VariantVisitor::operator() (set_military_spending_argume return false; } -bool GameActionManager::VariantVisitor::operator() (set_tariff_rate_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_tariff_rate_argument_t const& argument) const { const auto [country_index, tariff_rate] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -193,7 +192,7 @@ bool GameActionManager::VariantVisitor::operator() (set_tariff_rate_argument_t c } // Technology -bool GameActionManager::VariantVisitor::operator() (start_research_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(start_research_argument_t const& argument) const { const auto [country_index, technology_index] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -202,10 +201,10 @@ bool GameActionManager::VariantVisitor::operator() (start_research_argument_t co return false; } - Technology const* technology = instance_manager.definition_manager - .get_research_manager() - .get_technology_manager() - .get_technology_by_index(technology_index); + Technology const* technology = + instance_manager.definition_manager.get_research_manager().get_technology_manager().get_technology_by_index( + technology_index + ); if (OV_unlikely(technology == nullptr)) { spdlog::error_s("GAME_ACTION_START_RESEARCH called with invalid technology index: {}", technology_index); @@ -224,7 +223,7 @@ bool GameActionManager::VariantVisitor::operator() (start_research_argument_t co // Population // Trade -bool GameActionManager::VariantVisitor::operator() (set_good_automated_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_good_automated_argument_t const& argument) const { const auto [country_index, good_index, new_is_automated] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -249,7 +248,7 @@ bool GameActionManager::VariantVisitor::operator() (set_good_automated_argument_ return old_automated != good_data.is_automated; } -bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_good_trade_order_argument_t const& argument) const { const auto [country_index, good_index, new_is_selling, new_cutoff] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -268,10 +267,7 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen CountryInstance::good_data_t& good_data = country->get_good_data(*good); if (OV_unlikely(good_data.is_automated)) { - spdlog::error_s( - "GAME_ACTION_SET_GOOD_TRADE_ORDER called for automated good! Country: {}, good: {}", - *country, *good - ); + spdlog::error_s("GAME_ACTION_SET_GOOD_TRADE_ORDER called for automated good! Country: {}, good: {}", *country, *good); return false; } @@ -283,11 +279,9 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen if (good_data.stockpile_cutoff.is_negative()) { spdlog::error_s( - "GAME_ACTION_SET_GOOD_TRADE_ORDER called with negative stockpile cutoff {} for {} good \"{}\" in country \"{}\". Setting to 0.", - good_data.stockpile_cutoff, - *good, - good_data.is_selling ? "selling" : "buying", - *country + "GAME_ACTION_SET_GOOD_TRADE_ORDER called with negative stockpile cutoff {} for {} good \"{}\" in country \"{}\". " + "Setting to 0.", + good_data.stockpile_cutoff, *good, good_data.is_selling ? "selling" : "buying", *country ); good_data.stockpile_cutoff = 0; } @@ -298,7 +292,7 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen // Diplomacy // Military -bool GameActionManager::VariantVisitor::operator() (create_leader_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(create_leader_argument_t const& argument) const { const auto [country_index, unit_branch] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -315,14 +309,10 @@ bool GameActionManager::VariantVisitor::operator() (create_leader_argument_t con return false; } - return instance_manager.get_unit_instance_manager().create_leader( - *country, - unit_branch, - instance_manager.get_today() - ); + return instance_manager.get_unit_instance_manager().create_leader(*country, unit_branch, instance_manager.get_today()); } -bool GameActionManager::VariantVisitor::operator() (set_use_leader_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_use_leader_argument_t const& argument) const { const auto [unique_id, new_should_use] = argument; LeaderInstance* leader = instance_manager.get_unit_instance_manager().get_leader_instance_by_unique_id(unique_id); @@ -339,7 +329,7 @@ bool GameActionManager::VariantVisitor::operator() (set_use_leader_argument_t co return old_use != leader->get_can_be_used(); } -bool GameActionManager::VariantVisitor::operator() (set_auto_create_leaders_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_auto_create_leaders_argument_t const& argument) const { const auto [country_index, new_should_auto_create] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -355,7 +345,7 @@ bool GameActionManager::VariantVisitor::operator() (set_auto_create_leaders_argu return old_auto_create != country->get_auto_create_leaders(); } -bool GameActionManager::VariantVisitor::operator() (set_auto_assign_leaders_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_auto_assign_leaders_argument_t const& argument) const { const auto [country_index, new_should_auto_assign] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -371,7 +361,7 @@ bool GameActionManager::VariantVisitor::operator() (set_auto_assign_leaders_argu return old_auto_assign != country->get_auto_assign_leaders(); } -bool GameActionManager::VariantVisitor::operator() (set_mobilise_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_mobilise_argument_t const& argument) const { const auto [country_index, new_is_mobilised] = argument; CountryInstance* country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -387,21 +377,21 @@ bool GameActionManager::VariantVisitor::operator() (set_mobilise_argument_t cons return old_mobilise != country->is_mobilised(); } -bool GameActionManager::VariantVisitor::operator() (start_land_unit_recruitment_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(start_land_unit_recruitment_argument_t const& argument) const { const auto [regiment_type_index, province_index, pop_id_in_province] = argument; - RegimentType const* const regiment_type = instance_manager.definition_manager - .get_military_manager() - .get_unit_type_manager() - .get_regiment_type_by_index(regiment_type_index); + RegimentType const* const regiment_type = + instance_manager.definition_manager.get_military_manager().get_unit_type_manager().get_regiment_type_by_index( + regiment_type_index + ); if (OV_unlikely(regiment_type == nullptr)) { - spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid regiment type index: {}", regiment_type_index); + spdlog::error_s( + "GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid regiment type index: {}", regiment_type_index + ); return false; } - ProvinceInstance* province = instance_manager - .get_map_instance() - .get_province_instance_by_index(province_index); + ProvinceInstance* province = instance_manager.get_map_instance().get_province_instance_by_index(province_index); if (OV_unlikely(province == nullptr)) { spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid province index: {}", province_index); return false; @@ -409,13 +399,15 @@ bool GameActionManager::VariantVisitor::operator() (start_land_unit_recruitment_ Pop* pop = province->find_pop_by_id(pop_id_in_province); if (OV_unlikely(pop == nullptr)) { - spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid pop_id_in_province: {}", pop_id_in_province); + spdlog::error_s( + "GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid pop_id_in_province: {}", pop_id_in_province + ); return false; } - //these TODO's should be implemented in ProvinceInstance and/or some military type - //TODO verify pop's cultural status is acceptable for regiment type - //TODO verify pop is recruitable and has enough size (pop.try_recruit()) - //TODO actually instantiate a regiment in recruitment state + // these TODO's should be implemented in ProvinceInstance and/or some military type + // TODO verify pop's cultural status is acceptable for regiment type + // TODO verify pop is recruitable and has enough size (pop.try_recruit()) + // TODO actually instantiate a regiment in recruitment state return false; } diff --git a/src/openvic-simulation/misc/GameAction.hpp b/src/openvic-simulation/misc/GameAction.hpp index bbd544a3e..e729ea737 100644 --- a/src/openvic-simulation/misc/GameAction.hpp +++ b/src/openvic-simulation/misc/GameAction.hpp @@ -9,54 +9,54 @@ #include #include "openvic-simulation/population/PopIdInProvince.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/UniqueId.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { -namespace detail { - template - struct reduce_tuple { - using type = std::tuple; - static constexpr std::integral_constant size {}; - - template - static constexpr type construct(Args2&&... args) - requires requires { std::make_tuple(std::forward(args)...); } - { - return std::make_tuple(std::forward(args)...); - } - }; - - template - struct reduce_tuple { - using type = std::pair; - static constexpr std::integral_constant size {}; - - template - static constexpr type construct(InT1&& t1, InT2&& t2) - requires requires { std::make_pair(std::forward(t1), std::forward(t2)); } - { - return std::make_pair(std::forward(t1), std::forward(t2)); - } - }; + namespace detail { + template + struct reduce_tuple { + using type = std::tuple; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(Args2&&... args) + requires requires { std::make_tuple(std::forward(args)...); } + { + return std::make_tuple(std::forward(args)...); + } + }; - template - struct reduce_tuple { - using type = T; - static constexpr std::integral_constant size {}; + template + struct reduce_tuple { + using type = std::pair; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(InT1&& t1, InT2&& t2) + requires requires { std::make_pair(std::forward(t1), std::forward(t2)); } + { + return std::make_pair(std::forward(t1), std::forward(t2)); + } + }; - template - static constexpr type construct(InT&& t) - requires requires { std::forward(t); } - { - return std::forward(t); - } - }; + template + struct reduce_tuple { + using type = T; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(InT&& t) + requires requires { std::forward(t); } + { + return std::forward(t); + } + }; - struct ts_op_structured_binding_passthrough {}; -} + struct ts_op_structured_binding_passthrough {}; + } // To add a new game action: // 1. **Copy** an existing line. @@ -65,66 +65,62 @@ namespace detail { // The format for each action is: X(action_name, argument_type1, argument_type2, ...) // `none` is handled as example throughout the file #define FOR_EACH_GAME_ACTION(X) \ -X(tick, std::monostate) \ -X(set_pause, bool) \ -X(set_speed, int64_t) \ -X(set_ai, country_index_t, bool) \ -X(expand_province_building, country_index_t, province_index_t, province_building_index_t) \ -X(set_strata_tax, country_index_t, strata_index_t, fixed_point_t) \ -X(set_army_spending, country_index_t, fixed_point_t) \ -X(set_navy_spending, country_index_t, fixed_point_t) \ -X(set_construction_spending, country_index_t, fixed_point_t) \ -X(set_education_spending, country_index_t, fixed_point_t) \ -X(set_administration_spending, country_index_t, fixed_point_t) \ -X(set_social_spending, country_index_t, fixed_point_t) \ -X(set_military_spending, country_index_t, fixed_point_t) \ -X(set_tariff_rate, country_index_t, fixed_point_t) \ -X(start_research, country_index_t, technology_index_t) \ -X(set_good_automated, country_index_t, good_index_t, bool) \ -X(set_good_trade_order, country_index_t, good_index_t, bool, fixed_point_t) \ -X(create_leader, country_index_t, unit_branch_t) \ -X(set_use_leader, unique_id_t, bool) \ -X(set_auto_create_leaders, country_index_t, bool) \ -X(set_auto_assign_leaders, country_index_t, bool) \ -X(set_mobilise, country_index_t, bool) \ -X(start_land_unit_recruitment, regiment_type_index_t, province_index_t, pop_id_in_province_t) + X(tick, std::monostate) \ + X(set_pause, bool) \ + X(set_speed, int64_t) \ + X(set_ai, country_index_t, bool) \ + X(expand_province_building, country_index_t, province_index_t, province_building_index_t) \ + X(set_strata_tax, country_index_t, strata_index_t, fixed_point_t) \ + X(set_army_spending, country_index_t, fixed_point_t) \ + X(set_navy_spending, country_index_t, fixed_point_t) \ + X(set_construction_spending, country_index_t, fixed_point_t) \ + X(set_education_spending, country_index_t, fixed_point_t) \ + X(set_administration_spending, country_index_t, fixed_point_t) \ + X(set_social_spending, country_index_t, fixed_point_t) \ + X(set_military_spending, country_index_t, fixed_point_t) \ + X(set_tariff_rate, country_index_t, fixed_point_t) \ + X(start_research, country_index_t, technology_index_t) \ + X(set_good_automated, country_index_t, good_index_t, bool) \ + X(set_good_trade_order, country_index_t, good_index_t, bool, fixed_point_t) \ + X(create_leader, country_index_t, unit_branch_t) \ + X(set_use_leader, unique_id_t, bool) \ + X(set_auto_create_leaders, country_index_t, bool) \ + X(set_auto_assign_leaders, country_index_t, bool) \ + X(set_mobilise, country_index_t, bool) \ + X(start_land_unit_recruitment, regiment_type_index_t, province_index_t, pop_id_in_province_t) // <--- ADD NEW GAME ACTIONS HERE (copy/edit an X(...) line) -//the argument type alias for each game action +// the argument type alias for each game action #define ARG_TYPE(name) name##_argument_t -//define type aliases for game action arguments -//example: -struct none_argument_t : type_safe::strong_typedef { - using strong_typedef::strong_typedef; - constexpr none_argument_t(std::monostate const& value) : strong_typedef(value) {} - constexpr none_argument_t(std::monostate&& value) - : strong_typedef(static_cast(value)) {} -}; + // define type aliases for game action arguments + // example: + struct none_argument_t : type_safe::strong_typedef { + using strong_typedef::strong_typedef; + constexpr none_argument_t(std::monostate const& value) : strong_typedef(value) {} + constexpr none_argument_t(std::monostate&& value) : strong_typedef(static_cast(value)) {} + }; #define USING_ARG_TYPE(name, ...) \ -struct ARG_TYPE(name) \ - : type_safe::strong_typedef::type>, \ - detail::ts_op_structured_binding_passthrough { \ - using strong_typedef::strong_typedef; \ - using reduce_helper_t = detail::reduce_tuple<__VA_ARGS__>; \ - using underlying_type = reduce_helper_t::type; \ + struct ARG_TYPE(name) \ + : type_safe::strong_typedef::type>, \ + detail::ts_op_structured_binding_passthrough { \ + using strong_typedef::strong_typedef; \ + using reduce_helper_t = detail::reduce_tuple<__VA_ARGS__>; \ + using underlying_type = reduce_helper_t::type; \ \ - constexpr ARG_TYPE(name)(underlying_type const& value) : strong_typedef(value) {} \ - constexpr ARG_TYPE(name)(underlying_type && value) : strong_typedef(static_cast(value)) {} \ - template \ - constexpr ARG_TYPE(name)(Arg1 && arg1, Args&&... args) \ - : strong_typedef(reduce_helper_t::construct(std::forward(arg1), std::forward(args)...)) {} \ -}; - -FOR_EACH_GAME_ACTION(USING_ARG_TYPE) + constexpr ARG_TYPE(name)(underlying_type const& value) : strong_typedef(value) {} \ + constexpr ARG_TYPE(name)(underlying_type && value) : strong_typedef(static_cast(value)) {} \ + template \ + constexpr ARG_TYPE(name)(Arg1 && arg1, Args&&... args) \ + : strong_typedef(reduce_helper_t::construct(std::forward(arg1), std::forward(args)...)) {} \ + }; + + FOR_EACH_GAME_ACTION(USING_ARG_TYPE) #undef USING_ARG_TYPE -//define game_action_t as a variant of all possible game action arguments +// define game_action_t as a variant of all possible game action arguments #define COMMA_ARG_TYPE(name, ...) , ARG_TYPE(name) - using game_action_t = std::variant< - none_argument_t - FOR_EACH_GAME_ACTION(COMMA_ARG_TYPE) - >; + using game_action_t = std::variant; #undef COMMA_ARG_TYPE struct InstanceManager; @@ -134,17 +130,19 @@ FOR_EACH_GAME_ACTION(USING_ARG_TYPE) struct VariantVisitor { private: InstanceManager& instance_manager; + public: constexpr VariantVisitor(InstanceManager& new_instance_manager) : instance_manager { new_instance_manager } {} -//define a method for each game method +// define a method for each game method #define DEFINE_ARG_TYPE_AND_METHOD(name, ...) bool operator()(ARG_TYPE(name) const& argument) const; -//example: -bool operator()(none_argument_t const& argument) const; - FOR_EACH_GAME_ACTION(DEFINE_ARG_TYPE_AND_METHOD) + // example: + bool operator()(none_argument_t const& argument) const; + FOR_EACH_GAME_ACTION(DEFINE_ARG_TYPE_AND_METHOD) #undef DEFINE_ARG_TYPE_AND_METHOD }; VariantVisitor visitor; + public: constexpr GameActionManager(InstanceManager& new_instance_manager) : visitor { new_instance_manager } {} @@ -183,4 +181,4 @@ namespace std { } #undef ARG_TYPE -#undef FOR_EACH_GAME_ACTION \ No newline at end of file +#undef FOR_EACH_GAME_ACTION diff --git a/src/openvic-simulation/misc/GameRulesManager.cpp b/src/openvic-simulation/misc/GameRulesManager.cpp index acd021084..57dadab17 100644 --- a/src/openvic-simulation/misc/GameRulesManager.cpp +++ b/src/openvic-simulation/misc/GameRulesManager.cpp @@ -11,18 +11,16 @@ bool GameRulesManager::may_use_coastal_artisanal_production_types(ProvinceInstan const bool is_coastal_province = province.province_definition.is_coastal(); using enum artisan_coastal_restriction_t; switch (coastal_restriction_for_artisans) { - case Unrestricted: - return true; - case CountriesWithCoast: { - CountryInstance const* const country = province.get_country_to_report_economy(); - return is_coastal_province || (country != nullptr && country->is_coastal()); - } - case CoastalStates: { - State const* const state = province.get_state(); - return is_coastal_province || (state != nullptr && state->is_coastal()); - } - case CoastalProvinces: - return is_coastal_province; + case Unrestricted: return true; + case CountriesWithCoast: { + CountryInstance const* const country = province.get_country_to_report_economy(); + return is_coastal_province || (country != nullptr && country->is_coastal()); + } + case CoastalStates: { + State const* const state = province.get_state(); + return is_coastal_province || (state != nullptr && state->is_coastal()); + } + case CoastalProvinces: return is_coastal_province; } } @@ -30,14 +28,13 @@ bool GameRulesManager::may_use_coastal_factory_production_types(State const& sta const bool is_coastal_state = state.is_coastal(); using enum factory_coastal_restriction_t; switch (coastal_restriction_for_factories) { - case Unrestricted: - return true; - case CountriesWithCoast: { - CountryInstance const* const country = state.get_owner(); - return is_coastal_state || (country != nullptr && country->is_coastal()); - } - case CoastalStates: { - return is_coastal_state; - } + case Unrestricted: return true; + case CountriesWithCoast: { + CountryInstance const* const country = state.get_owner(); + return is_coastal_state || (country != nullptr && country->is_coastal()); + } + case CoastalStates: { + return is_coastal_state; } -} \ No newline at end of file + } +} diff --git a/src/openvic-simulation/misc/GameRulesManager.hpp b/src/openvic-simulation/misc/GameRulesManager.hpp index 76d1905f5..eb236e10b 100644 --- a/src/openvic-simulation/misc/GameRulesManager.hpp +++ b/src/openvic-simulation/misc/GameRulesManager.hpp @@ -2,37 +2,20 @@ #include -#include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { struct ProvinceInstance; struct State; - enum struct country_to_report_economy_t : uint8_t { - Owner, - Controller, - NeitherWhenOccupied - }; + enum struct country_to_report_economy_t : uint8_t { Owner, Controller, NeitherWhenOccupied }; - enum struct demand_category : uint8_t { - None, - PopNeeds, - FactoryNeeds - }; + enum struct demand_category : uint8_t { None, PopNeeds, FactoryNeeds }; - enum struct artisan_coastal_restriction_t : uint8_t { - Unrestricted, - CountriesWithCoast, - CoastalStates, - CoastalProvinces - }; + enum struct artisan_coastal_restriction_t : uint8_t { Unrestricted, CountriesWithCoast, CoastalStates, CoastalProvinces }; - enum struct factory_coastal_restriction_t : uint8_t { - Unrestricted, - CountriesWithCoast, - CoastalStates - }; + enum struct factory_coastal_restriction_t : uint8_t { Unrestricted, CountriesWithCoast, CoastalStates }; struct GameRulesManager { private: @@ -80,4 +63,4 @@ namespace OpenVic { coastal_restriction_for_factories = factory_coastal_restriction_t::CoastalStates; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/misc/SimulationClock.cpp b/src/openvic-simulation/misc/SimulationClock.cpp index bee19f013..c459dd8d2 100644 --- a/src/openvic-simulation/misc/SimulationClock.cpp +++ b/src/openvic-simulation/misc/SimulationClock.cpp @@ -4,10 +4,9 @@ using namespace OpenVic; -SimulationClock::SimulationClock( - tick_function_t new_tick_function, update_function_t new_update_function -) : tick_function { new_tick_function ? std::move(new_tick_function) : []() {} }, - update_function { new_update_function ? std::move(new_update_function) : []() {} } { +SimulationClock::SimulationClock(tick_function_t new_tick_function, update_function_t new_update_function) + : tick_function { new_tick_function ? std::move(new_tick_function) : []() {} }, + update_function { new_update_function ? std::move(new_update_function) : []() {} } { reset(); } diff --git a/src/openvic-simulation/misc/SimulationClock.hpp b/src/openvic-simulation/misc/SimulationClock.hpp index c4c3af0a4..76ade01c7 100644 --- a/src/openvic-simulation/misc/SimulationClock.hpp +++ b/src/openvic-simulation/misc/SimulationClock.hpp @@ -3,10 +3,10 @@ #include #include -#include "openvic-simulation/utility/Getters.hpp" - #include +#include "openvic-simulation/utility/Getters.hpp" + namespace OpenVic { /* Conditionally advances game depending on speed and pause state. */ class SimulationClock { @@ -26,9 +26,7 @@ namespace OpenVic { * (in descending duration order, hence increasing speed order). */ static constexpr speed_rates_t GAME_SPEEDS = []() constexpr -> speed_rates_t { using namespace std::chrono_literals; - return { - 3s, 2s, 1s, 100ms, 1ms - }; + return { 3s, 2s, 1s, 100ms, 1ms }; }(); static constexpr speed_t MIN_SPEED = 0, MAX_SPEED = std::size(GAME_SPEEDS) - 1; @@ -43,10 +41,7 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(paused, is, true); public: - - SimulationClock( - tick_function_t new_tick_function, update_function_t new_update_function - ); + SimulationClock(tick_function_t new_tick_function, update_function_t new_update_function); time_point_t get_now() const; @@ -60,7 +55,7 @@ namespace OpenVic { bool can_decrease_simulation_speed() const; void conditionally_advance_game(); - void force_advance_game(); //for debug only + void force_advance_game(); // for debug only void reset(); }; } diff --git a/src/openvic-simulation/misc/SongChance.cpp b/src/openvic-simulation/misc/SongChance.cpp index 3ce39ee58..90ef7f8ec 100644 --- a/src/openvic-simulation/misc/SongChance.cpp +++ b/src/openvic-simulation/misc/SongChance.cpp @@ -3,9 +3,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -SongChance::SongChance( - size_t new_index, std::string_view new_filename, ConditionalWeightFactorMul&& new_chance -) : HasIdentifier { std::to_string(new_index) }, file_name { new_filename }, chance { std::move(new_chance) } {} +SongChance::SongChance(size_t new_index, std::string_view new_filename, ConditionalWeightFactorMul&& new_chance) + : HasIdentifier { std::to_string(new_index) }, file_name { new_filename }, chance { std::move(new_chance) } {} bool SongChance::parse_scripts(DefinitionManager const& definition_manager) { return chance.parse_scripts(definition_manager); @@ -14,30 +13,24 @@ bool SongChance::parse_scripts(DefinitionManager const& definition_manager) { bool SongChanceManager::load_songs_file(ast::NodeCPtr root) { bool ret = true; - ret &= expect_dictionary_reserve_length( - song_chances, - [this](std::string_view key, ast::NodeCPtr value) -> bool { - using enum scope_type_t; + ret &= expect_dictionary_reserve_length(song_chances, [this](std::string_view key, ast::NodeCPtr value) -> bool { + using enum scope_type_t; - if (key != "song") { - spdlog::error_s("Invalid song declaration {}", key); - return false; - } - std::string_view name {}; - ConditionalWeightFactorMul chance { COUNTRY, COUNTRY, NO_SCOPE }; + if (key != "song") { + spdlog::error_s("Invalid song declaration {}", key); + return false; + } + std::string_view name {}; + ConditionalWeightFactorMul chance { COUNTRY, COUNTRY, NO_SCOPE }; - bool ret = expect_dictionary_keys( + bool ret = expect_dictionary_keys( "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), "chance", ONE_EXACTLY, chance.expect_conditional_weight() )(value); - ret &= song_chances.emplace_item( - name, - song_chances.size(), name, std::move(chance) - ); - return ret; - } - )(root); + ret &= song_chances.emplace_item(name, song_chances.size(), name, std::move(chance)); + return ret; + })(root); if (song_chances.size() == 0) { spdlog::error_s("No songs found in Songs.txt"); diff --git a/src/openvic-simulation/misc/SongChance.hpp b/src/openvic-simulation/misc/SongChance.hpp index 818dc3244..6e19e0d2a 100644 --- a/src/openvic-simulation/misc/SongChance.hpp +++ b/src/openvic-simulation/misc/SongChance.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/scripts/ConditionalWeight.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" namespace OpenVic { /*For music/Songs.txt if it exists*/ @@ -24,10 +24,9 @@ namespace OpenVic { struct SongChanceManager { private: IdentifierRegistry IDENTIFIER_REGISTRY(song_chance); - //Songs.txt + // Songs.txt public: bool load_songs_file(ast::NodeCPtr root); bool parse_scripts(DefinitionManager const& definition_manager); }; } - diff --git a/src/openvic-simulation/misc/SoundEffect.cpp b/src/openvic-simulation/misc/SoundEffect.cpp index 968cc1319..192a1879d 100644 --- a/src/openvic-simulation/misc/SoundEffect.cpp +++ b/src/openvic-simulation/misc/SoundEffect.cpp @@ -35,10 +35,7 @@ bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::s spdlog::warn_s("Sound filename {} was empty!", sfx_identifier); } - ret &= sound_effects.emplace_item( - sfx_identifier, - sfx_identifier, std::move(file), volume - ); + ret &= sound_effects.emplace_item(sfx_identifier, sfx_identifier, std::move(file), volume); return ret; } diff --git a/src/openvic-simulation/misc/SoundEffect.hpp b/src/openvic-simulation/misc/SoundEffect.hpp index 628090b98..fd55b38b5 100644 --- a/src/openvic-simulation/misc/SoundEffect.hpp +++ b/src/openvic-simulation/misc/SoundEffect.hpp @@ -2,9 +2,9 @@ #include +#include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/HasIdentifier.hpp" namespace OpenVic { class Dataloader; diff --git a/src/openvic-simulation/modifier/Modifier.cpp b/src/openvic-simulation/modifier/Modifier.cpp index 6df23b270..7d34b728c 100644 --- a/src/openvic-simulation/modifier/Modifier.cpp +++ b/src/openvic-simulation/modifier/Modifier.cpp @@ -6,24 +6,25 @@ std::string_view Modifier::modifier_type_to_string(modifier_type_t type) { using enum Modifier::modifier_type_t; switch (type) { -#define _CASE(X) case X: return #X; - _CASE(EVENT) - _CASE(STATIC) - _CASE(TRIGGERED) - _CASE(CRIME) - _CASE(TERRAIN) - _CASE(CLIMATE) - _CASE(CONTINENT) - _CASE(BUILDING) - _CASE(LEADER) - _CASE(UNIT_TERRAIN) - _CASE(NATIONAL_VALUE) - _CASE(NATIONAL_FOCUS) - _CASE(PARTY_POLICY) - _CASE(REFORM) - _CASE(TECHNOLOGY) - _CASE(INVENTION) - _CASE(TECH_SCHOOL) +#define _CASE(X) \ + case X: return #X; + _CASE(EVENT) + _CASE(STATIC) + _CASE(TRIGGERED) + _CASE(CRIME) + _CASE(TERRAIN) + _CASE(CLIMATE) + _CASE(CONTINENT) + _CASE(BUILDING) + _CASE(LEADER) + _CASE(UNIT_TERRAIN) + _CASE(NATIONAL_VALUE) + _CASE(NATIONAL_FOCUS) + _CASE(PARTY_POLICY) + _CASE(REFORM) + _CASE(TECHNOLOGY) + _CASE(INVENTION) + _CASE(TECH_SCHOOL) #undef _CASE default: return "INVALID MODIFIER TYPE"; } @@ -34,12 +35,14 @@ Modifier::Modifier(std::string_view new_identifier, ModifierValue&& new_values, IconModifier::IconModifier( std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon -) : Modifier { new_identifier, std::move(new_values), new_type }, icon { new_icon } {} +) + : Modifier { new_identifier, std::move(new_values), new_type }, icon { new_icon } {} TriggeredModifier::TriggeredModifier( std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon, ConditionScript&& new_trigger -) : IconModifier { new_identifier, std::move(new_values), new_type, new_icon }, trigger { std::move(new_trigger) } {} +) + : IconModifier { new_identifier, std::move(new_values), new_type, new_icon }, trigger { std::move(new_trigger) } {} bool TriggeredModifier::parse_scripts(DefinitionManager const& definition_manager, bool can_be_null) { return trigger.parse_script(can_be_null, definition_manager); diff --git a/src/openvic-simulation/modifier/Modifier.hpp b/src/openvic-simulation/modifier/Modifier.hpp index 662a6f681..6bd19c405 100644 --- a/src/openvic-simulation/modifier/Modifier.hpp +++ b/src/openvic-simulation/modifier/Modifier.hpp @@ -18,8 +18,23 @@ namespace OpenVic { friend struct LeaderTraitManager; enum struct modifier_type_t : uint8_t { - EVENT, STATIC, TRIGGERED, CRIME, TERRAIN, CLIMATE, CONTINENT, BUILDING, LEADER, UNIT_TERRAIN, - NATIONAL_VALUE, NATIONAL_FOCUS, PARTY_POLICY, REFORM, TECHNOLOGY, INVENTION, TECH_SCHOOL + EVENT, + STATIC, + TRIGGERED, + CRIME, + TERRAIN, + CLIMATE, + CONTINENT, + BUILDING, + LEADER, + UNIT_TERRAIN, + NATIONAL_VALUE, + NATIONAL_FOCUS, + PARTY_POLICY, + REFORM, + TECHNOLOGY, + INVENTION, + TECH_SCHOOL }; static std::string_view modifier_type_to_string(modifier_type_t type); diff --git a/src/openvic-simulation/modifier/ModifierEffect.cpp b/src/openvic-simulation/modifier/ModifierEffect.cpp index 9fd072a69..9743958fc 100644 --- a/src/openvic-simulation/modifier/ModifierEffect.cpp +++ b/src/openvic-simulation/modifier/ModifierEffect.cpp @@ -41,9 +41,10 @@ memory::string ModifierEffect::make_default_modifier_effect_localisation_key(std } ModifierEffect::ModifierEffect( - std::string_view new_identifier, format_t new_format, target_t new_targets, - std::string_view new_localisation_key, bool new_has_no_effect -) : HasIdentifier { new_identifier }, format { new_format }, targets { new_targets }, - localisation_key { - new_localisation_key.empty() ? make_default_modifier_effect_localisation_key(new_identifier) : new_localisation_key - }, has_no_effect { new_has_no_effect } {} + std::string_view new_identifier, format_t new_format, target_t new_targets, std::string_view new_localisation_key, + bool new_has_no_effect +) + : HasIdentifier { new_identifier }, format { new_format }, targets { new_targets }, + localisation_key { new_localisation_key.empty() ? make_default_modifier_effect_localisation_key(new_identifier) + : new_localisation_key }, + has_no_effect { new_has_no_effect } {} diff --git a/src/openvic-simulation/modifier/ModifierEffect.hpp b/src/openvic-simulation/modifier/ModifierEffect.hpp index 09bb5c284..bac5c0e68 100644 --- a/src/openvic-simulation/modifier/ModifierEffect.hpp +++ b/src/openvic-simulation/modifier/ModifierEffect.hpp @@ -19,17 +19,12 @@ namespace OpenVic { static constexpr size_t FORMAT_SUFFIX_BIT_OFFSET = FORMAT_DECIMAL_PLACES_BIT_OFFSET + FORMAT_DECIMAL_PLACES_BIT_COUNT; static constexpr size_t FORMAT_POS_NEG_BIT_OFFSET = FORMAT_SUFFIX_BIT_OFFSET + FORMAT_SUFFIX_BIT_COUNT; - enum suffix_t : uint8_t { - NO_SUFFIX = 0, - PERCENT = 1, - DAYS = 2, - SPEED = 3 - }; + enum suffix_t : uint8_t { NO_SUFFIX = 0, PERCENT = 1, DAYS = 2, SPEED = 3 }; enum class format_t : uint8_t { // 1 and 2 bits - FORMAT_PART_x1 = 0 << FORMAT_MULTIPLIER_BIT_OFFSET, - FORMAT_PART_x10 = 1 << FORMAT_MULTIPLIER_BIT_OFFSET, + FORMAT_PART_x1 = 0 << FORMAT_MULTIPLIER_BIT_OFFSET, + FORMAT_PART_x10 = 1 << FORMAT_MULTIPLIER_BIT_OFFSET, FORMAT_PART_x100 = 2 << FORMAT_MULTIPLIER_BIT_OFFSET, // 4 and 8 bits @@ -39,10 +34,10 @@ namespace OpenVic { FORMAT_PART_3DP = 3 << FORMAT_DECIMAL_PLACES_BIT_OFFSET, // 16 bit and 32 bit - FORMAT_PART_NO_SUFFIX = NO_SUFFIX << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_PERCENT_SUFFIX = PERCENT << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_DAYS_SUFFIX = DAYS << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_SPEED_SUFFIX = SPEED << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_NO_SUFFIX = NO_SUFFIX << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_PERCENT_SUFFIX = PERCENT << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_DAYS_SUFFIX = DAYS << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_SPEED_SUFFIX = SPEED << FORMAT_SUFFIX_BIT_OFFSET, // 64 bit FORMAT_PART_POS = 0 << FORMAT_POS_NEG_BIT_OFFSET, @@ -82,10 +77,10 @@ namespace OpenVic { }; enum class target_t : uint8_t { - NO_TARGETS = 0, - COUNTRY = 1 << 0, - PROVINCE = 1 << 1, - UNIT = 1 << 2, + NO_TARGETS = 0, + COUNTRY = 1 << 0, + PROVINCE = 1 << 1, + UNIT = 1 << 2, ALL_TARGETS = (1 << 3) - 1 }; @@ -95,7 +90,8 @@ namespace OpenVic { static memory::string make_default_modifier_effect_localisation_key(std::string_view identifier); - private:; + private: + ; memory::string PROPERTY(localisation_key); // TODO - format/precision, e.g. 80% vs 0.8 vs 0.800, 2 vs 2.0 vs 200% @@ -106,8 +102,8 @@ namespace OpenVic { const target_t targets; ModifierEffect( - std::string_view new_identifier, format_t new_format, target_t new_targets, - std::string_view new_localisation_key, bool new_has_no_effect + std::string_view new_identifier, format_t new_format, target_t new_targets, std::string_view new_localisation_key, + bool new_has_no_effect ); ModifierEffect(ModifierEffect&&) = default; @@ -120,7 +116,8 @@ namespace OpenVic { } }; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; inline constexpr bool ModifierEffect::excludes_targets(target_t targets, target_t excluded_targets) { using enum target_t; diff --git a/src/openvic-simulation/modifier/ModifierEffectCache.cpp b/src/openvic-simulation/modifier/ModifierEffectCache.cpp index 97164bc64..347722861 100644 --- a/src/openvic-simulation/modifier/ModifierEffectCache.cpp +++ b/src/openvic-simulation/modifier/ModifierEffectCache.cpp @@ -10,13 +10,15 @@ using namespace OpenVic; -ModifierEffectCache::building_type_effects_t const& ModifierEffectCache::get_building_type_effects(BuildingType const& key) const { +ModifierEffectCache::building_type_effects_t const& +ModifierEffectCache::get_building_type_effects(BuildingType const& key) const { return building_type_effects.at(key); } ModifierEffectCache::good_effects_t const& ModifierEffectCache::get_good_effects(GoodDefinition const& key) const { return good_effects.at(key); } -ModifierEffectCache::regiment_type_effects_t const& ModifierEffectCache::get_regiment_type_effects(RegimentType const& key) const { +ModifierEffectCache::regiment_type_effects_t const& +ModifierEffectCache::get_regiment_type_effects(RegimentType const& key) const { return regiment_type_effects.at(key); } ModifierEffectCache::ship_type_effects_t const& ModifierEffectCache::get_ship_type_effects(ShipType const& key) const { @@ -33,4 +35,4 @@ ModifierEffectCache::strata_effects_t const& ModifierEffectCache::get_strata_eff } ModifierEffect const* ModifierEffectCache::get_research_bonus_effects(TechnologyFolder const& key) const { return research_bonus_effects.at(key); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/modifier/ModifierEffectCache.hpp b/src/openvic-simulation/modifier/ModifierEffectCache.hpp index 1bd6a2849..890cac4ad 100644 --- a/src/openvic-simulation/modifier/ModifierEffectCache.hpp +++ b/src/openvic-simulation/modifier/ModifierEffectCache.hpp @@ -343,18 +343,17 @@ namespace OpenVic { /* Technology Effects */ OV_IFLATMAP_PROPERTY(TechnologyFolder, ModifierEffect const*, research_bonus_effects); - constexpr ModifierEffectCache() : - building_type_effects { decltype(building_type_effects)::create_empty() }, - good_effects { decltype(good_effects)::create_empty() }, - regiment_type_effects { decltype(regiment_type_effects)::create_empty() }, - ship_type_effects { decltype(ship_type_effects)::create_empty() }, - unit_terrain_effects { decltype(unit_terrain_effects)::create_empty() }, - rebel_org_gain_effects { decltype(rebel_org_gain_effects)::create_empty() }, - strata_effects { decltype(strata_effects)::create_empty() }, - research_bonus_effects { decltype(research_bonus_effects)::create_empty() } - {} + constexpr ModifierEffectCache() + : building_type_effects { decltype(building_type_effects)::create_empty() }, + good_effects { decltype(good_effects)::create_empty() }, + regiment_type_effects { decltype(regiment_type_effects)::create_empty() }, + ship_type_effects { decltype(ship_type_effects)::create_empty() }, + unit_terrain_effects { decltype(unit_terrain_effects)::create_empty() }, + rebel_org_gain_effects { decltype(rebel_org_gain_effects)::create_empty() }, + strata_effects { decltype(strata_effects)::create_empty() }, + research_bonus_effects { decltype(research_bonus_effects)::create_empty() } {} public: ModifierEffectCache(ModifierEffectCache&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/modifier/ModifierManager.cpp b/src/openvic-simulation/modifier/ModifierManager.cpp index 5a881cbe3..6f92eca95 100644 --- a/src/openvic-simulation/modifier/ModifierManager.cpp +++ b/src/openvic-simulation/modifier/ModifierManager.cpp @@ -20,12 +20,8 @@ void ModifierManager::lock_all_modifier_except_base_country_effects() { } bool ModifierManager::_register_modifier_effect( - modifier_effect_registry_t& registry, - ModifierEffect::target_t targets, - ModifierEffect const*& effect_cache, - const std::string_view identifier, - const ModifierEffect::format_t format, - const std::string_view localisation_key, + modifier_effect_registry_t& registry, ModifierEffect::target_t targets, ModifierEffect const*& effect_cache, + const std::string_view identifier, const ModifierEffect::format_t format, const std::string_view localisation_key, const bool has_no_effect ) { using enum ModifierEffect::target_t; @@ -42,24 +38,20 @@ bool ModifierManager::_register_modifier_effect( if (!is_power_of_two(static_cast(targets))) { spdlog::error_s( - "Invalid targets for modifier effect \"{}\" - {} (can only contain one target)", - identifier, ModifierEffect::target_to_string(targets) + "Invalid targets for modifier effect \"{}\" - {} (can only contain one target)", identifier, + ModifierEffect::target_to_string(targets) ); return false; } if (effect_cache != nullptr) { spdlog::error_s( - "Cache variable for modifier effect \"{}\" is already filled with modifier effect \"{}\"", - identifier, *effect_cache + "Cache variable for modifier effect \"{}\" is already filled with modifier effect \"{}\"", identifier, *effect_cache ); return false; } - const bool ret = registry.emplace_item( - identifier, - identifier, format, targets, localisation_key, has_no_effect - ); + const bool ret = registry.emplace_item(identifier, identifier, format, targets, localisation_key, has_no_effect); if (ret) { effect_cache = ®istry.back(); @@ -69,23 +61,15 @@ bool ModifierManager::_register_modifier_effect( } #define REGISTER_MODIFIER_EFFECT(MAPPING_TYPE, TARGETS) \ -bool ModifierManager::register_##MAPPING_TYPE##_modifier_effect( \ - ModifierEffect const*& effect_cache, \ - const std::string_view identifier, \ - const ModifierEffect::format_t format, \ - const std::string_view localisation_key, \ - const bool has_no_effect \ -) { \ - return _register_modifier_effect( \ - MAPPING_TYPE##_modifier_effects, \ - TARGETS, \ - effect_cache, \ - std::move(identifier), \ - format, \ - localisation_key, \ - has_no_effect \ - ); \ -} + bool ModifierManager::register_##MAPPING_TYPE##_modifier_effect( \ + ModifierEffect const*& effect_cache, const std::string_view identifier, const ModifierEffect::format_t format, \ + const std::string_view localisation_key, const bool has_no_effect \ + ) { \ + return _register_modifier_effect( \ + MAPPING_TYPE##_modifier_effects, TARGETS, effect_cache, std::move(identifier), format, localisation_key, \ + has_no_effect \ + ); \ + } REGISTER_MODIFIER_EFFECT(leader, UNIT) REGISTER_MODIFIER_EFFECT(unit_terrain, UNIT) @@ -120,8 +104,7 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.supply_range, "supply_range", FORMAT_x100_2DP_PC_POS, "SUPPLY_RANGE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.supply_limit_global_percentage_change, "supply_limit", FORMAT_x100_2DP_PC_POS, - "SUPPLY_LIMIT_TECH" + modifier_effect_cache.supply_limit_global_percentage_change, "supply_limit", FORMAT_x100_2DP_PC_POS, "SUPPLY_LIMIT_TECH" ); ret &= register_technology_modifier_effect( modifier_effect_cache.morale_global, "morale", FORMAT_x100_2DP_PC_POS, "MORALE_TECH" @@ -220,8 +203,7 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.factory_output_tech, "factory_output", FORMAT_x100_1DP_PC_POS, "FACTORY_OUTPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.factory_throughput_tech, "factory_throughput", FORMAT_x100_1DP_PC_POS, - "FACTORY_THROUGHPUT_TECH" + modifier_effect_cache.factory_throughput_tech, "factory_throughput", FORMAT_x100_1DP_PC_POS, "FACTORY_THROUGHPUT_TECH" ); ret &= register_technology_modifier_effect( modifier_effect_cache.artisan_input_tech, "artisan_input", FORMAT_x100_1DP_PC_NEG, "ARTISAN_INPUT_TECH", has_no_effect @@ -262,9 +244,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= register_base_country_modifier_effect( modifier_effect_cache.max_war_exhaustion, "max_war_exhaustion", FORMAT_x1_2DP_NEG, "MAX_WAR_EXHAUSTION" ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.leadership, "leadership", FORMAT_x1_2DP_POS, "LEADERSHIP" - ); + ret &= + register_base_country_modifier_effect(modifier_effect_cache.leadership, "leadership", FORMAT_x1_2DP_POS, "LEADERSHIP"); ret &= register_base_country_modifier_effect( modifier_effect_cache.leadership_modifier, "leadership_modifier", FORMAT_x100_1DP_PC_POS, ModifierEffect::make_default_modifier_effect_localisation_key("global_leadership_modifier") @@ -276,18 +257,15 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.unit_recruitment_time, "unit_recruitment_time", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect(modifier_effect_cache.org_regain, "org_regain", FORMAT_x100_1DP_PC_POS); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.reinforce_speed, "reinforce_speed", FORMAT_x100_1DP_PC_POS - ); + ret &= + register_base_country_modifier_effect(modifier_effect_cache.reinforce_speed, "reinforce_speed", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( modifier_effect_cache.land_organisation, "land_organisation", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( modifier_effect_cache.naval_organisation, "naval_organisation", FORMAT_x100_1DP_PC_POS ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.research_points, "research_points", FORMAT_x1_2DP_POS - ); + ret &= register_base_country_modifier_effect(modifier_effect_cache.research_points, "research_points", FORMAT_x1_2DP_POS); ret &= register_base_country_modifier_effect( modifier_effect_cache.research_points_modifier, "research_points_modifier", FORMAT_x100_1DP_PC_POS ); @@ -300,9 +278,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= register_base_country_modifier_effect( modifier_effect_cache.loan_interest_foreign, "loan_interest", FORMAT_x100_1DP_PC_NEG ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.tax_efficiency, "tax_efficiency", FORMAT_x100_1DP_PC_POS - ); + ret &= + register_base_country_modifier_effect(modifier_effect_cache.tax_efficiency, "tax_efficiency", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect(modifier_effect_cache.min_tax, "min_tax", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect(modifier_effect_cache.max_tax, "max_tax", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( @@ -349,9 +326,8 @@ bool ModifierManager::setup_modifier_effects() { ret &= register_base_country_modifier_effect( modifier_effect_cache.factory_throughput_country, "factory_throughput", FORMAT_x100_1DP_PC_POS ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.rgo_output_country, "rgo_output", FORMAT_x100_1DP_PC_POS - ); + ret &= + register_base_country_modifier_effect(modifier_effect_cache.rgo_output_country, "rgo_output", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( modifier_effect_cache.rgo_throughput_country, "rgo_throughput", FORMAT_x100_1DP_PC_POS ); @@ -370,9 +346,7 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.global_assimilation_rate, "global_assimilation_rate", FORMAT_x100_1DP_PC_POS, ModifierEffect::make_default_modifier_effect_localisation_key("assimilation_rate") ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.prestige_monthly_gain, "prestige", FORMAT_x1_3DP_POS - ); + ret &= register_base_country_modifier_effect(modifier_effect_cache.prestige_monthly_gain, "prestige", FORMAT_x1_3DP_POS); ret &= register_base_country_modifier_effect( modifier_effect_cache.factory_cost_country, "factory_cost", FORMAT_x100_1DP_PC_NEG ); @@ -380,7 +354,8 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.farm_rgo_output_global, "farm_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_FARM_EFFICIENCY" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mine_rgo_output_global, "mine_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_MINE_EFFICIENCY" //not sure about this one + modifier_effect_cache.mine_rgo_output_global, "mine_rgo_eff", FORMAT_x100_1DP_PC_POS, + "MODIFIER_MINE_EFFICIENCY" // not sure about this one ); ret &= register_base_country_modifier_effect( modifier_effect_cache.farm_rgo_size_fake, "farm_rgo_size", FORMAT_x100_1DP_PC_POS, @@ -548,18 +523,15 @@ bool ModifierManager::setup_modifier_effects() { ); ret &= register_base_province_modifier_effect( modifier_effect_cache.local_artisan_input, "local_artisan_input", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_input"), - has_no_effect + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_input"), has_no_effect ); ret &= register_base_province_modifier_effect( modifier_effect_cache.local_artisan_output, "local_artisan_output", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_output"), - has_no_effect + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_output"), has_no_effect ); ret &= register_base_province_modifier_effect( modifier_effect_cache.local_artisan_throughput, "local_artisan_throughput", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_throughput"), - has_no_effect + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_throughput"), has_no_effect ); ret &= register_base_province_modifier_effect( modifier_effect_cache.number_of_voters, "number_of_voters", FORMAT_x100_1DP_PC_NEG @@ -599,9 +571,7 @@ bool ModifierManager::setup_modifier_effects() { modifier_effect_cache.immigrant_push, "immigrant_push", FORMAT_x100_1DP_PC_POS, ModifierEffect::make_default_modifier_effect_localisation_key("immigant_push") ); - ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_repair, "local_repair", FORMAT_x100_1DP_PC_POS - ); + ret &= register_base_province_modifier_effect(modifier_effect_cache.local_repair, "local_repair", FORMAT_x100_1DP_PC_POS); ret &= register_base_province_modifier_effect( modifier_effect_cache.local_ship_build, "local_ship_build", FORMAT_x100_1DP_PC_NEG ); @@ -610,18 +580,13 @@ bool ModifierManager::setup_modifier_effects() { ); /* Terrain Modifier Effects */ - ret &= register_terrain_modifier_effect( - modifier_effect_cache.attrition_local, "attrition", FORMAT_x1_2DP_NEG, "ATTRITION" - ); + ret &= register_terrain_modifier_effect(modifier_effect_cache.attrition_local, "attrition", FORMAT_x1_2DP_NEG, "ATTRITION"); /* Military Modifier Effects */ ret &= register_leader_modifier_effect(modifier_effect_cache.attack_leader, "attack", FORMAT_x1_2DP_POS, "TRAIT_ATTACK"); - ret &= register_leader_modifier_effect( - modifier_effect_cache.defence_leader, "defence", FORMAT_x1_2DP_POS, "TRAIT_DEFEND" - ); - ret &= register_leader_modifier_effect( - modifier_effect_cache.morale_leader, "morale", FORMAT_x100_1DP_PC_POS, "TRAIT_MORALE" - ); + ret &= register_leader_modifier_effect(modifier_effect_cache.defence_leader, "defence", FORMAT_x1_2DP_POS, "TRAIT_DEFEND"); + ret &= + register_leader_modifier_effect(modifier_effect_cache.morale_leader, "morale", FORMAT_x100_1DP_PC_POS, "TRAIT_MORALE"); ret &= register_leader_modifier_effect( modifier_effect_cache.organisation, "organisation", FORMAT_x100_1DP_PC_POS, "TRAIT_ORGANISATION" ); @@ -652,16 +617,13 @@ bool ModifierManager::register_complex_modifier(const std::string_view identifie } memory::string ModifierManager::get_flat_identifier( - const std::string_view complex_modifier_identifier, - const std::string_view variant_identifier + const std::string_view complex_modifier_identifier, const std::string_view variant_identifier ) { return memory::fmt::format("{} {}", complex_modifier_identifier, variant_identifier); } bool ModifierManager::add_event_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, + const std::string_view identifier, ModifierValue&& values, const IconModifier::icon_t icon, const Modifier::modifier_type_t type ) { @@ -670,30 +632,23 @@ bool ModifierManager::add_event_modifier( return false; } - return event_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - identifier, std::move(values), type, icon - ); + return event_modifiers.emplace_item(identifier, duplicate_warning_callback, identifier, std::move(values), type, icon); } bool ModifierManager::load_event_modifiers(const ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - event_modifiers, - [this](std::string_view key, ast::NodeCPtr value) -> bool { - ModifierValue modifier_value; - IconModifier::icon_t icon = 0; + const bool ret = expect_dictionary_reserve_length(event_modifiers, [this](std::string_view key, ast::NodeCPtr value) -> bool { + ModifierValue modifier_value; + IconModifier::icon_t icon = 0; - bool ret = expect_dictionary_keys_and_default( - expect_base_province_modifier(modifier_value), - "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)) - )(value); + bool ret = + expect_dictionary_keys_and_default(expect_base_province_modifier(modifier_value), "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)))( + value + ); - ret &= add_event_modifier(key, std::move(modifier_value), icon); + ret &= add_event_modifier(key, std::move(modifier_value), icon); - return ret; - } - )(root); + return ret; + })(root); return ret; } @@ -703,10 +658,7 @@ bool ModifierManager::load_static_modifiers(const ast::NodeCPtr root) { } bool ModifierManager::add_triggered_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, - ConditionScript&& trigger + const std::string_view identifier, ModifierValue&& values, const IconModifier::icon_t icon, ConditionScript&& trigger ) { using enum Modifier::modifier_type_t; @@ -716,16 +668,13 @@ bool ModifierManager::add_triggered_modifier( } return triggered_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - identifier, std::move(values), TRIGGERED, icon, std::move(trigger) + identifier, duplicate_warning_callback, identifier, std::move(values), TRIGGERED, icon, std::move(trigger) ); } bool ModifierManager::load_triggered_modifiers(const ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - triggered_modifiers, - [this](const std::string_view key, const ast::NodeCPtr value) -> bool { + const bool ret = + expect_dictionary_reserve_length(triggered_modifiers, [this](const std::string_view key, const ast::NodeCPtr value) -> bool { using enum scope_type_t; ModifierValue modifier_value {}; @@ -741,8 +690,7 @@ bool ModifierManager::load_triggered_modifiers(const ast::NodeCPtr root) { ret &= add_triggered_modifier(key, std::move(modifier_value), icon, std::move(trigger)); return ret; - } - )(root); + })(root); lock_triggered_modifiers(); @@ -760,10 +708,7 @@ bool ModifierManager::parse_scripts(DefinitionManager const& definition_manager) } bool ModifierManager::_add_flattened_modifier_cb( - ModifierValue& modifier_value, - const std::string_view prefix, - const std::string_view key, - const ast::NodeCPtr value + ModifierValue& modifier_value, const std::string_view prefix, const std::string_view key, const ast::NodeCPtr value ) const { const memory::string flat_identifier = get_flat_identifier(prefix, key); ModifierEffect const* effect = technology_modifier_effects.get_item_by_identifier(flat_identifier); @@ -776,9 +721,7 @@ bool ModifierManager::_add_flattened_modifier_cb( }; bool ModifierManager::_add_modifier_cb( - ModifierValue& modifier_value, - ModifierEffect const* const effect, - const ast::NodeCPtr value + ModifierValue& modifier_value, ModifierEffect const* const effect, const ast::NodeCPtr value ) const { if (effect->has_no_effect) { spdlog::warn_s("This modifier does nothing: {}", *effect); @@ -786,23 +729,17 @@ bool ModifierManager::_add_modifier_cb( return expect_fixed_point(map_callback(modifier_value.values, effect))(value); } -key_value_callback_t ModifierManager::_expect_modifier_effect( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value -) const { +key_value_callback_t +ModifierManager::_expect_modifier_effect(modifier_effect_registry_t const& registry, ModifierValue& modifier_value) const { return _expect_modifier_effect_with_fallback(registry, modifier_value, key_value_warn_callback); } key_value_callback_t ModifierManager::_expect_modifier_effect_with_fallback( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value, - key_value_callback_t fallback + modifier_effect_registry_t const& registry, ModifierValue& modifier_value, key_value_callback_t fallback ) const { return [this, ®istry, &modifier_value, fallback](const std::string_view key, const ast::NodeCPtr value) mutable -> bool { if (dryad::node_has_kind(value) && complex_modifiers.contains(key)) { - return expect_dictionary([this, &modifier_value, key]( - const std::string_view inner_key, const ast::NodeCPtr inner_value - ) -> bool { + return expect_dictionary([this, &modifier_value, key](const std::string_view inner_key, const ast::NodeCPtr inner_value) -> bool { return _add_flattened_modifier_cb(modifier_value, key, inner_key, inner_value); })(value); } @@ -825,26 +762,22 @@ key_value_callback_t ModifierManager::expect_technology_modifier(ModifierValue& std::string_view faction_identifier; ast::NodeCPtr value_node = nullptr; - bool ret = expect_dictionary_keys( - "faction", ONE_EXACTLY, expect_identifier(assign_variable_callback(faction_identifier)), - "value", ONE_EXACTLY, assign_variable_callback(value_node) - )(value); + bool ret = + expect_dictionary_keys("faction", ONE_EXACTLY, expect_identifier(assign_variable_callback(faction_identifier)), "value", ONE_EXACTLY, assign_variable_callback(value_node))( + value + ); ret &= _add_flattened_modifier_cb(modifier_value, key, faction_identifier, value_node); return ret; } - return _expect_modifier_effect( - technology_modifier_effects, - modifier_value - )(key, value); + return _expect_modifier_effect(technology_modifier_effects, modifier_value)(key, value); }; } key_value_callback_t ModifierManager::expect_unit_terrain_modifier( - ModifierValue& modifier_value, - const std::string_view terrain_type_identifier + ModifierValue& modifier_value, const std::string_view terrain_type_identifier ) const { return [this, &modifier_value, terrain_type_identifier](const std::string_view key, const ast::NodeCPtr value) -> bool { const memory::string flat_identifier = get_flat_identifier(key, terrain_type_identifier); @@ -862,16 +795,12 @@ key_value_callback_t ModifierManager::expect_base_country_modifier(ModifierValue key_value_callback_t ModifierManager::expect_base_province_modifier(ModifierValue& modifier_value) const { return _expect_modifier_effect_with_fallback( - base_province_modifier_effects, - modifier_value, - expect_base_country_modifier(modifier_value) + base_province_modifier_effects, modifier_value, expect_base_country_modifier(modifier_value) ); } key_value_callback_t ModifierManager::expect_terrain_modifier(ModifierValue& modifier_value) const { return _expect_modifier_effect_with_fallback( - terrain_modifier_effects, - modifier_value, - expect_base_province_modifier(modifier_value) + terrain_modifier_effects, modifier_value, expect_base_province_modifier(modifier_value) ); } diff --git a/src/openvic-simulation/modifier/ModifierManager.hpp b/src/openvic-simulation/modifier/ModifierManager.hpp index d712ad464..5a49dd158 100644 --- a/src/openvic-simulation/modifier/ModifierManager.hpp +++ b/src/openvic-simulation/modifier/ModifierManager.hpp @@ -40,23 +40,16 @@ namespace OpenVic { StaticModifierCache PROPERTY(static_modifier_cache); bool _register_modifier_effect( - modifier_effect_registry_t& registry, - ModifierEffect::target_t targets, - ModifierEffect const*& effect_cache, - const std::string_view identifier, - const ModifierEffect::format_t format, - const std::string_view localisation_key, + modifier_effect_registry_t& registry, ModifierEffect::target_t targets, ModifierEffect const*& effect_cache, + const std::string_view identifier, const ModifierEffect::format_t format, const std::string_view localisation_key, const bool has_no_effect ); #define REGISTER_MODIFIER_EFFECT_DEFINITION(MAPPING_TYPE) \ - bool register_##MAPPING_TYPE##_modifier_effect( \ - ModifierEffect const*& effect_cache, \ - std::string_view identifier, \ - ModifierEffect::format_t format, \ - std::string_view localisation_key = {}, \ - bool has_no_effect = false \ - ); + bool register_##MAPPING_TYPE##_modifier_effect( \ + ModifierEffect const*& effect_cache, std::string_view identifier, ModifierEffect::format_t format, \ + std::string_view localisation_key = {}, bool has_no_effect = false \ + ); REGISTER_MODIFIER_EFFECT_DEFINITION(leader) REGISTER_MODIFIER_EFFECT_DEFINITION(unit_terrain) @@ -67,39 +60,28 @@ namespace OpenVic { #undef REGISTER_MODIFIER_EFFECT_DEFINITION bool _add_flattened_modifier_cb( - ModifierValue& modifier_value, - const std::string_view prefix, - const std::string_view key, - const ast::NodeCPtr value + ModifierValue& modifier_value, const std::string_view prefix, const std::string_view key, const ast::NodeCPtr value ) const; - bool _add_modifier_cb( - ModifierValue& modifier_value, - ModifierEffect const* const effect, - const ast::NodeCPtr value - ) const; + bool + _add_modifier_cb(ModifierValue& modifier_value, ModifierEffect const* const effect, const ast::NodeCPtr value) const; - NodeTools::key_value_callback_t _expect_modifier_effect( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value - ) const; + NodeTools::key_value_callback_t + _expect_modifier_effect(modifier_effect_registry_t const& registry, ModifierValue& modifier_value) const; NodeTools::key_value_callback_t _expect_modifier_effect_with_fallback( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value, - NodeTools::key_value_callback_t fallback + modifier_effect_registry_t const& registry, ModifierValue& modifier_value, NodeTools::key_value_callback_t fallback ) const; public: bool register_complex_modifier(const std::string_view identifier); - static memory::string get_flat_identifier(const std::string_view complex_modifier_identifier, const std::string_view variant_identifier); + static memory::string + get_flat_identifier(const std::string_view complex_modifier_identifier, const std::string_view variant_identifier); bool setup_modifier_effects(); bool add_event_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, + const std::string_view identifier, ModifierValue&& values, const IconModifier::icon_t icon, const Modifier::modifier_type_t type = Modifier::modifier_type_t::EVENT ); bool load_event_modifiers(const ast::NodeCPtr root); @@ -107,9 +89,7 @@ namespace OpenVic { bool load_static_modifiers(const ast::NodeCPtr root); bool add_triggered_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, + const std::string_view identifier, ModifierValue&& values, const IconModifier::icon_t icon, ConditionScript&& trigger ); bool load_triggered_modifiers(const ast::NodeCPtr root); @@ -119,10 +99,8 @@ namespace OpenVic { NodeTools::key_value_callback_t expect_leader_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_technology_modifier(ModifierValue& modifier_value) const; - NodeTools::key_value_callback_t expect_unit_terrain_modifier( - ModifierValue& modifier_value, - const std::string_view terrain_type_identifier - ) const; + NodeTools::key_value_callback_t + expect_unit_terrain_modifier(ModifierValue& modifier_value, const std::string_view terrain_type_identifier) const; NodeTools::key_value_callback_t expect_base_country_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_base_province_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_terrain_modifier(ModifierValue& modifier_value) const; diff --git a/src/openvic-simulation/modifier/ModifierSum.cpp b/src/openvic-simulation/modifier/ModifierSum.cpp index 1c4daba47..4ad069c81 100644 --- a/src/openvic-simulation/modifier/ModifierSum.cpp +++ b/src/openvic-simulation/modifier/ModifierSum.cpp @@ -1,10 +1,9 @@ #include "ModifierSum.hpp" -#include "openvic-simulation/modifier/Modifier.hpp" - +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/modifier/Modifier.hpp" using namespace OpenVic; @@ -19,9 +18,7 @@ std::string_view modifier_entry_t::source_to_string(modifier_source_t const& sou memory::string modifier_entry_t::to_string() const { return memory::fmt::format( - "[{}, {}, {}, {}]", - modifier, multiplier, source_to_string(source), - ModifierEffect::target_to_string(excluded_targets) + "[{}, {}, {}, {}]", modifier, multiplier, source_to_string(source), ModifierEffect::target_to_string(excluded_targets) ); } @@ -50,9 +47,7 @@ void ModifierSum::add_modifier( // called with an explcit/hardcoded value and so won't ever exclude everything. if (multiplier != 0) { modifier_entry_t const& new_entry = modifiers.emplace_back( - modifier, - multiplier, - modifier_entry_t::source_or_null_fallback(source, this_source), + modifier, multiplier, modifier_entry_t::source_or_null_fallback(source, this_source), excluded_targets | this_excluded_targets ); value_sum.multiply_add_exclude_targets(new_entry.modifier, new_entry.multiplier, new_entry.excluded_targets); @@ -66,10 +61,7 @@ void ModifierSum::add_modifier_sum(ModifierSum const& modifier_sum) { // called with an explcit/hardcoded value and so won't ever exclude everything. for (modifier_entry_t const& modifier_entry : modifier_sum.modifiers) { add_modifier( - modifier_entry.modifier, - modifier_entry.multiplier, - modifier_entry.source, - modifier_entry.excluded_targets + modifier_entry.modifier, modifier_entry.multiplier, modifier_entry.source, modifier_entry.excluded_targets ); } } diff --git a/src/openvic-simulation/modifier/ModifierSum.hpp b/src/openvic-simulation/modifier/ModifierSum.hpp index 5e5c78810..a3e77fd80 100644 --- a/src/openvic-simulation/modifier/ModifierSum.hpp +++ b/src/openvic-simulation/modifier/ModifierSum.hpp @@ -4,8 +4,8 @@ #include #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/modifier/ModifierValue.hpp" #include "openvic-simulation/modifier/Modifier.hpp" +#include "openvic-simulation/modifier/ModifierValue.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" @@ -19,11 +19,15 @@ namespace OpenVic { static std::string_view source_to_string(modifier_source_t const& source); static constexpr bool source_is_null(modifier_source_t const& source) { - return std::visit([](auto const* source) -> bool { return source == nullptr; }, source); + return std::visit( + [](auto const* source) -> bool { + return source == nullptr; + }, + source + ); } - static constexpr modifier_source_t const& source_or_null_fallback( - modifier_source_t const& source, modifier_source_t const& fallback - ) { + static constexpr modifier_source_t const& + source_or_null_fallback(modifier_source_t const& source, modifier_source_t const& fallback) { return std::visit( [&source, &fallback](auto const* source_ptr) -> modifier_source_t const& { return source_ptr == nullptr ? fallback : source; @@ -38,20 +42,15 @@ namespace OpenVic { ModifierEffect::target_t excluded_targets; constexpr modifier_entry_t( - Modifier const& new_modifier, - fixed_point_t new_multiplier, - modifier_source_t const& new_source, + Modifier const& new_modifier, fixed_point_t new_multiplier, modifier_source_t const& new_source, ModifierEffect::target_t new_excluded_targets - ) : modifier { new_modifier }, - multiplier { new_multiplier }, - source { new_source }, - excluded_targets { new_excluded_targets } {} + ) + : modifier { new_modifier }, multiplier { new_multiplier }, source { new_source }, + excluded_targets { new_excluded_targets } {} constexpr bool operator==(modifier_entry_t const& other) const { - return &modifier == &other.modifier - && multiplier == other.multiplier - && source == other.source - && excluded_targets == other.excluded_targets; + return &modifier == &other.modifier && multiplier == other.multiplier && source == other.source && + excluded_targets == other.excluded_targets; } constexpr CountryInstance const* get_source_country() const { @@ -65,9 +64,7 @@ namespace OpenVic { memory::string to_string() const; - constexpr fixed_point_t get_modifier_effect_value( - ModifierEffect const& effect, bool* effect_found = nullptr - ) const { + constexpr fixed_point_t get_modifier_effect_value(ModifierEffect const& effect, bool* effect_found = nullptr) const { if (ModifierEffect::excludes_targets(effect.targets, excluded_targets)) { return modifier.get_effect(effect, effect_found) * multiplier; } @@ -112,9 +109,7 @@ namespace OpenVic { bool has_modifier_effect(ModifierEffect const& effect) const; void add_modifier( - Modifier const& modifier, - fixed_point_t multiplier = 1, - modifier_entry_t::modifier_source_t const& source = {}, + Modifier const& modifier, fixed_point_t multiplier = 1, modifier_entry_t::modifier_source_t const& source = {}, ModifierEffect::target_t excluded_targets = ModifierEffect::target_t::NO_TARGETS ); // Reserves space for the number of modifier entries in the given sum and adds each of them using add_modifier @@ -124,9 +119,8 @@ namespace OpenVic { void add_modifier_sum(ModifierSum const& modifier_sum); // TODO - help calculate value_sum[effect]? Early return if lookup in value_sum fails? - constexpr void for_each_contributing_modifier( - ModifierEffect const& effect, ContributingModifierCallback auto callback - ) const { + constexpr void + for_each_contributing_modifier(ModifierEffect const& effect, ContributingModifierCallback auto callback) const { for (modifier_entry_t const& modifier_entry : modifiers) { const fixed_point_t contribution = modifier_entry.get_modifier_effect_value(effect); diff --git a/src/openvic-simulation/modifier/ModifierValue.cpp b/src/openvic-simulation/modifier/ModifierValue.cpp index a50fea1ac..189cda110 100644 --- a/src/openvic-simulation/modifier/ModifierValue.cpp +++ b/src/openvic-simulation/modifier/ModifierValue.cpp @@ -94,12 +94,9 @@ void ModifierValue::apply_exclude_targets(ModifierEffect::target_t excluded_targ // We could test if excluded_targets is NO_TARGETS (and so we do nothing) or ALL_TARGETS (and so we clear everything), // but so long as this is always called with an explicit/hardcoded value then we'll never have either of those cases. - erase_if( - values, - [excluded_targets](effect_map_t::value_type const& value) -> bool { - return !ModifierEffect::excludes_targets(value.first->targets, excluded_targets); - } - ); + erase_if(values, [excluded_targets](effect_map_t::value_type const& value) -> bool { + return !ModifierEffect::excludes_targets(value.first->targets, excluded_targets); + }); } void ModifierValue::multiply_add_exclude_targets( diff --git a/src/openvic-simulation/modifier/StaticModifierCache.cpp b/src/openvic-simulation/modifier/StaticModifierCache.cpp index bcd017804..cfc57ef6c 100644 --- a/src/openvic-simulation/modifier/StaticModifierCache.cpp +++ b/src/openvic-simulation/modifier/StaticModifierCache.cpp @@ -16,43 +16,38 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage bool ret = true; key_map_t key_map {}; - const auto set_static_country_modifier = [&key_map, &modifier_manager, &ret]( - Modifier& modifier - ) -> void { + const auto set_static_country_modifier = [&key_map, &modifier_manager, &ret](Modifier& modifier) -> void { ret &= add_key_map_entry( key_map, modifier.get_identifier(), ONE_EXACTLY, expect_dictionary(modifier_manager.expect_base_country_modifier(modifier)) ); }; - const auto set_country_event_modifier = [&key_map, &modifier_manager, &ret]( - const std::string_view identifier, const IconModifier::icon_t icon - ) -> void { + const auto set_country_event_modifier = [&key_map, &modifier_manager, + &ret](const std::string_view identifier, const IconModifier::icon_t icon) -> void { ret &= add_key_map_entry( - key_map, identifier, ONE_EXACTLY, - [&modifier_manager, identifier, icon](const ast::NodeCPtr value) -> bool { + key_map, identifier, ONE_EXACTLY, [&modifier_manager, identifier, icon](const ast::NodeCPtr value) -> bool { if (modifier_manager.get_event_modifier_by_identifier(identifier) != nullptr) { - return true; //an event modifier overrides a static modifier with the same identifier. + return true; // an event modifier overrides a static modifier with the same identifier. } ModifierValue modifier_value {}; - bool has_parsed_modifier = expect_dictionary(modifier_manager.expect_base_country_modifier(modifier_value))(value); + bool has_parsed_modifier = + expect_dictionary(modifier_manager.expect_base_country_modifier(modifier_value))(value); has_parsed_modifier &= modifier_manager.add_event_modifier(identifier, std::move(modifier_value), icon, STATIC); return has_parsed_modifier; } ); }; - const auto set_static_province_modifier = [&key_map, &modifier_manager, &ret]( - Modifier& modifier - ) -> void { + const auto set_static_province_modifier = [&key_map, &modifier_manager, &ret](Modifier& modifier) -> void { ret &= add_key_map_entry( key_map, modifier.get_identifier(), ONE_EXACTLY, expect_dictionary(modifier_manager.expect_base_province_modifier(modifier)) ); }; - #define SET_COUNTRY_MODIFIER(PROP, ...) set_static_country_modifier(PROP); +#define SET_COUNTRY_MODIFIER(PROP, ...) set_static_country_modifier(PROP); // Country modifiers COUNTRY_DIFFICULTY_MODIFIER_LIST(SET_COUNTRY_MODIFIER, SET_COUNTRY_MODIFIER) @@ -60,12 +55,10 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage ret &= add_key_map_entry( key_map, base_modifier.get_identifier(), ONE_EXACTLY, expect_dictionary_keys_and_default( - modifier_manager.expect_base_country_modifier(base_modifier), - "supply_limit", ZERO_OR_ONE, [this, &modifier_manager](const ast::NodeCPtr value) -> bool { + modifier_manager.expect_base_country_modifier(base_modifier), "supply_limit", ZERO_OR_ONE, + [this, &modifier_manager](const ast::NodeCPtr value) -> bool { return modifier_manager._add_modifier_cb( - base_modifier, - modifier_manager.get_modifier_effect_cache().get_supply_limit_global_base(), - value + base_modifier, modifier_manager.get_modifier_effect_cache().get_supply_limit_global_base(), value ); } ) @@ -73,7 +66,7 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage COUNTRY_MODIFIER_LIST(SET_COUNTRY_MODIFIER, SET_COUNTRY_MODIFIER) - #undef SET_COUNTRY_MODIFIER +#undef SET_COUNTRY_MODIFIER // Country Event modifiers static constexpr IconModifier::icon_t default_icon = 0; @@ -84,12 +77,12 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage set_country_event_modifier(in_bankruptcy_id, default_icon); set_country_event_modifier(generalised_debt_default_id, default_icon); - #define SET_PROVINCE_MODIFIER(PROP, ...) set_static_province_modifier(PROP); +#define SET_PROVINCE_MODIFIER(PROP, ...) set_static_province_modifier(PROP); // Province modifiers PROVINCE_MODIFIER_LIST(SET_PROVINCE_MODIFIER, SET_PROVINCE_MODIFIER) - #undef SET_PROVINCE_MODIFIER +#undef SET_PROVINCE_MODIFIER ret &= expect_dictionary_key_map_and_default(key_map, key_value_invalid_callback)(root); diff --git a/src/openvic-simulation/modifier/StaticModifierCache.hpp b/src/openvic-simulation/modifier/StaticModifierCache.hpp index b30ac50eb..74e9f83ef 100644 --- a/src/openvic-simulation/modifier/StaticModifierCache.hpp +++ b/src/openvic-simulation/modifier/StaticModifierCache.hpp @@ -12,7 +12,7 @@ F(very_easy_ai) \ F(easy_ai) \ F(hard_ai) \ - F(very_hard_ai) \ + F(very_hard_ai) #define COUNTRY_MODIFIER_LIST(F, ID_F) \ F(war) \ @@ -53,22 +53,22 @@ namespace OpenVic { friend struct ModifierManager; private: - #define DEFINE_PROPERTY_ID(PROP, ID) Modifier PROPERTY(PROP, { #ID, {}, Modifier::modifier_type_t::STATIC }); - #define DEFINE_PROPERTY(PROP) DEFINE_PROPERTY_ID(PROP, PROP) +#define DEFINE_PROPERTY_ID(PROP, ID) Modifier PROPERTY(PROP, { #ID, {}, Modifier::modifier_type_t::STATIC }); +#define DEFINE_PROPERTY(PROP) DEFINE_PROPERTY_ID(PROP, PROP) COUNTRY_DIFFICULTY_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) COUNTRY_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) PROVINCE_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) - #undef DEFINE_PROPERTY - #undef DEFINE_PROPERTY_NAME +#undef DEFINE_PROPERTY +#undef DEFINE_PROPERTY_NAME Modifier PROPERTY(base_modifier, { "base_values", {}, Modifier::modifier_type_t::STATIC }); // Country event modifiers Modifier const* PROPERTY(in_bankruptcy, nullptr); Modifier const* PROPERTY(bad_debtor, nullptr); - Modifier const* PROPERTY(generalised_debt_default, nullptr); //possibly, as it's used to trigger gunboat CB + Modifier const* PROPERTY(generalised_debt_default, nullptr); // possibly, as it's used to trigger gunboat CB StaticModifierCache(); diff --git a/src/openvic-simulation/pathfinding/AStarPathing.cpp b/src/openvic-simulation/pathfinding/AStarPathing.cpp index a4d314b20..8d96e2c69 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.cpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.cpp @@ -8,6 +8,7 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/map/MapDefinition.hpp" #include "openvic-simulation/map/MapInstance.hpp" @@ -16,7 +17,6 @@ #include "openvic-simulation/pathfinding/PointMap.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; @@ -99,12 +99,8 @@ bool AStarPathing::_solve(search_iterator begin_point, search_iterator end_point return found_route; } -ArmyAStarPathing::ArmyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance -) : map_instance { new_map_instance }, - AStarPathing(&new_map_definition.get_path_map_land()) - {} +ArmyAStarPathing::ArmyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance) + : map_instance { new_map_instance }, AStarPathing(&new_map_definition.get_path_map_land()) {} bool ArmyAStarPathing::_is_point_enabled(search_const_iterator it) const { if (!AStarPathing::_is_point_enabled(it)) { @@ -134,12 +130,8 @@ bool ArmyAStarPathing::_is_point_enabled(search_const_iterator it) const { return army_instance->get_country().can_army_units_enter(*province_owner); } -NavyAStarPathing::NavyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance -) : map_instance {new_map_instance}, - AStarPathing(&new_map_definition.get_path_map_land()) - {} +NavyAStarPathing::NavyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance) + : map_instance { new_map_instance }, AStarPathing(&new_map_definition.get_path_map_land()) {} bool NavyAStarPathing::_is_point_enabled(search_const_iterator it) const { if (!AStarPathing::_is_point_enabled(it)) { diff --git a/src/openvic-simulation/pathfinding/AStarPathing.hpp b/src/openvic-simulation/pathfinding/AStarPathing.hpp index c5074e48a..2d3ae7f20 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.hpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.hpp @@ -6,8 +6,8 @@ #include #include "openvic-simulation/pathfinding/PathingBase.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { struct MapDefinition; @@ -58,10 +58,7 @@ namespace OpenVic { }; struct ArmyAStarPathing final : public AStarPathing { - ArmyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance - ); + ArmyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance); protected: UnitInstanceGroupBranched const* PROPERTY_RW_ACCESS(army_instance, protected, nullptr); @@ -71,10 +68,7 @@ namespace OpenVic { }; struct NavyAStarPathing final : public AStarPathing { - NavyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance - ); + NavyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance); protected: UnitInstanceGroupBranched const* PROPERTY_RW_ACCESS(navy_instance, protected, nullptr); diff --git a/src/openvic-simulation/pathfinding/PathingBase.hpp b/src/openvic-simulation/pathfinding/PathingBase.hpp index 3ab4f0bf4..8dd6fa9ec 100644 --- a/src/openvic-simulation/pathfinding/PathingBase.hpp +++ b/src/openvic-simulation/pathfinding/PathingBase.hpp @@ -139,7 +139,8 @@ namespace OpenVic { } template - inline memory::vector generate_path_result(search_iterator from_it, search_iterator to_it, Projection projection = {}) { + inline memory::vector + generate_path_result(search_iterator from_it, search_iterator to_it, Projection projection = {}) { search_iterator p = to_it; int64_t pc = 1; // Begin point while (p != from_it) { diff --git a/src/openvic-simulation/pathfinding/PointMap.cpp b/src/openvic-simulation/pathfinding/PointMap.cpp index d4a05d3cc..c4461947b 100644 --- a/src/openvic-simulation/pathfinding/PointMap.cpp +++ b/src/openvic-simulation/pathfinding/PointMap.cpp @@ -11,10 +11,10 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/types/Vector.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; @@ -91,7 +91,9 @@ void PointMap::add_point( PointMap::Point const* PointMap::get_point(points_key_type id) const { points_const_iterator it = points.find(id); - OV_ERR_FAIL_COND_V_MSG(it == points.end(), nullptr, memory::fmt::format("Can't get a point. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_V_MSG( + it == points.end(), nullptr, memory::fmt::format("Can't get a point. Point with id: {} doesn't exist.", id) + ); return &it.value(); } @@ -116,7 +118,9 @@ ivec2_t PointMap::get_point_position(points_key_type id) const { void PointMap::set_point_position(points_key_type id, ivec2_t const& position) { points_iterator it = points.find(id); - OV_ERR_FAIL_COND_MSG(it == points.end(), memory::fmt::format("Can't set point's position. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + it == points.end(), memory::fmt::format("Can't set point's position. Point with id: {} doesn't exist.", id) + ); it.value().position = position; } @@ -218,10 +222,14 @@ void PointMap::connect_points(points_key_type id, points_key_type with_id, bool OV_ERR_FAIL_COND_MSG(id == with_id, memory::fmt::format("Can't connect point with id: {} to itself.", id)); points_iterator from_it = points.find(id); - OV_ERR_FAIL_COND_MSG(from_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + from_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", id) + ); points_iterator to_it = points.find(with_id); - OV_ERR_FAIL_COND_MSG(to_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", with_id)); + OV_ERR_FAIL_COND_MSG( + to_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", with_id) + ); from_it.value().neighbors.insert(to_it.key()); @@ -252,7 +260,9 @@ void PointMap::connect_points(points_key_type id, points_key_type with_id, bool void PointMap::disconnect_points(points_key_type id, points_key_type with_id, bool bidirectional) { points_iterator from_it = points.find(id); - OV_ERR_FAIL_COND_MSG(from_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + from_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", id) + ); points_iterator to_it = points.find(with_id); OV_ERR_FAIL_COND_MSG( @@ -309,7 +319,9 @@ void PointMap::reserve_space(size_t num_nodes) { OV_ERR_FAIL_COND_MSG(num_nodes <= 0, memory::fmt::format("New capacity must be greater than 0, new was: {}.", num_nodes)); OV_ERR_FAIL_COND_MSG( num_nodes <= points.capacity(), - memory::fmt::format("New capacity must be greater than current capacity: {}, new was: {}.", points.capacity(), num_nodes) + memory::fmt::format( + "New capacity must be greater than current capacity: {}, new was: {}.", points.capacity(), num_nodes + ) ); points.reserve(num_nodes); points_pointers_invalidated(); diff --git a/src/openvic-simulation/pathfinding/PointMap.hpp b/src/openvic-simulation/pathfinding/PointMap.hpp index cde85f497..efd0332b2 100644 --- a/src/openvic-simulation/pathfinding/PointMap.hpp +++ b/src/openvic-simulation/pathfinding/PointMap.hpp @@ -8,11 +8,11 @@ #include #include +#include "openvic-simulation/core/Hash.hpp" #include "openvic-simulation/core/template/EnumBitfield.hpp" #include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/types/Vector.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/core/Hash.hpp" namespace OpenVic { struct PointMap { @@ -62,8 +62,7 @@ namespace OpenVic { struct SegmentHash { inline constexpr std::size_t operator()(Segment const& segment) const { - return hash_murmur3(hash_murmur3(segment.key.first) << 32) | - hash_murmur3(segment.key.second); + return hash_murmur3(hash_murmur3(segment.key.first) << 32) | hash_murmur3(segment.key.second); } }; diff --git a/src/openvic-simulation/politics/BaseIssue.cpp b/src/openvic-simulation/politics/BaseIssue.cpp index 1fa3ba1f9..239d036c7 100644 --- a/src/openvic-simulation/politics/BaseIssue.cpp +++ b/src/openvic-simulation/politics/BaseIssue.cpp @@ -3,13 +3,8 @@ using namespace OpenVic; BaseIssue::BaseIssue( - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - RuleSet&& new_rules, - bool new_is_jingoism, + std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_values, RuleSet&& new_rules, bool new_is_jingoism, modifier_type_t new_type -) : Modifier { new_identifier, std::move(new_values), new_type }, - HasColour { new_colour, false }, - rules { std::move(new_rules) }, - is_jingoism { new_is_jingoism } {} \ No newline at end of file +) + : Modifier { new_identifier, std::move(new_values), new_type }, HasColour { new_colour, false }, + rules { std::move(new_rules) }, is_jingoism { new_is_jingoism } {} diff --git a/src/openvic-simulation/politics/BaseIssue.hpp b/src/openvic-simulation/politics/BaseIssue.hpp index 6aae4b6ea..2681e3d0b 100644 --- a/src/openvic-simulation/politics/BaseIssue.hpp +++ b/src/openvic-simulation/politics/BaseIssue.hpp @@ -8,16 +8,13 @@ namespace OpenVic { struct BaseIssue : Modifier, public HasColour { protected: BaseIssue( - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - RuleSet&& new_rules, - bool new_is_jingoism, - modifier_type_t new_type + std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_values, RuleSet&& new_rules, + bool new_is_jingoism, modifier_type_t new_type ); BaseIssue(BaseIssue&&) = default; + public: const bool is_jingoism; const RuleSet rules; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Government.cpp b/src/openvic-simulation/politics/Government.cpp index 5dadda8bd..d0e4f3df0 100644 --- a/src/openvic-simulation/politics/Government.cpp +++ b/src/openvic-simulation/politics/Government.cpp @@ -8,31 +8,21 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; GovernmentType::GovernmentType( - index_t new_index, - std::string_view new_identifier, - memory::vector>&& new_ideologies, - bool new_holds_elections, - bool new_can_appoint_ruling_party, - Timespan new_term_duration, + index_t new_index, std::string_view new_identifier, memory::vector>&& new_ideologies, + bool new_holds_elections, bool new_can_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier -) : HasIndex { new_index }, - HasIdentifier { new_identifier }, - ideologies { std::move(new_ideologies) }, - holds_elections { new_holds_elections }, - can_appoint_ruling_party { new_can_appoint_ruling_party }, - term_duration { new_term_duration }, - flag_type_identifier { new_flag_type_identifier } {} +) + : HasIndex { new_index }, HasIdentifier { new_identifier }, ideologies { std::move(new_ideologies) }, + holds_elections { new_holds_elections }, can_appoint_ruling_party { new_can_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 ranges::contains( - ideologies, - ideology - ); + return ranges::contains(ideologies, ideology); } bool GovernmentTypeManager::add_government_type( - std::string_view identifier, memory::vector>&& ideologies, bool elections, bool appoint_ruling_party, - Timespan term_duration, std::string_view flag_type + std::string_view identifier, memory::vector>&& ideologies, bool elections, + bool appoint_ruling_party, Timespan term_duration, std::string_view flag_type ) { spdlog::scope scope { fmt::format("government type {}", identifier) }; if (identifier.empty()) { @@ -51,8 +41,8 @@ bool GovernmentTypeManager::add_government_type( } const bool ret = government_types.emplace_item( - identifier, - GovernmentType::index_t { get_government_type_count() }, identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, flag_type + identifier, GovernmentType::index_t { get_government_type_count() }, identifier, std::move(ideologies), elections, + appoint_ruling_party, term_duration, flag_type ); /* flag_type can be empty here for default/non-ideological flag */ @@ -66,71 +56,58 @@ bool GovernmentTypeManager::add_government_type( /* REQUIREMENTS: FS-525, SIM-27 */ bool GovernmentTypeManager::load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/governments.txt" }; - bool ret = expect_dictionary_reserve_length( - government_types, - [this, &ideology_manager](std::string_view government_type_identifier, ast::NodeCPtr government_type_value) -> bool { - memory::vector> ideologies; - bool elections = false, appoint_ruling_party = false; - Timespan term_duration = 0; - std::string_view flag_type_identifier; - - size_t total_expected_ideologies = 0; - bool ret = expect_dictionary_keys_and_default( - increment_callback(total_expected_ideologies), - "election", ZERO_OR_ONE, expect_bool(assign_variable_callback(elections)), - "duration", ZERO_OR_ONE, expect_months(assign_variable_callback(term_duration)), - "appoint_ruling_party", ONE_EXACTLY, expect_bool(assign_variable_callback(appoint_ruling_party)), - "flagType", ZERO_OR_ONE, expect_identifier(assign_variable_callback(flag_type_identifier)) - )(government_type_value); - 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.contains(key)) { - return true; - } - Ideology const* ideology_ptr = ideology_manager.get_ideology_by_identifier(key); - if (ideology_ptr == nullptr) { - spdlog::error_s( - "When loading government type {}, specified ideology {} is invalid!", - government_type_identifier, key - ); - return false; - } - return expect_bool([&ideologies, &ideology = *ideology_ptr, government_type_identifier](bool val) -> bool { - if (val) { - if (!ranges::contains( - ideologies, - ideology - )) { - ideologies.emplace_back(ideology); - return true; - } - spdlog::error_s( - "Government type {} marked as supporting ideology {}", - government_type_identifier, ideology - ); - return false; + bool ret = expect_dictionary_reserve_length(government_types, [this, &ideology_manager](std::string_view government_type_identifier, ast::NodeCPtr government_type_value) -> bool { + memory::vector> ideologies; + bool elections = false, appoint_ruling_party = false; + Timespan term_duration = 0; + std::string_view flag_type_identifier; + + size_t total_expected_ideologies = 0; + bool + ret = + expect_dictionary_keys_and_default(increment_callback(total_expected_ideologies), "election", ZERO_OR_ONE, expect_bool(assign_variable_callback(elections)), "duration", ZERO_OR_ONE, expect_months(assign_variable_callback(term_duration)), "appoint_ruling_party", ONE_EXACTLY, expect_bool(assign_variable_callback(appoint_ruling_party)), "flagType", ZERO_OR_ONE, expect_identifier(assign_variable_callback(flag_type_identifier)))( + government_type_value + ); + 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.contains(key)) { + return true; + } + Ideology const* ideology_ptr = ideology_manager.get_ideology_by_identifier(key); + if (ideology_ptr == nullptr) { + spdlog::error_s( + "When loading government type {}, specified ideology {} is invalid!", government_type_identifier, key + ); + return false; + } + return expect_bool([&ideologies, &ideology = *ideology_ptr, government_type_identifier](bool val) -> bool { + if (val) { + if (!ranges::contains(ideologies, ideology)) { + ideologies.emplace_back(ideology); + return true; } spdlog::error_s( - "Government type {} redundantly marked as not supporting ideology {} multiple times", - government_type_identifier, ideology + "Government type {} marked as supporting ideology {}", government_type_identifier, ideology ); 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 - ); - return ret; - } - )(root); + } + spdlog::error_s( + "Government type {} redundantly marked as not supporting ideology {} multiple times", + government_type_identifier, ideology + ); + 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 + ); + return ret; + })(root); lock_government_types(); return ret; diff --git a/src/openvic-simulation/politics/Government.hpp b/src/openvic-simulation/politics/Government.hpp index 2ab8b7f9b..04ea387b7 100644 --- a/src/openvic-simulation/politics/Government.hpp +++ b/src/openvic-simulation/politics/Government.hpp @@ -24,13 +24,9 @@ namespace OpenVic { const Timespan term_duration; GovernmentType( - index_t new_index, - std::string_view new_identifier, - memory::vector>&& new_ideologies, - bool new_holds_elections, - bool new_can_appoint_ruling_party, - Timespan new_term_duration, - std::string_view new_flag_type_identifier + index_t new_index, std::string_view new_identifier, + memory::vector>&& new_ideologies, bool new_holds_elections, + bool new_can_appoint_ruling_party, Timespan new_term_duration, std::string_view new_flag_type_identifier ); GovernmentType(GovernmentType&&) = default; @@ -44,8 +40,8 @@ namespace OpenVic { public: bool add_government_type( - std::string_view identifier, memory::vector>&& ideologies, bool elections, bool appoint_ruling_party, - Timespan term_duration, std::string_view flag_type + std::string_view identifier, memory::vector>&& ideologies, bool elections, + bool appoint_ruling_party, Timespan term_duration, std::string_view flag_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 61067685e..65b5290ad 100644 --- a/src/openvic-simulation/politics/Ideology.cpp +++ b/src/openvic-simulation/politics/Ideology.cpp @@ -8,33 +8,20 @@ using namespace OpenVic::NodeTools; IdeologyGroup::IdeologyGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} Ideology::Ideology( - std::string_view new_identifier, - index_t new_index, - colour_t new_colour, - IdeologyGroup const& new_group, - bool new_is_allowed_for_uncivilised, - bool new_can_reduce_consciousness, - bool new_can_reduce_militancy, - std::optional new_spawn_date, - ConditionalWeightBase&& new_add_political_reform, - ConditionalWeightBase&& new_remove_political_reform, - ConditionalWeightBase&& new_add_social_reform, - ConditionalWeightBase&& new_remove_social_reform, - ConditionalWeightBase&& new_add_military_reform, + std::string_view new_identifier, index_t new_index, colour_t new_colour, IdeologyGroup const& new_group, + bool new_is_allowed_for_uncivilised, bool new_can_reduce_consciousness, bool new_can_reduce_militancy, + std::optional new_spawn_date, ConditionalWeightBase&& new_add_political_reform, + ConditionalWeightBase&& new_remove_political_reform, ConditionalWeightBase&& new_add_social_reform, + ConditionalWeightBase&& new_remove_social_reform, ConditionalWeightBase&& new_add_military_reform, ConditionalWeightBase&& new_add_economic_reform -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - group { new_group }, - is_allowed_for_uncivilised { new_is_allowed_for_uncivilised }, - can_reduce_consciousness { new_can_reduce_consciousness }, - can_reduce_militancy { new_can_reduce_militancy }, - spawn_date { new_spawn_date }, - add_political_reform { std::move(new_add_political_reform) }, - remove_political_reform { std::move(new_remove_political_reform) }, - add_social_reform { std::move(new_add_social_reform) }, - remove_social_reform { std::move(new_remove_social_reform) }, - add_military_reform { std::move(new_add_military_reform) }, - add_economic_reform { std::move(new_add_economic_reform) } {} +) + : HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, group { new_group }, + is_allowed_for_uncivilised { new_is_allowed_for_uncivilised }, can_reduce_consciousness { new_can_reduce_consciousness }, + can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date }, + add_political_reform { std::move(new_add_political_reform) }, + remove_political_reform { std::move(new_remove_political_reform) }, + add_social_reform { std::move(new_add_social_reform) }, remove_social_reform { std::move(new_remove_social_reform) }, + add_military_reform { std::move(new_add_military_reform) }, add_economic_reform { std::move(new_add_economic_reform) } {} bool Ideology::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -58,18 +45,10 @@ bool IdeologyManager::add_ideology_group(std::string_view identifier) { } bool IdeologyManager::add_ideology( - std::string_view identifier, - colour_t colour, - IdeologyGroup const* group, - bool uncivilised, - bool can_reduce_consciousness, - bool can_reduce_militancy, - std::optional spawn_date, - ConditionalWeightBase&& add_political_reform, - ConditionalWeightBase&& remove_political_reform, - ConditionalWeightBase&& add_social_reform, - ConditionalWeightBase&& remove_social_reform, - ConditionalWeightBase&& add_military_reform, + std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, bool can_reduce_consciousness, + bool can_reduce_militancy, std::optional spawn_date, ConditionalWeightBase&& add_political_reform, + ConditionalWeightBase&& remove_political_reform, ConditionalWeightBase&& add_social_reform, + ConditionalWeightBase&& remove_social_reform, ConditionalWeightBase&& add_military_reform, ConditionalWeightBase&& add_economic_reform ) { spdlog::scope scope { fmt::format("ideology {}", identifier) }; @@ -85,21 +64,9 @@ bool IdeologyManager::add_ideology( const Ideology::index_t new_index = Ideology::index_t { ideologies.size() }; return ideologies.emplace_item( - identifier, - identifier, - new_index, - colour, - *group, - uncivilised, - can_reduce_consciousness, - can_reduce_militancy, - spawn_date, - std::move(add_political_reform), - std::move(remove_political_reform), - std::move(add_social_reform), - std::move(remove_social_reform), - std::move(add_military_reform), - std::move(add_economic_reform) + identifier, identifier, new_index, colour, *group, uncivilised, can_reduce_consciousness, can_reduce_militancy, + spawn_date, std::move(add_political_reform), std::move(remove_political_reform), std::move(add_social_reform), + std::move(remove_social_reform), std::move(add_military_reform), std::move(add_economic_reform) ); } @@ -109,14 +76,12 @@ bool IdeologyManager::add_ideology( bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { spdlog::scope scope { "common/ideologies.txt" }; size_t expected_ideologies = 0; - bool ret = expect_dictionary_reserve_length( - ideology_groups, - [this, &expected_ideologies](std::string_view key, ast::NodeCPtr value) -> bool { + 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); return ret; - } - )(root); + })(root); lock_ideology_groups(); reserve_more_ideologies(expected_ideologies); @@ -152,19 +117,9 @@ bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { )(value); ret &= add_ideology( - key, - colour, - ideology_group, - uncivilised, - can_reduce_consciousness, - can_reduce_militancy, - spawn_date, - std::move(add_political_reform), - std::move(remove_political_reform), - std::move(add_social_reform), - std::move(remove_social_reform), - std::move(add_military_reform), - std::move(add_economic_reform) + key, colour, ideology_group, uncivilised, can_reduce_consciousness, can_reduce_militancy, spawn_date, + std::move(add_political_reform), std::move(remove_political_reform), std::move(add_social_reform), + std::move(remove_social_reform), std::move(add_military_reform), std::move(add_economic_reform) ); return ret; diff --git a/src/openvic-simulation/politics/Ideology.hpp b/src/openvic-simulation/politics/Ideology.hpp index 1b4e98ffe..79882c04b 100644 --- a/src/openvic-simulation/politics/Ideology.hpp +++ b/src/openvic-simulation/politics/Ideology.hpp @@ -41,19 +41,11 @@ namespace OpenVic { IdeologyGroup const& group; Ideology( - std::string_view new_identifier, - index_t new_index, - colour_t new_colour, - IdeologyGroup const& new_group, - bool new_is_allowed_for_uncivilised, - bool new_can_reduce_consciousness, - bool new_can_reduce_militancy, - std::optional new_spawn_date, - ConditionalWeightBase&& new_add_political_reform, - ConditionalWeightBase&& new_remove_political_reform, - ConditionalWeightBase&& new_add_social_reform, - ConditionalWeightBase&& new_remove_social_reform, - ConditionalWeightBase&& new_add_military_reform, + std::string_view new_identifier, index_t new_index, colour_t new_colour, IdeologyGroup const& new_group, + bool new_is_allowed_for_uncivilised, bool new_can_reduce_consciousness, bool new_can_reduce_militancy, + std::optional new_spawn_date, ConditionalWeightBase&& new_add_political_reform, + ConditionalWeightBase&& new_remove_political_reform, ConditionalWeightBase&& new_add_social_reform, + ConditionalWeightBase&& new_remove_social_reform, ConditionalWeightBase&& new_add_military_reform, ConditionalWeightBase&& new_add_economic_reform ); Ideology(Ideology&&) = default; @@ -68,19 +60,11 @@ namespace OpenVic { bool add_ideology_group(std::string_view identifier); bool add_ideology( - std::string_view identifier, - colour_t colour, - IdeologyGroup const* group, - bool uncivilised, - bool can_reduce_consciousness, - bool can_reduce_militancy, - std::optional spawn_date, - ConditionalWeightBase&& add_political_reform, - ConditionalWeightBase&& remove_political_reform, - ConditionalWeightBase&& add_social_reform, - ConditionalWeightBase&& remove_social_reform, - ConditionalWeightBase&& add_military_reform, - ConditionalWeightBase&& add_economic_reform + std::string_view identifier, colour_t colour, IdeologyGroup const* group, bool uncivilised, + bool can_reduce_consciousness, bool can_reduce_militancy, std::optional spawn_date, + ConditionalWeightBase&& add_political_reform, ConditionalWeightBase&& remove_political_reform, + ConditionalWeightBase&& add_social_reform, ConditionalWeightBase&& remove_social_reform, + ConditionalWeightBase&& add_military_reform, ConditionalWeightBase&& add_economic_reform ); bool load_ideology_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/IssueGroup.hpp b/src/openvic-simulation/politics/IssueGroup.hpp index 1b14d9cc1..0b288d77a 100644 --- a/src/openvic-simulation/politics/IssueGroup.hpp +++ b/src/openvic-simulation/politics/IssueGroup.hpp @@ -6,9 +6,6 @@ namespace OpenVic { struct PartyPolicyGroup; struct ReformGroup; - using issue_group_t = std::variant< - std::monostate, - std::reference_wrapper, - std::reference_wrapper - >; -} \ No newline at end of file + using issue_group_t = + std::variant, std::reference_wrapper>; +} diff --git a/src/openvic-simulation/politics/IssueManager.cpp b/src/openvic-simulation/politics/IssueManager.cpp index 479c2b0ef..40186bbef 100644 --- a/src/openvic-simulation/politics/IssueManager.cpp +++ b/src/openvic-simulation/politics/IssueManager.cpp @@ -1,7 +1,7 @@ #include "IssueManager.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -13,14 +13,13 @@ bool IssueManager::add_party_policy_group(std::string_view identifier) { } return party_policy_groups.emplace_item( - identifier, - identifier, PartyPolicyGroup::index_t { get_party_policy_group_count() } + identifier, identifier, PartyPolicyGroup::index_t { get_party_policy_group_count() } ); } bool IssueManager::add_party_policy( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, RuleSet&& rules, - bool jingoism + std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, + RuleSet&& rules, bool jingoism ) { if (identifier.empty()) { spdlog::error_s("Invalid party policy identifier - empty!"); @@ -28,10 +27,9 @@ bool IssueManager::add_party_policy( } if (!party_policies.emplace_item( - identifier, - PartyPolicy::index_t { get_party_policy_count() }, identifier, - new_colour, std::move(values), party_policy_group, std::move(rules), jingoism - )) { + identifier, PartyPolicy::index_t { get_party_policy_count() }, identifier, new_colour, std::move(values), + party_policy_group, std::move(rules), jingoism + )) { return false; } @@ -45,24 +43,18 @@ bool IssueManager::add_reform_type(std::string_view identifier, bool uncivilised return false; } - return reform_types.emplace_item( - identifier, - identifier, uncivilised - ); + return reform_types.emplace_item(identifier, identifier, uncivilised); } -bool IssueManager::add_reform_group( - std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative -) { +bool IssueManager::add_reform_group(std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative) { if (identifier.empty()) { spdlog::error_s("Invalid issue group identifier - empty!"); return false; } if (!reform_groups.emplace_item( - identifier, - identifier, ReformGroup::index_t { get_reform_group_count() }, reform_type, ordered, administrative - )) { + identifier, identifier, ReformGroup::index_t { get_reform_group_count() }, reform_type, ordered, administrative + )) { return false; } @@ -84,23 +76,19 @@ bool IssueManager::add_reform( if (ordinal == 0) { if (technology_cost != 0) { spdlog::warn_s( - "Non-zero technology cost {} found in ordinal 0 uncivilised reform {}!", - technology_cost, identifier + "Non-zero technology cost {} found in ordinal 0 uncivilised reform {}!", technology_cost, identifier ); } } else { if (technology_cost <= 0) { spdlog::warn_s( - "Non-positive technology cost {} found in ordinal {} uncivilised reform {}!", - technology_cost, ordinal, identifier + "Non-positive technology cost {} found in ordinal {} uncivilised reform {}!", technology_cost, ordinal, + identifier ); } } } else if (technology_cost != 0) { - spdlog::warn_s( - "Non-zero technology cost {} found in civilised reform {}!", - technology_cost, identifier - ); + spdlog::warn_s("Non-zero technology cost {} found in civilised reform {}!", technology_cost, identifier); } if (administrative_multiplier != 0 && !reform_group.is_administrative) { @@ -111,11 +99,10 @@ bool IssueManager::add_reform( } if (!reforms.emplace_item( - identifier, - Reform::index_t { get_reform_count() }, identifier, - new_colour, std::move(values), reform_group, ordinal, administrative_multiplier, std::move(rules), - technology_cost, std::move(allow), std::move(on_execute_trigger), std::move(on_execute_effect) - )) { + identifier, Reform::index_t { get_reform_count() }, identifier, new_colour, std::move(values), reform_group, + ordinal, administrative_multiplier, std::move(rules), technology_cost, std::move(allow), + std::move(on_execute_trigger), std::move(on_execute_effect) + )) { return false; } @@ -125,8 +112,7 @@ bool IssueManager::add_reform( bool IssueManager::_load_party_policy_group(size_t& expected_party_policies, std::string_view identifier, ast::NodeCPtr node) { spdlog::scope scope { fmt::format("party policy group {}", identifier) }; - return expect_length(add_variable_callback(expected_party_policies))(node) - & add_party_policy_group(identifier); + return expect_length(add_variable_callback(expected_party_policies))(node) & add_party_policy_group(identifier); } /* Each colour is made up of these components in some order: @@ -144,8 +130,8 @@ static constexpr size_t varying_colour_denominator = 60; /* 3! = 3 (choices for 0) * 2 (choices for 252) * 1 (choices for 4.25 * i) */ static constexpr size_t colour_pattern_period = 6; -static constexpr std::array dim_colour_indices { 0, 1, 2, 0, 1, 2 }; -static constexpr std::array bright_colour_indices { 1, 2, 0, 2, 0, 1 }; +static constexpr std::array dim_colour_indices { 0, 1, 2, 0, 1, 2 }; +static constexpr std::array bright_colour_indices { 1, 2, 0, 2, 0, 1 }; static constexpr std::array varying_colour_indices { 2, 0, 1, 1, 2, 0 }; static constexpr colour_t create_issue_reform_colour(size_t index) { @@ -157,15 +143,15 @@ static constexpr colour_t create_issue_reform_colour(size_t index) { ret[bright_colour_indices[periodic_index]] = bright_colour_component; - ret[varying_colour_indices[periodic_index]] = static_cast(colour_t::max_value) - * ((index * scattering_prime) % varying_colour_denominator) / varying_colour_denominator; + ret[varying_colour_indices[periodic_index]] = static_cast(colour_t::max_value) * + ((index * scattering_prime) % varying_colour_denominator) / varying_colour_denominator; return ret; } bool IssueManager::_load_party_policy( - ModifierManager const& modifier_manager, std::string_view identifier, - PartyPolicyGroup& party_policy_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, std::string_view identifier, PartyPolicyGroup& party_policy_group, + ast::NodeCPtr node ) { spdlog::scope scope { fmt::format("party policy {}", identifier) }; @@ -173,19 +159,15 @@ bool IssueManager::_load_party_policy( RuleSet rules; bool is_jingoism = false; - bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_base_country_modifier(values), - "is_jingoism", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_jingoism)), - "rules", ZERO_OR_ONE, RuleSet::expect_rule_set(move_variable_callback(rules)), - "war_exhaustion_effect", ZERO_OR_ONE, [](const ast::NodeCPtr _) -> bool { + bool + ret = NodeTools::expect_dictionary_keys_and_default(modifier_manager.expect_base_country_modifier(values), "is_jingoism", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_jingoism)), "rules", ZERO_OR_ONE, RuleSet::expect_rule_set(move_variable_callback(rules)), "war_exhaustion_effect", ZERO_OR_ONE, [](const ast::NodeCPtr _) -> bool { spdlog::warn_s("war_exhaustion_effect does nothing (vanilla issues have it)."); return true; - } - )(node); + })(node); ret &= add_party_policy( - identifier, create_issue_reform_colour(get_party_policy_count() + get_reform_count()), std::move(values), party_policy_group, - std::move(rules), is_jingoism + identifier, create_issue_reform_colour(get_party_policy_count() + get_reform_count()), std::move(values), + party_policy_group, std::move(rules), is_jingoism ); return ret; @@ -197,11 +179,10 @@ bool IssueManager::_load_reform_group( spdlog::scope scope { fmt::format("reform group {}", identifier) }; bool ordered = false, administrative = false; - bool ret = expect_dictionary_keys_and_default( - increment_callback(expected_reforms), - "next_step_only", ZERO_OR_ONE, expect_bool(assign_variable_callback(ordered)), - "administrative", ZERO_OR_ONE, expect_bool(assign_variable_callback(administrative)) - )(node); + bool ret = + expect_dictionary_keys_and_default(increment_callback(expected_reforms), "next_step_only", ZERO_OR_ONE, expect_bool(assign_variable_callback(ordered)), "administrative", ZERO_OR_ONE, expect_bool(assign_variable_callback(administrative)))( + node + ); ret &= add_reform_group(identifier, reform_type, ordered, administrative); @@ -209,8 +190,8 @@ bool IssueManager::_load_reform_group( } bool IssueManager::_load_reform( - ModifierManager const& modifier_manager, size_t ordinal, std::string_view identifier, - ReformGroup& reform_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, size_t ordinal, std::string_view identifier, ReformGroup& reform_group, + ast::NodeCPtr node ) { spdlog::scope scope { fmt::format("reform {}", identifier) }; using enum scope_type_t; @@ -253,20 +234,15 @@ bool IssueManager::_load_reform( * 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( - ModifierManager const& modifier_manager, ast::NodeCPtr root -) { +bool IssueManager::load_issues_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/issues.txt" }; bool party_issues_found = false; size_t expected_party_policy_groups = 0; size_t expected_reform_groups = 0; /* Reserve space for issue and reform groups and reserve space for and load reform types. */ - bool ret = expect_dictionary_reserve_length( - reform_types, - [this, &party_issues_found, &expected_party_policy_groups, &expected_reform_groups]( - std::string_view key, ast::NodeCPtr value - ) -> bool { + bool ret = + expect_dictionary_reserve_length(reform_types, [this, &party_issues_found, &expected_party_policy_groups, &expected_reform_groups](std::string_view key, ast::NodeCPtr value) -> bool { if (key == "party_issues") { if (party_issues_found) { /* Error emitted here allowing later passes to return true with no error message. */ @@ -277,15 +253,13 @@ bool IssueManager::load_issues_file( return expect_length(add_variable_callback(expected_party_policy_groups))(value); } else { - static const string_set_t uncivilised_reform_groups { - "economic_reforms", "education_reforms", "military_reforms" - }; + static const string_set_t uncivilised_reform_groups { "economic_reforms", "education_reforms", + "military_reforms" }; - return expect_length(add_variable_callback(expected_reform_groups))(value) - & add_reform_type(key, uncivilised_reform_groups.contains(key)); + return expect_length(add_variable_callback(expected_reform_groups))(value) & + add_reform_type(key, uncivilised_reform_groups.contains(key)); } - } - )(root); + })(root); lock_reform_types(); @@ -297,10 +271,8 @@ bool IssueManager::load_issues_file( size_t expected_reforms = 0; /* Load issue and reform groups. */ - ret &= expect_dictionary( - [this, &party_issues_found, &expected_party_policies, &expected_reforms]( - std::string_view type_key, ast::NodeCPtr type_value - ) -> bool { + ret &= + expect_dictionary([this, &party_issues_found, &expected_party_policies, &expected_reforms](std::string_view type_key, ast::NodeCPtr type_value) -> bool { if (type_key == "party_issues") { if (party_issues_found) { return true; /* Error will have been emitted in first pass. */ @@ -318,14 +290,11 @@ bool IssueManager::load_issues_file( return false; } - return expect_dictionary( - [this, reform_type, &expected_reforms](std::string_view key, ast::NodeCPtr value) -> bool { - return _load_reform_group(expected_reforms, key, *reform_type, value); - } - )(type_value); + return expect_dictionary([this, reform_type, &expected_reforms](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_reform_group(expected_reforms, key, *reform_type, value); + })(type_value); } - } - )(root); + })(root); lock_party_policy_groups(); lock_reform_groups(); @@ -336,58 +305,46 @@ bool IssueManager::load_issues_file( party_issues_found = false; /* Load issues and reforms. */ - ret &= expect_dictionary( - [this, &party_issues_found, &modifier_manager]( - std::string_view type_key, ast::NodeCPtr type_value - ) -> bool { - if (type_key == "party_issues") { - if (party_issues_found) { - return true; - } - party_issues_found = true; + ret &= expect_dictionary([this, &party_issues_found, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_value) -> bool { + if (type_key == "party_issues") { + if (party_issues_found) { + return true; + } + party_issues_found = true; - return expect_dictionary([this, &modifier_manager]( - std::string_view group_key, ast::NodeCPtr group_value - ) -> bool { - PartyPolicyGroup* party_policy_group = party_policy_groups.get_item_by_identifier(group_key); + return expect_dictionary([this, &modifier_manager](std::string_view group_key, ast::NodeCPtr group_value) -> bool { + PartyPolicyGroup* party_policy_group = party_policy_groups.get_item_by_identifier(group_key); - if (OV_unlikely(party_policy_group == nullptr)) { - spdlog::error_s("Party policy group \"{}\" not found!", group_key); - return false; - } + if (OV_unlikely(party_policy_group == nullptr)) { + spdlog::error_s("Party policy group \"{}\" not found!", group_key); + return false; + } - return expect_dictionary([this, &modifier_manager, party_policy_group]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - return _load_party_policy(modifier_manager, key, *party_policy_group, value); - })(group_value); - })(type_value); - } else { - return expect_dictionary([this, &party_issues_found, &modifier_manager]( - std::string_view group_key, ast::NodeCPtr group_value - ) -> bool { - ReformGroup* reform_group = reform_groups.get_item_by_identifier(group_key); - - if (OV_unlikely(reform_group == nullptr)) { - spdlog::error_s("Reform group \"{}\" not found!", group_key); - return false; - } + return expect_dictionary([this, &modifier_manager, party_policy_group](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_party_policy(modifier_manager, key, *party_policy_group, value); + })(group_value); + })(type_value); + } else { + return expect_dictionary([this, &party_issues_found, &modifier_manager](std::string_view group_key, ast::NodeCPtr group_value) -> bool { + ReformGroup* reform_group = reform_groups.get_item_by_identifier(group_key); - size_t ordinal = 0; + if (OV_unlikely(reform_group == nullptr)) { + spdlog::error_s("Reform group \"{}\" not found!", group_key); + return false; + } - return expect_dictionary([this, &modifier_manager, reform_group, &ordinal]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - if (key == "next_step_only" || key == "administrative") { - return true; - } + size_t ordinal = 0; - return _load_reform(modifier_manager, ordinal++, key, *reform_group, value); - })(group_value); - })(type_value); - } + return expect_dictionary([this, &modifier_manager, reform_group, &ordinal](std::string_view key, ast::NodeCPtr value) -> bool { + if (key == "next_step_only" || key == "administrative") { + return true; + } + + return _load_reform(modifier_manager, ordinal++, key, *reform_group, value); + })(group_value); + })(type_value); } - )(root); + })(root); lock_party_policies(); lock_reforms(); diff --git a/src/openvic-simulation/politics/IssueManager.hpp b/src/openvic-simulation/politics/IssueManager.hpp index 8f4e0dea2..321d9673a 100644 --- a/src/openvic-simulation/politics/IssueManager.hpp +++ b/src/openvic-simulation/politics/IssueManager.hpp @@ -21,15 +21,14 @@ namespace OpenVic { bool _load_party_policy_group(size_t& expected_party_policies, std::string_view identifier, ast::NodeCPtr node); bool _load_party_policy( - ModifierManager const& modifier_manager, std::string_view identifier, - PartyPolicyGroup& party_policy_group, ast::NodeCPtr node - ); - bool _load_reform_group( - size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node + ModifierManager const& modifier_manager, std::string_view identifier, PartyPolicyGroup& party_policy_group, + ast::NodeCPtr node ); + bool + _load_reform_group(size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node); bool _load_reform( - ModifierManager const& modifier_manager, size_t ordinal, - std::string_view identifier, ReformGroup& reform_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, size_t ordinal, std::string_view identifier, ReformGroup& reform_group, + ast::NodeCPtr node ); public: @@ -53,46 +52,41 @@ namespace OpenVic { return {}; } - constexpr NodeTools::NodeCallback auto expect_base_issue_group_identifier( - NodeTools::Callback auto callback, bool warn = false - ) const { - return NodeTools::expect_identifier( - [this, callback, warn](std::string_view identifier) -> bool { - if (identifier.empty()) { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Invalid base issue group identifier: empty!" - ); - return warn; - } - issue_group_t issue_group = get_base_issue_group_by_identifier(identifier); - if (std::holds_alternative(issue_group)) { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Invalid base issue group identifier: {}", identifier - ); - return warn; - } - - return callback(issue_group); + constexpr NodeTools::NodeCallback auto + expect_base_issue_group_identifier(NodeTools::Callback auto callback, bool warn = false) const { + return NodeTools::expect_identifier([this, callback, warn](std::string_view identifier) -> bool { + if (identifier.empty()) { + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Invalid base issue group identifier: empty!" + ); + return warn; + } + issue_group_t issue_group = get_base_issue_group_by_identifier(identifier); + if (std::holds_alternative(issue_group)) { + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Invalid base issue group identifier: {}", identifier + ); + return warn; } - ); + + return callback(issue_group); + }); } bool add_party_policy_group(std::string_view identifier); bool add_party_policy( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, RuleSet&& rules, - bool jingoism + std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, + RuleSet&& rules, bool jingoism ); bool add_reform_type(std::string_view identifier, bool uncivilised); bool add_reform_group(std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative); bool add_reform( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, ReformGroup& reform_group, - size_t ordinal, fixed_point_t administrative_multiplier, RuleSet&& rules, Reform::tech_cost_t technology_cost, + std::string_view identifier, colour_t new_colour, ModifierValue&& values, ReformGroup& reform_group, size_t ordinal, + fixed_point_t administrative_multiplier, RuleSet&& rules, Reform::tech_cost_t technology_cost, ConditionScript&& allow, ConditionScript&& on_execute_trigger, EffectScript&& on_execute_effect ); bool load_issues_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/NationalFocus.cpp b/src/openvic-simulation/politics/NationalFocus.cpp index f62bd07d1..0afaa775f 100644 --- a/src/openvic-simulation/politics/NationalFocus.cpp +++ b/src/openvic-simulation/politics/NationalFocus.cpp @@ -1,10 +1,10 @@ #include "NationalFocus.hpp" +#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/population/PopManager.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -12,33 +12,18 @@ using namespace OpenVic::NodeTools; NationalFocusGroup::NationalFocusGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} NationalFocus::NationalFocus( - std::string_view new_identifier, - NationalFocusGroup const& new_group, - uint8_t new_icon, - bool new_has_flashpoint, - fixed_point_t new_flashpoint_tension, - bool new_own_provinces, - bool new_outliner_show_as_percent, - ModifierValue&& new_modifiers, - Ideology const* new_loyalty_ideology, - fixed_point_t new_loyalty_value, - fixed_point_t new_encourage_railroads, - fixed_point_map_t&& new_encourage_goods, - fixed_point_map_t&& new_encourage_pop_types, - ConditionScript&& new_limit -) : Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_FOCUS }, - group { new_group }, - icon { new_icon }, - has_flashpoint { new_has_flashpoint }, - flashpoint_tension { new_flashpoint_tension }, - own_provinces { new_own_provinces }, - outliner_show_as_percent { new_outliner_show_as_percent }, - loyalty_ideology { new_loyalty_ideology }, - loyalty_value { new_loyalty_value }, - encourage_railroads { new_encourage_railroads }, - encourage_goods { std::move(new_encourage_goods) }, - encourage_pop_types { std::move(new_encourage_pop_types) }, - limit { std::move(new_limit) } {} + std::string_view new_identifier, NationalFocusGroup const& new_group, uint8_t new_icon, bool new_has_flashpoint, + fixed_point_t new_flashpoint_tension, bool new_own_provinces, bool new_outliner_show_as_percent, + ModifierValue&& new_modifiers, Ideology const* new_loyalty_ideology, fixed_point_t new_loyalty_value, + fixed_point_t new_encourage_railroads, fixed_point_map_t&& new_encourage_goods, + fixed_point_map_t&& new_encourage_pop_types, ConditionScript&& new_limit +) + : Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_FOCUS }, group { new_group }, + icon { new_icon }, has_flashpoint { new_has_flashpoint }, flashpoint_tension { new_flashpoint_tension }, + own_provinces { new_own_provinces }, outliner_show_as_percent { new_outliner_show_as_percent }, + loyalty_ideology { new_loyalty_ideology }, loyalty_value { new_loyalty_value }, + encourage_railroads { new_encourage_railroads }, encourage_goods { std::move(new_encourage_goods) }, + encourage_pop_types { std::move(new_encourage_pop_types) }, limit { std::move(new_limit) } {} bool NationalFocus::parse_scripts(DefinitionManager const& definition_manager) { spdlog::scope scope { fmt::format("national focus {}", get_identifier()) }; @@ -55,19 +40,10 @@ inline bool NationalFocusManager::add_national_focus_group(std::string_view iden } inline bool NationalFocusManager::add_national_focus( - std::string_view identifier, - NationalFocusGroup const& group, - uint8_t icon, - bool has_flashpoint, - fixed_point_t flashpoint_tension, - bool own_provinces, - bool outliner_show_as_percent, - ModifierValue&& modifiers, - Ideology const* loyalty_ideology, - fixed_point_t loyalty_value, - fixed_point_t encourage_railroads, - fixed_point_map_t&& encourage_goods, - fixed_point_map_t&& encourage_pop_types, + std::string_view identifier, NationalFocusGroup const& group, uint8_t icon, bool has_flashpoint, + fixed_point_t flashpoint_tension, bool own_provinces, bool outliner_show_as_percent, ModifierValue&& modifiers, + Ideology const* loyalty_ideology, fixed_point_t loyalty_value, fixed_point_t encourage_railroads, + fixed_point_map_t&& encourage_goods, fixed_point_map_t&& encourage_pop_types, ConditionScript&& limit ) { spdlog::scope scope { fmt::format("national focus {}", identifier) }; @@ -83,14 +59,13 @@ inline bool NationalFocusManager::add_national_focus( if ((loyalty_ideology == nullptr) != (loyalty_value == 0)) { spdlog::warn_s( - "Party loyalty incorrectly defined for national focus {}: ideology = {}, value = {}", - identifier, ovfmt::validate(loyalty_ideology), loyalty_value + "Party loyalty incorrectly defined for national focus {}: ideology = {}, value = {}", identifier, + ovfmt::validate(loyalty_ideology), loyalty_value ); } return national_foci.emplace_item( - identifier, - identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, + identifier, identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, std::move(modifiers), loyalty_ideology, loyalty_value, encourage_railroads, std::move(encourage_goods), std::move(encourage_pop_types), std::move(limit) ); @@ -103,43 +78,33 @@ bool NationalFocusManager::load_national_foci_file( spdlog::scope scope { "common/national_focus.txt" }; size_t expected_national_foci = 0; - bool ret = expect_dictionary_reserve_length( - national_focus_groups, - [this, &expected_national_foci](std::string_view identifier, ast::NodeCPtr node) -> bool { + bool ret = + expect_dictionary_reserve_length(national_focus_groups, [this, &expected_national_foci](std::string_view identifier, ast::NodeCPtr node) -> bool { return expect_length(add_variable_callback(expected_national_foci))(node) & add_national_focus_group(identifier); - } - )(root); + })(root); lock_national_focus_groups(); reserve_more_national_foci(expected_national_foci); - ret &= expect_national_focus_group_dictionary( - [this, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager]( - NationalFocusGroup const& group, ast::NodeCPtr group_node - ) -> bool { - return expect_dictionary( - [this, &group, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager]( - std::string_view identifier, ast::NodeCPtr node - ) -> bool { - spdlog::scope scope { fmt::format("national focus {}", identifier) }; - using enum scope_type_t; - - uint8_t icon = 0; - bool has_flashpoint = false, own_provinces = true, outliner_show_as_percent = false; - fixed_point_t flashpoint_tension = 0; - ModifierValue modifiers; - Ideology const* loyalty_ideology = nullptr; - fixed_point_t loyalty_value = 0; - fixed_point_t encourage_railroads = 0; - fixed_point_map_t encourage_goods; - fixed_point_map_t encourage_pop_types; - ConditionScript limit { - PROVINCE | COUNTRY, PROVINCE | COUNTRY, NO_SCOPE - }; - - auto expect_base_province_modifier_cb = modifier_manager.expect_base_province_modifier(modifiers); - bool ret = NodeTools::expect_dictionary_keys_and_default( + ret &= expect_national_focus_group_dictionary([this, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager](NationalFocusGroup const& group, ast::NodeCPtr group_node) -> bool { + return expect_dictionary([this, &group, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + spdlog::scope scope { fmt::format("national focus {}", identifier) }; + using enum scope_type_t; + + uint8_t icon = 0; + bool has_flashpoint = false, own_provinces = true, outliner_show_as_percent = false; + fixed_point_t flashpoint_tension = 0; + ModifierValue modifiers; + Ideology const* loyalty_ideology = nullptr; + fixed_point_t loyalty_value = 0; + fixed_point_t encourage_railroads = 0; + fixed_point_map_t encourage_goods; + fixed_point_map_t encourage_pop_types; + ConditionScript limit { PROVINCE | COUNTRY, PROVINCE | COUNTRY, NO_SCOPE }; + + auto expect_base_province_modifier_cb = modifier_manager.expect_base_province_modifier(modifiers); + bool ret = NodeTools::expect_dictionary_keys_and_default( [&good_definition_manager, &encourage_goods, &pop_manager, &encourage_pop_types, &expect_base_province_modifier_cb]( std::string_view key, ast::NodeCPtr value ) mutable -> bool { @@ -168,17 +133,15 @@ bool NationalFocusManager::load_national_foci_file( "railroads", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(encourage_railroads)) )(node); - ret &= add_national_focus( - identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, - std::move(modifiers), loyalty_ideology, loyalty_value, encourage_railroads, - std::move(encourage_goods), std::move(encourage_pop_types), std::move(limit) - ); - - return ret; - } - )(group_node); - } - )(root); + ret &= add_national_focus( + identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, + std::move(modifiers), loyalty_ideology, loyalty_value, encourage_railroads, std::move(encourage_goods), + std::move(encourage_pop_types), std::move(limit) + ); + + return ret; + })(group_node); + })(root); lock_national_foci(); diff --git a/src/openvic-simulation/politics/NationalFocus.hpp b/src/openvic-simulation/politics/NationalFocus.hpp index 4fccee361..82b7bd333 100644 --- a/src/openvic-simulation/politics/NationalFocus.hpp +++ b/src/openvic-simulation/politics/NationalFocus.hpp @@ -40,20 +40,11 @@ namespace OpenVic { const fixed_point_map_t encourage_pop_types; NationalFocus( - std::string_view new_identifier, - NationalFocusGroup const& new_group, - uint8_t new_icon, - bool new_has_flashpoint, - fixed_point_t new_flashpoint_tension, - bool new_own_provinces, - bool new_outliner_show_as_percent, - ModifierValue&& new_modifiers, - Ideology const* new_loyalty_ideology, - fixed_point_t new_loyalty_value, - fixed_point_t new_encourage_railroads, - fixed_point_map_t&& new_encourage_goods, - fixed_point_map_t&& new_encourage_pop_types, - ConditionScript&& new_limit + std::string_view new_identifier, NationalFocusGroup const& new_group, uint8_t new_icon, bool new_has_flashpoint, + fixed_point_t new_flashpoint_tension, bool new_own_provinces, bool new_outliner_show_as_percent, + ModifierValue&& new_modifiers, Ideology const* new_loyalty_ideology, fixed_point_t new_loyalty_value, + fixed_point_t new_encourage_railroads, fixed_point_map_t&& new_encourage_goods, + fixed_point_map_t&& new_encourage_pop_types, ConditionScript&& new_limit ); NationalFocus(NationalFocus&&) = default; }; @@ -71,19 +62,10 @@ namespace OpenVic { inline bool add_national_focus_group(std::string_view identifier); inline bool add_national_focus( - std::string_view identifier, - NationalFocusGroup const& group, - uint8_t icon, - bool has_flashpoint, - fixed_point_t flashpoint_tension, - bool own_provinces, - bool outliner_show_as_percent, - ModifierValue&& modifiers, - Ideology const* loyalty_ideology, - fixed_point_t loyalty_value, - fixed_point_t encourage_railroads, - fixed_point_map_t&& encourage_goods, - fixed_point_map_t&& encourage_pop_types, + std::string_view identifier, NationalFocusGroup const& group, uint8_t icon, bool has_flashpoint, + fixed_point_t flashpoint_tension, bool own_provinces, bool outliner_show_as_percent, ModifierValue&& modifiers, + Ideology const* loyalty_ideology, fixed_point_t loyalty_value, fixed_point_t encourage_railroads, + fixed_point_map_t&& encourage_goods, fixed_point_map_t&& encourage_pop_types, ConditionScript&& limit ); diff --git a/src/openvic-simulation/politics/NationalValue.cpp b/src/openvic-simulation/politics/NationalValue.cpp index ef9bbee86..d3c85a1ba 100644 --- a/src/openvic-simulation/politics/NationalValue.cpp +++ b/src/openvic-simulation/politics/NationalValue.cpp @@ -14,28 +14,21 @@ bool NationalValueManager::add_national_value(std::string_view identifier, Modif return false; } - return national_values.emplace_item( - identifier, - identifier, std::move(modifiers) - ); + return national_values.emplace_item(identifier, identifier, std::move(modifiers)); } bool NationalValueManager::load_national_values_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/nationalvalues.txt" }; - bool ret = expect_dictionary_reserve_length( - national_values, - [this, &modifier_manager](std::string_view national_value_identifier, ast::NodeCPtr value) -> bool { + bool ret = + expect_dictionary_reserve_length(national_values, [this, &modifier_manager](std::string_view national_value_identifier, ast::NodeCPtr value) -> bool { spdlog::scope scope { fmt::format("national value {}", national_value_identifier) }; ModifierValue modifiers; - bool ret = NodeTools::expect_dictionary( - modifier_manager.expect_base_country_modifier(modifiers) - )(value); + bool ret = NodeTools::expect_dictionary(modifier_manager.expect_base_country_modifier(modifiers))(value); ret &= add_national_value(national_value_identifier, std::move(modifiers)); return ret; - } - )(root); + })(root); lock_national_values(); diff --git a/src/openvic-simulation/politics/PartyPolicy.hpp b/src/openvic-simulation/politics/PartyPolicy.hpp index f4c57a65f..5c55ddaa7 100644 --- a/src/openvic-simulation/politics/PartyPolicy.hpp +++ b/src/openvic-simulation/politics/PartyPolicy.hpp @@ -12,14 +12,13 @@ namespace OpenVic { // PartyPolicy group (i.e. trade_policy) struct PartyPolicyGroup : HasIndex, HasIdentifier { friend struct IssueManager; + private: memory::vector> SPAN_PROPERTY(party_policies); public: - PartyPolicyGroup( - std::string_view new_identifier, - index_t new_index - ) : HasIndex { new_index }, HasIdentifier { new_identifier } {} + PartyPolicyGroup(std::string_view new_identifier, index_t new_index) + : HasIndex { new_index }, HasIdentifier { new_identifier } {} PartyPolicyGroup(PartyPolicyGroup&&) = default; }; @@ -29,23 +28,12 @@ namespace OpenVic { PartyPolicyGroup const& group; PartyPolicy( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - PartyPolicyGroup const& new_issue_group, - RuleSet&& new_rules, - bool new_is_jingoism - ) : HasIndex { new_index }, - BaseIssue { - new_identifier, - new_colour, - std::move(new_values), - std::move(new_rules), - new_is_jingoism, - modifier_type_t::PARTY_POLICY - }, - group { new_issue_group } {} + index_t new_index, std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_values, + PartyPolicyGroup const& new_issue_group, RuleSet&& new_rules, bool new_is_jingoism + ) + : HasIndex { new_index }, BaseIssue { new_identifier, new_colour, std::move(new_values), + std::move(new_rules), new_is_jingoism, modifier_type_t::PARTY_POLICY }, + group { new_issue_group } {} PartyPolicy(PartyPolicy&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/PoliticsInstanceManager.cpp b/src/openvic-simulation/politics/PoliticsInstanceManager.cpp index eea1305c2..83150aa11 100644 --- a/src/openvic-simulation/politics/PoliticsInstanceManager.cpp +++ b/src/openvic-simulation/politics/PoliticsInstanceManager.cpp @@ -6,11 +6,9 @@ using namespace OpenVic; PoliticsInstanceManager::PoliticsInstanceManager( - InstanceManager const& new_instance_manager, - forwardable_span ideologies + InstanceManager const& new_instance_manager, forwardable_span ideologies ) - : instance_manager { new_instance_manager }, - ideology_spawn_date { ideologies } {} + : instance_manager { new_instance_manager }, ideology_spawn_date { ideologies } {} void PoliticsInstanceManager::setup_starting_ideologies() { const Date today = instance_manager.get_today(); @@ -39,16 +37,13 @@ void PoliticsInstanceManager::unlock_ideology(Ideology const& ideology) { if (!spawn_date.has_value()) { spawn_date = instance_manager.get_today(); } else { - spdlog::warn_s( - "Cannot unlock ideology \"{}\" - it was already unlocked on: {}", - ideology, *spawn_date - ); + spdlog::warn_s("Cannot unlock ideology \"{}\" - it was already unlocked on: {}", ideology, *spawn_date); } } void PoliticsInstanceManager::set_great_wars_enabled(bool enabled) { // if (enabled && !great_wars_enabled) { - // TODO - trigger "Great Wars discovered!" popup + // TODO - trigger "Great Wars discovered!" popup // } great_wars_enabled = enabled; diff --git a/src/openvic-simulation/politics/PoliticsInstanceManager.hpp b/src/openvic-simulation/politics/PoliticsInstanceManager.hpp index a333c94fa..7634c332e 100644 --- a/src/openvic-simulation/politics/PoliticsInstanceManager.hpp +++ b/src/openvic-simulation/politics/PoliticsInstanceManager.hpp @@ -2,10 +2,10 @@ #include +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" namespace OpenVic { struct InstanceManager; @@ -22,10 +22,7 @@ namespace OpenVic { bool PROPERTY(world_wars_enabled, false); public: - PoliticsInstanceManager( - InstanceManager const& new_instance_manager, - forwardable_span ideologies - ); + PoliticsInstanceManager(InstanceManager const& new_instance_manager, forwardable_span ideologies); PoliticsInstanceManager(PoliticsInstanceManager&&) = default; void setup_starting_ideologies(); @@ -37,4 +34,4 @@ namespace OpenVic { void set_great_wars_enabled(bool enabled); void set_world_wars_enabled(bool enabled); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Rebel.cpp b/src/openvic-simulation/politics/Rebel.cpp index 8f09f92fa..db08808b5 100644 --- a/src/openvic-simulation/politics/Rebel.cpp +++ b/src/openvic-simulation/politics/Rebel.cpp @@ -2,35 +2,34 @@ #include +#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/politics/Government.hpp" #include "openvic-simulation/politics/Ideology.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; RebelType::RebelType( - index_t new_index, std::string_view new_identifier, - RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, + index_t new_index, std::string_view new_identifier, RebelType::icon_t icon, RebelType::area_t area, + bool break_alliance_on_win, RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, ConditionalWeightFactorMul&& new_will_rise, ConditionalWeightFactorMul&& new_spawn_chance, ConditionalWeightFactorMul&& new_movement_evaluation, ConditionScript&& new_siege_won_trigger, EffectScript&& new_siege_won_effect, ConditionScript&& new_demands_enforced_trigger, EffectScript&& new_demands_enforced_effect -) : HasIndex { new_index }, - HasIdentifier { new_identifier }, - icon { icon }, area { area }, will_break_alliance_on_win { break_alliance_on_win }, - desired_governments { std::move(desired_governments) }, defection_type { defection }, independence_type { independence }, - defect_delay { defect_delay }, ideology { ideology }, allows_all_cultures { allow_all_cultures }, - allows_all_culture_groups { allow_all_culture_groups }, allows_all_religions { allow_all_religions }, - allows_all_ideologies { allow_all_ideologies }, is_resilient { resilient }, is_reinforcing { reinforcing }, has_generals { general }, - is_smart { smart }, will_transfer_units { unit_transfer }, occupation_mult { occupation_mult }, - will_rise { std::move(new_will_rise) }, spawn_chance { std::move(new_spawn_chance) }, - movement_evaluation { std::move(new_movement_evaluation) }, siege_won_trigger { std::move(new_siege_won_trigger) }, - siege_won_effect { std::move(new_siege_won_effect) }, demands_enforced_trigger { std::move(new_demands_enforced_trigger) }, - demands_enforced_effect { std::move(new_demands_enforced_effect) } {} +) + : HasIndex { new_index }, HasIdentifier { new_identifier }, icon { icon }, area { area }, + will_break_alliance_on_win { break_alliance_on_win }, desired_governments { std::move(desired_governments) }, + defection_type { defection }, independence_type { independence }, defect_delay { defect_delay }, ideology { ideology }, + allows_all_cultures { allow_all_cultures }, allows_all_culture_groups { allow_all_culture_groups }, + allows_all_religions { allow_all_religions }, allows_all_ideologies { allow_all_ideologies }, is_resilient { resilient }, + is_reinforcing { reinforcing }, has_generals { general }, is_smart { smart }, will_transfer_units { unit_transfer }, + occupation_mult { occupation_mult }, will_rise { std::move(new_will_rise) }, spawn_chance { std::move(new_spawn_chance) }, + movement_evaluation { std::move(new_movement_evaluation) }, siege_won_trigger { std::move(new_siege_won_trigger) }, + siege_won_effect { std::move(new_siege_won_effect) }, + demands_enforced_trigger { std::move(new_demands_enforced_trigger) }, + demands_enforced_effect { std::move(new_demands_enforced_effect) } {} bool RebelType::parse_scripts(DefinitionManager const& definition_manager) { spdlog::scope scope { fmt::format("rebel type {}", get_identifier()) }; @@ -47,10 +46,10 @@ bool RebelType::parse_scripts(DefinitionManager const& definition_manager) { bool RebelManager::add_rebel_type( std::string_view new_identifier, RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, - RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, - bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, - bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, ConditionalWeightFactorMul&& will_rise, + RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, RebelType::independence_t independence, + uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, bool allow_all_culture_groups, + bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, bool general, bool smart, + bool unit_transfer, fixed_point_t occupation_mult, ConditionalWeightFactorMul&& will_rise, ConditionalWeightFactorMul&& spawn_chance, ConditionalWeightFactorMul&& movement_evaluation, ConditionScript&& siege_won_trigger, EffectScript&& siege_won_effect, ConditionScript&& demands_enforced_trigger, EffectScript&& demands_enforced_effect @@ -61,13 +60,12 @@ bool RebelManager::add_rebel_type( } return rebel_types.emplace_item( - new_identifier, - RebelType::index_t { get_rebel_type_count() }, new_identifier, - icon, area, break_alliance_on_win, std::move(desired_governments), defection, independence, - defect_delay, ideology, allow_all_cultures, allow_all_culture_groups, allow_all_religions, allow_all_ideologies, - resilient, reinforcing, general, smart, unit_transfer, occupation_mult, std::move(will_rise), std::move(spawn_chance), - std::move(movement_evaluation), std::move(siege_won_trigger), std::move(siege_won_effect), - std::move(demands_enforced_trigger), std::move(demands_enforced_effect) + new_identifier, RebelType::index_t { get_rebel_type_count() }, new_identifier, icon, area, break_alliance_on_win, + std::move(desired_governments), defection, independence, defect_delay, ideology, allow_all_cultures, + allow_all_culture_groups, allow_all_religions, allow_all_ideologies, resilient, reinforcing, general, smart, + unit_transfer, occupation_mult, std::move(will_rise), std::move(spawn_chance), std::move(movement_evaluation), + std::move(siege_won_trigger), std::move(siege_won_effect), std::move(demands_enforced_trigger), + std::move(demands_enforced_effect) ); } @@ -76,15 +74,13 @@ bool RebelManager::load_rebels_file( ) { spdlog::scope scope { "common/rebel_types.txt" }; - static const string_map_t area_map = { - { "nation", RebelType::area_t::NATION }, - { "nation_religion", RebelType::area_t::NATION_RELIGION }, - { "nation_culture", RebelType::area_t::NATION_CULTURE }, - { "culture", RebelType::area_t::CULTURE }, - { "culture_group", RebelType::area_t::CULTURE_GROUP }, - { "religion", RebelType::area_t::RELIGION }, - { "all", RebelType::area_t::ALL } - }; + static const string_map_t area_map = { { "nation", RebelType::area_t::NATION }, + { "nation_religion", RebelType::area_t::NATION_RELIGION }, + { "nation_culture", RebelType::area_t::NATION_CULTURE }, + { "culture", RebelType::area_t::CULTURE }, + { "culture_group", RebelType::area_t::CULTURE_GROUP }, + { "religion", RebelType::area_t::RELIGION }, + { "all", RebelType::area_t::ALL } }; static const string_map_t defection_map = { { "none", RebelType::defection_t::NONE }, @@ -106,9 +102,8 @@ bool RebelManager::load_rebels_file( { "any", RebelType::independence_t::ANY } }; - bool ret = expect_dictionary_reserve_length( - rebel_types, - [this, &ideology_manager, &government_type_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + bool ret = + expect_dictionary_reserve_length(rebel_types, [this, &ideology_manager, &government_type_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { using enum scope_type_t; spdlog::scope scope { fmt::format("rebel type {}", identifier) }; @@ -121,8 +116,8 @@ bool RebelManager::load_rebels_file( uint16_t defect_delay = 0; Ideology const* ideology = nullptr; bool break_alliance_on_win = false, allow_all_cultures = true, allow_all_culture_groups = true, - allow_all_religions = true, allow_all_ideologies = true, resilient = true, reinforcing = true, general = true, - smart = true, unit_transfer = false; + allow_all_religions = true, allow_all_ideologies = true, resilient = true, reinforcing = true, general = true, + smart = true, unit_transfer = false; fixed_point_t occupation_mult = 0; ConditionalWeightFactorMul will_rise { POP, COUNTRY, NO_SCOPE }; ConditionalWeightFactorMul spawn_chance { POP, POP, NO_SCOPE }; @@ -175,15 +170,14 @@ bool RebelManager::load_rebels_file( ret &= add_rebel_type( identifier, icon, area, break_alliance_on_win, std::move(desired_governments), defection, independence, - defect_delay, ideology, allow_all_cultures, allow_all_culture_groups, allow_all_religions, - allow_all_ideologies, resilient, reinforcing, general, smart, unit_transfer, occupation_mult, - std::move(will_rise), std::move(spawn_chance), std::move(movement_evaluation), std::move(siege_won_trigger), + defect_delay, ideology, allow_all_cultures, allow_all_culture_groups, allow_all_religions, allow_all_ideologies, + resilient, reinforcing, general, smart, unit_transfer, occupation_mult, std::move(will_rise), + std::move(spawn_chance), std::move(movement_evaluation), std::move(siege_won_trigger), std::move(siege_won_effect), std::move(demands_enforced_trigger), std::move(demands_enforced_effect) ); return ret; - } - )(root); + })(root); lock_rebel_types(); @@ -206,13 +200,12 @@ bool RebelManager::generate_modifiers(ModifierManager& modifier_manager) const { ); auto& rebel_org_gain_effects = modifier_manager.modifier_effect_cache.rebel_org_gain_effects; - rebel_org_gain_effects = std::move(decltype(ModifierEffectCache::rebel_org_gain_effects){get_rebel_types()}); + rebel_org_gain_effects = std::move(decltype(ModifierEffectCache::rebel_org_gain_effects) { get_rebel_types() }); for (RebelType const& rebel_type : get_rebel_types()) { ret &= modifier_manager.register_technology_modifier_effect( rebel_org_gain_effects.at(rebel_type), - ModifierManager::get_flat_identifier(identifier, rebel_type.get_identifier()), - FORMAT_x100_2DP_PC_NEG, + ModifierManager::get_flat_identifier(identifier, rebel_type.get_identifier()), FORMAT_x100_2DP_PC_NEG, memory::fmt::format("${}_title$ $TECH_REBEL_ORG_GAIN$", rebel_type) ); } diff --git a/src/openvic-simulation/politics/Rebel.hpp b/src/openvic-simulation/politics/Rebel.hpp index efccb83f7..98311b20f 100644 --- a/src/openvic-simulation/politics/Rebel.hpp +++ b/src/openvic-simulation/politics/Rebel.hpp @@ -24,20 +24,11 @@ namespace OpenVic { using government_map_t = ordered_map; using icon_t = uint16_t; - enum class area_t { - NATION, NATION_RELIGION, NATION_CULTURE, - CULTURE, CULTURE_GROUP, RELIGION, ALL - }; + enum class area_t { NATION, NATION_RELIGION, NATION_CULTURE, CULTURE, CULTURE_GROUP, RELIGION, ALL }; - enum class defection_t { - NONE, CULTURE, CULTURE_GROUP, RELIGION, - IDEOLOGY, PAN_NATIONALIST, ANY - }; + enum class defection_t { NONE, CULTURE, CULTURE_GROUP, RELIGION, IDEOLOGY, PAN_NATIONALIST, ANY }; - enum class independence_t { - NONE, CULTURE, CULTURE_GROUP, RELIGION, - COLONIAL, PAN_NATIONALIST, ANY - }; + enum class independence_t { NONE, CULTURE, CULTURE_GROUP, RELIGION, COLONIAL, PAN_NATIONALIST, ANY }; private: ConditionalWeightFactorMul PROPERTY(will_rise); @@ -71,9 +62,8 @@ namespace OpenVic { const fixed_point_t occupation_mult; RebelType( - index_t new_index, std::string_view new_identifier, - RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, + index_t new_index, std::string_view new_identifier, RebelType::icon_t icon, RebelType::area_t area, + bool break_alliance_on_win, RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, @@ -108,4 +98,4 @@ namespace OpenVic { bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Reform.cpp b/src/openvic-simulation/politics/Reform.cpp index 378d268ed..58930296e 100644 --- a/src/openvic-simulation/politics/Reform.cpp +++ b/src/openvic-simulation/politics/Reform.cpp @@ -6,34 +6,22 @@ ReformType::ReformType(std::string_view new_identifier, bool new_is_civilizing) : HasIdentifier { new_identifier }, is_civilizing { new_is_civilizing } {} ReformGroup::ReformGroup( - std::string_view new_identifier, - index_t new_index, - ReformType const& new_reform_type, - bool new_is_ordered, + std::string_view new_identifier, index_t new_index, ReformType const& new_reform_type, bool new_is_ordered, bool new_is_administrative -) : HasIdentifier { new_identifier }, - HasIndex { new_index }, - reform_type { new_reform_type }, - is_ordered { new_is_ordered }, - is_administrative { new_is_administrative } {} +) + : HasIdentifier { new_identifier }, HasIndex { new_index }, reform_type { new_reform_type }, is_ordered { new_is_ordered }, + is_administrative { new_is_administrative } {} Reform::Reform( - index_t new_index, std::string_view new_identifier, - colour_t new_colour, ModifierValue&& new_values, ReformGroup const& new_reform_group, - size_t new_ordinal, fixed_point_t new_administrative_multiplier, RuleSet&& new_rules, tech_cost_t new_technology_cost, - ConditionScript&& new_allow, ConditionScript&& new_on_execute_trigger, EffectScript&& new_on_execute_effect -) : BaseIssue { - new_identifier, new_colour, std::move(new_values), std::move(new_rules), false, - modifier_type_t::REFORM - }, - HasIndex { new_index }, - ordinal { new_ordinal }, - administrative_multiplier { new_administrative_multiplier }, - technology_cost { new_technology_cost }, - group { new_reform_group }, - allow { std::move(new_allow) }, - on_execute_trigger { std::move(new_on_execute_trigger) }, - on_execute_effect { std::move(new_on_execute_effect) } {} + index_t new_index, std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_values, + ReformGroup const& new_reform_group, size_t new_ordinal, fixed_point_t new_administrative_multiplier, RuleSet&& new_rules, + tech_cost_t new_technology_cost, ConditionScript&& new_allow, ConditionScript&& new_on_execute_trigger, + EffectScript&& new_on_execute_effect +) + : BaseIssue { new_identifier, new_colour, std::move(new_values), std::move(new_rules), false, modifier_type_t::REFORM }, + HasIndex { new_index }, ordinal { new_ordinal }, administrative_multiplier { new_administrative_multiplier }, + technology_cost { new_technology_cost }, group { new_reform_group }, allow { std::move(new_allow) }, + on_execute_trigger { std::move(new_on_execute_trigger) }, on_execute_effect { std::move(new_on_execute_effect) } {} bool Reform::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -43,4 +31,4 @@ bool Reform::parse_scripts(DefinitionManager const& definition_manager) { ret &= on_execute_effect.parse_script(true, definition_manager); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Reform.hpp b/src/openvic-simulation/politics/Reform.hpp index b67c9de06..522e8f9b4 100644 --- a/src/openvic-simulation/politics/Reform.hpp +++ b/src/openvic-simulation/politics/Reform.hpp @@ -9,7 +9,7 @@ #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -namespace OpenVic { +namespace OpenVic { struct ReformGroup; // Reform type (i.e. political_issues) @@ -42,10 +42,7 @@ namespace OpenVic { const bool is_administrative; ReformGroup( - std::string_view new_identifier, - index_t new_index, - ReformType const& new_reform_type, - bool new_is_ordered, + std::string_view new_identifier, index_t new_index, ReformType const& new_reform_type, bool new_is_ordered, bool new_is_administrative ); ReformGroup(ReformGroup&&) = default; @@ -75,12 +72,11 @@ namespace OpenVic { ReformGroup const& group; Reform( - index_t new_index, std::string_view new_identifier, - colour_t new_colour, ModifierValue&& new_values, ReformGroup const& new_reform_group, - size_t new_ordinal, fixed_point_t new_administrative_multiplier, + index_t new_index, std::string_view new_identifier, colour_t new_colour, ModifierValue&& new_values, + ReformGroup const& new_reform_group, size_t new_ordinal, fixed_point_t new_administrative_multiplier, RuleSet&& new_rules, tech_cost_t new_technology_cost, ConditionScript&& new_allow, ConditionScript&& new_on_execute_trigger, EffectScript&& new_on_execute_effect ); Reform(Reform&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/RuleSet.hpp b/src/openvic-simulation/politics/RuleSet.hpp index b27d50eaf..b06d13513 100644 --- a/src/openvic-simulation/politics/RuleSet.hpp +++ b/src/openvic-simulation/politics/RuleSet.hpp @@ -3,32 +3,19 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/string/StringLiteral.hpp" #include "openvic-simulation/core/string/Utility.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/OptionalBool.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/utility/Logger.hpp" namespace OpenVic { - //TODO replace with strategy pattern? - enum struct ApportionmentMethod : std::uint8_t { - largest_share, - dhont, - sainte_laque - }; - enum struct UpperHouseComposition : std::uint8_t { - same_as_ruling_party, - rich_only, - state_vote, - population_vote - }; - enum struct CulturalVotingRight : std::uint8_t { - primary_culture_voting, - culture_voting, - all_voting - }; + // TODO replace with strategy pattern? + enum struct ApportionmentMethod : std::uint8_t { largest_share, dhont, sainte_laque }; + enum struct UpperHouseComposition : std::uint8_t { same_as_ruling_party, rich_only, state_vote, population_vote }; + enum struct CulturalVotingRight : std::uint8_t { primary_culture_voting, culture_voting, all_voting }; struct RuleSet { private: @@ -42,47 +29,45 @@ namespace OpenVic { } }; - //in the order of Vic2 tooltip - #define DO_FOR_ALL_RULES_SEP(F, SEP) \ - F(build_factory) SEP \ - F(expand_factory) SEP \ - F(open_factory) SEP \ - F(destroy_factory) SEP \ - F(build_railway) SEP \ - F(factory_priority) SEP \ - F(can_subsidise) SEP \ - F(pop_build_factory) SEP \ - F(pop_expand_factory) SEP \ - F(pop_open_factory) SEP \ - F(delete_factory_if_no_input) SEP \ - F(build_factory_invest) SEP \ - F(expand_factory_invest) SEP \ - F(open_factory_invest) SEP \ - F(build_railway_invest) SEP \ - F(can_invest_in_pop_projects) SEP \ - F(pop_build_factory_invest) SEP \ - F(pop_expand_factory_invest) SEP \ - F(pop_open_factory_invest) SEP \ - F(allow_foreign_investment) SEP \ - F(primary_culture_voting) SEP \ - F(culture_voting) SEP \ - F(all_voting) SEP \ - F(largest_share) SEP \ - F(dhont) SEP \ - F(sainte_laque) SEP \ - F(rich_only) SEP \ - F(same_as_ruling_party) SEP \ - F(state_vote) SEP \ - F(population_vote) SEP \ - F(slavery_allowed) - - #define RULE_FIELDS(RULE) \ - OptionalBool RULE : 2 = OptionalBool::UNSPECIFIED; - - DO_FOR_ALL_RULES_SEP(RULE_FIELDS,) - #undef RULE_FIELDS - - template +// in the order of Vic2 tooltip +#define DO_FOR_ALL_RULES_SEP(F, SEP) \ + F(build_factory) SEP F(expand_factory) \ + SEP F(open_factory) \ + SEP F(destroy_factory) \ + SEP F(build_railway) \ + SEP F(factory_priority) \ + SEP F(can_subsidise) \ + SEP F(pop_build_factory) \ + SEP F(pop_expand_factory) \ + SEP F(pop_open_factory) \ + SEP F(delete_factory_if_no_input) \ + SEP F(build_factory_invest) \ + SEP F(expand_factory_invest) \ + SEP F(open_factory_invest) \ + SEP F(build_railway_invest) \ + SEP F(can_invest_in_pop_projects) \ + SEP F(pop_build_factory_invest) \ + SEP F(pop_expand_factory_invest) \ + SEP F(pop_open_factory_invest) \ + SEP F(allow_foreign_investment) \ + SEP F(primary_culture_voting) \ + SEP F(culture_voting) \ + SEP F(all_voting) \ + SEP F(largest_share) \ + SEP F(dhont) \ + SEP F(sainte_laque) \ + SEP F(rich_only) \ + SEP F(same_as_ruling_party) \ + SEP F(state_vote) \ + SEP F(population_vote) \ + SEP F(slavery_allowed) + +#define RULE_FIELDS(RULE) OptionalBool RULE : 2 = OptionalBool::UNSPECIFIED; + + DO_FOR_ALL_RULES_SEP(RULE_FIELDS, ) +#undef RULE_FIELDS + + template EnumType select_with_priority(const RuleDefinition (&rules)[N]) const { const std::string_view context_name = type_name(); @@ -93,10 +78,7 @@ namespace OpenVic { for (size_t j = i + 1; j < N; ++j) { if (OV_unlikely(rules[j].value == OptionalBool::TRUE)) { spdlog::warn_s( - "Both {} and {} are enabled for {}. {} is picked.", - rules[i].name, - rules[j].name, - context_name, + "Both {} and {} are enabled for {}. {} is picked.", rules[i].name, rules[j].name, context_name, rules[i].name ); } @@ -118,9 +100,9 @@ namespace OpenVic { return EnumType(0); } - #define DEF(VALUE) RuleDefinition::Define<#VALUE>(VALUE) +#define DEF(VALUE) RuleDefinition::Define<#VALUE>(VALUE) - #define RESOLVE_DEFAULT_FALSE(METHOD_NAME, FIELD) \ +#define RESOLVE_DEFAULT_FALSE(METHOD_NAME, FIELD) \ bool METHOD_NAME() const { \ const bool is_true = FIELD == OptionalBool::TRUE; \ if (FIELD == OptionalBool::UNSPECIFIED) { \ @@ -129,95 +111,78 @@ namespace OpenVic { return is_true; \ } - [[nodiscard]] OptionalBool merge_rule(OptionalBool current, OptionalBool other, std::string_view name) { - // If they are the same or 'other' provides no new info, stay as we are. - if (current == other || other == OptionalBool::UNSPECIFIED) { - return current; - } + [[nodiscard]] OptionalBool merge_rule(OptionalBool current, OptionalBool other, std::string_view name) { + // If they are the same or 'other' provides no new info, stay as we are. + if (current == other || other == OptionalBool::UNSPECIFIED) { + return current; + } - // If we were unspecified, take whatever 'other' has. - if (current == OptionalBool::UNSPECIFIED) { - return other; + // If we were unspecified, take whatever 'other' has. + if (current == OptionalBool::UNSPECIFIED) { + return other; + } + + // Conflict: One is TRUE and the other is FALSE. + // Since 'other' isn't UNSPECIFIED and isn't the same as 'current', + // and we know 'current' isn't UNSPECIFIED, they must be TRUE/FALSE opposites. + spdlog::warn_s("{} is both false and true, true wins.", name); + return OptionalBool::TRUE; } - // Conflict: One is TRUE and the other is FALSE. - // Since 'other' isn't UNSPECIFIED and isn't the same as 'current', - // and we know 'current' isn't UNSPECIFIED, they must be TRUE/FALSE opposites. - spdlog::warn_s("{} is both false and true, true wins.", name); - return OptionalBool::TRUE; - } - - static memory::string make_rule_localisation_key(std::string_view identifier) { - return "RULE_" + ascii_toupper(identifier); - } + static memory::string make_rule_localisation_key(std::string_view identifier) { + return "RULE_" + ascii_toupper(identifier); + } public: - #define MAP_FROM_BOOL(RULE) \ - #RULE, ZERO_OR_ONE, NodeTools::expect_bool( \ - [&ruleset](const bool value) mutable -> bool { \ - const bool ret = ruleset.RULE == OptionalBool::UNSPECIFIED; \ - ruleset.RULE = value ? OptionalBool::TRUE : OptionalBool::FALSE; \ - return ret; \ - } \ - ) - #define COMMA , +#define MAP_FROM_BOOL(RULE) \ + #RULE, ZERO_OR_ONE, NodeTools::expect_bool([&ruleset](const bool value) mutable -> bool { \ + const bool ret = ruleset.RULE == OptionalBool::UNSPECIFIED; \ + ruleset.RULE = value ? OptionalBool::TRUE : OptionalBool::FALSE; \ + return ret; \ + }) +#define COMMA , static NodeTools::node_callback_t expect_rule_set(NodeTools::callback_t ruleset_callback) { return [ruleset_callback](ast::NodeCPtr root) mutable -> bool { RuleSet ruleset; using enum NodeTools::dictionary_entry_t::expected_count_t; - bool outer_result = NodeTools::expect_dictionary_keys( - DO_FOR_ALL_RULES_SEP(MAP_FROM_BOOL, COMMA) - )(root); + bool outer_result = NodeTools::expect_dictionary_keys(DO_FOR_ALL_RULES_SEP(MAP_FROM_BOOL, COMMA))(root); outer_result &= ruleset_callback(std::move(ruleset)); return outer_result; }; } - #undef COMMA - #undef MAP_FROM_BOOL +#undef COMMA +#undef MAP_FROM_BOOL - #define ADD_IF_NOT_UNSPECIFIED(RULE) \ - if (RULE != OptionalBool::UNSPECIFIED) { \ - result.emplace(make_rule_localisation_key(#RULE), RULE == OptionalBool::TRUE); \ - } +#define ADD_IF_NOT_UNSPECIFIED(RULE) \ + if (RULE != OptionalBool::UNSPECIFIED) { \ + result.emplace(make_rule_localisation_key(#RULE), RULE == OptionalBool::TRUE); \ + } ordered_map get_localisation_keys_and_values() const { ordered_map result {}; - DO_FOR_ALL_RULES_SEP(ADD_IF_NOT_UNSPECIFIED,) + DO_FOR_ALL_RULES_SEP(ADD_IF_NOT_UNSPECIFIED, ) return result; } - #undef ADD_IF_NOT_UNSPECIFIED +#undef ADD_IF_NOT_UNSPECIFIED - //political + // political ApportionmentMethod get_apportionment_method() const { - const RuleDefinition rules[] { - DEF(largest_share), - DEF(dhont), - DEF(sainte_laque) - }; + const RuleDefinition rules[] { DEF(largest_share), DEF(dhont), DEF(sainte_laque) }; return select_with_priority(rules); } UpperHouseComposition get_upper_house_composition() const { - const RuleDefinition rules[] { - DEF(same_as_ruling_party), - DEF(rich_only), - DEF(state_vote), - DEF(population_vote) - }; + const RuleDefinition rules[] { DEF(same_as_ruling_party), DEF(rich_only), DEF(state_vote), DEF(population_vote) }; return select_with_priority(rules); } CulturalVotingRight get_cultural_voting_rights() const { - const RuleDefinition rules[] { - DEF(primary_culture_voting), - DEF(culture_voting), - DEF(all_voting) - }; + const RuleDefinition rules[] { DEF(primary_culture_voting), DEF(culture_voting), DEF(all_voting) }; return select_with_priority(rules); } - #undef DEF +#undef DEF RESOLVE_DEFAULT_FALSE(is_slavery_legal, slavery_allowed) - //economic + // economic RESOLVE_DEFAULT_FALSE(may_expand_infrastructure_domestically, build_railway) RESOLVE_DEFAULT_FALSE(may_build_factory_domestically, build_factory) RESOLVE_DEFAULT_FALSE(may_expand_factory_domestically, expand_factory) @@ -244,13 +209,13 @@ namespace OpenVic { RESOLVE_DEFAULT_FALSE(may_invest_in_expanding_infrastructure_abroad, build_railway_invest) RESOLVE_DEFAULT_FALSE(foreigners_may_invest, allow_foreign_investment) - #undef RESOLVE_DEFAULT_FALSE +#undef RESOLVE_DEFAULT_FALSE - #define ASSIGN_MERGED_RULE(RULE) RULE = merge_rule(RULE, other.RULE, #RULE); +#define ASSIGN_MERGED_RULE(RULE) RULE = merge_rule(RULE, other.RULE, #RULE); void add_ruleset(RuleSet const& other) { - DO_FOR_ALL_RULES_SEP(ASSIGN_MERGED_RULE,) + DO_FOR_ALL_RULES_SEP(ASSIGN_MERGED_RULE, ) } - #undef ASSIGN_MERGED_RULE - #undef DO_FOR_ALL_RULES +#undef ASSIGN_MERGED_RULE +#undef DO_FOR_ALL_RULES }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/Culture.cpp b/src/openvic-simulation/population/Culture.cpp index 3880ee4a0..58cce7a04 100644 --- a/src/openvic-simulation/population/Culture.cpp +++ b/src/openvic-simulation/population/Culture.cpp @@ -1,12 +1,13 @@ #include "Culture.hpp" + #include +#include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/string/Utility.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/Colour.hpp" -#include "openvic-simulation/core/string/Utility.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -16,15 +17,17 @@ GraphicalCultureType::GraphicalCultureType(std::string_view new_identifier) : Ha CultureGroup::CultureGroup( std::string_view new_identifier, std::string_view new_leader, GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas, CountryDefinition const* new_union_country -) : HasIdentifier { new_identifier }, leader { new_leader }, unit_graphical_culture_type { new_unit_graphical_culture_type }, - is_overseas { new_is_overseas }, union_country { new_union_country } {} +) + : HasIdentifier { new_identifier }, leader { new_leader }, unit_graphical_culture_type { new_unit_graphical_culture_type }, + is_overseas { new_is_overseas }, union_country { new_union_country } {} Culture::Culture( std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, name_list_t&& new_first_names, name_list_t&& new_last_names, fixed_point_t new_radicalism, CountryDefinition const* new_primary_country -) : HasIdentifierAndColour { new_identifier, new_colour, false }, group { new_group }, - first_names { std::move(new_first_names) }, last_names { std::move(new_last_names) }, radicalism { new_radicalism }, - primary_country { new_primary_country } {} +) + : HasIdentifierAndColour { new_identifier, new_colour, false }, group { new_group }, + first_names { std::move(new_first_names) }, last_names { std::move(new_last_names) }, radicalism { new_radicalism }, + primary_country { new_primary_country } {} CultureManager::CultureManager() : default_graphical_culture_type { nullptr } {} @@ -33,10 +36,7 @@ bool CultureManager::add_graphical_culture_type(std::string_view identifier) { spdlog::error_s("Invalid graphical culture type identifier - empty!"); return false; } - return graphical_culture_types.emplace_item( - identifier, - identifier - ); + return graphical_culture_types.emplace_item(identifier, identifier); } bool CultureManager::add_culture_group( @@ -65,17 +65,13 @@ bool CultureManager::add_culture_group( } leader = default_leader; spdlog::warn_s( - "In culture group \"{}\" - group leader is undefined, set to default of: \"{}\".", - identifier, default_leader + "In culture group \"{}\" - group leader is undefined, set to default of: \"{}\".", identifier, default_leader ); } - if (!culture_groups.emplace_item( - identifier, - identifier, leader, *graphical_culture_type, is_overseas, union_country - )) { + if (!culture_groups.emplace_item(identifier, identifier, leader, *graphical_culture_type, is_overseas, union_country)) { return false; } - + leader_picture_counts.emplace(leader, general_admiral_picture_count_t { 0, 0 }); return true; } @@ -96,16 +92,15 @@ bool CultureManager::add_culture( // TODO - check radicalism range return cultures.emplace_item( - identifier, - identifier, colour, group, std::move(first_names), std::move(last_names), radicalism, primary_country + identifier, identifier, colour, group, std::move(first_names), std::move(last_names), radicalism, primary_country ); } bool CultureManager::load_graphical_culture_type_file(ast::NodeCPtr root) { - const bool ret = expect_list_reserve_length( - graphical_culture_types, - expect_identifier(std::bind_front(&CultureManager::add_graphical_culture_type, this)) - )(root); + const bool ret = + expect_list_reserve_length(graphical_culture_types, expect_identifier(std::bind_front(&CultureManager::add_graphical_culture_type, this)))( + root + ); lock_graphical_culture_types(); @@ -192,36 +187,28 @@ bool CultureManager::load_culture_file(CountryDefinitionManager const& country_d } size_t total_expected_cultures = 0; - bool ret = expect_dictionary_reserve_length(culture_groups, - [this, &country_definition_manager, &total_expected_cultures]( - std::string_view key, ast::NodeCPtr value - ) -> bool { + bool ret = + expect_dictionary_reserve_length(culture_groups, [this, &country_definition_manager, &total_expected_cultures](std::string_view key, ast::NodeCPtr value) -> bool { return _load_culture_group(country_definition_manager, total_expected_cultures, key, value); - } - )(root); + })(root); lock_culture_groups(); reserve_more_cultures(total_expected_cultures); - ret &= expect_culture_group_dictionary( - [this, &country_definition_manager](CultureGroup const& culture_group, ast::NodeCPtr culture_group_value) -> bool { - return expect_dictionary( - [this, &country_definition_manager, &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.contains(key)) { - return true; - } - return _load_culture(country_definition_manager, culture_group, key, value); - } - )(culture_group_value); - } - )(root); + ret &= expect_culture_group_dictionary([this, &country_definition_manager](CultureGroup const& culture_group, ast::NodeCPtr culture_group_value) -> bool { + return expect_dictionary([this, &country_definition_manager, &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.contains(key)) { + return true; + } + return _load_culture(country_definition_manager, culture_group, key, value); + })(culture_group_value); + })(root); lock_cultures(); return ret; } -memory::string CultureManager::make_leader_picture_name( - std::string_view cultural_type, unit_branch_t branch, leader_count_t count -) { +memory::string +CultureManager::make_leader_picture_name(std::string_view cultural_type, unit_branch_t branch, leader_count_t count) { if (cultural_type.empty()) { spdlog::error_s("Cannot construct leader picture name - empty cultural type!"); return {}; @@ -235,15 +222,11 @@ memory::string CultureManager::make_leader_picture_name( using enum unit_branch_t; switch (branch) { - case LAND: - branch_text = &GENERAL_TEXT; - break; - case NAVAL: - branch_text = &ADMIRAL_TEXT; - break; - default: - spdlog::error_s("Cannot construct leader picture name - invalid branch type: {}", static_cast(branch)); - return {}; + case LAND: branch_text = &GENERAL_TEXT; break; + case NAVAL: branch_text = &ADMIRAL_TEXT; break; + default: + spdlog::error_s("Cannot construct leader picture name - invalid branch type: {}", static_cast(branch)); + return {}; } return append_string_views(cultural_type, *branch_text, std::to_string(count)); @@ -267,22 +250,19 @@ bool CultureManager::find_cultural_leader_pictures(Dataloader const& dataloader) bool ret = true; for (auto [cultural_type, general_and_admiral_count] : mutable_iterator(leader_picture_counts)) { - const auto search = [&dataloader, &cultural_type, &ret]( - unit_branch_t branch, leader_count_t& leader_count - ) -> void { - while ( - leader_count < std::numeric_limits::max() && - !dataloader.lookup_file( - make_leader_picture_path(make_leader_picture_name(cultural_type, branch, leader_count)), false - ).empty() - ) { + const auto search = [&dataloader, &cultural_type, &ret](unit_branch_t branch, leader_count_t& leader_count) -> void { + while (leader_count < std::numeric_limits::max() && + !dataloader + .lookup_file( + make_leader_picture_path(make_leader_picture_name(cultural_type, branch, leader_count)), false + ) + .empty()) { leader_count++; } if (leader_count < 1) { spdlog::error_s( - "No {} pictures found for cultural type \"{}\"!", - get_branched_leader_name(branch), cultural_type + "No {} pictures found for cultural type \"{}\"!", get_branched_leader_name(branch), cultural_type ); ret = false; } @@ -309,24 +289,19 @@ memory::string CultureManager::get_leader_picture_name(std::string_view cultural using enum unit_branch_t; switch (branch) { - case LAND: - desired_picture_count = it->second.first; - break; - case NAVAL: - desired_picture_count = it->second.second; - break; + case LAND: desired_picture_count = it->second.first; break; + case NAVAL: desired_picture_count = it->second.second; break; default: spdlog::error_s( - "Cannot get \"{}\" leader picture name - invalid branch type: {}", - cultural_type, static_cast(branch) + "Cannot get \"{}\" leader picture name - invalid branch type: {}", cultural_type, static_cast(branch) ); return {}; } if (desired_picture_count < 1) { spdlog::error_s( - "Cannot get \"{}\" {} picture name - no pictures of this type were found during game loading!", - cultural_type, get_branched_leader_name(branch) + "Cannot get \"{}\" {} picture name - no pictures of this type were found during game loading!", cultural_type, + get_branched_leader_name(branch) ); return {}; } diff --git a/src/openvic-simulation/population/Culture.hpp b/src/openvic-simulation/population/Culture.hpp index 1b03ab969..0edeb804e 100644 --- a/src/openvic-simulation/population/Culture.hpp +++ b/src/openvic-simulation/population/Culture.hpp @@ -1,8 +1,8 @@ #pragma once +#include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" -#include "openvic-simulation/types/HasIdentifier.hpp" namespace OpenVic { struct CultureManager; @@ -103,9 +103,8 @@ namespace OpenVic { bool load_graphical_culture_type_file(ast::NodeCPtr root); bool load_culture_file(CountryDefinitionManager const& country_definition_manager, ast::NodeCPtr root); - static memory::string make_leader_picture_name( - std::string_view cultural_type, unit_branch_t branch, leader_count_t count - ); + static memory::string + make_leader_picture_name(std::string_view cultural_type, unit_branch_t branch, leader_count_t count); static memory::string make_leader_picture_path(std::string_view leader_picture_name); bool find_cultural_leader_pictures(Dataloader const& dataloader); diff --git a/src/openvic-simulation/population/Pop.cpp b/src/openvic-simulation/population/Pop.cpp index a180c5d47..2cb494f74 100644 --- a/src/openvic-simulation/population/Pop.cpp +++ b/src/openvic-simulation/population/Pop.cpp @@ -1,5 +1,4 @@ #include "Pop.hpp" -#include "PopDeps.hpp" #include // IWYU pragma: keep for lambda #include @@ -8,13 +7,14 @@ #include #include + #include -#include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/Typedefs.hpp" -#include "openvic-simulation/country/CountryParty.hpp" +#include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" +#include "openvic-simulation/country/CountryParty.hpp" #include "openvic-simulation/defines/MilitaryDefines.hpp" #include "openvic-simulation/defines/PopsDefines.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" @@ -23,8 +23,8 @@ #include "openvic-simulation/economy/production/ProductionType.hpp" #include "openvic-simulation/economy/trading/BuyResult.hpp" #include "openvic-simulation/economy/trading/BuyUpToOrder.hpp" -#include "openvic-simulation/economy/trading/MarketSellOrder.hpp" #include "openvic-simulation/economy/trading/MarketInstance.hpp" +#include "openvic-simulation/economy/trading/MarketSellOrder.hpp" #include "openvic-simulation/economy/trading/SellResult.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/modifier/ModifierEffectCache.hpp" @@ -35,43 +35,38 @@ #include "openvic-simulation/population/PopType.hpp" #include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/population/Religion.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/Logger.hpp" +#include "PopDeps.hpp" using namespace OpenVic; PopBase::PopBase( PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size, fixed_point_t new_militancy, fixed_point_t new_consciousness, RebelType const* new_rebel_type -) : type { new_type }, culture { new_culture }, religion { new_religion }, size { new_size }, militancy { new_militancy }, - consciousness { new_consciousness }, rebel_type { new_rebel_type } {} +) + : type { new_type }, culture { new_culture }, religion { new_religion }, size { new_size }, militancy { new_militancy }, + consciousness { new_consciousness }, rebel_type { new_rebel_type } {} Pop::Pop( - ProvinceInstance& new_location, - PopBase const& pop_base, - decltype(supporter_equivalents_by_ideology)::keys_span_type ideology_keys, - PopDeps const& pop_deps, + ProvinceInstance& new_location, PopBase const& pop_base, + decltype(supporter_equivalents_by_ideology)::keys_span_type ideology_keys, PopDeps const& pop_deps, const pop_id_in_province_t new_id_in_province -) : PopBase { pop_base }, - location { new_location }, - id_in_province { new_id_in_province }, - market_instance { pop_deps.market_instance }, - artisanal_producer_optional { - pop_base.get_type().is_artisan - ? std::optional { - pop_deps.artisanal_producer_deps - } - : std::optional {} - }, - supporter_equivalents_by_ideology { ideology_keys } { - reserve_needs_fulfilled_goods(); - } +) + : PopBase { pop_base }, location { new_location }, id_in_province { new_id_in_province }, + market_instance { pop_deps.market_instance }, + artisanal_producer_optional { pop_base.get_type().is_artisan + ? std::optional { pop_deps.artisanal_producer_deps } + : std::optional {} }, + supporter_equivalents_by_ideology { ideology_keys } { + reserve_needs_fulfilled_goods(); +} fixed_point_t Pop::get_unemployment_fraction() const { if (!get_type().can_be_unemployed) { @@ -97,13 +92,15 @@ void Pop::setup_pop_test_values(IssueManager const& issue_manager) { num_grown + num_promoted + num_demoted + num_migrated_internal + num_migrated_external + num_migrated_colonial; /* Generates a number between 0 and max (inclusive) and sets map[&key] to it if it's at least min. */ - auto test_weight_indexed = [](IndexedFlatMap& map, U const& key, int32_t min, int32_t max) -> void { + auto test_weight_indexed = + [](IndexedFlatMap& map, U const& key, int32_t min, int32_t max) -> void { const int32_t value = rand() % (max + 1); if (value >= min) { map.set(key, value); } }; - auto test_weight_ordered = [](ordered_map& map, U const& key, int32_t min, int32_t max) -> void { + auto test_weight_ordered = + [](ordered_map& map, U const& key, int32_t min, int32_t max) -> void { if constexpr (std::is_convertible_v || std::is_convertible_v) { const int32_t value = rand() % (max + 1); if (value >= min) { @@ -115,7 +112,10 @@ void Pop::setup_pop_test_values(IssueManager const& issue_manager) { } } else { // Optional: Handle the case where the conversion is not possible, perhaps with a static_assert. - static_assert(std::is_convertible_v || std::is_convertible_v, "Type U is not convertible to T const*."); + static_assert( + std::is_convertible_v || std::is_convertible_v, + "Type U is not convertible to T const*." + ); } }; @@ -181,11 +181,9 @@ void Pop::update_location_based_attributes() { } CountryDefinition const& country_definition = owner->country_definition; - auto view = country_definition.get_parties() | std::views::transform( - [](CountryParty const& key) { - return std::make_pair(&key, fixed_point_t::_0); - } - ); + auto view = country_definition.get_parties() | std::views::transform([](CountryParty const& key) { + return std::make_pair(&key, fixed_point_t::_0); + }); vote_equivalents_by_party.insert(view.begin(), view.end()); // TODO - calculate vote distribution } @@ -213,9 +211,7 @@ fixed_point_t Pop::get_vote_equivalents_by_party(CountryParty const& party) cons } void Pop::update_gamestate( - MilitaryDefines const& military_defines, - CountryInstance const* owner, - const fixed_point_t pop_size_per_regiment_multiplier + MilitaryDefines const& military_defines, CountryInstance const* owner, const fixed_point_t pop_size_per_regiment_multiplier ) { using enum culture_status_t; @@ -242,10 +238,8 @@ void Pop::update_gamestate( consciousness = std::clamp(consciousness, MIN_CONSCIOUSNESS, MAX_CONSCIOUSNESS); literacy = std::clamp(literacy, MIN_LITERACY, MAX_LITERACY); - if ( - size < military_defines.get_min_pop_size_for_regiment() || owner == nullptr || - !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status) - ) { + if (size < military_defines.get_min_pop_size_for_regiment() || owner == nullptr || + !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status)) { max_supported_regiments = 0; } else { max_supported_regiments = ( @@ -256,30 +250,29 @@ void Pop::update_gamestate( memory::string Pop::get_pop_context_text() const { return memory::fmt::format( - "location: {} type: {} culture: {} religion: {} size: {}", - location, type, culture, religion, size + "location: {} type: {} culture: {} religion: {} size: {}", location, type, culture, religion, size ); } void Pop::reserve_needs_fulfilled_goods() { PopType const& pop_type = type.get(); - #define RESERVE_NEEDS(need_category) \ - need_category##_needs_fulfilled_goods.reserve(pop_type.get_##need_category##_needs().size()); +#define RESERVE_NEEDS(need_category) \ + need_category##_needs_fulfilled_goods.reserve(pop_type.get_##need_category##_needs().size()); OV_DO_FOR_ALL_NEED_CATEGORIES(RESERVE_NEEDS) - #undef RESERVE_NEEDS +#undef RESERVE_NEEDS } void Pop::fill_needs_fulfilled_goods_with_false() { PopType const& pop_type = type.get(); - #define FILL_WITH_FALSE(need_category) \ - need_category##_needs_fulfilled_goods.clear(); \ - for (auto [good, base_demand] : pop_type.get_##need_category##_needs()) { \ - need_category##_needs_fulfilled_goods.emplace(good, false); \ - } +#define FILL_WITH_FALSE(need_category) \ + need_category##_needs_fulfilled_goods.clear(); \ + for (auto [good, base_demand] : pop_type.get_##need_category##_needs()) { \ + need_category##_needs_fulfilled_goods.emplace(good, false); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(FILL_WITH_FALSE) - #undef FILL_WITH_FALSE +#undef FILL_WITH_FALSE } void Pop::pay_income_tax(fixed_point_t& income) { @@ -287,7 +280,8 @@ void Pop::pay_income_tax(fixed_point_t& income) { if (tax_collector_nullable == nullptr) { return; } - const fixed_point_t effective_tax_rate = tax_collector_nullable->get_effective_tax_rate_by_strata(get_type().strata).get_untracked(); + const fixed_point_t effective_tax_rate = + tax_collector_nullable->get_effective_tax_rate_by_strata(get_type().strata).get_untracked(); const fixed_point_t tax = effective_tax_rate * income; tax_collector_nullable->report_pop_income_tax(type, income, tax); income -= tax; @@ -310,10 +304,7 @@ void Pop::add_artisanal_revenue(const fixed_point_t revenue) { if (OV_unlikely(!artisanal_producer_optional.has_value())) { income = revenue; } else { - income = std::max( - fixed_point_t::_0, - revenue - artisanal_producer_optional->get_costs_of_production() - ); + income = std::max(fixed_point_t::_0, revenue - artisanal_producer_optional->get_costs_of_production()); } pay_income_tax(income); @@ -329,7 +320,7 @@ template void Pop::add_artisanal_revenue(const fixed_point_t revenue); template void Pop::add_artisanal_revenue(const fixed_point_t revenue); #define DEFINE_ADD_INCOME_FUNCTIONS(name) \ - void Pop::add_##name(fixed_point_t amount){ \ + void Pop::add_##name(fixed_point_t amount) { \ if (OV_unlikely(amount == 0)) { \ spdlog::warn_s("Adding " #name " of 0 to pop. Context{}", get_pop_context_text()); \ return; \ @@ -348,7 +339,7 @@ OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DEFINE_ADD_INCOME_FUNCTIONS) #undef DEFINE_ADD_INCOME_FUNCTIONS #define DEFINE_ADD_EXPENSE_FUNCTIONS(name) \ - void Pop::add_##name(const fixed_point_t amount){ \ + void Pop::add_##name(const fixed_point_t amount) { \ if (OV_unlikely(amount == 0)) { \ spdlog::warn_s("Adding " #name " of 0 to pop. Context:{}", get_pop_context_text()); \ return; \ @@ -357,15 +348,15 @@ OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DEFINE_ADD_INCOME_FUNCTIONS) const fixed_point_t expenses_copy = expenses += amount; \ if (OV_unlikely(expenses_copy < 0)) { \ spdlog::error_s( \ - "Total expenses became negative ({}) after adding " #name " of {} to pop. Context:{}", \ - expenses_copy, amount, get_pop_context_text() \ + "Total expenses became negative ({}) after adding " #name " of {} to pop. Context:{}", expenses_copy, amount, \ + get_pop_context_text() \ ); \ } \ const fixed_point_t cash_copy = cash -= amount; \ if (OV_unlikely(cash_copy < 0)) { \ spdlog::error_s( \ - "Total cash became negative ({}) after adding " #name " of {} to pop. Context:{}", \ - cash_copy, amount, get_pop_context_text() \ + "Total cash became negative ({}) after adding " #name " of {} to pop. Context:{}", cash_copy, amount, \ + get_pop_context_text() \ ); \ } \ } @@ -374,8 +365,8 @@ OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DEFINE_ADD_EXPENSE_FUNCTIONS) #undef DEFINE_ADD_EXPENSE_FUNCTIONS void Pop::add_import_subsidies(const fixed_point_t amount) { - //It's not income, otherwise we'd pay income tax. - //It's not a negative expense, otherwise total expense might go negative. + // It's not income, otherwise we'd pay income tax. + // It's not a negative expense, otherwise total expense might go negative. cash += amount; } @@ -391,11 +382,8 @@ OV_DO_FOR_ALL_NEED_CATEGORIES(DEFINE_NEEDS_FULFILLED) #undef DEFINE_NEEDS_FULFILLED void Pop::allocate_for_needs( - fixed_point_map_t const& scaled_needs, - forwardable_span money_to_spend_per_good, - memory::vector& reusable_vector, - fixed_point_t& weights_sum, - fixed_point_t& cash_left_to_spend + fixed_point_map_t const& scaled_needs, forwardable_span money_to_spend_per_good, + memory::vector& reusable_vector, fixed_point_t& weights_sum, fixed_point_t& cash_left_to_spend ) { if (weights_sum <= 0) { return; @@ -413,20 +401,14 @@ void Pop::allocate_for_needs( GoodDefinition const& good_definition = *good_definition_ptr; const fixed_point_t max_quantity_to_buy = it.value(); const ptrdiff_t i = it - scaled_needs.begin(); - const fixed_point_t max_money_to_spend = market_instance.get_max_money_to_allocate_to_buy_quantity( - good_definition, - max_quantity_to_buy - ); + const fixed_point_t max_money_to_spend = + market_instance.get_max_money_to_allocate_to_buy_quantity(good_definition, max_quantity_to_buy); if (money_to_spend_per_good_draft[i] >= max_money_to_spend) { continue; } fixed_point_t weight = market_instance.get_good_instance(good_definition).get_price_inverse(); - fixed_point_t cash_available_for_good = fixed_point_t::mul_div( - cash_left_to_spend_draft, - weight, - weights_sum - ); + fixed_point_t cash_available_for_good = fixed_point_t::mul_div(cash_left_to_spend_draft, weight, weights_sum); if (cash_available_for_good >= max_money_to_spend) { cash_left_to_spend_draft -= max_money_to_spend; @@ -436,7 +418,8 @@ void Pop::allocate_for_needs( break; } - const fixed_point_t max_possible_quantity_bought = cash_available_for_good / market_instance.get_min_next_price(good_definition); + const fixed_point_t max_possible_quantity_bought = + cash_available_for_good / market_instance.get_min_next_price(good_definition); if (max_possible_quantity_bought < fixed_point_t::epsilon) { money_to_spend_per_good_draft[i] = 0; } else { @@ -458,33 +441,20 @@ void Pop::allocate_for_needs( } void Pop::pop_tick( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, + PopValuesFromProvince const& shared_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ) { - pop_tick_without_cleanup( - shared_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + pop_tick_without_cleanup(shared_values, random_number_generator, reusable_goods_mask, reusable_vectors); for (auto& reusable_vector : reusable_vectors) { reusable_vector.clear(); } } void Pop::pop_tick_without_cleanup( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, + PopValuesFromProvince const& shared_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ) { forwardable_span good_keys = reusable_goods_mask.get_keys(); memory::vector& reusable_vector_0 = reusable_vectors[0]; @@ -495,32 +465,23 @@ void Pop::pop_tick_without_cleanup( money_to_spend_per_good.resize(good_keys.size(), 0); cash_allocated_for_artisanal_spending = 0; fill_needs_fulfilled_goods_with_false(); - + fixed_point_map_t goods_to_sell {}; if (artisanal_producer_optional.has_value()) { - //execute artisan_tick before needs + // execute artisan_tick before needs ArtisanalProducer& artisanal_producer = artisanal_producer_optional.value(); artisanal_producer.artisan_tick( - market_instance, - *this, - shared_values, - random_number_generator, - reusable_goods_mask, - max_quantity_to_buy_per_good, - money_to_spend_per_good, - reusable_vector_0, - reusable_vector_1, - goods_to_sell + market_instance, *this, shared_values, random_number_generator, reusable_goods_mask, max_quantity_to_buy_per_good, + money_to_spend_per_good, reusable_vector_0, reusable_vector_1, goods_to_sell ); } - //after artisan_tick as it uses income & expenses - #define SET_TO_ZERO(name) \ - name = 0; +// after artisan_tick as it uses income & expenses +#define SET_TO_ZERO(name) name = 0; OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(SET_TO_ZERO) OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(SET_TO_ZERO) - #undef SET_TO_ZERO +#undef SET_TO_ZERO income = expenses = 0; CountryInstance* const country_to_report_economy_nullable = get_location().get_country_to_report_economy(); @@ -528,80 +489,79 @@ void Pop::pop_tick_without_cleanup( if (country_to_report_economy_nullable != nullptr) { country_to_report_economy_nullable->request_salaries_and_welfare_and_import_subsidies(*this); } - - //unemployment subsidies are based on yesterdays unemployment + + // unemployment subsidies are based on yesterdays unemployment employed = 0; - //import subsidies are based on yesterday + // import subsidies are based on yesterday yesterdays_import_value = 0; PopType const& pop_type = type; PopStrataValuesFromProvince const& shared_strata_values = shared_values.get_effects_by_strata(pop_type.strata); PopsDefines const& defines = shared_values.defines; - const fixed_point_t base_needs_scalar = ( - fixed_point_t::_1 + 2 * consciousness / defines.get_pdef_base_con() - ) * size; - - #define FILL_NEEDS(need_category) \ - need_category##_needs.clear(); \ - const fixed_point_t need_category##_needs_scalar = base_needs_scalar * shared_strata_values.get_shared_##need_category##_needs_scalar(); \ - fixed_point_t need_category##_needs_price_inverse_sum = 0; \ - if (OV_likely(need_category##_needs_scalar > 0)) { \ - need_category##_needs_acquired_quantity = need_category##_needs_desired_quantity = 0; \ - for (auto [good_definition_ptr, quantity] : pop_type.get_##need_category##_needs()) { \ - GoodDefinition const& good_definition = *good_definition_ptr; \ - if (!market_instance.get_is_available(good_definition)) { \ - continue; \ - } \ - fixed_point_t max_quantity_to_buy = quantity * need_category##_needs_scalar / size_denominator; \ - if (max_quantity_to_buy == 0) { \ - continue; \ - } \ + const fixed_point_t base_needs_scalar = (fixed_point_t::_1 + 2 * consciousness / defines.get_pdef_base_con()) * size; + +#define FILL_NEEDS(need_category) \ + need_category##_needs.clear(); \ + const fixed_point_t need_category##_needs_scalar = \ + base_needs_scalar * shared_strata_values.get_shared_##need_category##_needs_scalar(); \ + fixed_point_t need_category##_needs_price_inverse_sum = 0; \ + if (OV_likely(need_category##_needs_scalar > 0)) { \ + need_category##_needs_acquired_quantity = need_category##_needs_desired_quantity = 0; \ + for (auto [good_definition_ptr, quantity] : pop_type.get_##need_category##_needs()) { \ + GoodDefinition const& good_definition = *good_definition_ptr; \ + if (!market_instance.get_is_available(good_definition)) { \ + continue; \ + } \ + fixed_point_t max_quantity_to_buy = quantity * need_category##_needs_scalar / size_denominator; \ + if (max_quantity_to_buy == 0) { \ + continue; \ + } \ + if (country_to_report_economy_nullable != nullptr) { \ + country_to_report_economy_nullable->report_pop_need_demand(pop_type, good_definition, max_quantity_to_buy); \ + } \ + need_category##_needs_desired_quantity += max_quantity_to_buy; \ + auto goods_to_sell_iterator = goods_to_sell.find(good_definition_ptr); \ + if (goods_to_sell_iterator != goods_to_sell.end() && goods_to_sell_iterator.value() > 0) { \ + const fixed_point_t own_produce_consumed = std::min(goods_to_sell_iterator.value(), max_quantity_to_buy); \ + goods_to_sell_iterator.value() -= own_produce_consumed; \ + max_quantity_to_buy -= own_produce_consumed; \ + need_category##_needs_acquired_quantity += own_produce_consumed; \ if (country_to_report_economy_nullable != nullptr) { \ - country_to_report_economy_nullable->report_pop_need_demand(pop_type, good_definition, max_quantity_to_buy); \ - } \ - need_category##_needs_desired_quantity += max_quantity_to_buy; \ - auto goods_to_sell_iterator = goods_to_sell.find(good_definition_ptr); \ - if (goods_to_sell_iterator != goods_to_sell.end() && goods_to_sell_iterator.value() > 0) { \ - const fixed_point_t own_produce_consumed = std::min(goods_to_sell_iterator.value(), max_quantity_to_buy); \ - goods_to_sell_iterator.value() -= own_produce_consumed; \ - max_quantity_to_buy -= own_produce_consumed; \ - need_category##_needs_acquired_quantity += own_produce_consumed; \ - if (country_to_report_economy_nullable != nullptr) { \ - country_to_report_economy_nullable->report_pop_need_consumption(pop_type, good_definition, own_produce_consumed); \ - } \ - } \ - if (OV_likely(max_quantity_to_buy > 0)) { \ - need_category##_needs_price_inverse_sum += market_instance.get_good_instance(good_definition).get_price_inverse(); \ - need_category##_needs[good_definition_ptr] += max_quantity_to_buy; \ - max_quantity_to_buy_per_good[type_safe::get(good_definition.index)] += max_quantity_to_buy; \ + country_to_report_economy_nullable->report_pop_need_consumption( \ + pop_type, good_definition, own_produce_consumed \ + ); \ } \ } \ - } + if (OV_likely(max_quantity_to_buy > 0)) { \ + need_category##_needs_price_inverse_sum += \ + market_instance.get_good_instance(good_definition).get_price_inverse(); \ + need_category##_needs[good_definition_ptr] += max_quantity_to_buy; \ + max_quantity_to_buy_per_good[type_safe::get(good_definition.index)] += max_quantity_to_buy; \ + } \ + } \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(FILL_NEEDS) - #undef FILL_NEEDS - - //It's safe to use cash as this happens before cash is updated via spending - fixed_point_t cash_left_to_spend = cash.get_copy_of_value() / shared_values.get_max_cost_multiplier() - - cash_allocated_for_artisanal_spending; - - #define ALLOCATE_FOR_NEEDS(need_category) \ - if (cash_left_to_spend > 0) { \ - allocate_for_needs( \ - need_category##_needs, \ - money_to_spend_per_good, \ - reusable_vector_0, \ - need_category##_needs_price_inverse_sum, \ - cash_left_to_spend \ - ); \ - } +#undef FILL_NEEDS + + // It's safe to use cash as this happens before cash is updated via spending + fixed_point_t cash_left_to_spend = + cash.get_copy_of_value() / shared_values.get_max_cost_multiplier() - cash_allocated_for_artisanal_spending; + +#define ALLOCATE_FOR_NEEDS(need_category) \ + if (cash_left_to_spend > 0) { \ + allocate_for_needs( \ + need_category##_needs, money_to_spend_per_good, reusable_vector_0, need_category##_needs_price_inverse_sum, \ + cash_left_to_spend \ + ); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(ALLOCATE_FOR_NEEDS) - #undef ALLOCATE_FOR_NEEDS +#undef ALLOCATE_FOR_NEEDS const std::optional country_index_optional = country_to_report_economy_nullable == nullptr ? std::nullopt - : std::optional{country_to_report_economy_nullable->index}; + : std::optional { country_to_report_economy_nullable->index }; for (auto it = good_keys.begin(); it < good_keys.end(); it++) { const ptrdiff_t i = it - good_keys.begin(); @@ -610,18 +570,13 @@ void Pop::pop_tick_without_cleanup( if (max_quantity_to_buy <= 0) { continue; } - + GoodDefinition const& good_definition = *it; const fixed_point_t money_to_spend = money_to_spend_per_good[i]; - market_instance.place_buy_up_to_order({ - good_definition, - country_index_optional, - max_quantity_to_buy, - money_to_spend, - this, - after_buy - }); + market_instance.place_buy_up_to_order( + { good_definition, country_index_optional, max_quantity_to_buy, money_to_spend, this, after_buy } + ); } for (const auto [good_ptr, quantity_to_sell] : goods_to_sell) { @@ -634,14 +589,7 @@ void Pop::pop_tick_without_cleanup( } market_instance.place_market_sell_order( - { - good, - country_index_optional, - quantity_to_sell, - this, - after_sell - }, - reusable_vectors[4] + { good, country_index_optional, quantity_to_sell, this, after_sell }, reusable_vectors[4] ); } } @@ -653,7 +601,7 @@ void Pop::after_buy(void* actor, BuyResult const& buy_result) { return; } - Pop& pop = *static_cast(actor); + Pop& pop = *static_cast(actor); CountryInstance* const country_to_report_economy_nullable = pop.get_location().get_country_to_report_economy(); fixed_point_t money_spent = buy_result.money_spent_total; @@ -669,58 +617,51 @@ void Pop::after_buy(void* actor, BuyResult const& buy_result) { if (quantity_left_to_consume <= 0) { return; } - const fixed_point_t quantity_added_to_stockpile = pop.artisanal_producer_optional.value().add_to_stockpile( - good_definition, - quantity_left_to_consume - ); + const fixed_point_t quantity_added_to_stockpile = + pop.artisanal_producer_optional.value().add_to_stockpile(good_definition, quantity_left_to_consume); if (quantity_added_to_stockpile > 0) { quantity_left_to_consume -= quantity_added_to_stockpile; - const fixed_point_t expense = fixed_point_t::mul_div( - money_spent, - quantity_added_to_stockpile, - quantity_bought - ); + const fixed_point_t expense = fixed_point_t::mul_div(money_spent, quantity_added_to_stockpile, quantity_bought); pop.add_artisan_inputs_expense(expense); } } CountryInstance* get_country_to_report_economy_nullable = pop.get_location().get_country_to_report_economy(); - #define CONSUME_NEED(need_category) \ - if (quantity_left_to_consume <= 0) { \ - return; \ +#define CONSUME_NEED(need_category) \ + if (quantity_left_to_consume <= 0) { \ + return; \ + } \ + const fixed_point_map_t::const_iterator need_category##it = \ + pop.need_category##_needs.find(&good_definition); \ + if (need_category##it != pop.need_category##_needs.end()) { \ + const fixed_point_t desired_quantity = need_category##it->second; \ + fixed_point_t consumed_quantity; \ + if (quantity_left_to_consume >= desired_quantity) { \ + consumed_quantity = desired_quantity; \ + pop.need_category##_needs_fulfilled_goods.at(&good_definition) = true; \ + } else { \ + consumed_quantity = quantity_left_to_consume; \ } \ - const fixed_point_map_t::const_iterator need_category##it = pop.need_category##_needs.find(&good_definition); \ - if (need_category##it != pop.need_category##_needs.end()) { \ - const fixed_point_t desired_quantity = need_category##it->second; \ - fixed_point_t consumed_quantity; \ - if (quantity_left_to_consume >= desired_quantity) { \ - consumed_quantity = desired_quantity; \ - pop.need_category##_needs_fulfilled_goods.at(&good_definition) = true; \ - } else { \ - consumed_quantity = quantity_left_to_consume; \ - } \ - pop.need_category##_needs_acquired_quantity += consumed_quantity; \ - quantity_left_to_consume -= consumed_quantity; \ - if (get_country_to_report_economy_nullable != nullptr) { \ - get_country_to_report_economy_nullable->report_pop_need_consumption(pop.type, good_definition, consumed_quantity); \ - } \ - const fixed_point_t expense = fixed_point_t::mul_div( \ - money_spent, \ - consumed_quantity, \ - quantity_bought \ - ); \ - pop.add_##need_category##_needs_expense(expense); \ - } + pop.need_category##_needs_acquired_quantity += consumed_quantity; \ + quantity_left_to_consume -= consumed_quantity; \ + if (get_country_to_report_economy_nullable != nullptr) { \ + get_country_to_report_economy_nullable->report_pop_need_consumption(pop.type, good_definition, consumed_quantity); \ + } \ + const fixed_point_t expense = fixed_point_t::mul_div(money_spent, consumed_quantity, quantity_bought); \ + pop.add_##need_category##_needs_expense(expense); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(CONSUME_NEED) - #undef CONSUME_NEED +#undef CONSUME_NEED } void Pop::after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { Pop& pop = *static_cast(actor); if (sell_result.money_gained > 0) { - OV_ERR_FAIL_COND_MSG(!pop.artisanal_producer_optional.has_value(), "Pop is selling artisanal goods but has no artisan."); + OV_ERR_FAIL_COND_MSG( + !pop.artisanal_producer_optional.has_value(), "Pop is selling artisanal goods but has no artisan." + ); ArtisanalProducer& artisan = pop.artisanal_producer_optional.value(); if (artisan.get_last_produced_good() != nullptr && *artisan.get_last_produced_good() == sell_result.good_definition) { pop.add_artisanal_revenue(sell_result.money_gained); @@ -737,22 +678,13 @@ void Pop::allocate_cash_for_artisanal_spending(fixed_point_t money_to_spend) { void Pop::hire(pop_size_t count) { if (OV_unlikely(count <= 0)) { - spdlog::warn_s( - "Tried employing non-positive number of pops. {} Context{}", - count, get_pop_context_text() - ); + spdlog::warn_s("Tried employing non-positive number of pops. {} Context{}", count, get_pop_context_text()); } employed += count; if (OV_unlikely(employed > size)) { - spdlog::error_s( - "Employed count became greater than pop size. {} Context{}", - employed, get_pop_context_text() - ); + spdlog::error_s("Employed count became greater than pop size. {} Context{}", employed, get_pop_context_text()); } else if (OV_unlikely(employed < 0)) { - spdlog::error_s( - "Employed count became negative. {} Context{}", - employed, get_pop_context_text() - ); + spdlog::error_s("Employed count became negative. {} Context{}", employed, get_pop_context_text()); } } @@ -772,4 +704,4 @@ bool Pop::try_recruit_understrength() { ++regiment_count; return true; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/Pop.hpp b/src/openvic-simulation/population/Pop.hpp index efb10130c..df5bf2f23 100644 --- a/src/openvic-simulation/population/Pop.hpp +++ b/src/openvic-simulation/population/Pop.hpp @@ -3,20 +3,20 @@ #include #include +#include + #include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/economy/production/ArtisanalProducer.hpp" #include "openvic-simulation/population/PopIdInProvince.hpp" #include "openvic-simulation/population/PopNeedsMacro.hpp" #include "openvic-simulation/population/PopSize.hpp" +#include "openvic-simulation/types/IndexedFlatMap.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/fixed_point/Atomic.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/types/IndexedFlatMap.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include - namespace OpenVic { struct BaseIssue; struct BuyResult; @@ -51,37 +51,36 @@ namespace OpenVic { PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size, fixed_point_t new_militancy, fixed_point_t new_consciousness, RebelType const* new_rebel_type ); + public: Culture const& culture; Religion const& religion; }; - #define OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(F) \ - F(rgo_owner_income) \ - F(rgo_worker_income) \ - F(factory_worker_income) \ - F(factory_owner_income) \ - F(unemployment_subsidies) \ - F(pensions) \ - F(government_salary_administration) \ - F(government_salary_education) \ - F(government_salary_military) \ - F(event_and_decision_income) \ - F(loan_interest_payments) - - #define OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(F) \ - F(life_needs_expense) \ - F(everyday_needs_expense) \ - F(luxury_needs_expense) \ - F(artisan_inputs_expense) +#define OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(F) \ + F(rgo_owner_income) \ + F(rgo_worker_income) \ + F(factory_worker_income) \ + F(factory_owner_income) \ + F(unemployment_subsidies) \ + F(pensions) \ + F(government_salary_administration) \ + F(government_salary_education) \ + F(government_salary_military) \ + F(event_and_decision_income) \ + F(loan_interest_payments) + +#define OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(F) \ + F(life_needs_expense) \ + F(everyday_needs_expense) \ + F(luxury_needs_expense) \ + F(artisan_inputs_expense) /* REQUIREMENTS: * POP-18, POP-19, POP-20, POP-21, POP-34, POP-35, POP-36, POP-37 */ struct Pop : PopBase { - enum struct culture_status_t : uint8_t { - UNACCEPTED, ACCEPTED, PRIMARY - }; + enum struct culture_status_t : uint8_t { UNACCEPTED, ACCEPTED, PRIMARY }; static constexpr bool is_culture_status_allowed(regiment_allowed_cultures_t allowed, culture_status_t status) { return static_cast(allowed) <= static_cast(status); @@ -106,7 +105,6 @@ namespace OpenVic { } private: - /* Last day's size change by source. */ pop_size_t PROPERTY(total_change, 0); pop_size_t PROPERTY(num_grown, 0); @@ -127,7 +125,7 @@ namespace OpenVic { OV_IFLATMAP_PROPERTY(Ideology, fixed_point_t, supporter_equivalents_by_ideology); fixed_point_map_t PROPERTY(supporter_equivalents_by_issue); fixed_point_map_t PROPERTY(vote_equivalents_by_party); - + public: // The values returned by these functions are scaled by pop size, so they must be divided by pop size to get // the support as a proportion of 1.0 @@ -141,31 +139,36 @@ namespace OpenVic { return size - employed; } fixed_point_t get_unemployment_fraction() const; + private: fixed_point_t PROPERTY(income); fixed_point_t PROPERTY(savings); moveable_atomic_fixed_point_t PROPERTY(cash); - moveable_atomic_fixed_point_t PROPERTY(expenses); //positive value means POP paid for goods. This is displayed * -1 in UI. + moveable_atomic_fixed_point_t + PROPERTY(expenses); // positive value means POP paid for goods. This is displayed * -1 in UI. moveable_atomic_fixed_point_t PROPERTY(yesterdays_import_value); - #define NEED_MEMBERS(need_category) \ - moveable_atomic_fixed_point_t need_category##_needs_acquired_quantity, need_category##_needs_desired_quantity; \ - public: \ - fixed_point_t get_##need_category##_needs_fulfilled() const; \ - private: \ - fixed_point_map_t PROPERTY(need_category##_needs); /* TODO pool? (if recalculating in UI is acceptable) */ \ - ordered_map PROPERTY(need_category##_needs_fulfilled_goods); +#define NEED_MEMBERS(need_category) \ + moveable_atomic_fixed_point_t need_category##_needs_acquired_quantity, need_category##_needs_desired_quantity; \ +\ +public: \ + fixed_point_t get_##need_category##_needs_fulfilled() const; \ +\ +private: \ + fixed_point_map_t PROPERTY( \ + need_category##_needs \ + ); /* TODO pool? (if recalculating in UI is acceptable) */ \ + ordered_map PROPERTY(need_category##_needs_fulfilled_goods); OV_DO_FOR_ALL_NEED_CATEGORIES(NEED_MEMBERS) - #undef NEED_MEMBERS +#undef NEED_MEMBERS fixed_point_t PROPERTY(artisanal_revenue); - #define DECLARE_POP_MONEY_STORES(money_type) \ - fixed_point_t PROPERTY(money_type); +#define DECLARE_POP_MONEY_STORES(money_type) fixed_point_t PROPERTY(money_type); OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DECLARE_POP_MONEY_STORES); OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DECLARE_POP_MONEY_STORES); - #undef DECLARE_POP_MONEY_STORES +#undef DECLARE_POP_MONEY_STORES std::size_t PROPERTY(regiment_count, 0); std::size_t PROPERTY(max_supported_regiments, 0); @@ -175,19 +178,13 @@ namespace OpenVic { void fill_needs_fulfilled_goods_with_false(); void allocate_for_needs( fixed_point_map_t const& scaled_needs, - forwardable_span money_to_spend_per_good, - memory::vector& reusable_vector, - fixed_point_t& price_inverse_sum, - fixed_point_t& cash_left_to_spend + forwardable_span money_to_spend_per_good, memory::vector& reusable_vector, + fixed_point_t& price_inverse_sum, fixed_point_t& cash_left_to_spend ); void pop_tick_without_cleanup( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, + PopValuesFromProvince const& shared_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ); void pay_income_tax(fixed_point_t& income); @@ -195,17 +192,13 @@ namespace OpenVic { void add_artisanal_revenue(const fixed_point_t revenue); static void after_buy(void* actor, BuyResult const& buy_result); - //matching GoodMarketSellOrder::callback_t + // matching GoodMarketSellOrder::callback_t static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector); public: - Pop( - ProvinceInstance& new_location, - PopBase const& pop_base, - decltype(supporter_equivalents_by_ideology)::keys_span_type ideology_keys, - PopDeps const& pop_deps, - const pop_id_in_province_t new_id_in_province - ); + Pop(ProvinceInstance& new_location, PopBase const& pop_base, + decltype(supporter_equivalents_by_ideology)::keys_span_type ideology_keys, PopDeps const& pop_deps, + const pop_id_in_province_t new_id_in_province); Pop(Pop const&) = delete; Pop(Pop&&) = default; Pop& operator=(Pop const&) = delete; @@ -216,32 +209,26 @@ namespace OpenVic { void update_location_based_attributes(); void update_gamestate( - MilitaryDefines const& military_defines, - CountryInstance const* owner, + MilitaryDefines const& military_defines, CountryInstance const* owner, const fixed_point_t pop_size_per_regiment_multiplier ); - #define DECLARE_POP_MONEY_STORE_FUNCTIONS(name) \ - void add_##name(fixed_point_t amount); +#define DECLARE_POP_MONEY_STORE_FUNCTIONS(name) void add_##name(fixed_point_t amount); OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DECLARE_POP_MONEY_STORE_FUNCTIONS) OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DECLARE_POP_MONEY_STORE_FUNCTIONS) DECLARE_POP_MONEY_STORE_FUNCTIONS(import_subsidies) - #undef DECLARE_POP_MONEY_STORE_FUNCTIONS +#undef DECLARE_POP_MONEY_STORE_FUNCTIONS void pop_tick( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, + PopValuesFromProvince const& shared_values, RandomU32& random_number_generator, IndexedFlatMap& reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ); void allocate_cash_for_artisanal_spending(const fixed_point_t money_to_spend); void hire(pop_size_t count); - //recruit or conscript + // recruit or conscript bool try_recruit(); bool try_recruit_understrength(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopDeps.hpp b/src/openvic-simulation/population/PopDeps.hpp index 8d7707bf6..2de3d1be2 100644 --- a/src/openvic-simulation/population/PopDeps.hpp +++ b/src/openvic-simulation/population/PopDeps.hpp @@ -8,4 +8,4 @@ namespace OpenVic { ArtisanalProducerDeps const& artisanal_producer_deps; MarketInstance& market_instance; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopIdInProvince.hpp b/src/openvic-simulation/population/PopIdInProvince.hpp index c9b02ed0d..5dd48959d 100644 --- a/src/openvic-simulation/population/PopIdInProvince.hpp +++ b/src/openvic-simulation/population/PopIdInProvince.hpp @@ -9,17 +9,21 @@ namespace OpenVic { struct pop_id_in_province_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic { + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic { using strong_typedef::strong_typedef; - constexpr bool is_null() const { return type_safe::get(*this) == 0; } - constexpr bool operator!() const { return is_null(); } + constexpr bool is_null() const { + return type_safe::get(*this) == 0; + } + constexpr bool operator!() const { + return is_null(); + } }; } namespace std { - template <> + template<> struct hash : type_safe::hashable {}; } template<> @@ -27,4 +31,4 @@ struct fmt::formatter : fmt::formatter::format(type_safe::get(value), ctx); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/population/PopManager.cpp b/src/openvic-simulation/population/PopManager.cpp index 9e9fb80b5..71cc1809a 100644 --- a/src/openvic-simulation/population/PopManager.cpp +++ b/src/openvic-simulation/population/PopManager.cpp @@ -2,31 +2,31 @@ #include +#include + +#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" +#include "openvic-simulation/military/UnitType.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/politics/IssueManager.hpp" #include "openvic-simulation/politics/Rebel.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/military/UnitType.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" -#include "openvic-simulation/utility/Logger.hpp" #include "openvic-simulation/population/PopSize.hpp" - -#include +#include "openvic-simulation/utility/Logger.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; PopManager::PopManager() - : slave_sprite { 0 }, administrative_sprite { 0 }, - promotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - demotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - migration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - colonialmigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - emigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - assimilation_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - conversion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE } {} + : slave_sprite { 0 }, administrative_sprite { 0 }, + promotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + demotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + migration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + colonialmigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + emigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + assimilation_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + conversion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE } {} bool PopManager::setup_stratas() { if (stratas_are_locked()) { @@ -34,9 +34,7 @@ bool PopManager::setup_stratas() { return false; } - static constexpr std::array STRATA_IDENTIFIERS { - "poor", "middle", "rich" - }; + static constexpr std::array STRATA_IDENTIFIERS { "poor", "middle", "rich" }; reserve_more_stratas(STRATA_IDENTIFIERS.size()); @@ -64,48 +62,21 @@ bool PopManager::add_strata(std::string_view identifier) { spdlog::error_s("Invalid strata identifier - empty!"); return false; } - return stratas.emplace_item( - identifier, - identifier, Strata::index_t { get_strata_count() } - ); + return stratas.emplace_item(identifier, identifier, Strata::index_t { get_strata_count() }); } bool PopManager::add_pop_type( - std::string_view identifier, - colour_t colour, - Strata* strata, - pop_sprite_t sprite, - fixed_point_map_t&& life_needs, - fixed_point_map_t&& everyday_needs, - fixed_point_map_t&& luxury_needs, - PopType::income_type_t life_needs_income_types, - PopType::income_type_t everyday_needs_income_types, - PopType::income_type_t luxury_needs_income_types, - ast::NodeCPtr rebel_units, - pop_size_t max_size, - pop_size_t merge_max_size, - bool state_capital_only, - bool demote_migrant, - bool is_artisan, - bool allowed_to_vote, - bool is_slave, - bool can_be_recruited, - bool can_reduce_consciousness, - bool administrative_efficiency, - bool can_invest, - bool factory, - bool can_work_factory, - bool unemployment, - fixed_point_t research_points, - fixed_point_t leadership_points, - fixed_point_t research_leadership_optimum, - fixed_point_t state_administration_multiplier, - ast::NodeCPtr equivalent, - ConditionalWeightFactorMul&& country_migration_target, - ConditionalWeightFactorMul&& migration_target, - ast::NodeCPtr promote_to_node, - PopType::ideology_weight_map_t&& ideologies, - ast::NodeCPtr issues_node + std::string_view identifier, colour_t colour, Strata* strata, pop_sprite_t sprite, + fixed_point_map_t&& life_needs, fixed_point_map_t&& everyday_needs, + fixed_point_map_t&& luxury_needs, PopType::income_type_t life_needs_income_types, + PopType::income_type_t everyday_needs_income_types, PopType::income_type_t luxury_needs_income_types, + ast::NodeCPtr rebel_units, pop_size_t max_size, pop_size_t merge_max_size, bool state_capital_only, bool demote_migrant, + bool is_artisan, bool allowed_to_vote, bool is_slave, bool can_be_recruited, bool can_reduce_consciousness, + bool administrative_efficiency, bool can_invest, bool factory, bool can_work_factory, bool unemployment, + fixed_point_t research_points, fixed_point_t leadership_points, fixed_point_t research_leadership_optimum, + fixed_point_t state_administration_multiplier, ast::NodeCPtr equivalent, + ConditionalWeightFactorMul&& country_migration_target, ConditionalWeightFactorMul&& migration_target, + ast::NodeCPtr promote_to_node, PopType::ideology_weight_map_t&& ideologies, ast::NodeCPtr issues_node ) { if (identifier.empty()) { spdlog::error_s("Invalid pop type identifier - empty!"); @@ -116,31 +87,22 @@ bool PopManager::add_pop_type( return false; } if (sprite <= 0) { - spdlog::error_s( - "Invalid pop type sprite index for {}: {} (must be positive)", - identifier, sprite - ); + spdlog::error_s("Invalid pop type sprite index for {}: {} (must be positive)", identifier, sprite); return false; } if (max_size <= 0) { - spdlog::error_s( - "Invalid pop type max size for {}: {} (must be positive)", - identifier, max_size - ); + spdlog::error_s("Invalid pop type max size for {}: {} (must be positive)", identifier, max_size); return false; } if (merge_max_size <= 0) { - spdlog::error_s( - "Invalid pop type merge max size for {}: {} (must be positive)", - identifier, merge_max_size - ); + spdlog::error_s("Invalid pop type merge max size for {}: {} (must be positive)", identifier, merge_max_size); return false; } if (research_leadership_optimum < 0) { spdlog::error_s( - "Invalid pop type research/leadership optimum for {}: {} (cannot be negative)", - identifier, research_leadership_optimum + "Invalid pop type research/leadership optimum for {}: {} (cannot be negative)", identifier, + research_leadership_optimum ); return false; } @@ -154,44 +116,16 @@ bool PopManager::add_pop_type( } if (OV_unlikely(!pop_types.emplace_item( - identifier, - identifier, - colour, - PopType::index_t { get_pop_type_count() }, - *strata, - sprite, - std::move(life_needs), - std::move(everyday_needs), - std::move(luxury_needs), - life_needs_income_types, - everyday_needs_income_types, - luxury_needs_income_types, - PopType::rebel_units_t{}, - max_size, - merge_max_size, - state_capital_only, - demote_migrant, - is_artisan, - allowed_to_vote, - is_slave, - can_be_recruited, - can_reduce_consciousness, - administrative_efficiency, - can_invest, - factory, - can_work_factory, - unemployment, - research_points, - leadership_points, - research_leadership_optimum, - state_administration_multiplier, - static_cast(nullptr), - std::move(country_migration_target), - std::move(migration_target), - PopType::poptype_weight_map_t { PopType::poptype_weight_map_t::create_empty() }, - std::move(ideologies), - PopType::issue_weight_map_t{} - ))) { + identifier, identifier, colour, PopType::index_t { get_pop_type_count() }, *strata, sprite, std::move(life_needs), + std::move(everyday_needs), std::move(luxury_needs), life_needs_income_types, everyday_needs_income_types, + luxury_needs_income_types, PopType::rebel_units_t {}, max_size, merge_max_size, state_capital_only, demote_migrant, + is_artisan, allowed_to_vote, is_slave, can_be_recruited, can_reduce_consciousness, administrative_efficiency, + can_invest, factory, can_work_factory, unemployment, research_points, leadership_points, + research_leadership_optimum, state_administration_multiplier, static_cast(nullptr), + std::move(country_migration_target), std::move(migration_target), + PopType::poptype_weight_map_t { PopType::poptype_weight_map_t::create_empty() }, std::move(ideologies), + PopType::issue_weight_map_t {} + ))) { return false; } @@ -223,16 +157,14 @@ void PopManager::reserve_pop_types_and_delayed_nodes(size_t size) { static NodeCallback auto expect_needs_income(PopType::income_type_t& types) { using enum PopType::income_type_t; - static const string_map_t income_type_map { - { "administration", ADMINISTRATION }, - { "education", EDUCATION }, - { "military", MILITARY } - }; + static const string_map_t income_type_map { { "administration", ADMINISTRATION }, + { "education", EDUCATION }, + { "military", MILITARY } }; constexpr bool is_warning = true; return expect_dictionary_keys_and_default_map( - map_key_value_ignore_invalid_callback>, - "type", ONE_OR_MORE, expect_identifier(expect_mapped_string( + map_key_value_ignore_invalid_callback>, "type", ONE_OR_MORE, + expect_identifier(expect_mapped_string( income_type_map, [&types](PopType::income_type_t type) -> bool { if (OV_unlikely(share_income_type(types, type))) { @@ -263,14 +195,14 @@ bool PopManager::load_pop_type_file( pop_sprite_t sprite = 0; fixed_point_map_t life_needs, everyday_needs, luxury_needs; PopType::income_type_t life_needs_income_types = NO_INCOME_TYPE, everyday_needs_income_types = NO_INCOME_TYPE, - luxury_needs_income_types = NO_INCOME_TYPE; + luxury_needs_income_types = NO_INCOME_TYPE; ast::NodeCPtr rebel_units = nullptr; pop_size_t max_size = Pop::MAX_SIZE, merge_max_size = Pop::MAX_SIZE; bool state_capital_only = false, demote_migrant = false, is_artisan = false, allowed_to_vote = true, is_slave = false, - can_be_recruited = false, can_reduce_consciousness = false, administrative_efficiency = false, can_invest = false, - factory = false, can_work_factory = false, unemployment = false; + can_be_recruited = false, can_reduce_consciousness = false, administrative_efficiency = false, can_invest = false, + factory = false, can_work_factory = false, unemployment = false; fixed_point_t research_points = 0, leadership_points = 0, research_leadership_optimum = 0, - state_administration_multiplier = 0; + state_administration_multiplier = 0; ast::NodeCPtr equivalent = nullptr; ConditionalWeightFactorMul country_migration_target { COUNTRY, POP, NO_SCOPE }; ConditionalWeightFactorMul migration_target { PROVINCE, POP, NO_SCOPE }; @@ -332,48 +264,17 @@ bool PopManager::load_pop_type_file( )(root); ret &= add_pop_type( - filestem, - colour, - strata, - sprite, - std::move(life_needs), - std::move(everyday_needs), - std::move(luxury_needs), - life_needs_income_types, - everyday_needs_income_types, - luxury_needs_income_types, - rebel_units, - max_size, - merge_max_size, - state_capital_only, - demote_migrant, - is_artisan, - allowed_to_vote, - is_slave, - can_be_recruited, - can_reduce_consciousness, - administrative_efficiency, - can_invest, - factory, - can_work_factory, - unemployment, - research_points, - leadership_points, - research_leadership_optimum, - state_administration_multiplier, - equivalent, - std::move(country_migration_target), - std::move(migration_target), - promote_to_node, - std::move(ideologies), - issues_node + filestem, colour, strata, sprite, std::move(life_needs), std::move(everyday_needs), std::move(luxury_needs), + life_needs_income_types, everyday_needs_income_types, luxury_needs_income_types, rebel_units, max_size, merge_max_size, + state_capital_only, demote_migrant, is_artisan, allowed_to_vote, is_slave, can_be_recruited, can_reduce_consciousness, + administrative_efficiency, can_invest, factory, can_work_factory, unemployment, research_points, leadership_points, + research_leadership_optimum, state_administration_multiplier, equivalent, std::move(country_migration_target), + std::move(migration_target), promote_to_node, std::move(ideologies), issues_node ); return ret; } -bool PopManager::load_delayed_parse_pop_type_data( - UnitTypeManager const& unit_type_manager, IssueManager const& issue_manager -) { +bool PopManager::load_delayed_parse_pop_type_data(UnitTypeManager const& unit_type_manager, IssueManager const& issue_manager) { using enum scope_type_t; bool ret = true; @@ -381,24 +282,22 @@ bool PopManager::load_delayed_parse_pop_type_data( const auto [rebel_units, equivalent, promote_to_node, issues_node] = delayed_parse_nodes[index]; PopType* pop_type = pop_types.get_item_by_index(pop_type_index_t(index)); - pop_type->promote_to = std::move(decltype(PopType::promote_to){get_pop_types()}); + pop_type->promote_to = std::move(decltype(PopType::promote_to) { get_pop_types() }); - if (rebel_units != nullptr && !unit_type_manager.expect_unit_type_decimal_map( - move_variable_callback(pop_type->rebel_units) - )(rebel_units)) { + if (rebel_units != nullptr && + !unit_type_manager.expect_unit_type_decimal_map(move_variable_callback(pop_type->rebel_units))(rebel_units)) { spdlog::error_s("Errors parsing rebel unit distribution for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (equivalent != nullptr && !expect_pop_type_identifier( - assign_variable_callback_pointer(pop_type->equivalent) - )(equivalent)) { + if (equivalent != nullptr && + !expect_pop_type_identifier(assign_variable_callback_pointer(pop_type->equivalent))(equivalent)) { spdlog::error_s("Errors parsing equivalent pop type for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (promote_to_node != nullptr && !expect_pop_type_dictionary( - [pop_type](PopType const& type, ast::NodeCPtr node) -> bool { + if (promote_to_node != nullptr && + !expect_pop_type_dictionary([pop_type](PopType const& type, ast::NodeCPtr node) -> bool { if (pop_type && type == *pop_type) { spdlog::error_s("Pop type {} cannot have promotion weight to itself!", type); return false; @@ -407,15 +306,13 @@ bool PopManager::load_delayed_parse_pop_type_data( bool ret = weight.expect_conditional_weight()(node); ret &= map_callback(pop_type->promote_to, &type)(std::move(weight)); return ret; - } - )(promote_to_node)) { + })(promote_to_node)) { spdlog::error_s("Errors parsing promotion weights for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (issues_node != nullptr && !expect_dictionary_reserve_length( - pop_type->issues, - [pop_type, &issue_manager](std::string_view key, ast::NodeCPtr node) -> bool { + if (issues_node != nullptr && + !expect_dictionary_reserve_length(pop_type->issues, [pop_type, &issue_manager](std::string_view key, ast::NodeCPtr node) -> bool { BaseIssue const* issue = issue_manager.get_base_issue_by_identifier(key); if (issue == nullptr) { spdlog::error_s("Invalid issue in pop type {} issue weights: {}", ovfmt::validate(pop_type), key); @@ -425,8 +322,7 @@ bool PopManager::load_delayed_parse_pop_type_data( bool ret = weight.expect_conditional_weight()(node); ret &= map_callback(pop_type->issues, issue)(std::move(weight)); return ret; - } - )(issues_node)) { + })(issues_node)) { spdlog::error_s("Errors parsing issue weights for pop type {}!", ovfmt::validate(pop_type)); ret = false; } @@ -449,7 +345,7 @@ bool PopManager::load_pop_type_chances_file(ast::NodeCPtr root) { bool PopManager::load_pop_bases_into_vector( RebelManager const& rebel_manager, memory::vector& vec, PopType const& type, ast::NodeCPtr pop_node, - bool *non_integer_size + bool* non_integer_size ) const { Culture const* culture = nullptr; Religion const* religion = nullptr; @@ -475,12 +371,13 @@ bool PopManager::load_pop_bases_into_vector( return true; } - if (culture != nullptr && religion != nullptr && size >= 1 && size <= std::numeric_limits>::max()) { + if (culture != nullptr && religion != nullptr && size >= 1 && + size <= std::numeric_limits>::max()) { vec.emplace_back(PopBase { type, *culture, *religion, size.floor(), militancy, consciousness, rebel_type }); } else { spdlog::warn_s( - "Some pop arguments are invalid: culture = {}, religion = {}, size = {}", - ovfmt::validate(culture), ovfmt::validate(religion), size + "Some pop arguments are invalid: culture = {}, religion = {}, size = {}", ovfmt::validate(culture), + ovfmt::validate(religion), size ); } return ret; @@ -495,15 +392,15 @@ bool PopManager::generate_modifiers(ModifierManager& modifier_manager) const { IndexedFlatMap& strata_effects = modifier_manager.modifier_effect_cache.strata_effects; - strata_effects = std::move(decltype(ModifierEffectCache::strata_effects){get_stratas()}); + strata_effects = std::move(decltype(ModifierEffectCache::strata_effects) { get_stratas() }); bool ret = true; for (Strata const& strata : get_stratas()) { const auto strata_modifier = [&modifier_manager, &ret, &strata]( - ModifierEffect const*& effect_cache, std::string_view suffix, ModifierEffect::format_t format, - bool has_no_effect = false - ) -> void { + ModifierEffect const*& effect_cache, std::string_view suffix, + ModifierEffect::format_t format, bool has_no_effect = false + ) -> void { ret &= modifier_manager.register_base_country_modifier_effect( effect_cache, append_string_views(strata.get_identifier(), suffix), format, {}, has_no_effect ); diff --git a/src/openvic-simulation/population/PopManager.hpp b/src/openvic-simulation/population/PopManager.hpp index 38bbd2e2a..27310cdf6 100644 --- a/src/openvic-simulation/population/PopManager.hpp +++ b/src/openvic-simulation/population/PopManager.hpp @@ -1,8 +1,8 @@ #pragma once #include "openvic-simulation/population/Culture.hpp" -#include "openvic-simulation/population/Religion.hpp" #include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/Religion.hpp" namespace OpenVic { struct GoodDefinitionManager; @@ -51,41 +51,17 @@ namespace OpenVic { bool add_strata(std::string_view identifier); bool add_pop_type( - std::string_view identifier, - colour_t new_colour, - Strata* strata, - pop_sprite_t sprite, - fixed_point_map_t&& life_needs, - fixed_point_map_t&& everyday_needs, - fixed_point_map_t&& luxury_needs, - PopType::income_type_t life_needs_income_types, - PopType::income_type_t everyday_needs_income_types, - PopType::income_type_t luxury_needs_income_types, - ast::NodeCPtr rebel_units, - pop_size_t max_size, - pop_size_t merge_max_size, - bool state_capital_only, - bool demote_migrant, - bool is_artisan, - bool allowed_to_vote, - bool is_slave, - bool can_be_recruited, - bool can_reduce_consciousness, - bool administrative_efficiency, - bool can_invest, - bool factory, - bool can_work_factory, - bool unemployment, - fixed_point_t research_points, - fixed_point_t leadership_points, - fixed_point_t research_leadership_optimum, - fixed_point_t state_administration_multiplier, - ast::NodeCPtr equivalent, - ConditionalWeightFactorMul&& country_migration_target, - ConditionalWeightFactorMul&& migration_target, - ast::NodeCPtr promote_to_node, - PopType::ideology_weight_map_t&& ideologies, - ast::NodeCPtr issues_node + std::string_view identifier, colour_t new_colour, Strata* strata, pop_sprite_t sprite, + fixed_point_map_t&& life_needs, fixed_point_map_t&& everyday_needs, + fixed_point_map_t&& luxury_needs, PopType::income_type_t life_needs_income_types, + PopType::income_type_t everyday_needs_income_types, PopType::income_type_t luxury_needs_income_types, + ast::NodeCPtr rebel_units, pop_size_t max_size, pop_size_t merge_max_size, bool state_capital_only, + bool demote_migrant, bool is_artisan, bool allowed_to_vote, bool is_slave, bool can_be_recruited, + bool can_reduce_consciousness, bool administrative_efficiency, bool can_invest, bool factory, bool can_work_factory, + bool unemployment, fixed_point_t research_points, fixed_point_t leadership_points, + fixed_point_t research_leadership_optimum, fixed_point_t state_administration_multiplier, ast::NodeCPtr equivalent, + ConditionalWeightFactorMul&& country_migration_target, ConditionalWeightFactorMul&& migration_target, + ast::NodeCPtr promote_to_node, PopType::ideology_weight_map_t&& ideologies, ast::NodeCPtr issues_node ); bool setup_stratas(); @@ -102,11 +78,11 @@ namespace OpenVic { bool load_pop_bases_into_vector( RebelManager const& rebel_manager, memory::vector& vec, PopType const& type, ast::NodeCPtr pop_node, - bool *non_integer_size + bool* non_integer_size ) const; bool generate_modifiers(ModifierManager& modifier_manager) const; bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopSize.hpp b/src/openvic-simulation/population/PopSize.hpp index c1245842f..340ccae44 100644 --- a/src/openvic-simulation/population/PopSize.hpp +++ b/src/openvic-simulation/population/PopSize.hpp @@ -5,10 +5,10 @@ #include #include -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" - #include +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" + namespace OpenVic { struct pop_size_t : type_safe::strong_typedef, type_safe::strong_typedef_op::equality_comparison, diff --git a/src/openvic-simulation/population/PopSum.hpp b/src/openvic-simulation/population/PopSum.hpp index 9a5f9d773..59984489a 100644 --- a/src/openvic-simulation/population/PopSum.hpp +++ b/src/openvic-simulation/population/PopSum.hpp @@ -6,11 +6,11 @@ #include #include +#include + #include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include - namespace OpenVic { namespace detail { template diff --git a/src/openvic-simulation/population/PopType.cpp b/src/openvic-simulation/population/PopType.cpp index c17778fa2..333427789 100644 --- a/src/openvic-simulation/population/PopType.cpp +++ b/src/openvic-simulation/population/PopType.cpp @@ -8,81 +8,38 @@ using namespace OpenVic; -Strata::Strata(std::string_view new_identifier, index_t new_index) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} +Strata::Strata(std::string_view new_identifier, index_t new_index) : HasIdentifier { new_identifier }, HasIndex { new_index } {} PopType::PopType( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - Strata const& new_strata, - pop_sprite_t new_sprite, - fixed_point_map_t&& new_life_needs, - fixed_point_map_t&& new_everyday_needs, - fixed_point_map_t&& new_luxury_needs, - income_type_t new_life_needs_income_types, - income_type_t new_everyday_needs_income_types, - income_type_t new_luxury_needs_income_types, - rebel_units_t&& new_rebel_units, - pop_size_t new_max_size, - pop_size_t new_merge_max_size, - bool new_state_capital_only, - bool new_demote_migrant, - bool new_is_artisan, - bool new_allowed_to_vote, - bool new_is_slave, - bool new_can_be_recruited, - bool new_can_reduce_consciousness, - bool new_is_administrator, - bool new_can_invest, - bool new_factory, - bool new_can_work_factory, - bool new_can_be_unemployed, - fixed_point_t new_research_points, - fixed_point_t new_leadership_points, - fixed_point_t new_research_leadership_optimum, - fixed_point_t new_state_administration_multiplier, - PopType const* new_equivalent, - ConditionalWeightFactorMul&& new_country_migration_target, - ConditionalWeightFactorMul&& new_migration_target, - poptype_weight_map_t&& new_promote_to, - ideology_weight_map_t&& new_ideologies, - issue_weight_map_t&& new_issues -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - 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) }, - life_needs_income_types { new_life_needs_income_types }, - everyday_needs_income_types { new_everyday_needs_income_types }, - luxury_needs_income_types { new_luxury_needs_income_types }, - 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 }, - allowed_to_vote { new_allowed_to_vote }, - is_slave { new_is_slave }, - can_be_recruited { new_can_be_recruited }, - can_reduce_consciousness { new_can_reduce_consciousness }, - is_administrator { new_is_administrator }, - can_invest { new_can_invest }, - factory { new_factory }, - can_work_factory { new_can_work_factory }, - can_be_unemployed { new_can_be_unemployed }, - research_points { new_research_points }, - leadership_points { new_leadership_points }, - research_leadership_optimum { new_research_leadership_optimum }, - state_administration_multiplier { new_state_administration_multiplier }, - equivalent { new_equivalent }, - country_migration_target { std::move(new_country_migration_target) }, - migration_target { std::move(new_migration_target) }, - promote_to { std::move(new_promote_to) }, - ideologies { std::move(new_ideologies) }, - issues { std::move(new_issues) } {} + std::string_view new_identifier, colour_t new_colour, index_t new_index, Strata const& new_strata, pop_sprite_t new_sprite, + fixed_point_map_t&& new_life_needs, fixed_point_map_t&& new_everyday_needs, + fixed_point_map_t&& new_luxury_needs, income_type_t new_life_needs_income_types, + income_type_t new_everyday_needs_income_types, income_type_t new_luxury_needs_income_types, rebel_units_t&& new_rebel_units, + pop_size_t new_max_size, pop_size_t new_merge_max_size, bool new_state_capital_only, bool new_demote_migrant, + bool new_is_artisan, bool new_allowed_to_vote, bool new_is_slave, bool new_can_be_recruited, + bool new_can_reduce_consciousness, bool new_is_administrator, bool new_can_invest, bool new_factory, + bool new_can_work_factory, bool new_can_be_unemployed, fixed_point_t new_research_points, + fixed_point_t new_leadership_points, fixed_point_t new_research_leadership_optimum, + fixed_point_t new_state_administration_multiplier, PopType const* new_equivalent, + ConditionalWeightFactorMul&& new_country_migration_target, ConditionalWeightFactorMul&& new_migration_target, + poptype_weight_map_t&& new_promote_to, ideology_weight_map_t&& new_ideologies, issue_weight_map_t&& new_issues +) + : HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, 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) }, life_needs_income_types { new_life_needs_income_types }, + everyday_needs_income_types { new_everyday_needs_income_types }, + luxury_needs_income_types { new_luxury_needs_income_types }, 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 }, allowed_to_vote { new_allowed_to_vote }, + is_slave { new_is_slave }, can_be_recruited { new_can_be_recruited }, + can_reduce_consciousness { new_can_reduce_consciousness }, is_administrator { new_is_administrator }, + can_invest { new_can_invest }, factory { new_factory }, can_work_factory { new_can_work_factory }, + can_be_unemployed { new_can_be_unemployed }, research_points { new_research_points }, + leadership_points { new_leadership_points }, research_leadership_optimum { new_research_leadership_optimum }, + state_administration_multiplier { new_state_administration_multiplier }, equivalent { new_equivalent }, + country_migration_target { std::move(new_country_migration_target) }, + migration_target { std::move(new_migration_target) }, promote_to { std::move(new_promote_to) }, + ideologies { std::move(new_ideologies) }, issues { std::move(new_issues) } {} bool PopType::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; diff --git a/src/openvic-simulation/population/PopType.hpp b/src/openvic-simulation/population/PopType.hpp index 86ceb0a4f..42ed2898d 100644 --- a/src/openvic-simulation/population/PopType.hpp +++ b/src/openvic-simulation/population/PopType.hpp @@ -2,15 +2,15 @@ #include +#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/scripts/ConditionalWeight.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" -#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/types/PopSprite.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { @@ -40,10 +40,10 @@ namespace OpenVic { /* This is a bitfield - PopTypes can have up to one of each income source for each need category. */ enum struct income_type_t : uint8_t { - NO_INCOME_TYPE = 0, - ADMINISTRATION = 1 << 0, - EDUCATION = 1 << 1, - MILITARY = 1 << 2 + NO_INCOME_TYPE = 0, + ADMINISTRATION = 1 << 0, + EDUCATION = 1 << 1, + MILITARY = 1 << 2 }; using rebel_units_t = fixed_point_map_t; @@ -92,54 +92,33 @@ namespace OpenVic { const fixed_point_t state_administration_multiplier; PopType( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - Strata const& new_strata, - pop_sprite_t new_sprite, - fixed_point_map_t&& new_life_needs, + std::string_view new_identifier, colour_t new_colour, index_t new_index, Strata const& new_strata, + pop_sprite_t new_sprite, fixed_point_map_t&& new_life_needs, fixed_point_map_t&& new_everyday_needs, - fixed_point_map_t&& new_luxury_needs, - income_type_t new_life_needs_income_types, - income_type_t new_everyday_needs_income_types, - income_type_t new_luxury_needs_income_types, - rebel_units_t&& new_rebel_units, - pop_size_t new_max_size, - pop_size_t new_merge_max_size, - bool new_state_capital_only, - bool new_demote_migrant, - bool new_is_artisan, - bool new_allowed_to_vote, - bool new_is_slave, - bool new_can_be_recruited, - bool new_can_reduce_consciousness, - bool new_is_administrator, - bool new_can_invest, - bool new_factory, - bool new_can_work_factory, - bool new_can_be_unemployed, - fixed_point_t new_research_points, - fixed_point_t new_leadership_points, - fixed_point_t new_research_leadership_optimum, - fixed_point_t new_state_administration_multiplier, - PopType const* new_equivalent, - ConditionalWeightFactorMul&& new_country_migration_target, - ConditionalWeightFactorMul&& new_migration_target, - poptype_weight_map_t&& new_promote_to, - ideology_weight_map_t&& new_ideologies, - issue_weight_map_t&& new_issues + fixed_point_map_t&& new_luxury_needs, income_type_t new_life_needs_income_types, + income_type_t new_everyday_needs_income_types, income_type_t new_luxury_needs_income_types, + rebel_units_t&& new_rebel_units, pop_size_t new_max_size, pop_size_t new_merge_max_size, + bool new_state_capital_only, bool new_demote_migrant, bool new_is_artisan, bool new_allowed_to_vote, + bool new_is_slave, bool new_can_be_recruited, bool new_can_reduce_consciousness, bool new_is_administrator, + bool new_can_invest, bool new_factory, bool new_can_work_factory, bool new_can_be_unemployed, + fixed_point_t new_research_points, fixed_point_t new_leadership_points, + fixed_point_t new_research_leadership_optimum, fixed_point_t new_state_administration_multiplier, + PopType const* new_equivalent, ConditionalWeightFactorMul&& new_country_migration_target, + ConditionalWeightFactorMul&& new_migration_target, poptype_weight_map_t&& new_promote_to, + ideology_weight_map_t&& new_ideologies, issue_weight_map_t&& new_issues ); PopType(PopType&&) = default; constexpr bool has_income_type(income_type_t income_type) const; }; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; constexpr bool PopType::has_income_type(income_type_t income_type) const { - return (life_needs_income_types & income_type) == income_type - || (everyday_needs_income_types & income_type) == income_type - || (luxury_needs_income_types & income_type) == income_type; + return (life_needs_income_types & income_type) == income_type || + (everyday_needs_income_types & income_type) == income_type || + (luxury_needs_income_types & income_type) == income_type; } /* This returns true if at least one income type is shared by both arguments. */ @@ -172,4 +151,4 @@ namespace OpenVic { } return stream << ']'; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopValuesFromProvince.cpp b/src/openvic-simulation/population/PopValuesFromProvince.cpp index bc205fda5..014ad485a 100644 --- a/src/openvic-simulation/population/PopValuesFromProvince.cpp +++ b/src/openvic-simulation/population/PopValuesFromProvince.cpp @@ -1,4 +1,5 @@ #include "PopValuesFromProvince.hpp" + #include #include "openvic-simulation/country/CountryInstance.hpp" @@ -6,23 +7,21 @@ #include "openvic-simulation/economy/GoodInstance.hpp" #include "openvic-simulation/economy/production/ArtisanalProducer.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" -#include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" +#include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/population/PopType.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" using namespace OpenVic; void PopStrataValuesFromProvince::update_pop_strata_values_from_province( - PopsDefines const& defines, - ModifierEffectCache const& modifier_effect_cache, - Strata const& strata, + PopsDefines const& defines, ModifierEffectCache const& modifier_effect_cache, Strata const& strata, ProvinceInstance const& province ) { ModifierEffectCache::strata_effects_t const& strata_effects = modifier_effect_cache.get_strata_effects(strata); - fixed_point_t shared_base_needs_scalar = defines.get_base_goods_demand() - * (fixed_point_t::_1 + province.get_modifier_effect_value(*modifier_effect_cache.get_goods_demand())); + fixed_point_t shared_base_needs_scalar = defines.get_base_goods_demand() * + (fixed_point_t::_1 + province.get_modifier_effect_value(*modifier_effect_cache.get_goods_demand())); fixed_point_t invention_needs_scalar = 1; CountryInstance const* const owner_nullable = province.get_owner(); @@ -32,30 +31,22 @@ void PopStrataValuesFromProvince::update_pop_strata_values_from_province( invention_needs_scalar += owner.get_inventions_count_untracked() * defines.get_invention_impact_on_demand(); } - shared_life_needs_scalar = shared_base_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_life_needs())); - shared_everyday_needs_scalar = shared_base_needs_scalar - * invention_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_everyday_needs())); - shared_luxury_needs_scalar = shared_base_needs_scalar - * invention_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_luxury_needs())); + shared_life_needs_scalar = + shared_base_needs_scalar * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_life_needs())); + shared_everyday_needs_scalar = shared_base_needs_scalar * invention_needs_scalar * + (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_everyday_needs())); + shared_luxury_needs_scalar = shared_base_needs_scalar * invention_needs_scalar * + (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_luxury_needs())); } PopValuesFromProvince::PopValuesFromProvince( - GameRulesManager const& new_game_rules_manager, - GoodInstanceManager const& new_good_instance_manager, - ModifierEffectCache const& new_modifier_effect_cache, - ProductionTypeManager const& new_production_type_manager, - PopsDefines const& new_defines, - decltype(effects_by_strata)::keys_span_type strata_keys -) : game_rules_manager { new_game_rules_manager }, - good_instance_manager { new_good_instance_manager }, - modifier_effect_cache { new_modifier_effect_cache }, - production_type_manager { new_production_type_manager }, - defines { new_defines }, - effects_by_strata { strata_keys } - {} + GameRulesManager const& new_game_rules_manager, GoodInstanceManager const& new_good_instance_manager, + ModifierEffectCache const& new_modifier_effect_cache, ProductionTypeManager const& new_production_type_manager, + PopsDefines const& new_defines, decltype(effects_by_strata)::keys_span_type strata_keys +) + : game_rules_manager { new_game_rules_manager }, good_instance_manager { new_good_instance_manager }, + modifier_effect_cache { new_modifier_effect_cache }, production_type_manager { new_production_type_manager }, + defines { new_defines }, effects_by_strata { strata_keys } {} PopStrataValuesFromProvince const& PopValuesFromProvince::get_effects_by_strata(Strata const& key) const { return effects_by_strata.at(key); @@ -66,35 +57,33 @@ void PopValuesFromProvince::update_pop_values_from_province(ProvinceInstance& pr values.update_pop_strata_values_from_province(defines, modifier_effect_cache, strata, province); } - max_cost_multiplier = 1; + max_cost_multiplier = 1; CountryInstance* const country_to_report_economy_nullable = province.get_country_to_report_economy(); if (country_to_report_economy_nullable != nullptr) { const fixed_point_t tariff_rate = country_to_report_economy_nullable->effective_tariff_rate.get_untracked(); if (tariff_rate > fixed_point_t::_0) { - max_cost_multiplier += tariff_rate; //max (domestic cost, imported cost) + max_cost_multiplier += tariff_rate; // max (domestic cost, imported cost) } } - + ranked_artisanal_production_types.clear(); ranked_artisanal_production_types.reserve(production_type_manager.get_production_type_count()); for (auto const& production_type : production_type_manager.get_production_types()) { const std::optional estimated_score = ArtisanalProducer::estimate_production_type_score( - good_instance_manager, - production_type, - province, - max_cost_multiplier + good_instance_manager, production_type, province, max_cost_multiplier ); if (estimated_score.has_value() && estimated_score.value() > 0) { - ranked_artisanal_production_types.push_back({&production_type, estimated_score.value()}); + ranked_artisanal_production_types.push_back({ &production_type, estimated_score.value() }); } } if (!ranked_artisanal_production_types.empty()) { - std::stable_sort(ranked_artisanal_production_types.begin(), ranked_artisanal_production_types.end(), + std::stable_sort( + ranked_artisanal_production_types.begin(), ranked_artisanal_production_types.end(), [](const auto& a, const auto& b) { return a.second > b.second; } ); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopValuesFromProvince.hpp b/src/openvic-simulation/population/PopValuesFromProvince.hpp index c5de706ba..4471746ec 100644 --- a/src/openvic-simulation/population/PopValuesFromProvince.hpp +++ b/src/openvic-simulation/population/PopValuesFromProvince.hpp @@ -20,11 +20,10 @@ namespace OpenVic { fixed_point_t PROPERTY(shared_life_needs_scalar); fixed_point_t PROPERTY(shared_everyday_needs_scalar); fixed_point_t PROPERTY(shared_luxury_needs_scalar); + public: void update_pop_strata_values_from_province( - PopsDefines const& defines, - ModifierEffectCache const& modifier_effect_cache, - Strata const& strata, + PopsDefines const& defines, ModifierEffectCache const& modifier_effect_cache, Strata const& strata, ProvinceInstance const& province ); }; @@ -36,22 +35,20 @@ namespace OpenVic { ProductionTypeManager const& production_type_manager; fixed_point_t PROPERTY(max_cost_multiplier); OV_IFLATMAP_PROPERTY(Strata, PopStrataValuesFromProvince, effects_by_strata); - //excludes availability of goods on market + // excludes availability of goods on market memory::vector> SPAN_PROPERTY(ranked_artisanal_production_types); + public: PopsDefines const& defines; GameRulesManager const& game_rules_manager; PopValuesFromProvince( - GameRulesManager const& new_game_rules_manager, - GoodInstanceManager const& new_good_instance_manager, - ModifierEffectCache const& new_modifier_effect_cache, - ProductionTypeManager const& new_production_type_manager, - PopsDefines const& new_defines, - decltype(effects_by_strata)::keys_span_type strata_keys + GameRulesManager const& new_game_rules_manager, GoodInstanceManager const& new_good_instance_manager, + ModifierEffectCache const& new_modifier_effect_cache, ProductionTypeManager const& new_production_type_manager, + PopsDefines const& new_defines, decltype(effects_by_strata)::keys_span_type strata_keys ); PopValuesFromProvince(PopValuesFromProvince&&) = default; void update_pop_values_from_province(ProvinceInstance& province); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopsAggregate.cpp b/src/openvic-simulation/population/PopsAggregate.cpp index 5d9afe735..750db8e6b 100644 --- a/src/openvic-simulation/population/PopsAggregate.cpp +++ b/src/openvic-simulation/population/PopsAggregate.cpp @@ -2,33 +2,28 @@ #include +#include + #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/population/Pop.hpp" #include "openvic-simulation/population/PopType.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/OrderedContainersMath.hpp" - -#include +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" using namespace OpenVic; PopsAggregate::PopsAggregate( - decltype(population_by_strata)::keys_span_type strata_keys, - decltype(population_by_type)::keys_span_type pop_type_keys, + decltype(population_by_strata)::keys_span_type strata_keys, decltype(population_by_type)::keys_span_type pop_type_keys, decltype(supporter_equivalents_by_ideology)::keys_span_type ideology_keys -) : population_by_strata { strata_keys }, - militancy_by_strata_running_total_raw { strata_keys }, - life_needs_fulfilled_by_strata_running_total_raw { strata_keys }, - everyday_needs_fulfilled_by_strata_running_total_raw { strata_keys }, - luxury_needs_fulfilled_by_strata_running_total_raw { strata_keys }, - militancy_by_strata { strata_keys }, - life_needs_fulfilled_by_strata { strata_keys }, - everyday_needs_fulfilled_by_strata { strata_keys }, - luxury_needs_fulfilled_by_strata { strata_keys }, - population_by_type { pop_type_keys }, - unemployed_pops_by_type { pop_type_keys }, - supporter_equivalents_by_ideology { ideology_keys } {} +) + : population_by_strata { strata_keys }, militancy_by_strata_running_total_raw { strata_keys }, + life_needs_fulfilled_by_strata_running_total_raw { strata_keys }, + everyday_needs_fulfilled_by_strata_running_total_raw { strata_keys }, + luxury_needs_fulfilled_by_strata_running_total_raw { strata_keys }, militancy_by_strata { strata_keys }, + life_needs_fulfilled_by_strata { strata_keys }, everyday_needs_fulfilled_by_strata { strata_keys }, + luxury_needs_fulfilled_by_strata { strata_keys }, population_by_type { pop_type_keys }, + unemployed_pops_by_type { pop_type_keys }, supporter_equivalents_by_ideology { ideology_keys } {} pop_sum_t PopsAggregate::get_population_by_type(PopType const& pop_type) const { return population_by_type.at(pop_type); @@ -127,24 +122,24 @@ void PopsAggregate::add_pops_aggregate(PopsAggregate& part) { const pop_sum_t part_population = part.get_total_population(); const int64_t part_population_v = type_safe::get(part_population); - literacy_running_total_raw += part_population_v - * static_cast(part.get_average_literacy().get_raw_value()); - consciousness_running_total_raw += part_population_v - * static_cast(part.get_average_consciousness().get_raw_value()); - militancy_running_total_raw += part_population_v - * static_cast(part.get_average_militancy().get_raw_value()); + literacy_running_total_raw += + part_population_v * static_cast(part.get_average_literacy().get_raw_value()); + consciousness_running_total_raw += + part_population_v * static_cast(part.get_average_consciousness().get_raw_value()); + militancy_running_total_raw += + part_population_v * static_cast(part.get_average_militancy().get_raw_value()); for (auto const& [strata, strata_population] : part.get_population_by_strata()) { population_by_strata.at(strata) += strata_population; const int64_t strata_population_v = type_safe::get(strata_population); - militancy_by_strata_running_total_raw.at(strata) += strata_population_v - * static_cast(part.militancy_by_strata.at(strata).get_raw_value()); - life_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v - * static_cast(part.life_needs_fulfilled_by_strata.at(strata).get_raw_value()); - everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v - * static_cast(part.everyday_needs_fulfilled_by_strata.at(strata).get_raw_value()); - luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v - * static_cast(part.luxury_needs_fulfilled_by_strata.at(strata).get_raw_value()); + militancy_by_strata_running_total_raw.at(strata) += + strata_population_v * static_cast(part.militancy_by_strata.at(strata).get_raw_value()); + life_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v * + static_cast(part.life_needs_fulfilled_by_strata.at(strata).get_raw_value()); + everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v * + static_cast(part.everyday_needs_fulfilled_by_strata.at(strata).get_raw_value()); + luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) += strata_population_v * + static_cast(part.luxury_needs_fulfilled_by_strata.at(strata).get_raw_value()); } population_by_type += part.get_population_by_type(); @@ -162,25 +157,23 @@ void PopsAggregate::add_pops_aggregate(Pop const& pop) { total_population += pop_size; yesterdays_import_value += pop.get_yesterdays_import_value().get_copy_of_value(); const int64_t pop_size_v = type_safe::get(pop_size); - literacy_running_total_raw += pop_size_v - * static_cast(pop.get_literacy().get_raw_value()); - consciousness_running_total_raw += pop_size_v - * static_cast(pop.get_consciousness().get_raw_value()); - militancy_running_total_raw += pop_size_v - * static_cast(pop.get_militancy().get_raw_value()); + literacy_running_total_raw += pop_size_v * static_cast(pop.get_literacy().get_raw_value()); + consciousness_running_total_raw += + pop_size_v * static_cast(pop.get_consciousness().get_raw_value()); + militancy_running_total_raw += pop_size_v * static_cast(pop.get_militancy().get_raw_value()); PopType const& pop_type = pop.get_type(); Strata const& strata = pop_type.strata; population_by_strata.at(strata) += pop_size; - militancy_by_strata_running_total_raw.at(strata) += pop_size_v - * static_cast(pop.get_militancy().get_raw_value()); - life_needs_fulfilled_by_strata_running_total_raw.at(strata) += pop_size_v - * static_cast(pop.get_life_needs_fulfilled().get_raw_value()); - everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) += pop_size_v - * static_cast(pop.get_everyday_needs_fulfilled().get_raw_value()); - luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) += pop_size_v - * static_cast(pop.get_luxury_needs_fulfilled().get_raw_value()); + militancy_by_strata_running_total_raw.at(strata) += + pop_size_v * static_cast(pop.get_militancy().get_raw_value()); + life_needs_fulfilled_by_strata_running_total_raw.at(strata) += + pop_size_v * static_cast(pop.get_life_needs_fulfilled().get_raw_value()); + everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) += + pop_size_v * static_cast(pop.get_everyday_needs_fulfilled().get_raw_value()); + luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) += + pop_size_v * static_cast(pop.get_luxury_needs_fulfilled().get_raw_value()); population_by_type.at(pop_type) += pop_size; unemployed_pops_by_type.at(pop_type) += pop.get_unemployed(); @@ -201,23 +194,24 @@ void PopsAggregate::normalise_pops_aggregate() { if (total_population > 0) { const int64_t total_population_v = type_safe::get(total_population); average_literacy = fixed_point_t::parse_raw(static_cast(literacy_running_total_raw / total_population_v)); - average_consciousness = fixed_point_t::parse_raw(static_cast(consciousness_running_total_raw / total_population_v)); + average_consciousness = + fixed_point_t::parse_raw(static_cast(consciousness_running_total_raw / total_population_v)); average_militancy = fixed_point_t::parse_raw(static_cast(militancy_running_total_raw / total_population_v)); for (auto const& [strata, strata_population] : population_by_strata) { const int64_t strata_population_v = type_safe::get(strata_population); - militancy_by_strata.at(strata) = fixed_point_t::parse_raw(static_cast( - militancy_by_strata_running_total_raw.at(strata) / strata_population_v - )); - life_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw(static_cast( - life_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v - )); - everyday_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw(static_cast( - everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v - )); - luxury_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw(static_cast( - luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v - )); + militancy_by_strata.at(strata) = fixed_point_t::parse_raw( + static_cast(militancy_by_strata_running_total_raw.at(strata) / strata_population_v) + ); + life_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw( + static_cast(life_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v) + ); + everyday_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw( + static_cast(everyday_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v) + ); + luxury_needs_fulfilled_by_strata.at(strata) = fixed_point_t::parse_raw( + static_cast(luxury_needs_fulfilled_by_strata_running_total_raw.at(strata) / strata_population_v) + ); } } } @@ -228,11 +222,9 @@ void PopsAggregate::update_parties_for_votes(CountryDefinition const* country_de return; } - auto view = country_definition->get_parties() | std::views::transform( - [](CountryParty const& key) { - return std::make_pair(&key, fixed_point_t::_0); - } - ); + auto view = country_definition->get_parties() | std::views::transform([](CountryParty const& key) { + return std::make_pair(&key, fixed_point_t::_0); + }); vote_equivalents_by_party.insert(view.begin(), view.end()); } void PopsAggregate::update_parties_for_votes(CountryInstance const* country_instance) { @@ -241,4 +233,4 @@ void PopsAggregate::update_parties_for_votes(CountryInstance const* country_inst return; } update_parties_for_votes(&country_instance->country_definition); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopsAggregate.hpp b/src/openvic-simulation/population/PopsAggregate.hpp index 566bc4c5a..748bb352a 100644 --- a/src/openvic-simulation/population/PopsAggregate.hpp +++ b/src/openvic-simulation/population/PopsAggregate.hpp @@ -1,10 +1,10 @@ #pragma once -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" +#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" -#include "openvic-simulation/population/PopSum.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/reactive/MutableState.hpp" @@ -68,6 +68,7 @@ namespace OpenVic { void normalise_pops_aggregate(); void update_parties_for_votes(CountryDefinition const* country_definition); void update_parties_for_votes(CountryInstance const* country_instance); + public: // The values returned by these functions are scaled by population size, so they must be divided by population size // to get the support as a proportion of 1.0 @@ -77,4 +78,4 @@ namespace OpenVic { pop_sum_t get_population_by_culture(Culture const& culture) const; pop_sum_t get_population_by_religion(Religion const& religion) const; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/Religion.cpp b/src/openvic-simulation/population/Religion.cpp index 49cd2f4f0..dc8abf597 100644 --- a/src/openvic-simulation/population/Religion.cpp +++ b/src/openvic-simulation/population/Religion.cpp @@ -8,15 +8,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, false }, - group { new_group }, - icon { new_icon }, - pagan { new_pagan } {} + 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, false }, group { new_group }, icon { new_icon }, + pagan { new_pagan } {} bool ReligionManager::add_religion_group(std::string_view identifier) { if (identifier.empty()) { @@ -41,10 +36,7 @@ bool ReligionManager::add_religion( spdlog::error_s("Invalid religion icon for {}: {}", identifier, icon); return false; } - return religions.emplace_item( - identifier, - identifier, colour, group, icon, pagan - ); + return religions.emplace_item(identifier, identifier, colour, group, icon, pagan); } /* REQUIREMENTS: @@ -53,33 +45,28 @@ bool ReligionManager::add_religion( */ bool ReligionManager::load_religion_file(ast::NodeCPtr root) { size_t total_expected_religions = 0; - bool ret = expect_dictionary_reserve_length( - religion_groups, - [this, &total_expected_religions](std::string_view key, ast::NodeCPtr value) -> bool { + 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); return ret; - } - )(root); + })(root); lock_religion_groups(); reserve_more_religions(total_expected_religions); - ret &= expect_religion_group_dictionary( - [this](ReligionGroup const& religion_group, ast::NodeCPtr religion_group_value) -> bool { - return expect_dictionary([this, &religion_group](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = colour_t::null(); - Religion::icon_t icon = 0; - bool pagan = false; + ret &= expect_religion_group_dictionary([this](ReligionGroup const& religion_group, ast::NodeCPtr religion_group_value) -> bool { + return expect_dictionary([this, &religion_group](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = colour_t::null(); + 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/research/Invention.cpp b/src/openvic-simulation/research/Invention.cpp index 75a0b676a..ef10a6eeb 100644 --- a/src/openvic-simulation/research/Invention.cpp +++ b/src/openvic-simulation/research/Invention.cpp @@ -10,29 +10,17 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Invention::Invention( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - bool new_is_news, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - crime_set_t&& new_enabled_crimes, - bool new_unlocks_gas_attack, - bool new_unlocks_gas_defence, - ConditionScript&& new_limit, - ConditionalWeightBase&& new_chance, + index_t new_index, std::string_view new_identifier, ModifierValue&& new_values, bool new_is_news, + unit_set_t&& new_activated_units, building_set_t&& new_activated_buildings, crime_set_t&& new_enabled_crimes, + bool new_unlocks_gas_attack, bool new_unlocks_gas_defence, ConditionScript&& new_limit, ConditionalWeightBase&& new_chance, memory::vector&& new_raw_associated_tech_identifiers -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(new_values), modifier_type_t::INVENTION }, - is_news { new_is_news }, - activated_units { std::move(new_activated_units) }, - activated_buildings { std::move(new_activated_buildings) }, - enabled_crimes { std::move(new_enabled_crimes) }, - unlocks_gas_attack { new_unlocks_gas_attack }, - unlocks_gas_defence { new_unlocks_gas_defence }, - limit { std::move(new_limit) }, - chance { std::move(new_chance) }, - raw_associated_tech_identifiers { std::move(new_raw_associated_tech_identifiers) } {} +) + : HasIndex { new_index }, Modifier { new_identifier, std::move(new_values), modifier_type_t::INVENTION }, + is_news { new_is_news }, activated_units { std::move(new_activated_units) }, + activated_buildings { std::move(new_activated_buildings) }, enabled_crimes { std::move(new_enabled_crimes) }, + unlocks_gas_attack { new_unlocks_gas_attack }, unlocks_gas_defence { new_unlocks_gas_defence }, + limit { std::move(new_limit) }, chance { std::move(new_chance) }, + raw_associated_tech_identifiers { std::move(new_raw_associated_tech_identifiers) } {} bool Invention::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -57,8 +45,7 @@ bool InventionManager::add_invention( return inventions.emplace_item( identifier, Invention::index_t { get_invention_count() }, identifier, std::move(values), news, std::move(activated_units), std::move(activated_buildings), std::move(enabled_crimes), unlock_gas_attack, - unlock_gas_defence, std::move(limit), std::move(chance), - std::move(raw_associated_tech_identifiers) + unlock_gas_defence, std::move(limit), std::move(chance), std::move(raw_associated_tech_identifiers) ); } @@ -87,22 +74,19 @@ bool InventionManager::load_inventions_file( memory::vector found_tech_ids; auto parse_limit_and_find_techs = [&](ast::NodeCPtr node) -> bool { + if (!limit.expect_script()(node)) { + return false; + } + + expect_dictionary([&](std::string_view key, ast::NodeCPtr /*value*/) -> bool { + if (tech_manager.get_technology_by_identifier(key) != nullptr) { + found_tech_ids.push_back(memory::string(key)); + } + return true; + })(node); - if (!limit.expect_script()(node)) { - return false; - } - - expect_dictionary( - [&](std::string_view key, ast::NodeCPtr /*value*/) -> bool { - if (tech_manager.get_technology_by_identifier(key) != nullptr) { - found_tech_ids.push_back(memory::string(key)); - } - return true; - } - )(node); - - return true; - }; + return true; + }; bool ret = NodeTools::expect_dictionary_keys_and_default( modifier_manager.expect_base_country_modifier(loose_modifiers), diff --git a/src/openvic-simulation/research/Invention.hpp b/src/openvic-simulation/research/Invention.hpp index 9fe755763..0c0566c06 100644 --- a/src/openvic-simulation/research/Invention.hpp +++ b/src/openvic-simulation/research/Invention.hpp @@ -23,7 +23,7 @@ namespace OpenVic { struct Invention : HasIndex, Modifier { friend struct InventionManager; - //TODO implement limit and chance + // TODO implement limit and chance using unit_set_t = ordered_set; using building_set_t = ordered_set; using crime_set_t = ordered_set; @@ -31,7 +31,7 @@ namespace OpenVic { private: ConditionScript PROPERTY(limit); ConditionalWeightBase PROPERTY(chance); - + memory::vector raw_associated_tech_identifiers; bool parse_scripts(DefinitionManager const& definition_manager); @@ -45,18 +45,10 @@ namespace OpenVic { const bool unlocks_gas_defence; Invention( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - bool new_is_news, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - crime_set_t&& new_enabled_crimes, - bool new_unlocks_gas_attack, - bool new_unlocks_gas_defence, - ConditionScript&& new_limit, - ConditionalWeightBase&& new_chance, - memory::vector&& new_raw_associated_tech_identifiers + index_t new_index, std::string_view new_identifier, ModifierValue&& new_values, bool new_is_news, + unit_set_t&& new_activated_units, building_set_t&& new_activated_buildings, crime_set_t&& new_enabled_crimes, + bool new_unlocks_gas_attack, bool new_unlocks_gas_defence, ConditionScript&& new_limit, + ConditionalWeightBase&& new_chance, memory::vector&& new_raw_associated_tech_identifiers ); Invention(Invention&&) = default; }; @@ -73,13 +65,13 @@ namespace OpenVic { ); bool load_inventions_file( - TechnologyManager const& tech_manager, - ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, - BuildingTypeManager const& building_type_manager, CrimeManager const& crime_manager, ast::NodeCPtr root + TechnologyManager const& tech_manager, ModifierManager const& modifier_manager, + UnitTypeManager const& unit_type_manager, BuildingTypeManager const& building_type_manager, + CrimeManager const& crime_manager, ast::NodeCPtr root ); // inventions/*.txt bool generate_invention_links(TechnologyManager& tech_manager); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/research/Technology.cpp b/src/openvic-simulation/research/Technology.cpp index 76b5ca0f8..1e60f03d0 100644 --- a/src/openvic-simulation/research/Technology.cpp +++ b/src/openvic-simulation/research/Technology.cpp @@ -14,29 +14,16 @@ TechnologyArea::TechnologyArea(std::string_view new_identifier, TechnologyFolder : HasIdentifier { new_identifier }, folder { new_folder } {} Technology::Technology( - std::string_view new_identifier, - index_t new_index, - TechnologyArea const& new_area, - Date::year_t new_year, - fixed_point_t new_cost, - area_index_t new_index_in_area, - bool new_unciv_military, - std::optional&& new_unit_variant, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - ModifierValue&& new_values, - ConditionalWeightFactorMul&& new_ai_chance -) : Modifier { new_identifier, std::move(new_values), modifier_type_t::TECHNOLOGY }, - HasIndex { new_index }, - area { new_area }, - year { new_year }, - cost { new_cost }, - index_in_area { new_index_in_area }, - unciv_military { new_unciv_military }, - unit_variant { std::move(new_unit_variant) }, - activated_units { std::move(new_activated_units) }, - activated_buildings { std::move(new_activated_buildings) }, - ai_chance { std::move(new_ai_chance) } {} + std::string_view new_identifier, index_t new_index, TechnologyArea const& new_area, Date::year_t new_year, + fixed_point_t new_cost, area_index_t new_index_in_area, bool new_unciv_military, + std::optional&& new_unit_variant, unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, ModifierValue&& new_values, ConditionalWeightFactorMul&& new_ai_chance +) + : Modifier { new_identifier, std::move(new_values), modifier_type_t::TECHNOLOGY }, HasIndex { new_index }, + area { new_area }, year { new_year }, cost { new_cost }, index_in_area { new_index_in_area }, + unciv_military { new_unciv_military }, unit_variant { std::move(new_unit_variant) }, + activated_units { std::move(new_activated_units) }, activated_buildings { std::move(new_activated_buildings) }, + ai_chance { std::move(new_ai_chance) } {} bool Technology::parse_scripts(DefinitionManager const& definition_manager) { return ai_chance.parse_scripts(definition_manager); @@ -51,10 +38,7 @@ bool TechnologyManager::add_technology_folder(std::string_view identifier) { return false; } - return technology_folders.emplace_item( - identifier, - identifier, TechnologyFolder::index_t { get_technology_folder_count() } - ); + return technology_folders.emplace_item(identifier, identifier, TechnologyFolder::index_t { get_technology_folder_count() }); } bool TechnologyManager::add_technology_area(std::string_view identifier, TechnologyFolder const& folder) { @@ -63,10 +47,7 @@ bool TechnologyManager::add_technology_area(std::string_view identifier, Technol return false; } - return technology_areas.emplace_item( - identifier, - identifier, folder - ); + return technology_areas.emplace_item(identifier, identifier, folder); } bool TechnologyManager::add_technology( @@ -97,20 +78,10 @@ bool TechnologyManager::add_technology( } if (!technologies.emplace_item( - identifier, - identifier, - Technology::index_t { get_technology_count() }, - *area, - year, - cost, - static_cast(index_in_area), - unciv_military, - std::move(unit_variant), - std::move(activated_units), - std::move(activated_buildings), - std::move(values), - std::move(ai_chance) - )) { + identifier, identifier, Technology::index_t { get_technology_count() }, *area, year, cost, + static_cast(index_in_area), unciv_military, std::move(unit_variant), + std::move(activated_units), std::move(activated_buildings), std::move(values), std::move(ai_chance) + )) { return false; } @@ -124,10 +95,7 @@ bool TechnologyManager::add_technology_school(std::string_view identifier, Modif return false; } - return technology_schools.emplace_item( - identifier, - identifier, std::move(values) - ); + return technology_schools.emplace_item(identifier, identifier, std::move(values)); } bool TechnologyManager::load_technology_file_folders_and_areas(ast::NodeCPtr root) { @@ -165,9 +133,7 @@ bool TechnologyManager::load_technology_file_folders_and_areas(ast::NodeCPtr roo )(root); } -bool TechnologyManager::load_technology_file_schools( - ModifierManager const& modifier_manager, ast::NodeCPtr root -) { +bool TechnologyManager::load_technology_file_schools(ModifierManager const& modifier_manager, ast::NodeCPtr root) { if (!technology_folders.is_locked() || !technology_areas.is_locked()) { spdlog::error_s("Cannot load technology schools until technology folders and areas are locked!"); return false; @@ -203,9 +169,7 @@ bool TechnologyManager::load_technologies_file( ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root ) { - return expect_dictionary_reserve_length(technologies, [this, &modifier_manager, &unit_type_manager, &building_type_manager]( - std::string_view tech_key, ast::NodeCPtr tech_value - ) -> bool { + return expect_dictionary_reserve_length(technologies, [this, &modifier_manager, &unit_type_manager, &building_type_manager](std::string_view tech_key, ast::NodeCPtr tech_value) -> bool { using enum scope_type_t; ModifierValue modifiers; @@ -248,7 +212,7 @@ bool TechnologyManager::generate_modifiers(ModifierManager& modifier_manager) co IndexedFlatMap& research_bonus_effects = modifier_manager.modifier_effect_cache.research_bonus_effects; - research_bonus_effects = std::move(decltype(ModifierEffectCache::research_bonus_effects){get_technology_folders()}); + research_bonus_effects = std::move(decltype(ModifierEffectCache::research_bonus_effects) { get_technology_folders() }); bool ret = true; @@ -292,8 +256,8 @@ bool TechnologyManager::generate_technology_lists() { for (TechnologyArea const& area : technology_areas.get_items()) { if (area.get_technologies().size() != area.get_tech_count()) { spdlog::error_s( - "Technology area \"{}\" has a mismatch between tech count ({}) and tech list size ({})!", - area, area.get_tech_count(), area.get_technologies().size() + "Technology area \"{}\" has a mismatch between tech count ({}) and tech list size ({})!", area, + area.get_tech_count(), area.get_technologies().size() ); ret = false; } diff --git a/src/openvic-simulation/research/Technology.hpp b/src/openvic-simulation/research/Technology.hpp index 9ec16e2b6..0c45d069d 100644 --- a/src/openvic-simulation/research/Technology.hpp +++ b/src/openvic-simulation/research/Technology.hpp @@ -71,18 +71,10 @@ namespace OpenVic { const building_set_t activated_buildings; Technology( - std::string_view new_identifier, - index_t new_index, - TechnologyArea const& new_area, - Date::year_t new_year, - fixed_point_t new_cost, - area_index_t new_index_in_area, - bool new_unciv_military, - std::optional&& new_unit_variant, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - ModifierValue&& new_values, - ConditionalWeightFactorMul&& new_ai_chance + std::string_view new_identifier, index_t new_index, TechnologyArea const& new_area, Date::year_t new_year, + fixed_point_t new_cost, area_index_t new_index_in_area, bool new_unciv_military, + std::optional&& new_unit_variant, unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, ModifierValue&& new_values, ConditionalWeightFactorMul&& new_ai_chance ); Technology(Technology&&) = default; diff --git a/src/openvic-simulation/scripts/Condition.cpp b/src/openvic-simulation/scripts/Condition.cpp index 08cc1d384..5a86cb9d9 100644 --- a/src/openvic-simulation/scripts/Condition.cpp +++ b/src/openvic-simulation/scripts/Condition.cpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/utility/Containers.hpp" using namespace OpenVic; @@ -14,19 +14,18 @@ using enum scope_type_t; using enum identifier_type_t; Condition::Condition( - std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, - scope_type_t new_scope_change, identifier_type_t new_key_identifier_type, - identifier_type_t new_value_identifier_type -) : HasIdentifier { new_identifier }, value_type { new_value_type }, scope { new_scope }, - scope_change { new_scope_change }, key_identifier_type { new_key_identifier_type }, - value_identifier_type { new_value_identifier_type } {} + std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, scope_type_t new_scope_change, + identifier_type_t new_key_identifier_type, identifier_type_t new_value_identifier_type +) + : HasIdentifier { new_identifier }, value_type { new_value_type }, scope { new_scope }, scope_change { new_scope_change }, + key_identifier_type { new_key_identifier_type }, value_identifier_type { new_value_identifier_type } {} ConditionNode::ConditionNode( - Condition const* new_condition, value_t&& new_value, bool new_valid, - HasIdentifier const* new_condition_key_item, + Condition const* new_condition, value_t&& new_value, bool new_valid, HasIdentifier const* new_condition_key_item, HasIdentifier const* new_condition_value_item -) : condition { new_condition }, value { std::move(new_value) }, valid { new_valid }, - condition_key_item { new_condition_key_item }, condition_value_item { new_condition_key_item } {} +) + : condition { new_condition }, value { std::move(new_value) }, valid { new_valid }, + condition_key_item { new_condition_key_item }, condition_value_item { new_condition_key_item } {} bool ConditionManager::add_condition( std::string_view identifier, value_type_t value_type, scope_type_t scope, scope_type_t scope_change, @@ -38,17 +37,11 @@ bool ConditionManager::add_condition( } if (value_type == NO_TYPE || value_type > MAX_VALUE) { - spdlog::error_s( - "Condition {} has invalid value type: {}", - identifier, static_cast(value_type) - ); + spdlog::error_s("Condition {} has invalid value type: {}", identifier, static_cast(value_type)); return false; } if (scope == NO_SCOPE || scope > MAX_SCOPE) { - spdlog::error_s( - "Condition {} has invalid scope: {}", - identifier, static_cast(scope) - ); + spdlog::error_s("Condition {} has invalid scope: {}", identifier, static_cast(scope)); return false; } @@ -65,8 +58,7 @@ bool ConditionManager::add_condition( } return conditions.emplace_item( - identifier, - identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type + identifier, identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type ); } @@ -76,7 +68,7 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana /* Special Scopes */ ret &= add_condition("THIS", GROUP, COUNTRY, THIS); ret &= add_condition("FROM", GROUP, COUNTRY, FROM); - ret &= add_condition("independence", GROUP, COUNTRY, COUNTRY); //only from rebels! + ret &= add_condition("independence", GROUP, COUNTRY, COUNTRY); // only from rebels! /* Trigger Country Scopes */ ret &= add_condition("all_core", GROUP, COUNTRY, PROVINCE); @@ -114,7 +106,7 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana /* Global Conditions */ ret &= add_condition("year", INTEGER, COUNTRY); ret &= add_condition("month", INTEGER, COUNTRY); - ret &= add_condition("has_global_flag", IDENTIFIER, COUNTRY, NO_SCOPE, NO_IDENTIFIER, GLOBAL_FLAG); + ret &= add_condition("has_global_flag", IDENTIFIER, COUNTRY, NO_SCOPE, NO_IDENTIFIER, GLOBAL_FLAG); ret &= add_condition("is_canal_enabled", INTEGER, COUNTRY); ret &= add_condition("always", BOOLEAN, COUNTRY); ret &= add_condition("world_wars_enabled", BOOLEAN, COUNTRY); @@ -341,111 +333,64 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana ret &= add_condition("type", IDENTIFIER, POP, NO_SCOPE, NO_IDENTIFIER, POP_TYPE); const auto import_identifiers = [this, &ret]( - memory::vector const& identifiers, - value_type_t value_type, - scope_type_t scope, - scope_type_t scope_change = NO_SCOPE, - identifier_type_t key_identifier_type = NO_IDENTIFIER, - identifier_type_t value_identifier_type = NO_IDENTIFIER - ) -> void { + memory::vector const& identifiers, value_type_t value_type, + scope_type_t scope, scope_type_t scope_change = NO_SCOPE, + identifier_type_t key_identifier_type = NO_IDENTIFIER, + identifier_type_t value_identifier_type = NO_IDENTIFIER + ) -> void { for (std::string_view const& identifier : identifiers) { - ret &= add_condition( - identifier, value_type, scope, scope_change, - key_identifier_type, value_identifier_type - ); + ret &= add_condition(identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type); } }; /* Scopes from other registries */ import_identifiers( - definition_manager.get_country_definition_manager().get_country_definition_identifiers(), - GROUP, - COUNTRY, - COUNTRY, - COUNTRY_TAG, - NO_IDENTIFIER + definition_manager.get_country_definition_manager().get_country_definition_identifiers(), GROUP, COUNTRY, COUNTRY, + COUNTRY_TAG, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_map_definition().get_region_identifiers(), - GROUP, - COUNTRY, - STATE, - REGION, - NO_IDENTIFIER + definition_manager.get_map_definition().get_region_identifiers(), GROUP, COUNTRY, STATE, REGION, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_map_definition().get_province_definition_identifiers(), - GROUP, - COUNTRY, - PROVINCE, - PROVINCE_ID, + definition_manager.get_map_definition().get_province_definition_identifiers(), GROUP, COUNTRY, PROVINCE, PROVINCE_ID, NO_IDENTIFIER ); /* Conditions from other registries */ import_identifiers( - definition_manager.get_politics_manager().get_ideology_manager().get_ideology_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - IDEOLOGY, - NO_IDENTIFIER + definition_manager.get_politics_manager().get_ideology_manager().get_ideology_identifiers(), REAL, COUNTRY, NO_SCOPE, + IDEOLOGY, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_reform_group_identifiers(), - IDENTIFIER, - COUNTRY, - NO_SCOPE, - REFORM_GROUP, - REFORM + definition_manager.get_politics_manager().get_issue_manager().get_reform_group_identifiers(), IDENTIFIER, COUNTRY, + NO_SCOPE, REFORM_GROUP, REFORM ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_reform_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - REFORM, + definition_manager.get_politics_manager().get_issue_manager().get_reform_identifiers(), REAL, COUNTRY, NO_SCOPE, REFORM, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_party_policy_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - PARTY_POLICY, - NO_IDENTIFIER + definition_manager.get_politics_manager().get_issue_manager().get_party_policy_identifiers(), REAL, COUNTRY, NO_SCOPE, + PARTY_POLICY, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_pop_manager().get_pop_type_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - POP_TYPE, - NO_IDENTIFIER + definition_manager.get_pop_manager().get_pop_type_identifiers(), REAL, COUNTRY, NO_SCOPE, POP_TYPE, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_research_manager().get_technology_manager().get_technology_identifiers(), - BOOLEAN_INT, - COUNTRY, - NO_SCOPE, - TECHNOLOGY, - NO_IDENTIFIER + definition_manager.get_research_manager().get_technology_manager().get_technology_identifiers(), BOOLEAN_INT, COUNTRY, + NO_SCOPE, TECHNOLOGY, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_economy_manager().get_good_definition_manager().get_good_definition_identifiers(), - INTEGER, - COUNTRY, - NO_SCOPE, - TRADE_GOOD, - NO_IDENTIFIER + definition_manager.get_economy_manager().get_good_definition_manager().get_good_definition_identifiers(), INTEGER, + COUNTRY, NO_SCOPE, TRADE_GOOD, NO_IDENTIFIER ); lock_conditions(); @@ -462,29 +407,31 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana } callback_t ConditionManager::expect_parse_identifier( - DefinitionManager const& definition_manager, identifier_type_t identifier_type, - callback_t callback + DefinitionManager const& definition_manager, identifier_type_t identifier_type, callback_t callback ) const { return [this, &definition_manager, identifier_type, callback](std::string_view identifier) mutable -> bool { HasIdentifier const* identified = nullptr; - #define EXPECT_CALL(type, name, manager, ...) \ - if (share_identifier_type(identifier_type, type)) { \ - identified = manager.get_##name##_by_identifier(identifier); \ - if (identified != nullptr) { \ - return callback(identified); \ - } __VA_OPT__(else { \ - /* TODO: the set is just a placeholder for actual logic */ \ - static const case_insensitive_string_set_t chances { __VA_ARGS__ }; \ - if (chances.contains(identifier)) { \ - return true; \ - } \ - }) \ - } +#define EXPECT_CALL(type, name, manager, ...) \ + if (share_identifier_type(identifier_type, type)) { \ + identified = manager.get_##name##_by_identifier(identifier); \ + if (identified != nullptr) { \ + return callback(identified); \ + } \ + __VA_OPT__(else { \ + /* TODO: the set is just a placeholder for actual logic */ \ + static const case_insensitive_string_set_t chances { __VA_ARGS__ }; \ + if (chances.contains(identifier)) { \ + return true; \ + } \ + }) \ + } - //TODO: placeholder for not implemented stuff - #define EXPECT_CALL_PLACEHOLDER(type) \ - if (share_identifier_type(identifier_type, type)) { return true; } +// TODO: placeholder for not implemented stuff +#define EXPECT_CALL_PLACEHOLDER(type) \ + if (share_identifier_type(identifier_type, type)) { \ + return true; \ + } EXPECT_CALL_PLACEHOLDER(VARIABLE); EXPECT_CALL_PLACEHOLDER(GLOBAL_FLAG); @@ -511,7 +458,9 @@ callback_t ConditionManager::expect_parse_identifier( EXPECT_CALL(BUILDING, building_type, definition_manager.get_economy_manager().get_building_type_manager(), "FACTORY"); EXPECT_CALL(CASUS_BELLI, wargoal_type, definition_manager.get_military_manager().get_wargoal_type_manager()); EXPECT_CALL(GOVERNMENT_TYPE, government_type, definition_manager.get_politics_manager().get_government_type_manager()); - EXPECT_CALL(COUNTRY_EVENT_MODIFIER | PROVINCE_EVENT_MODIFIER, event_modifier, definition_manager.get_modifier_manager()); + EXPECT_CALL( + COUNTRY_EVENT_MODIFIER | PROVINCE_EVENT_MODIFIER, event_modifier, definition_manager.get_modifier_manager() + ); EXPECT_CALL(COUNTRY_EVENT_MODIFIER, triggered_modifier, definition_manager.get_modifier_manager()); EXPECT_CALL(NATIONAL_VALUE, national_value, definition_manager.get_politics_manager().get_national_value_manager()); EXPECT_CALL( @@ -521,8 +470,8 @@ callback_t ConditionManager::expect_parse_identifier( EXPECT_CALL(CRIME, crime_modifier, definition_manager.get_crime_manager()); EXPECT_CALL(TERRAIN, terrain_type, definition_manager.get_map_definition().get_terrain_type_manager()); - #undef EXPECT_CALL - #undef EXPECT_CALL_PLACEHOLDER +#undef EXPECT_CALL +#undef EXPECT_CALL_PLACEHOLDER return false; }; @@ -532,9 +481,8 @@ node_callback_t ConditionManager::expect_condition_node( DefinitionManager const& definition_manager, Condition const& condition, scope_type_t current_scope, scope_type_t this_scope, scope_type_t from_scope, callback_t callback ) const { - return [this, &definition_manager, &condition, callback, current_scope, this_scope, from_scope]( - ast::NodeCPtr node - ) mutable -> bool { + return [this, &definition_manager, &condition, callback, current_scope, this_scope, + from_scope](ast::NodeCPtr node) mutable -> bool { bool ret = false; ConditionNode::value_t value; @@ -547,19 +495,14 @@ node_callback_t ConditionManager::expect_condition_node( HasIdentifier const* value_item = nullptr; - const auto get_identifiable = [this, &definition_manager]( - identifier_type_t item_type, std::string_view id, bool log - ) -> HasIdentifier const* { + const auto get_identifiable = + [this, &definition_manager](identifier_type_t item_type, std::string_view id, bool log) -> HasIdentifier const* { HasIdentifier const* keyval = nullptr; - bool ret = expect_parse_identifier( - definition_manager, - item_type, - assign_variable_callback(keyval) - )(id); + bool ret = expect_parse_identifier(definition_manager, item_type, assign_variable_callback(keyval))(id); if (log && !ret) { spdlog::error_s( - "Invalid identifier {} expected to have type {} found during condition node parsing!", - id, fmt::underlying(item_type) + "Invalid identifier {} expected to have type {} found during condition node parsing!", id, + fmt::underlying(item_type) ); } return keyval; @@ -571,8 +514,7 @@ node_callback_t ConditionManager::expect_condition_node( if (ret) { value = ConditionNode::string_t { value_identifier }; value_item = get_identifiable( - value_identifier_type, - value_identifier, + value_identifier_type, value_identifier, value_type == IDENTIFIER // don't log if there's a fallback ); ret |= value_item != nullptr; @@ -581,35 +523,27 @@ node_callback_t ConditionManager::expect_condition_node( if (!ret && share_value_type(value_type, STRING)) { std::string_view value_identifier {}; - bool local_ret = expect_identifier_or_string( - assign_variable_callback(value_identifier) - )(node); + bool local_ret = expect_identifier_or_string(assign_variable_callback(value_identifier))(node); ret |= local_ret; if (local_ret) { value = ConditionNode::string_t { value_identifier }; } } - ret |= (!ret && share_value_type(value_type, BOOLEAN)) - && expect_bool(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, BOOLEAN_INT)) - && expect_int_bool(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, INTEGER)) - && expect_uint64(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, REAL)) - && expect_fixed_point(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, BOOLEAN)) && expect_bool(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, BOOLEAN_INT)) && expect_int_bool(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, INTEGER)) && expect_uint64(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, REAL)) && expect_fixed_point(assign_variable_callback(value))(node); - //entries with magic syntax, thanks paradox! + // entries with magic syntax, thanks paradox! if (!ret && share_value_type(value_type, COMPLEX)) { - const auto expect_pair = [&ret, &value, node]( - std::string_view identifier_key, std::string_view value_key - ) -> void { + const auto expect_pair = [&ret, &value, node](std::string_view identifier_key, std::string_view value_key) -> void { std::string_view pair_identifier {}; fixed_point_t pair_value = 0; - ret |= expect_dictionary_keys( - identifier_key, ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(pair_identifier)), - value_key, ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pair_value)) - )(node); + ret |= + expect_dictionary_keys(identifier_key, ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(pair_identifier)), value_key, ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pair_value)))( + node + ); if (ret) { value = ConditionNode::identifier_real_t { pair_identifier, pair_value }; } @@ -617,11 +551,10 @@ node_callback_t ConditionManager::expect_condition_node( if (identifier == "can_build_railway_in_capital" || identifier == "can_build_fort_in_capital") { bool in_whole_capital_state = false, limit_to_world_greatest_level = false; - ret |= expect_dictionary_keys( - "in_whole_capital_state", ONE_EXACTLY, expect_bool(assign_variable_callback(in_whole_capital_state)), - "limit_to_world_greatest_level", ONE_EXACTLY, - expect_bool(assign_variable_callback(limit_to_world_greatest_level)) - )(node); + ret |= + expect_dictionary_keys("in_whole_capital_state", ONE_EXACTLY, expect_bool(assign_variable_callback(in_whole_capital_state)), "limit_to_world_greatest_level", ONE_EXACTLY, expect_bool(assign_variable_callback(limit_to_world_greatest_level)))( + node + ); if (ret) { value = ConditionNode::double_boolean_t { in_whole_capital_state, limit_to_world_greatest_level }; } @@ -638,9 +571,10 @@ node_callback_t ConditionManager::expect_condition_node( } else if (identifier == "work_available") { // { worker = [type] } std::string_view worker {}; - ret |= expect_dictionary_keys( - "worker", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(worker)) - )(node); + ret |= + expect_dictionary_keys("worker", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(worker)))( + node + ); if (ret) { value = ConditionNode::string_t { worker }; } @@ -648,18 +582,15 @@ node_callback_t ConditionManager::expect_condition_node( spdlog::error_s("Attempted to parse unknown complex condition {}!", identifier); } - #undef EXPECT_PAIR +#undef EXPECT_PAIR } if (!ret && share_value_type(value_type, GROUP)) { ConditionNode::condition_list_t node_list; - ret |= expect_condition_node_list( - definition_manager, - scope_change == NO_SCOPE ? current_scope : scope_change, - this_scope, - from_scope, - vector_callback(node_list) - )(node); + ret |= + expect_condition_node_list(definition_manager, scope_change == NO_SCOPE ? current_scope : scope_change, this_scope, from_scope, vector_callback(node_list))( + node + ); value = std::move(node_list); } @@ -673,8 +604,8 @@ node_callback_t ConditionManager::expect_condition_node( if (!share_scope_type(scope, effective_current_scope) && effective_current_scope > scope) { spdlog::warn_s( - "Condition or scope {} was found in wrong scope {}, expected {}!", - identifier, fmt::underlying(effective_current_scope), fmt::underlying(scope) + "Condition or scope {} was found in wrong scope {}, expected {}!", identifier, + fmt::underlying(effective_current_scope), fmt::underlying(scope) ); ret = false; } @@ -689,22 +620,10 @@ node_callback_t ConditionManager::expect_condition_node( if (!ret) { spdlog::warn_s("Could not parse condition node {}, will always evaluate to false!", identifier); Condition const* always_condition = conditions.get_item_by_identifier("always"); - return callback({ - always_condition, - std::move(ConditionNode::value_t(false)), - true, - key_item, - value_item - }); + return callback({ always_condition, std::move(ConditionNode::value_t(false)), true, key_item, value_item }); } - ret &= callback({ - &condition, - std::move(value), - ret, - key_item, - value_item - }); + ret &= callback({ &condition, std::move(value), ret, key_item, value_item }); return ret; }; @@ -726,36 +645,43 @@ node_callback_t ConditionManager::expect_condition_node_list( callback_t callback, bool top_scope ) const { return [this, &definition_manager, callback, current_scope, this_scope, from_scope, top_scope](ast::NodeCPtr node) -> bool { - const auto expect_node = [this, &definition_manager, callback, current_scope, this_scope, from_scope] - (Condition const& condition, ast::NodeCPtr node) -> bool { - return expect_condition_node( - definition_manager, condition, current_scope, this_scope, from_scope, callback - )(node); + const auto expect_node = [this, &definition_manager, callback, current_scope, this_scope, + from_scope](Condition const& condition, ast::NodeCPtr node) -> bool { + return expect_condition_node(definition_manager, condition, current_scope, this_scope, from_scope, callback)(node); }; const auto invalid_condition_node = [this, &expect_node, top_scope](std::string_view id, ast::NodeCPtr node) -> bool { - if (top_scope && id == "factor") { return true; } + if (top_scope && id == "factor") { + return true; + } if (ast::FlatValue const* node_name = dryad::node_try_cast(node); node_name && node_name->value()) { spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", - id, node_name->value().view() + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", id, + node_name->value().view() ); // TODO: make this error message more useful by pinning down node to an actual file or something } else if (ast::ListValue const* list_values = dryad::node_try_cast(node); list_values) { for (ast::Statement const* statement : list_values->statements()) { - dryad::visit_node(statement, - [&](ast::AssignStatement const* assign){ - if (ast::FlatValue const* node_name = dryad::node_try_cast(assign->left()); node_name && node_name->value()) { + dryad::visit_node( + statement, + [&](ast::AssignStatement const* assign) { + if (ast::FlatValue const* node_name = dryad::node_try_cast(assign->left()); + node_name && node_name->value()) { spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to " + "false!", id, node_name->value().view() - ); // TODO: make this error message more useful by pinning down node to an actual file or something + ); // TODO: make this error message more useful by pinning down node to an actual file or + // something } }, [&](ast::ValueStatement const* value) { - if (ast::FlatValue const* node_name = dryad::node_try_cast(value->value()); node_name && node_name->value()) { + if (ast::FlatValue const* node_name = dryad::node_try_cast(value->value()); + node_name && node_name->value()) { spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to " + "false!", id, node_name->value().view() - ); // TODO: make this error message more useful by pinning down node to an actual file or something + ); // TODO: make this error message more useful by pinning down node to an actual file or + // something } } ); @@ -764,28 +690,21 @@ node_callback_t ConditionManager::expect_condition_node_list( return true; }; - return conditions.expect_item_dictionary_and_default( - invalid_condition_node, - expect_node - )(node); + return conditions.expect_item_dictionary_and_default(invalid_condition_node, expect_node)(node); }; } bool ConditionManager::expect_condition_script( - DefinitionManager const& definition_manager, scope_type_t initial_scope, scope_type_t this_scope, - scope_type_t from_scope, NodeTools::callback_t callback, std::span nodes + DefinitionManager const& definition_manager, scope_type_t initial_scope, scope_type_t this_scope, scope_type_t from_scope, + NodeTools::callback_t callback, std::span nodes ) const { ConditionNode::condition_list_t conds; bool ret = true; for (const ast::NodeCPtr node : nodes) { - ret &= expect_condition_node_list( - definition_manager, - initial_scope, - this_scope, - from_scope, - NodeTools::vector_callback(conds), - true - )(node); + ret &= + expect_condition_node_list(definition_manager, initial_scope, this_scope, from_scope, NodeTools::vector_callback(conds), true)( + node + ); } ret &= callback({ root_condition, std::move(conds), true }); diff --git a/src/openvic-simulation/scripts/Condition.hpp b/src/openvic-simulation/scripts/Condition.hpp index 2e9633531..f074a2aab 100644 --- a/src/openvic-simulation/scripts/Condition.hpp +++ b/src/openvic-simulation/scripts/Condition.hpp @@ -16,69 +16,72 @@ namespace OpenVic { struct DefinitionManager; enum class value_type_t : uint8_t { - NO_TYPE = 0, - IDENTIFIER = 1 << 0, - STRING = 1 << 1, - BOOLEAN = 1 << 2, + NO_TYPE = 0, + IDENTIFIER = 1 << 0, + STRING = 1 << 1, + BOOLEAN = 1 << 2, BOOLEAN_INT = 1 << 3, - INTEGER = 1 << 4, - REAL = 1 << 5, - COMPLEX = 1 << 6, - GROUP = 1 << 7, - MAX_VALUE = (1 << 8) - 1 + INTEGER = 1 << 4, + REAL = 1 << 5, + COMPLEX = 1 << 6, + GROUP = 1 << 7, + MAX_VALUE = (1 << 8) - 1 }; // Order matters in this enum, for the fallback system to work // smaller entities must have smaller integers associated! - enum class scope_type_t : uint8_t { //TODO: maybe distinguish TRANSPARENT from NO_SCOPE - NO_SCOPE = 0, - POP = 1 << 0, - PROVINCE = 1 << 1, - STATE = 1 << 2, - COUNTRY = 1 << 3, - THIS = 1 << 4, - FROM = 1 << 5, - MAX_SCOPE = (1 << 6) - 1 + enum class scope_type_t : uint8_t { // TODO: maybe distinguish TRANSPARENT from NO_SCOPE + NO_SCOPE = 0, + POP = 1 << 0, + PROVINCE = 1 << 1, + STATE = 1 << 2, + COUNTRY = 1 << 3, + THIS = 1 << 4, + FROM = 1 << 5, + MAX_SCOPE = (1 << 6) - 1 }; enum class identifier_type_t : uint32_t { - NO_IDENTIFIER = 0, - VARIABLE = 1 << 0, - GLOBAL_FLAG = 1 << 1, - COUNTRY_FLAG = 1 << 2, - PROVINCE_FLAG = 1 << 3, - COUNTRY_TAG = 1 << 4, - PROVINCE_ID = 1 << 5, - REGION = 1 << 6, - IDEOLOGY = 1 << 7, - REFORM_GROUP = 1 << 8, - REFORM = 1 << 9, - PARTY_POLICY = 1 << 10, - POP_TYPE = 1 << 11, - POP_STRATA = 1 << 12, - TECHNOLOGY = 1 << 13, - INVENTION = 1 << 14, - TECH_SCHOOL = 1 << 15, - CULTURE = 1 << 16, - CULTURE_GROUP = 1 << 17, - RELIGION = 1 << 18, - TRADE_GOOD = 1 << 19, - BUILDING = 1 << 20, - CASUS_BELLI = 1 << 21, + NO_IDENTIFIER = 0, + VARIABLE = 1 << 0, + GLOBAL_FLAG = 1 << 1, + COUNTRY_FLAG = 1 << 2, + PROVINCE_FLAG = 1 << 3, + COUNTRY_TAG = 1 << 4, + PROVINCE_ID = 1 << 5, + REGION = 1 << 6, + IDEOLOGY = 1 << 7, + REFORM_GROUP = 1 << 8, + REFORM = 1 << 9, + PARTY_POLICY = 1 << 10, + POP_TYPE = 1 << 11, + POP_STRATA = 1 << 12, + TECHNOLOGY = 1 << 13, + INVENTION = 1 << 14, + TECH_SCHOOL = 1 << 15, + CULTURE = 1 << 16, + CULTURE_GROUP = 1 << 17, + RELIGION = 1 << 18, + TRADE_GOOD = 1 << 19, + BUILDING = 1 << 20, + CASUS_BELLI = 1 << 21, GOVERNMENT_TYPE = 1 << 22, COUNTRY_EVENT_MODIFIER = 1 << 23, PROVINCE_EVENT_MODIFIER = 1 << 24, - NATIONAL_VALUE = 1 << 25, - CULTURE_UNION = 1 << 26, // same as COUNTRY_TAG but also accepts scope this_union - CONTINENT = 1 << 27, - CRIME = 1 << 28, - TERRAIN = 1 << 29 + NATIONAL_VALUE = 1 << 25, + CULTURE_UNION = 1 << 26, // same as COUNTRY_TAG but also accepts scope this_union + CONTINENT = 1 << 27, + CRIME = 1 << 28, + TERRAIN = 1 << 29 }; /* Allows enum types to be used with bitwise operators. */ - template<> struct enable_bitfield : std::true_type {}; - template<> struct enable_bitfield : std::true_type {}; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; /* Returns true if the values have any bit in common. */ inline constexpr bool share_value_type(value_type_t lhs, value_type_t rhs) { @@ -207,9 +210,8 @@ namespace OpenVic { const identifier_type_t value_identifier_type; Condition( - std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, - scope_type_t new_scope_change, identifier_type_t new_key_identifier_type, - identifier_type_t new_value_identifier_type + std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, scope_type_t new_scope_change, + identifier_type_t new_key_identifier_type, identifier_type_t new_value_identifier_type ); Condition(Condition&&) = default; }; @@ -225,9 +227,8 @@ namespace OpenVic { using real_t = fixed_point_t; using identifier_real_t = std::pair; using condition_list_t = memory::vector; - using value_t = std::variant< - string_t, boolean_t, double_boolean_t, integer_t, real_t, identifier_real_t, condition_list_t - >; + using value_t = + std::variant; private: Condition const* PROPERTY(condition); @@ -237,10 +238,8 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(valid, is); ConditionNode( - Condition const* new_condition = nullptr, value_t&& new_value = 0, - bool new_valid = false, - HasIdentifier const* new_condition_key_item = nullptr, - HasIdentifier const* new_condition_value_item = nullptr + Condition const* new_condition = nullptr, value_t&& new_value = 0, bool new_valid = false, + HasIdentifier const* new_condition_key_item = nullptr, HasIdentifier const* new_condition_value_item = nullptr ); }; diff --git a/src/openvic-simulation/scripts/ConditionScript.cpp b/src/openvic-simulation/scripts/ConditionScript.cpp index 4fc97d83c..d510994a9 100644 --- a/src/openvic-simulation/scripts/ConditionScript.cpp +++ b/src/openvic-simulation/scripts/ConditionScript.cpp @@ -5,17 +5,11 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -ConditionScript::ConditionScript( - scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope -) : initial_scope { new_initial_scope }, this_scope { new_this_scope }, from_scope { new_from_scope } {} +ConditionScript::ConditionScript(scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope) + : initial_scope { new_initial_scope }, this_scope { new_this_scope }, from_scope { new_from_scope } {} bool ConditionScript::_parse_script(std::span nodes, DefinitionManager const& definition_manager) { return definition_manager.get_script_manager().get_condition_manager().expect_condition_script( - definition_manager, - initial_scope, - this_scope, - from_scope, - move_variable_callback(condition_root), - nodes + definition_manager, initial_scope, this_scope, from_scope, move_variable_callback(condition_root), nodes ); } diff --git a/src/openvic-simulation/scripts/ConditionalWeight.cpp b/src/openvic-simulation/scripts/ConditionalWeight.cpp index c5a72da35..2dfb3aaeb 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.cpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.cpp @@ -14,9 +14,8 @@ ConditionalWeight::ConditionalWeight( from_scope { new_from_scope } {} template -static NodeCallback auto expect_modifier( - memory::vector& items, scope_type_t initial_scope, scope_type_t this_scope, scope_type_t from_scope -) { +static NodeCallback auto +expect_modifier(memory::vector& items, scope_type_t initial_scope, scope_type_t this_scope, scope_type_t from_scope) { return [&items, initial_scope, this_scope, from_scope](ast::NodeCPtr node) -> bool { fixed_point_t weight = 0; bool successful = false; @@ -37,16 +36,12 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { key_map_t key_map; bool successfully_set_up_base_keys = true; - if constexpr(TYPE == BASE) { - successfully_set_up_base_keys &= add_key_map_entry( - key_map, - "base", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) - ); + if constexpr (TYPE == BASE) { + successfully_set_up_base_keys &= + add_key_map_entry(key_map, "base", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base))); } else if constexpr (TYPE == FACTOR_ADD || TYPE == FACTOR_MUL) { - successfully_set_up_base_keys &= add_key_map_entry( - key_map, - "factor", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) - ); + successfully_set_up_base_keys &= + add_key_map_entry(key_map, "factor", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base))); } else if constexpr (TYPE == TIME) { const auto time_callback = [this](std::string_view key, Timespan (*to_timespan)(Timespan::day_t)) -> auto { return [this, key, to_timespan](uint32_t value) -> bool { @@ -65,10 +60,9 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { }; successfully_set_up_base_keys &= add_key_map_entries( - key_map, - "days", ZERO_OR_ONE, expect_uint(time_callback("days", Timespan::from_days)), - "months", ZERO_OR_ONE, expect_uint(time_callback("months", Timespan::from_months)), - "years", ZERO_OR_ONE, expect_uint(time_callback("years", Timespan::from_years)) + key_map, "days", ZERO_OR_ONE, expect_uint(time_callback("days", Timespan::from_days)), "months", + ZERO_OR_ONE, expect_uint(time_callback("months", Timespan::from_months)), "years", ZERO_OR_ONE, + expect_uint(time_callback("years", Timespan::from_years)) ); } else { successfully_set_up_base_keys = false; @@ -84,14 +78,15 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { } return expect_dictionary_key_map( - std::move(key_map), - "modifier", ZERO_OR_MORE, expect_modifier(condition_weight_items, initial_scope, this_scope, from_scope), - "group", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { + std::move(key_map), "modifier", ZERO_OR_MORE, + expect_modifier(condition_weight_items, initial_scope, this_scope, from_scope), "group", ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { condition_weight_group_t items; - const bool ret = expect_dictionary_keys( - "modifier", ONE_OR_MORE, expect_modifier(items, initial_scope, this_scope, from_scope) - )(node); + const bool ret = + expect_dictionary_keys("modifier", ONE_OR_MORE, expect_modifier(items, initial_scope, this_scope, from_scope))( + node + ); if (!items.empty()) { condition_weight_items.emplace_back(std::move(items)); @@ -130,9 +125,7 @@ bool ConditionalWeight::parse_scripts(DefinitionManager const& definition_ template bool ConditionalWeight::operator==(ConditionalWeight const& other) const { - return initial_scope == other.initial_scope && - this_scope == other.this_scope && - from_scope == other.from_scope; + return initial_scope == other.initial_scope && this_scope == other.this_scope && from_scope == other.from_scope; } template struct OpenVic::ConditionalWeight; diff --git a/src/openvic-simulation/scripts/ConditionalWeight.hpp b/src/openvic-simulation/scripts/ConditionalWeight.hpp index f789ba2b0..840186957 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.hpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.hpp @@ -9,9 +9,7 @@ #include "openvic-simulation/utility/Containers.hpp" namespace OpenVic { - enum class conditional_weight_type_t : uint8_t { - BASE, FACTOR_ADD, FACTOR_MUL, TIME - }; + enum class conditional_weight_type_t : uint8_t { BASE, FACTOR_ADD, FACTOR_MUL, TIME }; constexpr bool conditional_weight_type_is_additive(conditional_weight_type_t type) { return type == conditional_weight_type_t::BASE || type == conditional_weight_type_t::FACTOR_ADD; @@ -37,8 +35,7 @@ namespace OpenVic { public: ConditionalWeight( - scope_type_t new_initial_scope = scope_type_t::NO_SCOPE, - scope_type_t new_this_scope = scope_type_t::NO_SCOPE, + scope_type_t new_initial_scope = scope_type_t::NO_SCOPE, scope_type_t new_this_scope = scope_type_t::NO_SCOPE, scope_type_t new_from_scope = scope_type_t::NO_SCOPE ); ConditionalWeight(ConditionalWeight&&) = default; diff --git a/src/openvic-simulation/testing/Requirement.hpp b/src/openvic-simulation/testing/Requirement.hpp index 06332b101..f72ea318b 100644 --- a/src/openvic-simulation/testing/Requirement.hpp +++ b/src/openvic-simulation/testing/Requirement.hpp @@ -1,5 +1,6 @@ #pragma once #include + #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/testing/TestScript.cpp b/src/openvic-simulation/testing/TestScript.cpp index 58959918c..72f42d433 100644 --- a/src/openvic-simulation/testing/TestScript.cpp +++ b/src/openvic-simulation/testing/TestScript.cpp @@ -63,7 +63,7 @@ void TestScript::pass_or_fail_req_with_actual_and_target_values( memory::string req_name, memory::string target_value, memory::string actual_value ) { Requirement* req = get_requirement_by_id(req_name); - if (req == nullptr){ + if (req == nullptr) { return; } req->set_target_value(target_value); diff --git a/src/openvic-simulation/types/BasicIterator.hpp b/src/openvic-simulation/types/BasicIterator.hpp index f1155a4c2..b81c656f7 100644 --- a/src/openvic-simulation/types/BasicIterator.hpp +++ b/src/openvic-simulation/types/BasicIterator.hpp @@ -3,8 +3,8 @@ #include #include -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/Compare.hpp" +#include "openvic-simulation/core/Typedefs.hpp" namespace OpenVic { template diff --git a/src/openvic-simulation/types/ClampedValue.hpp b/src/openvic-simulation/types/ClampedValue.hpp index 5aea6bf64..48b5f4812 100644 --- a/src/openvic-simulation/types/ClampedValue.hpp +++ b/src/openvic-simulation/types/ClampedValue.hpp @@ -13,20 +13,14 @@ namespace OpenVic { fixed_point_t PROPERTY_ACCESS(max, protected); OV_STATE_PROPERTY_ACCESS(fixed_point_t, value, protected); constexpr ReadOnlyClampedValue() {}; - ReadOnlyClampedValue( - const fixed_point_t new_min, - const fixed_point_t new_max - ) : min { new_min }, max { new_max } {}; + ReadOnlyClampedValue(const fixed_point_t new_min, const fixed_point_t new_max) : min { new_min }, max { new_max } {}; }; struct ClampedValue : public ReadOnlyClampedValue { public: constexpr ClampedValue() {}; - ClampedValue( - const fixed_point_t new_min, - const fixed_point_t new_max, - const fixed_point_t new_value - ) : ReadOnlyClampedValue(new_min, new_max) { + ClampedValue(const fixed_point_t new_min, const fixed_point_t new_max, const fixed_point_t new_value) + : ReadOnlyClampedValue(new_min, new_max) { set_value(new_value); }; diff --git a/src/openvic-simulation/types/ColonyStatus.hpp b/src/openvic-simulation/types/ColonyStatus.hpp index 5746ad23d..4ec7f06ef 100644 --- a/src/openvic-simulation/types/ColonyStatus.hpp +++ b/src/openvic-simulation/types/ColonyStatus.hpp @@ -9,4 +9,4 @@ namespace OpenVic { static constexpr bool is_colonial(colony_status_t colony_status) { return colony_status != colony_status_t::STATE; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/Colour.hpp b/src/openvic-simulation/types/Colour.hpp index acfb2605b..1699542e9 100644 --- a/src/openvic-simulation/types/Colour.hpp +++ b/src/openvic-simulation/types/Colour.hpp @@ -25,10 +25,10 @@ #include -#include "openvic-simulation/types/StackString.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/string/CharConv.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/string/CharConv.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/StackString.hpp" namespace OpenVic { template @@ -57,10 +57,12 @@ namespace OpenVic { OV_SPEED_INLINE static constexpr integer_type make_rgb_integer(value_type red, value_type green, value_type blue) { return (red << red_shift) | (green << green_shift) | (blue << blue_shift); } - OV_SPEED_INLINE static constexpr integer_type make_rgba_integer(value_type red, value_type green, value_type blue, value_type alpha) { + OV_SPEED_INLINE static constexpr integer_type + make_rgba_integer(value_type red, value_type green, value_type blue, value_type alpha) { return (make_rgb_integer(red, green, blue) << component_bit_size) | (alpha << rgba_alpha_shift); } - OV_SPEED_INLINE static constexpr integer_type make_argb_integer(value_type red, value_type green, value_type blue, value_type alpha) { + OV_SPEED_INLINE static constexpr integer_type + make_argb_integer(value_type red, value_type green, value_type blue, value_type alpha) { return make_rgb_integer(red, green, blue) | static_cast(alpha << argb_alpha_shift); } @@ -192,39 +194,28 @@ namespace OpenVic { } } - OV_SPEED_INLINE static constexpr basic_colour_t from_argb(integer_type integer) - { + OV_SPEED_INLINE static constexpr basic_colour_t from_argb(integer_type integer) { if constexpr (colour_traits::has_alpha) { - return { - colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), - colour_traits::blue_from_argb(integer), colour_traits::alpha_from_argb(integer) - }; + return { colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), + colour_traits::blue_from_argb(integer), colour_traits::alpha_from_argb(integer) }; } else { return from_rgb(integer); } } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgba(integer_type integer) - { + OV_SPEED_INLINE static constexpr basic_colour_t from_rgba(integer_type integer) { if constexpr (colour_traits::has_alpha) { - return { - colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), - colour_traits::blue_from_rgb(integer), colour_traits::alpha_from_rgba(integer) - }; + return { colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), + colour_traits::blue_from_rgb(integer), colour_traits::alpha_from_rgba(integer) }; } else { - return { - colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), - colour_traits::blue_from_rgb(integer) - }; + return { colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), + colour_traits::blue_from_rgb(integer) }; } } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgb(integer_type integer) - { - return { - colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), - colour_traits::blue_from_argb(integer) - }; + OV_SPEED_INLINE static constexpr basic_colour_t from_rgb(integer_type integer) { + return { colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), + colour_traits::blue_from_argb(integer) }; } OV_SPEED_INLINE static constexpr basic_colour_t from_floats( // @@ -232,10 +223,8 @@ namespace OpenVic { ) requires(colour_traits::has_alpha) { - return { - colour_traits::red_from_float(r), colour_traits::green_from_float(g), colour_traits::blue_from_float(b), - colour_traits::alpha_from_float(a) - }; + return { colour_traits::red_from_float(r), colour_traits::green_from_float(g), colour_traits::blue_from_float(b), + colour_traits::alpha_from_float(a) }; } OV_SPEED_INLINE static constexpr basic_colour_t from_floats(float r, float g, float b) @@ -267,7 +256,8 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t + from_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars(str.data(), str.data() + str.size()); @@ -287,7 +277,8 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgba_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t + from_rgba_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_rgba(str.data(), str.data() + str.size()); @@ -307,7 +298,8 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_argb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t + from_argb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_argb(str.data(), str.data() + str.size()); @@ -327,7 +319,8 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t + from_rgb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_rgb(str.data(), str.data() + str.size()); @@ -443,7 +436,8 @@ namespace OpenVic { return colour_traits::alpha_to_float(alpha); } - OV_SPEED_INLINE constexpr std::to_chars_result to_hex_chars(char* first, char* last, bool alpha = colour_traits::has_alpha) const { + OV_SPEED_INLINE constexpr std::to_chars_result + to_hex_chars(char* first, char* last, bool alpha = colour_traits::has_alpha) const { constexpr size_t component_str_width = (std::bit_width(max_value) + 3) / 4; std::to_chars_result result = OpenVic::to_chars(first, last, alpha ? as_rgba() : as_rgb(), 16); @@ -566,7 +560,9 @@ namespace OpenVic { return new_colour; } - OV_SPEED_INLINE constexpr basic_colour_t full_invert() const requires(colour_traits::has_alpha) { + OV_SPEED_INLINE constexpr basic_colour_t full_invert() const + requires(colour_traits::has_alpha) + { basic_colour_t new_colour = *this; new_colour.red = max_value - new_colour.red; new_colour.green = max_value - new_colour.green; @@ -796,7 +792,7 @@ struct fmt::formatter { if (_specs.align() != align::none) { report_error("invalid format specifier"); } - + if (_specs.alt()) { report_error("invalid format specifier"); } @@ -865,7 +861,7 @@ struct fmt::formatter { out = detail::write(out, "0x"); } } - + if (!upper) { std::array lower; size_t i = 0; @@ -879,7 +875,7 @@ struct fmt::formatter { return detail::write(out, string_view { lower.data(), i }, specs, ctx.locale()); } } else if (_specs.alt()) { - *out++ = '#'; + *out++ = '#'; } return detail::write(out, string_view { result.data(), result.size() }, specs, ctx.locale()); diff --git a/src/openvic-simulation/types/CowPtr.hpp b/src/openvic-simulation/types/CowPtr.hpp index 15fc88d8a..e10b32f81 100644 --- a/src/openvic-simulation/types/CowPtr.hpp +++ b/src/openvic-simulation/types/CowPtr.hpp @@ -7,8 +7,8 @@ #include #include -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" namespace OpenVic { /** diff --git a/src/openvic-simulation/types/CowVector.hpp b/src/openvic-simulation/types/CowVector.hpp index 22b7abb3e..c5157c108 100644 --- a/src/openvic-simulation/types/CowVector.hpp +++ b/src/openvic-simulation/types/CowVector.hpp @@ -12,11 +12,11 @@ #include #include "openvic-simulation/core/Assert.hpp" -#include "openvic-simulation/types/BasicIterator.hpp" -#include "openvic-simulation/utility/Allocator.hpp" #include "openvic-simulation/core/Compare.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/BasicIterator.hpp" +#include "openvic-simulation/utility/Allocator.hpp" namespace OpenVic { /** @@ -98,8 +98,7 @@ namespace OpenVic { swap(other, *this); } else if (!other.empty()) { _data = _allocate_payload(other.size()); - _data->array_end = - uninitialized_move(other._data->array, other._data->array_end, _data->array, alloc); + _data->array_end = uninitialized_move(other._data->array, other._data->array_end, _data->array, alloc); destroy(_data->array, _data->array_end, alloc); _data->array_end = _data->array; } @@ -129,8 +128,9 @@ namespace OpenVic { cow_vector tmp = std::move(x); writer& tmp_writer = *reinterpret_cast(&tmp); - if constexpr (allocator_traits::propagate_on_container_move_assignment::value || - allocator_traits::is_always_equal::value) { + if constexpr ( + allocator_traits::propagate_on_container_move_assignment::value || allocator_traits::is_always_equal::value + ) { self_writer.swap(tmp_writer); } else if (alloc == x.alloc) { self_writer.swap(tmp_writer); @@ -450,8 +450,7 @@ namespace OpenVic { if constexpr (move_insertable_allocator) { _relocate(_data->array, _data->array_end, new_data->array, alloc); } else { - new_data->array_end = - uninitialized_move(_data->array, _data->array_end, new_data->array, alloc); + new_data->array_end = uninitialized_move(_data->array, _data->array_end, new_data->array, alloc); destroy(_data->array, _data->array_end, alloc); } _deallocate_payload(_data); diff --git a/src/openvic-simulation/types/Date.hpp b/src/openvic-simulation/types/Date.hpp index 90c45b410..88fd9fa85 100644 --- a/src/openvic-simulation/types/Date.hpp +++ b/src/openvic-simulation/types/Date.hpp @@ -16,12 +16,12 @@ #include +#include "openvic-simulation/core/Hash.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" +#include "openvic-simulation/core/string/CharConv.hpp" #include "openvic-simulation/types/StackString.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/core/Typedefs.hpp" -#include "openvic-simulation/core/Hash.hpp" namespace OpenVic { // A relative period between points in time, measured in days @@ -119,9 +119,8 @@ namespace OpenVic { static constexpr Timespan::day_t MONTHS_IN_YEAR = DAYS_IN_MONTH.size(); static constexpr Timespan::day_t MAX_DAYS_IN_MONTH = *ranges::max_element(DAYS_IN_MONTH); - static constexpr Timespan::day_t DAYS_IN_YEAR = std::accumulate( - DAYS_IN_MONTH.begin(), DAYS_IN_MONTH.end(), Timespan::day_t { 0 } - ); + static constexpr Timespan::day_t DAYS_IN_YEAR = + std::accumulate(DAYS_IN_MONTH.begin(), DAYS_IN_MONTH.end(), Timespan::day_t { 0 }); static_assert(DAYS_IN_YEAR == 365); static constexpr std::array DAYS_UP_TO_MONTH = [] { @@ -148,8 +147,8 @@ namespace OpenVic { static constexpr char SEPARATOR_CHARACTER = '.'; static constexpr std::array MONTH_NAMES { - "January", "February", "March", "April", "May", "June", // - "July", "August", "September", "October", "November", "December" // + "January", "February", "March", "April", "May", "June", // + "July", "August", "September", "October", "November", "December" // }; static constexpr std::string_view INVALID_MONTH_NAME = "Invalid Month"; @@ -177,7 +176,8 @@ namespace OpenVic { // Negative Timespans indicate dates before Jan 1st, Year 0. OV_ALWAYS_INLINE constexpr Date(Timespan new_timespan) : timespan { new_timespan } {} // Year month day specification - OV_ALWAYS_INLINE constexpr Date(year_t year = 0, month_t month = 1, day_t day = 1) : timespan { _date_to_timespan(year, month, day) } {} + OV_ALWAYS_INLINE constexpr Date(year_t year = 0, month_t month = 1, day_t day = 1) + : timespan { _date_to_timespan(year, month, day) } {} OV_SPEED_INLINE constexpr Timespan::day_t get_day_of_year() const { Timespan::day_t day_in_year = static_cast(timespan) % DAYS_IN_YEAR; @@ -188,10 +188,9 @@ namespace OpenVic { } OV_SPEED_INLINE constexpr year_t get_year() const { - return (timespan >= 0 - ? static_cast(timespan) - : static_cast(timespan) - DAYS_IN_YEAR + 1 - ) / DAYS_IN_YEAR; + return (timespan >= 0 ? static_cast(timespan) + : static_cast(timespan) - DAYS_IN_YEAR + 1) / + DAYS_IN_YEAR; } OV_SPEED_INLINE constexpr month_t get_month() const { return MONTH_FROM_DAY_IN_YEAR[get_day_of_year()]; @@ -344,7 +343,8 @@ namespace OpenVic { } struct stack_string; - OV_SPEED_INLINE constexpr stack_string to_array(bool pad_year = false, bool pad_month = true, bool pad_day = true) const; + OV_SPEED_INLINE constexpr stack_string + to_array(bool pad_year = false, bool pad_month = true, bool pad_day = true) const; struct stack_string final : StackString< fmt::detail::count_digits(uint64_t(std::numeric_limits::max())) + @@ -404,8 +404,8 @@ namespace OpenVic { } if (OV_unlikely( - year_check > std::numeric_limits::max() || year_check < std::numeric_limits::min() - )) { + year_check > std::numeric_limits::max() || year_check < std::numeric_limits::min() + )) { result.ec = std::errc::value_too_large; result.ptr = first; return result; @@ -563,7 +563,9 @@ namespace OpenVic { from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::day && from_chars->ptr == from_chars->type_first, date, - memory::fmt::format("Day value cannot be larger than {} for {}.", DAYS_IN_MONTH[date.get_month() - 1], date.get_month()) + memory::fmt::format( + "Day value cannot be larger than {} for {}.", DAYS_IN_MONTH[date.get_month() - 1], date.get_month() + ) ); return date; diff --git a/src/openvic-simulation/types/FixedVector.hpp b/src/openvic-simulation/types/FixedVector.hpp index ce6a97bb7..f90554d7d 100644 --- a/src/openvic-simulation/types/FixedVector.hpp +++ b/src/openvic-simulation/types/FixedVector.hpp @@ -7,12 +7,12 @@ #include #include "openvic-simulation/core/Assert.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" namespace OpenVic::_detail { - //fixed capacity + not movable + not copyable - template > + // fixed capacity + not movable + not copyable + template> class FixedVector { private: using allocator_traits = std::allocator_traits; @@ -28,78 +28,70 @@ namespace OpenVic::_detail { using size_type = size_t; using value_type = T; - constexpr size_t size() const { return _size; } - constexpr size_t capacity() const { return _max_size; } - constexpr size_t max_size() const { return _max_size; } - constexpr T* data() { return _data_start_ptr; } - constexpr T const* data() const { return _data_start_ptr; } - constexpr bool empty() const { return _size == 0; } + constexpr size_t size() const { + return _size; + } + constexpr size_t capacity() const { + return _max_size; + } + constexpr size_t max_size() const { + return _max_size; + } + constexpr T* data() { + return _data_start_ptr; + } + constexpr T const* data() const { + return _data_start_ptr; + } + constexpr bool empty() const { + return _size == 0; + } /** - * @brief Creates an uninitialised vector with fixed capacity - */ + * @brief Creates an uninitialised vector with fixed capacity + */ explicit FixedVector(const size_t capacity) - : _max_size(capacity), - _size(0), - _allocator(), - _data_start_ptr(allocator_traits::allocate(_allocator, capacity)) {} + : _max_size(capacity), _size(0), _allocator(), _data_start_ptr(allocator_traits::allocate(_allocator, capacity)) {} FixedVector(const size_t size, T const& value_for_all_indices) - : _max_size(size), - _size(size), - _allocator(), - _data_start_ptr(allocator_traits::allocate(_allocator, size)) { + : _max_size(size), _size(size), _allocator(), _data_start_ptr(allocator_traits::allocate(_allocator, size)) { std::fill(_data_start_ptr, _data_start_ptr + size, value_for_all_indices); } - //Generator (size_t i) -> U (where T is constructable from U) + // Generator (size_t i) -> U (where T is constructable from U) template // The generator must NOT return a tuple - requires (!specialization_of>, std::tuple>) - // The type must be constructible from the generator's single return value - && std::constructible_from()(std::declval()))> + requires(!specialization_of>, std::tuple>) + // The type must be constructible from the generator's single return value + && std::constructible_from()(std::declval()))> FixedVector(const size_t size, GeneratorTemplateType&& generator) - : _max_size(size), - _size(size), - _allocator(), - _data_start_ptr(allocator_traits::allocate(_allocator, size)) { + : _max_size(size), _size(size), _allocator(), _data_start_ptr(allocator_traits::allocate(_allocator, size)) { for (size_t i = 0; i < size; ++i) { - allocator_traits::construct( - _allocator, - begin()+i, - generator(i) - ); + allocator_traits::construct(_allocator, begin() + i, generator(i)); } } - //Generator (size_t i) -> std::tuple (where T is constructable from Args) + // Generator (size_t i) -> std::tuple (where T is constructable from Args) template // The generator must return a tuple requires specialization_of>, std::tuple> - // The tuple must be constructible into a T - && requires(GeneratorTemplateType&& generator) { - { - std::apply( - [](auto&&... args) { - T obj{std::forward(args)...}; - }, - generator(std::declval()) - ) - }; - } + // The tuple must be constructible into a T + && requires(GeneratorTemplateType&& generator) { + { + std::apply( + [](auto&&... args) { + T obj { std::forward(args)... }; + }, + generator(std::declval()) + ) + }; + } FixedVector(const size_t size, GeneratorTemplateType&& generator) - : _max_size(size), - _size(size), - _allocator(), - _data_start_ptr(allocator_traits::allocate(_allocator, size)) { + : _max_size(size), _size(size), _allocator(), _data_start_ptr(allocator_traits::allocate(_allocator, size)) { for (size_t i = 0; i < size; ++i) { std::apply( [this, i](auto&&... args) { - allocator_traits::construct( - _allocator, - begin()+i, - std::forward(args)... - ); + allocator_traits::construct(_allocator, begin() + i, std::forward(args)...); }, generator(i) ); @@ -115,28 +107,52 @@ namespace OpenVic::_detail { clear(); allocator_traits::deallocate(_allocator, _data_start_ptr, _max_size); } - + using iterator = T*; using const_iterator = const T*; - iterator begin() { return _data_start_ptr; } - const_iterator begin() const { return _data_start_ptr; } - const_iterator cbegin() const { return _data_start_ptr; } + iterator begin() { + return _data_start_ptr; + } + const_iterator begin() const { + return _data_start_ptr; + } + const_iterator cbegin() const { + return _data_start_ptr; + } + + iterator end() { + return begin() + _size; + } + const_iterator end() const { + return begin() + _size; + } + const_iterator cend() const { + return cbegin() + _size; + } - iterator end() { return begin() + _size; } - const_iterator end() const { return begin() + _size; } - const_iterator cend() const { return cbegin() + _size; } - using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } + reverse_iterator rbegin() { + return reverse_iterator(end()); + } + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end()); + } + const_reverse_iterator crbegin() const { + return const_reverse_iterator(end()); + } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } + reverse_iterator rend() { + return reverse_iterator(begin()); + } + const_reverse_iterator rend() const { + return const_reverse_iterator(begin()); + } + const_reverse_iterator crend() const { + return const_reverse_iterator(begin()); + } T& operator[](const size_t index) { OV_HARDEN_ASSERT_ACCESS(index, "operator[]"); @@ -157,55 +173,45 @@ namespace OpenVic::_detail { } T& back() { OV_HARDEN_ASSERT_NONEMPTY("back"); - return *(end()-1); + return *(end() - 1); } const T& back() const { OV_HARDEN_ASSERT_NONEMPTY("back"); - return *(cend()-1); + return *(cend() - 1); } - template + template iterator emplace_back(Args&&... args) { if (_size >= _max_size) { return end(); } - allocator_traits::construct( - _allocator, - begin() + _size, - std::forward(args)... - ); + allocator_traits::construct(_allocator, begin() + _size, std::forward(args)...); ++_size; - return end()-1; + return end() - 1; } void pop_back() { - if (_size > 0) { - allocator_traits::destroy( - _allocator, - end() - 1 - ); + if (_size > 0) { + allocator_traits::destroy(_allocator, end() - 1); --_size; } } void clear() { - for (iterator it = end(); it != begin(); ) { + for (iterator it = end(); it != begin();) { --it; - allocator_traits::destroy( - _allocator, - it - ); + allocator_traits::destroy(_allocator, it); } _size = 0; } }; } -#include - #include "openvic-simulation/utility/MemoryTracker.hpp" +#include + namespace OpenVic::memory { template using FixedVector = _detail::FixedVector>>; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/FlagStrings.cpp b/src/openvic-simulation/types/FlagStrings.cpp index 72d3b7b0a..1e4f2f296 100644 --- a/src/openvic-simulation/types/FlagStrings.cpp +++ b/src/openvic-simulation/types/FlagStrings.cpp @@ -13,10 +13,7 @@ bool FlagStrings::set_flag(std::string_view flag, bool warn) { } if (!flags.emplace(flag).second && warn) { - spdlog::warn_s( - "Attempted to set {} flag \"{}\": already set!", - name, flag - ); + spdlog::warn_s("Attempted to set {} flag \"{}\": already set!", name, flag); } return true; @@ -29,10 +26,7 @@ bool FlagStrings::clear_flag(std::string_view flag, bool warn) { } if (flags.erase(flag) == 0 && warn) { - spdlog::warn_s( - "Attempted to clear {} flag \"{}\": not set!", - name, flag - ); + spdlog::warn_s("Attempted to clear {} flag \"{}\": not set!", name, flag); } return true; diff --git a/src/openvic-simulation/types/HasIdentifier.hpp b/src/openvic-simulation/types/HasIdentifier.hpp index e51389339..20863b86e 100644 --- a/src/openvic-simulation/types/HasIdentifier.hpp +++ b/src/openvic-simulation/types/HasIdentifier.hpp @@ -3,8 +3,8 @@ #include #include #include -#include #include +#include #include @@ -23,7 +23,7 @@ namespace OpenVic { memory::string PROPERTY(identifier); protected: - HasIdentifier(std::string_view new_identifier): identifier { new_identifier } { + HasIdentifier(std::string_view new_identifier) : identifier { new_identifier } { assert(!identifier.empty()); } HasIdentifier(HasIdentifier const&) = default; @@ -33,16 +33,16 @@ namespace OpenVic { HasIdentifier& operator=(HasIdentifier const&) = delete; HasIdentifier& operator=(HasIdentifier&&) = delete; - template T, std::convertible_to U> - requires (!has_index) + template T, std::convertible_to U> + requires(!has_index) friend bool operator==(T const& lhs, U const& rhs) { return lhs.get_identifier() == static_cast(rhs).get_identifier(); } - template - requires specialization_of, std::reference_wrapper> - && std::derived_from::type, HasIdentifier> - && equalable::type const&, U> + template + requires specialization_of, std::reference_wrapper> && + std::derived_from::type, HasIdentifier> && + equalable::type const&, U> friend bool operator==(T const& lhs, U const& rhs) { return lhs.get() == rhs; } @@ -63,7 +63,7 @@ namespace OpenVic { const ColourT PROPERTY(colour); protected: - _HasColour(ColourT new_colour, bool cannot_be_null): colour { new_colour } { + _HasColour(ColourT new_colour, bool cannot_be_null) : colour { new_colour } { assert(!cannot_be_null || !colour.is_null()); } _HasColour(_HasColour const&) = default; @@ -98,7 +98,7 @@ namespace OpenVic { } template -requires (!OpenVic::has_get_name) +requires(!OpenVic::has_get_name) struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(T const& has_id, fmt::format_context& ctx) const { return fmt::formatter::format(has_id.get_identifier(), ctx); @@ -106,7 +106,7 @@ struct fmt::formatter : fmt::formatter { }; template -requires (!OpenVic::has_get_identifier) +requires(!OpenVic::has_get_identifier) struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(T const& has_id, fmt::format_context& ctx) const { return fmt::formatter::format(has_id.get_name(), ctx); @@ -115,20 +115,20 @@ struct fmt::formatter : fmt::formatter { namespace std { template - requires (!OpenVic::has_index) + requires(!OpenVic::has_index) struct hash { [[nodiscard]] std::size_t operator()(T const& obj) const noexcept { - return std::hash{}(obj.get_identifier()); + return std::hash {}(obj.get_identifier()); } }; } namespace std { template - requires (!OpenVic::has_index) + requires(!OpenVic::has_index) struct hash> { [[nodiscard]] std::size_t operator()(std::remove_const_t const& obj) const noexcept { - return std::hash{}(obj.get_identifier()); + return std::hash {}(obj.get_identifier()); } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/HasIndex.hpp b/src/openvic-simulation/types/HasIndex.hpp index 358f3b8b5..8fe4d7cc2 100644 --- a/src/openvic-simulation/types/HasIndex.hpp +++ b/src/openvic-simulation/types/HasIndex.hpp @@ -37,7 +37,7 @@ namespace std { requires OpenVic::derived_from_specialization_of, OpenVic::HasIndex> struct hash { [[nodiscard]] std::size_t operator()(T const& obj) const noexcept { - return std::hash::index_t>{}(obj.index); + return std::hash::index_t> {}(obj.index); } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/IdentifierRegistry.hpp b/src/openvic-simulation/types/IdentifierRegistry.hpp index 577bd61ea..5aaa90047 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.hpp +++ b/src/openvic-simulation/types/IdentifierRegistry.hpp @@ -3,9 +3,9 @@ #include #include +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/Logger.hpp" @@ -13,15 +13,15 @@ namespace OpenVic { /* 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) { spdlog::error_s( - "Failure adding item to the {} registry - an item with the identifier \"{}\" already exists!", - registry_name, duplicate_identifier + "Failure adding item to the {} registry - an item with the identifier \"{}\" already exists!", registry_name, + duplicate_identifier ); return false; } static bool duplicate_warning_callback(std::string_view registry_name, std::string_view duplicate_identifier) { spdlog::warn_s( - "Warning adding item to the {} registry - an item with the identifier \"{}\" already exists!", - registry_name, duplicate_identifier + "Warning adding item to the {} registry - an item with the identifier \"{}\" already exists!", registry_name, + duplicate_identifier ); return true; } @@ -31,13 +31,12 @@ namespace OpenVic { /* Registry Value Info - the type that is being registered, and a unique identifier string getter. */ template - concept RegistryValueInfo = requires( - typename ValueInfo::internal_value_type& item, typename ValueInfo::internal_value_type const& const_item - ) { - { ValueInfo::get_identifier(item) } -> std::same_as; - { ValueInfo::get_external_value(item) } -> std::same_as; - { ValueInfo::get_external_value(const_item) } -> std::same_as; - }; + concept RegistryValueInfo = + requires(typename ValueInfo::internal_value_type& item, typename ValueInfo::internal_value_type const& const_item) { + { ValueInfo::get_identifier(item) } -> std::same_as; + { ValueInfo::get_external_value(item) } -> std::same_as; + { ValueInfo::get_external_value(const_item) } -> std::same_as; + }; template struct RegistryValueInfoHasGetIdentifier { using internal_value_type = Value; @@ -71,12 +70,11 @@ namespace OpenVic { /* Registry Item Info - how individual elements of the registered type are stored, and type from item getters. */ template typename ItemInfo, typename Value> - concept RegistryItemInfo = requires( - typename ItemInfo::item_type& item, typename ItemInfo::item_type const& const_item - ) { - { ItemInfo::get_value(item) } -> std::same_as; - { ItemInfo::get_value(const_item) } -> std::same_as; - }; + concept RegistryItemInfo = + requires(typename ItemInfo::item_type& item, typename ItemInfo::item_type const& const_item) { + { ItemInfo::get_value(item) } -> std::same_as; + { ItemInfo::get_value(const_item) } -> std::same_as; + }; template struct RegistryItemInfoValue { using item_type = Value; @@ -113,12 +111,9 @@ namespace OpenVic { /* Registry Storage Info - how items are stored and indexed, and item-index conversion functions. */ template typename StorageInfo, typename Item> - concept RegistryStorageInfo = - std::same_as::storage_type::value_type, Item> && - requires( - typename StorageInfo::storage_type& items, typename StorageInfo::storage_type const& const_items, - typename StorageInfo::index_type index - ) { + concept RegistryStorageInfo = std::same_as::storage_type::value_type, Item> && + requires(typename StorageInfo::storage_type& items, typename StorageInfo::storage_type const& const_items, + typename StorageInfo::index_type index) { { StorageInfo::get_back_index(items) } -> std::same_as::index_type>; { StorageInfo::get_item_from_index(items, index) } -> std::same_as; { StorageInfo::get_item_from_index(const_items, index) } -> std::same_as; @@ -157,9 +152,10 @@ namespace OpenVic { template< RegistryValueInfo ValueInfo, /* The type that is being registered and that has unique string identifiers */ template typename _ItemInfo, /* How the type is being stored, usually either by value or std::unique_ptr */ - template typename _StorageInfo = RegistryStorageInfoVector, /* How items are stored, including indexing type */ + template typename _StorageInfo = + RegistryStorageInfoVector, /* How items are stored, including indexing type */ string_map_case Case = StringMapCaseSensitive /* Identifier map parameters */ - > + > requires( RegistryItemInfo<_ItemInfo, typename ValueInfo::internal_value_type> && RegistryStorageInfo<_StorageInfo, typename _ItemInfo::item_type> @@ -207,10 +203,8 @@ namespace OpenVic { return emplace_via_move(std::move(item), duplicate_fail_callback); } - constexpr bool emplace_via_move( - item_type&& item, - NodeTools::Callback auto duplicate_callback - ) { + constexpr bool + emplace_via_move(item_type&& item, NodeTools::Callback auto duplicate_callback) { if (locked) { spdlog::error_s("Cannot add item to the {} registry - locked!", name); return false; @@ -229,8 +223,7 @@ namespace OpenVic { template constexpr bool emplace_item( const std::string_view new_identifier, - NodeTools::Callback auto duplicate_callback, - Args&&... args + NodeTools::Callback auto duplicate_callback, Args&&... args ) { if (locked) { spdlog::error_s("Cannot add item to the {} registry - locked!", name); @@ -245,19 +238,13 @@ namespace OpenVic { emplace_identifier_index(); return true; } - + constexpr bool emplace_via_copy(item_type const& item_to_copy) { - return emplace_item( - ValueInfo::get_identifier(ItemInfo::get_value(item_to_copy)), - item_to_copy - ); + return emplace_item(ValueInfo::get_identifier(ItemInfo::get_value(item_to_copy)), item_to_copy); } template - constexpr bool emplace_item( - const std::string_view new_identifier, - Args&&... args - ) { + constexpr bool emplace_item(const std::string_view new_identifier, Args&&... args) { return emplace_item(new_identifier, duplicate_fail_callback, std::forward(args)...); } @@ -298,19 +285,13 @@ namespace OpenVic { constexpr void reserve(std::size_t size) { if constexpr (storage_type_reservable) { if (locked) { - spdlog::error_s( - "Failed to reserve space for {} items in {} registry - already locked!", - size, name - ); + spdlog::error_s("Failed to reserve space for {} items in {} registry - already locked!", size, name); } else { items.reserve(size); identifier_index_map.reserve(size); } } else { - spdlog::error_s( - "Cannot reserve space for {} {} - storage_type not reservable!", - size, name - ); + spdlog::error_s("Cannot reserve space for {} {} - storage_type not reservable!", size, name); } } @@ -353,8 +334,7 @@ namespace OpenVic { return reinterpret_cast(item); \ } \ spdlog::error_s( \ - "Invalid type for item \"{}\": {} (expected {})", \ - identifier, item->get_type(), T::get_type_static() \ + "Invalid type for item \"{}\": {} (expected {})", identifier, item->get_type(), T::get_type_static() \ ); \ } \ return nullptr; \ @@ -374,10 +354,7 @@ namespace OpenVic { if (allow_empty) { \ return true; \ } else { \ - spdlog::log_s( \ - warn ? spdlog::level::warn : spdlog::level::err, \ - "Invalid {} identifier: empty!", name \ - ); \ + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Invalid {} identifier: empty!", name); \ return warn; \ } \ } \ @@ -385,10 +362,7 @@ namespace OpenVic { if (item != nullptr) { \ return callback(*item); \ } \ - spdlog::log_s( \ - warn ? spdlog::level::warn : spdlog::level::err, \ - "Invalid {} identifier: {}", name, identifier \ - ); \ + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Invalid {} identifier: {}", name, identifier); \ return warn; \ }; \ } \ @@ -428,62 +402,43 @@ namespace OpenVic { return expect_item_assign_and_default(key_value_invalid_callback(name), callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_length_and_default( \ - NodeTools::LengthCallback auto length_callback, \ - NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::LengthCallback auto length_callback, NodeTools::KeyValueCallback auto default_callback, \ NodeTools::Callback auto callback \ ) CONST { \ - return NodeTools::expect_list_and_length( \ - length_callback, expect_item_assign_and_default(default_callback, callback) \ - ); \ + return NodeTools::expect_list_and_length(length_callback, expect_item_assign_and_default(default_callback, callback)); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_length( \ NodeTools::LengthCallback auto length_callback, \ NodeTools::Callback auto callback \ ) CONST { \ - return expect_item_dictionary_and_length_and_default( \ - length_callback, \ - key_value_invalid_callback(name), \ - callback \ - ); \ + return expect_item_dictionary_and_length_and_default(length_callback, key_value_invalid_callback(name), callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_default( \ NodeTools::KeyValueCallback auto default_callback, \ NodeTools::Callback auto callback \ ) CONST { \ - return expect_item_dictionary_and_length_and_default( \ - NodeTools::default_length_callback, \ - default_callback, \ - callback \ - ); \ + return expect_item_dictionary_and_length_and_default(NodeTools::default_length_callback, default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary( \ NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::default_length_callback, \ - key_value_invalid_callback(name), \ - callback \ + NodeTools::default_length_callback, key_value_invalid_callback(name), callback \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_reserve_length_and_default( \ - reservable auto& reservable, \ - NodeTools::KeyValueCallback auto default_callback, \ + reservable auto& reservable, NodeTools::KeyValueCallback auto default_callback, \ NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::reserve_length_callback(reservable), \ - default_callback, \ - callback \ + NodeTools::reserve_length_callback(reservable), default_callback, callback \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_reserve_length( \ - reservable auto& reservable, \ - NodeTools::Callback auto callback \ + reservable auto& reservable, NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::reserve_length_callback(reservable), \ - key_value_invalid_callback(name), \ - callback \ + NodeTools::reserve_length_callback(reservable), key_value_invalid_callback(name), callback \ ); \ } @@ -528,16 +483,13 @@ namespace OpenVic { return [this, callback, fixed_point_functor](ast::NodeCPtr node) -> bool { fixed_point_map_t map; - bool ret = expect_item_dictionary( - [&map, fixed_point_functor](external_value_type const& key, ast::NodeCPtr value) -> bool { - return NodeTools::expect_fixed_point( - [&map, fixed_point_functor, &key](fixed_point_t val) -> bool { - map.emplace(&key, fixed_point_functor(val)); - return true; - } - )(value); - } - )(node); + bool ret = + expect_item_dictionary([&map, fixed_point_functor](external_value_type const& key, ast::NodeCPtr value) -> bool { + return NodeTools::expect_fixed_point([&map, fixed_point_functor, &key](fixed_point_t val) -> bool { + map.emplace(&key, fixed_point_functor(val)); + return true; + })(value); + })(node); ret &= callback(std::move(map)); @@ -549,52 +501,45 @@ namespace OpenVic { /* Item Specialisations */ template< RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, typename RegistryItemInfoValue::item_type> using ValueRegistry = UniqueKeyRegistry; template< RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, typename RegistryItemInfoInstance::item_type> using InstanceRegistry = UniqueKeyRegistry; template< RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, typename RegistryItemInfoBaseInstance::item_type> using BaseInstanceRegistry = UniqueKeyRegistry; /* has_get_identifier Specialisations */ template< has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + string_map_case Case = StringMapCaseSensitive> using IdentifierRegistry = ValueRegistry, StorageInfo, Case>; template< has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + string_map_case Case = StringMapCaseSensitive> using IdentifierPointerRegistry = ValueRegistry>, StorageInfo, Case>; template< has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + string_map_case Case = StringMapCaseSensitive> using IdentifierInstanceRegistry = InstanceRegistry, StorageInfo, Case>; template< has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + string_map_case Case = StringMapCaseSensitive> using IdentifierBaseInstanceRegistry = BaseInstanceRegistry, StorageInfo, Case>; /* Case-Insensitive has_get_identifier Specialisations */ @@ -608,18 +553,19 @@ namespace OpenVic { using CaseInsensitiveIdentifierInstanceRegistry = IdentifierInstanceRegistry; template typename StorageInfo = RegistryStorageInfoVector> - using CaseInsensitiveIdentifierBaseInstanceRegistry = IdentifierBaseInstanceRegistry; + using CaseInsensitiveIdentifierBaseInstanceRegistry = + IdentifierBaseInstanceRegistry; -/* Macros to generate declaration and constant accessor methods for a UniqueKeyRegistry member variable. */ + /* Macros to generate declaration and constant accessor methods for a UniqueKeyRegistry member variable. */ -#define IDENTIFIER_REGISTRY(name, ...) \ - IDENTIFIER_REGISTRY_CUSTOM_PLURAL(name, name##s, __VA_ARGS__) +#define IDENTIFIER_REGISTRY(name, ...) IDENTIFIER_REGISTRY_CUSTOM_PLURAL(name, name##s, __VA_ARGS__) #define IDENTIFIER_REGISTRY_CUSTOM_PLURAL(singular, plural, ...) \ IDENTIFIER_REGISTRY_FULL_CUSTOM(singular, plural, plural, plural, __VA_ARGS__) #define IDENTIFIER_REGISTRY_FULL_CUSTOM(singular, plural, registry, debug_name, ...) \ - registry { #debug_name __VA_OPT__(,) __VA_ARGS__ }; \ + registry { #debug_name __VA_OPT__(, ) __VA_ARGS__ }; \ +\ public: \ constexpr void lock_##plural() { \ registry.lock(); \ @@ -628,11 +574,15 @@ public: \ return registry.is_locked(); \ } \ template \ - constexpr void reserve_##plural(size_t size) requires(decltype(registry)::storage_type_reservable) { \ + constexpr void reserve_##plural(size_t size) \ + requires(decltype(registry)::storage_type_reservable) \ + { \ registry.reserve(size); \ } \ template \ - constexpr void reserve_more_##plural(size_t size) requires(decltype(registry)::storage_type_reservable) { \ + constexpr void reserve_more_##plural(size_t size) \ + requires(decltype(registry)::storage_type_reservable) \ + { \ registry.reserve_more(size); \ } \ constexpr bool has_##singular##_identifier(std::string_view identifier) const { \ @@ -642,7 +592,9 @@ public: \ return registry.size(); \ } \ template \ - constexpr std::size_t get_##plural##_capacity() const requires(decltype(registry)::storage_type_reservable) { \ + constexpr std::size_t get_##plural##_capacity() const \ + requires(decltype(registry)::storage_type_reservable) \ + { \ return registry.capacity(); \ } \ constexpr bool plural##_empty() const { \ @@ -661,16 +613,15 @@ public: \ IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, const) \ private: -/* Macros to generate non-constant accessor methods for a UniqueKeyRegistry member variable. */ + /* Macros to generate non-constant accessor methods for a UniqueKeyRegistry member variable. */ -#define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(name) \ - IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(name, name##s) +#define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(name) IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(name, name##s) #define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(singular, plural) \ IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_FULL_CUSTOM(singular, plural, plural, plural) #define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_FULL_CUSTOM(singular, plural, registry, debug_name) \ - IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry,) + IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, ) #define IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, const_kw) \ constexpr decltype(registry)::external_value_type const_kw& get_front_##singular() const_kw { \ @@ -679,14 +630,16 @@ public: \ constexpr decltype(registry)::external_value_type const_kw& get_back_##singular() const_kw { \ return registry.back(); \ } \ - constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_identifier(std::string_view identifier) const_kw { \ + constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_identifier(std::string_view identifier) \ + const_kw { \ return registry.get_item_by_identifier(identifier); \ } \ template T> \ constexpr T const_kw* get_cast_##singular##_by_identifier(std::string_view identifier) const_kw { \ return registry.get_cast_item_by_identifier(identifier); \ } \ - constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_index(decltype(registry)::index_t index) const_kw { \ + constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_index(decltype(registry)::index_t index) \ + const_kw { \ return registry.get_item_by_index(index); \ } \ constexpr decltype(registry)::storage_type const_kw& get_##plural() const_kw { \ @@ -727,8 +680,7 @@ public: \ return registry.expect_item_assign(callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_and_length_and_default( \ - NodeTools::LengthCallback auto length_callback, \ - NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::LengthCallback auto length_callback, NodeTools::KeyValueCallback auto default_callback, \ NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_and_length_and_default(length_callback, default_callback, callback); \ @@ -745,8 +697,7 @@ public: \ return registry.expect_item_dictionary(callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_reserve_length_and_default( \ - reservable auto& reservable, \ - NodeTools::KeyValueCallback auto default_callback, \ + reservable auto& reservable, NodeTools::KeyValueCallback auto default_callback, \ NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_reserve_length_and_default(reservable, default_callback, callback); \ diff --git a/src/openvic-simulation/types/IndexedFlatMap.hpp b/src/openvic-simulation/types/IndexedFlatMap.hpp index fdaf41fd6..e9f0ed62d 100644 --- a/src/openvic-simulation/types/IndexedFlatMap.hpp +++ b/src/openvic-simulation/types/IndexedFlatMap.hpp @@ -6,14 +6,14 @@ #include #include -#include - #include -#include "openvic-simulation/types/FixedVector.hpp" +#include + +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/FixedVector.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/utility/Logger.hpp" #define OV_IFLATMAP_PROPERTY(KEYTYPE, VALUETYPE, NAME) OV_IFLATMAP_PROPERTY_ACCESS(KEYTYPE, VALUETYPE, NAME, private) @@ -30,55 +30,50 @@ public: \ namespace OpenVic { /** - * @brief A dictionary-like type that uses std::vector for contiguous storage, - * providing O(1) access time by directly using an integer index obtained from the KeyType. - * It strictly assumes that keys provided at construction are ordered and continuous - * in their index values. - * @tparam KeyType The type of keys used to access values. This type must provide a - * `size_t getIndex() const` method. - * @tparam ValueType The type of values to be stored in the map. - * - * This class assumes that an integer index can be obtained from the key type - * via its `getIndex()` method. The indices used with this map must be within - * the specified range [min_index, max_index]. - * - * @warning This class stores a `std::span` of the provided keys. This means the - * `IndexedFlatMap` does NOT own the lifetime of the keys. The caller is - * responsible for ensuring that the underlying data (the `std::vector` or array) - * that the `std::span` refers to remains valid and outlives the `IndexedFlatMap` instance. - */ - template + * @brief A dictionary-like type that uses std::vector for contiguous storage, + * providing O(1) access time by directly using an integer index obtained from the KeyType. + * It strictly assumes that keys provided at construction are ordered and continuous + * in their index values. + * @tparam KeyType The type of keys used to access values. This type must provide a + * `size_t getIndex() const` method. + * @tparam ValueType The type of values to be stored in the map. + * + * This class assumes that an integer index can be obtained from the key type + * via its `getIndex()` method. The indices used with this map must be within + * the specified range [min_index, max_index]. + * + * @warning This class stores a `std::span` of the provided keys. This means the + * `IndexedFlatMap` does NOT own the lifetime of the keys. The caller is + * responsible for ensuring that the underlying data (the `std::vector` or array) + * that the `std::span` refers to remains valid and outlives the `IndexedFlatMap` instance. + */ + template struct IndexedFlatMap { using keys_span_type = forwardable_span; using values_vector_type = std::conditional_t< - std::is_move_constructible_v || std::is_copy_constructible_v, - memory::vector, - memory::FixedVector - >; + std::is_move_constructible_v || std::is_copy_constructible_v, memory::vector, + memory::FixedVector>; private: values_vector_type values; - keys_span_type keys; //non-owning! + keys_span_type keys; // non-owning! size_t min_index; size_t max_index; /** - * @brief Converts an external key's index to an internal vector index. - * Logs a fatal error if the key's index is out of bounds. - * @param key The key whose index is to be converted. - * @return The internal index, or 0 if out of bounds (after logging error). - */ + * @brief Converts an external key's index to an internal vector index. + * Logs a fatal error if the key's index is out of bounds. + * @param key The key whose index is to be converted. + * @return The internal index, or 0 if out of bounds (after logging error). + */ constexpr size_t get_internal_index_from_key(ForwardedKeyType const& key) const { static_assert(has_index); const size_t index = type_safe::get(key.index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access key with index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access key with index {} which is outside the " + "map's defined range [{}, {}].", + type_name(), type_name(), index, min_index, max_index ); assert(index >= min_index && index <= max_index); return 0; @@ -87,11 +82,11 @@ namespace OpenVic { } /** - * @brief Validates that the provided span of keys is ordered and continuous. - * Logs errors if validation fails. - * @param new_keys The span of keys to validate. - * @return True if keys are valid, false otherwise. - */ + * @brief Validates that the provided span of keys is ordered and continuous. + * Logs errors if validation fails. + * @param new_keys The span of keys to validate. + * @return True if keys are valid, false otherwise. + */ static bool validate_new_keys(keys_span_type new_keys) { static_assert(has_index); if (new_keys.empty()) { @@ -111,11 +106,9 @@ namespace OpenVic { if (new_keys.size() != expected_capacity) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with incremental indices. Expected capacity {} but got {} keys.", - type_name(), - type_name(), - expected_capacity, - new_keys.size() + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with " + "incremental indices. Expected capacity {} but got {} keys.", + type_name(), type_name(), expected_capacity, new_keys.size() ); assert(new_keys.size() == expected_capacity); return false; @@ -125,13 +118,10 @@ namespace OpenVic { const auto expected_index = index_type { underlying_type(min_index + i) }; if (new_keys[i].index != expected_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with incremental indices. " + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with " + "incremental indices. " "Expected index {} but got {} at position {}.", - type_name(), - type_name(), - expected_index, - new_keys[i].index, - i + type_name(), type_name(), expected_index, new_keys[i].index, i ); assert(new_keys[i].index == expected_index); return false; @@ -141,10 +131,10 @@ namespace OpenVic { return true; } - //could be rewritten to return iterators for both this and other. - //that would overcomplicate it with const & non-const - template - keys_span_type get_shared_keys(IndexedFlatMap const& other) const { + // could be rewritten to return iterators for both this and other. + // that would overcomplicate it with const & non-const + template + keys_span_type get_shared_keys(IndexedFlatMap const& other) const { if (other.get_min_index() >= min_index && other.get_max_index() <= max_index) { return other.get_keys(); } @@ -158,47 +148,44 @@ namespace OpenVic { const size_t shared_count = 1 + max_shared_index - min_shared_index; const size_t other_keys_offset = min_shared_index - other.get_min_index(); - return {other.get_keys().data() + other_keys_offset, shared_count}; + return { other.get_keys().data() + other_keys_offset, shared_count }; } /** - * @brief Checks if the 'other' IndexedFlatMap's key span is a subset of 'this' map's key span, - * based purely on index ranges. - * Logs a fatal error if not compatible. - * @param other The other IndexedFlatMap to compare with. - * @return True if compatible as a subset, false otherwise. - */ - template - bool check_subset_span_match(IndexedFlatMap const& other) const { + * @brief Checks if the 'other' IndexedFlatMap's key span is a subset of 'this' map's key span, + * based purely on index ranges. + * Logs a fatal error if not compatible. + * @param other The other IndexedFlatMap to compare with. + * @return True if compatible as a subset, false otherwise. + */ + template + bool check_subset_span_match(IndexedFlatMap const& other) const { // Check if 'other's index range is contained within 'this's index range if (!(other.get_min_index() >= min_index && other.get_max_index() <= max_index)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> subset operation requires the right-hand map's index range " "({}-{}) to be a subset of the left-hand map's index range ({}-{}).", - type_name(), - type_name(), - other.get_min_index(), - other.get_max_index(), - min_index, - max_index + type_name(), type_name(), other.get_min_index(), other.get_max_index(), + min_index, max_index ); assert(other.get_min_index() >= min_index && other.get_max_index() <= max_index); return false; } - // There is no check for keys.data() being identical as KeyType objects are considered functionally equivalent if their index values match. + // There is no check for keys.data() being identical as KeyType objects are considered functionally equivalent if + // their index values match. return true; } - - //vector + + // vector constexpr IndexedFlatMap() requires std::is_move_constructible_v || std::is_copy_constructible_v - : values(), keys(), min_index(0), max_index(0) {} + : values(), keys(), min_index(0), max_index(0) {} - //FixedVector + // FixedVector constexpr IndexedFlatMap() - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - : values(0), keys(), min_index(0), max_index(0) {} + requires(!std::is_move_constructible_v) && (!std::is_copy_constructible_v) + : values(0), keys(), min_index(0), max_index(0) {} public: static constexpr IndexedFlatMap create_empty() { @@ -206,30 +193,28 @@ namespace OpenVic { } /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct + * `ValueType`. This is used to generate values for each key in the provided span. + */ template - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - //value_generator(key) doesn't return std:tuple<...> - && (!specialization_of>, std::tuple>) - //ValueType(value_generator(key)) is valid constructor call - && std::constructible_from()(std::declval()))> - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { new_keys.front().index }, - max_index { new_keys.back().index }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) + // value_generator(key) doesn't return std:tuple<...> + && + (!specialization_of< + std::remove_cvref_t>, std::tuple>) + // ValueType(value_generator(key)) is valid constructor call + && std::constructible_from< + ValueType, decltype(std::declval()(std::declval()))> + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) + : keys(new_keys), min_index { new_keys.front().index }, max_index { new_keys.back().index }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -246,30 +231,30 @@ namespace OpenVic { } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct + * `ValueType`. This is used to generate values for each key in the provided span. + */ template - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - //value_generator(key) doesn't return std:tuple<...> - && (!specialization_of>, std::tuple>) - //ValueType(value_generator(key)) is valid constructor call - && std::constructible_from()(std::declval()))> - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { new_keys.front().index }, - max_index { new_keys.back().index }, - values { new_keys.size() } { + requires(!std::is_move_constructible_v) && + (!std::is_copy_constructible_v) + // value_generator(key) doesn't return std:tuple<...> + && + (!specialization_of< + std::remove_cvref_t>, std::tuple>) + // ValueType(value_generator(key)) is valid constructor call + && std::constructible_from< + ValueType, decltype(std::declval()(std::declval()))> + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) + : keys(new_keys), min_index { new_keys.front().index }, max_index { new_keys.back().index }, + values { new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -285,37 +270,36 @@ namespace OpenVic { } /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. + * This is used to generate values for each key in the provided span. + */ template - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - //value_generator(key) returns tuple - && specialization_of>, std::tuple> - //ValueType(...value_generator(key)) is valid constructor call - && requires(GeneratorTemplateType&& value_generator) { { - std::apply( - [](auto&&... args) { - ValueType obj{std::forward(args)...}; - }, - value_generator(std::declval()) - ) - }; } - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType&& value_generator - ) : keys(new_keys), - min_index { new_keys.front().index }, - max_index { new_keys.back().index }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) + // value_generator(key) returns tuple + && + specialization_of< + std::remove_cvref_t>, std::tuple> + // ValueType(...value_generator(key)) is valid constructor call + && requires(GeneratorTemplateType&& value_generator) { + { + std::apply( + [](auto&&... args) { + ValueType obj { std::forward(args)... }; + }, + value_generator(std::declval()) + ) + }; + } + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType&& value_generator) + : keys(new_keys), min_index { new_keys.front().index }, max_index { new_keys.back().index }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -333,37 +317,38 @@ namespace OpenVic { } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. + * This is used to generate values for each key in the provided span. + */ template - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - //value_generator(key) returns tuple - && specialization_of>, std::tuple> - //ValueType(...value_generator(key)) is valid constructor call - && requires(GeneratorTemplateType value_generator) { { - std::apply( - [](auto&&... args) { - ValueType obj{std::forward(args)...}; - }, - value_generator(std::declval()) - ) - }; } - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values { new_keys.size() } { + requires(!std::is_move_constructible_v) && + (!std::is_copy_constructible_v) + // value_generator(key) returns tuple + && + specialization_of< + std::remove_cvref_t>, std::tuple> + // ValueType(...value_generator(key)) is valid constructor call + && requires(GeneratorTemplateType value_generator) { + { + std::apply( + [](auto&&... args) { + ValueType obj { std::forward(args)... }; + }, + value_generator(std::declval()) + ) + }; + } + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) + : keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values { new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -380,22 +365,22 @@ namespace OpenVic { } /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. - * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking `KeyType const&`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * - * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. + * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking + * `KeyType const&`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * + * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. + */ IndexedFlatMap(keys_span_type new_keys) - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - && (std::default_initializable || std::constructible_from) - : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) && + (std::default_initializable || std::constructible_from) + : keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -413,22 +398,22 @@ namespace OpenVic { } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. - * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking `KeyType const&`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * - * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. + * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking + * `KeyType const&`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * + * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. + */ IndexedFlatMap(keys_span_type new_keys) - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - && (std::default_initializable || std::constructible_from) - : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values { new_keys.size() } { + requires(!std::is_move_constructible_v) && (!std::is_copy_constructible_v) && + (std::default_initializable || std::constructible_from) + : keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values { new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -447,24 +432,23 @@ namespace OpenVic { } /** - * @brief Sets the value associated with a key using copy assignment. - */ + * @brief Sets the value associated with a key using copy assignment. + */ void set(ForwardedKeyType const& key, ValueType const& value) - requires std::assignable_from { + requires std::assignable_from + { static_assert(has_index); values[get_internal_index_from_key(key)] = value; } /** - * @brief Sets the value associated with a key using move assignment (via std::swap). - */ + * @brief Sets the value associated with a key using move assignment (via std::swap). + */ void set(ForwardedKeyType const& key, ValueType&& value) - requires std::movable { + requires std::movable + { static_assert(has_index); - std::swap( - values[get_internal_index_from_key(key)], - value - ); + std::swap(values[get_internal_index_from_key(key)], value); } constexpr ValueType& at(ForwardedKeyType const& key) { @@ -478,18 +462,14 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ValueType& at_index(const index_t typed_index) { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), type_name(), index, min_index, max_index ); assert(index >= min_index && index <= max_index); } @@ -497,18 +477,14 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ValueType const& at_index(const index_t typed_index) const { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), type_name(), index, min_index, max_index ); assert(index >= min_index && index <= max_index); } @@ -516,18 +492,14 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ForwardedKeyType const& get_key_at_index(const index_t typed_index) const { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), type_name(), index, min_index, max_index ); assert(index >= min_index && index <= max_index); } @@ -540,8 +512,7 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr bool contains_index(const index_t typed_external_index) const { const std::size_t external_index = get_index_as_size_t(typed_external_index); return external_index >= min_index && external_index <= max_index; @@ -550,7 +521,7 @@ namespace OpenVic { constexpr keys_span_type const& get_keys() const { return keys; } - + constexpr forwardable_span get_values() { return values; } @@ -576,19 +547,21 @@ namespace OpenVic { } /** - * @brief Fills all elements in the map with a specified value. - * The capacity and index range remain unchanged. - * @param value The value to fill all elements with. - * - * @note This method requires `ValueType` to be copy-constructible and copy-assignable. - */ + * @brief Fills all elements in the map with a specified value. + * The capacity and index range remain unchanged. + * @param value The value to fill all elements with. + * + * @note This method requires `ValueType` to be copy-constructible and copy-assignable. + */ void fill(ValueType const& value) - requires std::copy_constructible && std::assignable_from { + requires std::copy_constructible && std::assignable_from + { values.assign(values.size(), value); } constexpr void copy_values_from(IndexedFlatMap const& other) - requires std::assignable_from { + requires std::assignable_from + { static_assert(has_index); for (ForwardedKeyType const& key : get_shared_keys(other)) { set(key, other.at(key)); @@ -596,16 +569,17 @@ namespace OpenVic { } /** - * @brief Reinitializes all elements in the map using a provided value generator function. - * This overload is chosen for types that are copyable (have a copy constructor and copy assignment). - * The capacity and index range remain unchanged. - * @param value_generator A callable that takes a `KeyType const&` and - * returns a `ValueType`. This is used to generate a new value for each slot. - * - * @note This method requires `ValueType` to be copy-assignable. - */ + * @brief Reinitializes all elements in the map using a provided value generator function. + * This overload is chosen for types that are copyable (have a copy constructor and copy assignment). + * The capacity and index range remain unchanged. + * @param value_generator A callable that takes a `KeyType const&` and + * returns a `ValueType`. This is used to generate a new value for each slot. + * + * @note This method requires `ValueType` to be copy-assignable. + */ void reinitialize_with_generator(strict_regular_invocable_r auto&& value_generator) - requires std::copyable { + requires std::copyable + { for (iterator it = begin(); it < end(); it++) { auto& [key, value] = *it; value = value_generator(key); // Copy/Move assignment @@ -613,17 +587,18 @@ namespace OpenVic { } /** - * @brief Reinitializes all elements in the map using a provided value generator function. - * This overload is chosen for types that are movable but NOT copyable. - * The capacity and index range remain unchanged. - * @param value_generator A callable that takes a `KeyType const&` and - * returns a `ValueType`. This is used to generate a new value for each slot. - * - * @note This method destroys existing elements and constructs new ones in place, - * which is often more efficient for move-only types. - */ + * @brief Reinitializes all elements in the map using a provided value generator function. + * This overload is chosen for types that are movable but NOT copyable. + * The capacity and index range remain unchanged. + * @param value_generator A callable that takes a `KeyType const&` and + * returns a `ValueType`. This is used to generate a new value for each slot. + * + * @note This method destroys existing elements and constructs new ones in place, + * which is often more efficient for move-only types. + */ void reinitialize_with_generator(strict_regular_invocable_r auto&& value_generator) - requires std::movable && (!std::copyable) { + requires std::movable && (!std::copyable) + { values.clear(); for (ForwardedKeyType const& key : keys) { // Emplace directly, using move construction if generator returns rvalue @@ -641,16 +616,19 @@ namespace OpenVic { // Unary minus operator IndexedFlatMap operator-() const - requires unary_negatable { + requires unary_negatable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return -this->at(key); }); } - template - IndexedFlatMap operator+(IndexedFlatMap const& other) const - requires addable { + template + IndexedFlatMap + operator+(IndexedFlatMap const& other) const + requires addable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -670,9 +648,11 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator-(IndexedFlatMap const& other) const - requires subtractable { + template + IndexedFlatMap + operator-(IndexedFlatMap const& other) const + requires subtractable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -687,9 +667,11 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator*(IndexedFlatMap const& other) const - requires multipliable { + template + IndexedFlatMap + operator*(IndexedFlatMap const& other) const + requires multipliable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -704,9 +686,11 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator/(IndexedFlatMap const& other) const - requires divisible { + template + IndexedFlatMap + operator/(IndexedFlatMap const& other) const + requires divisible + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -718,12 +702,10 @@ namespace OpenVic { if (other.at(key) == static_cast(0)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + type_name(), type_name(), key.index ); assert(other.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } return this->at(key) / other.at(key); } else { @@ -732,11 +714,13 @@ namespace OpenVic { }); } - template + template IndexedFlatMap divide_handle_zero( - IndexedFlatMap const& other, + IndexedFlatMap const& other, strict_regular_invocable_r auto&& handle_div_by_zero - ) const requires divisible { + ) const + requires divisible + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -745,10 +729,7 @@ namespace OpenVic { return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { if (other.contains(key)) { if (other.at(key) == static_cast(0)) { - return std::forward(handle_div_by_zero)( - this->at(key), - other.at(key) - ); + return std::forward(handle_div_by_zero)(this->at(key), other.at(key)); } return this->at(key) / other.at(key); } else { @@ -758,9 +739,10 @@ namespace OpenVic { } // Binary addition operator (Map + Scalar) - template + template IndexedFlatMap operator+(ScalarType const& scalar) const - requires addable { + requires addable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) + scalar; @@ -768,9 +750,10 @@ namespace OpenVic { } // Binary subtraction operator (Map - Scalar) - template + template IndexedFlatMap operator-(ScalarType const& scalar) const - requires subtractable { + requires subtractable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) - scalar; @@ -778,9 +761,10 @@ namespace OpenVic { } // Binary multiplication operator (Map * Scalar) - template + template IndexedFlatMap operator*(ScalarType const& scalar) const - requires multipliable { + requires multipliable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) * scalar; @@ -788,27 +772,28 @@ namespace OpenVic { } // Binary division operator (Map / Scalar) - template + template IndexedFlatMap operator/(ScalarType const& scalar) const - requires divisible { + requires divisible + { static_assert(has_index); if (scalar == static_cast(0)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero for scalar operation.", - type_name(), - type_name() + type_name(), type_name() ); assert(scalar != static_cast(0)); - //continue and let it throw + // continue and let it throw } return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) / scalar; }); } - template - IndexedFlatMap& operator+=(IndexedFlatMap const& other) - requires add_assignable { + template + IndexedFlatMap& operator+=(IndexedFlatMap const& other) + requires add_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; // Return current state on error @@ -821,9 +806,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator-=(IndexedFlatMap const& other) - requires subtract_assignable { + template + IndexedFlatMap& operator-=(IndexedFlatMap const& other) + requires subtract_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -835,9 +821,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator*=(IndexedFlatMap const& other) - requires multiply_assignable { + template + IndexedFlatMap& operator*=(IndexedFlatMap const& other) + requires multiply_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -849,9 +836,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator/=(IndexedFlatMap const& other) - requires divide_assignable && equalable { + template + IndexedFlatMap& operator/=(IndexedFlatMap const& other) + requires divide_assignable && equalable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -861,12 +849,10 @@ namespace OpenVic { if (other.at(key) == static_cast(0)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + type_name(), type_name(), key.index ); assert(other.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } this->at(key) /= other.at(key); } @@ -874,9 +860,10 @@ namespace OpenVic { } // Compound assignment addition operator (Map += Scalar) - template + template IndexedFlatMap& operator+=(ScalarType const& scalar) - requires add_assignable { + requires add_assignable + { for (ValueType& val : values) { val += scalar; } @@ -884,9 +871,10 @@ namespace OpenVic { } // Compound assignment subtraction operator (Map -= Scalar) - template + template IndexedFlatMap& operator-=(ScalarType const& scalar) - requires subtract_assignable { + requires subtract_assignable + { for (ValueType& val : values) { val -= scalar; } @@ -894,9 +882,10 @@ namespace OpenVic { } // Compound assignment multiplication operator (Map *= Scalar) - template + template IndexedFlatMap& operator*=(ScalarType const& scalar) - requires multiply_assignable { + requires multiply_assignable + { for (ValueType& val : values) { val *= scalar; } @@ -904,17 +893,17 @@ namespace OpenVic { } // Compound assignment division operator (Map /= Scalar) - template + template IndexedFlatMap& operator/=(ScalarType const& scalar) - requires divide_assignable { + requires divide_assignable + { if (scalar == static_cast(0)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero for scalar operation.", - type_name(), - type_name() + type_name(), type_name() ); assert(scalar != static_cast(0)); - //continue and let it throw + // continue and let it throw } for (ValueType& val : values) { val /= scalar; @@ -922,12 +911,11 @@ namespace OpenVic { return *this; } - template + template constexpr IndexedFlatMap& rescale(ScalarType const& new_total) - requires std::default_initializable - && add_assignable - && multiply_assignable - && divide_assignable { + requires std::default_initializable && add_assignable && + multiply_assignable && divide_assignable + { static_assert(has_index); bool has_any_non_zero_value = false; const ValueType zero = static_cast(0); @@ -945,7 +933,7 @@ namespace OpenVic { } // --- Iterators for Key-Value Pairs --- - template + template class BasicIterator { public: using value_type = std::pair>; @@ -954,19 +942,22 @@ namespace OpenVic { using iterator_category = std::random_access_iterator_tag; private: - std::conditional_t value_it; + std::conditional_t + value_it; typename keys_span_type::iterator key_it; public: // Constructor BasicIterator( - std::conditional_t val_it, + std::conditional_t + val_it, typename keys_span_type::iterator k_it - ) : value_it(val_it), key_it(k_it) {} + ) + : value_it(val_it), key_it(k_it) {} // Dereference operator reference operator*() const { - return {*key_it, *value_it}; + return { *key_it, *value_it }; } // Arrow operator (for member access) @@ -980,7 +971,7 @@ namespace OpenVic { // For now, direct access to first/second is assumed. }; Proxy operator->() const { - return {*key_it, *value_it}; + return { *key_it, *value_it }; } // Pre-increment @@ -1102,19 +1093,17 @@ namespace OpenVic { }; // Non-member binary operators for (Scalar op Map) - template - IndexedFlatMap operator+( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires addable { + template + IndexedFlatMap operator+(ScalarType const& scalar, IndexedFlatMap const& map) + requires addable + { return map + scalar; // Delegate to the member operator } - template - IndexedFlatMap operator-( - ValueType const& scalar, - IndexedFlatMap const& map - ) requires subtractable { + template + IndexedFlatMap operator-(ValueType const& scalar, IndexedFlatMap const& map) + requires subtractable + { static_assert(has_index); // Scalar - Map is not simply map - scalar, so we implement it directly return IndexedFlatMap(map.get_keys(), [&](KeyType const& key) { @@ -1122,32 +1111,28 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator*( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires multipliable { + template + IndexedFlatMap operator*(ScalarType const& scalar, IndexedFlatMap const& map) + requires multipliable + { return map * scalar; // Delegate to the member operator } - template - IndexedFlatMap operator/( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires divisible { + template + IndexedFlatMap operator/(ScalarType const& scalar, IndexedFlatMap const& map) + requires divisible + { static_assert(has_index); return IndexedFlatMap(map.get_keys(), [&](KeyType const& key) { if (map.at(key) == static_cast(0)) { spdlog::error_s( "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> scalar division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + type_name(), type_name(), key.index ); assert(map.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } return scalar / map.at(key); }); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/OptionalBool.hpp b/src/openvic-simulation/types/OptionalBool.hpp index 4770eebac..d44ccffbe 100644 --- a/src/openvic-simulation/types/OptionalBool.hpp +++ b/src/openvic-simulation/types/OptionalBool.hpp @@ -3,9 +3,5 @@ #include namespace OpenVic { - enum struct OptionalBool : std::uint8_t { - UNSPECIFIED = 0, - TRUE = 1, - FALSE = 2 - }; -} \ No newline at end of file + enum struct OptionalBool : std::uint8_t { UNSPECIFIED = 0, TRUE = 1, FALSE = 2 }; +} diff --git a/src/openvic-simulation/types/OrderedContainers.hpp b/src/openvic-simulation/types/OrderedContainers.hpp index f1c1d942f..aeb68e94a 100644 --- a/src/openvic-simulation/types/OrderedContainers.hpp +++ b/src/openvic-simulation/types/OrderedContainers.hpp @@ -8,10 +8,10 @@ #include #include -#include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/core/portable/Deque.hpp" #include "openvic-simulation/core/string/Utility.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/utility/Containers.hpp" #include #include @@ -55,12 +55,12 @@ namespace OpenVic { // Specialization for reference_wrapper template - struct default_equal_to_selector> { - using type = std::equal_to>; + struct default_equal_to_selector> { + using type = std::equal_to>; }; template - struct default_equal_to_selector> { - using type = std::equal_to>; + struct default_equal_to_selector> { + using type = std::equal_to>; }; template diff --git a/src/openvic-simulation/types/OrderedContainersMath.hpp b/src/openvic-simulation/types/OrderedContainersMath.hpp index 5527ba03d..3387ab1a8 100644 --- a/src/openvic-simulation/types/OrderedContainersMath.hpp +++ b/src/openvic-simulation/types/OrderedContainersMath.hpp @@ -3,114 +3,108 @@ #include #include -#include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/OrderedContainers.hpp" namespace OpenVic { - template + template constexpr ordered_map operator-(ordered_map const& rhs) { ordered_map result {}; - auto view = rhs | std::views::transform( - [](KeyType const& key, ValueType const& value) { - return std::make_pair(key, -value); - } - ); + auto view = rhs | std::views::transform([](KeyType const& key, ValueType const& value) { + return std::make_pair(key, -value); + }); result.insert(view.begin(), view.end()); return result; } - template - constexpr ordered_map& operator+=( - ordered_map& lhs, - ordered_map const& rhs - ) requires add_assignable { + template + constexpr ordered_map& + operator+=(ordered_map& lhs, ordered_map const& rhs) + requires add_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] += rhs_value; } return lhs; } - template - constexpr ordered_map& operator-=( - ordered_map& lhs, - ordered_map const& rhs - ) requires subtract_assignable { + template + constexpr ordered_map& + operator-=(ordered_map& lhs, ordered_map const& rhs) + requires subtract_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] -= rhs_value; } return lhs; } - template - constexpr ordered_map& operator*=( - ordered_map& lhs, - ordered_map const& rhs - ) requires multiply_assignable { + template + constexpr ordered_map& + operator*=(ordered_map& lhs, ordered_map const& rhs) + requires multiply_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] *= rhs_value; } return lhs; } - template - constexpr ordered_map& operator/=( - ordered_map& lhs, - ordered_map const& rhs - ) requires divide_assignable { + template + constexpr ordered_map& + operator/=(ordered_map& lhs, ordered_map const& rhs) + requires divide_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] = rhs_value; } return lhs; } - template - constexpr ordered_map& operator+=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires add_assignable { + template + constexpr ordered_map& operator+=(ordered_map& lhs, RhsValueType const& rhs) + requires add_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() += rhs; } return lhs; } - template - constexpr ordered_map& operator-=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires subtract_assignable { + template + constexpr ordered_map& operator-=(ordered_map& lhs, RhsValueType const& rhs) + requires subtract_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() -= rhs; } return lhs; } - template - constexpr ordered_map& operator*=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires multiply_assignable { + template + constexpr ordered_map& operator*=(ordered_map& lhs, RhsValueType const& rhs) + requires multiply_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() *= rhs; } return lhs; } - template - constexpr ordered_map& operator/=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires divide_assignable { + template + constexpr ordered_map& operator/=(ordered_map& lhs, RhsValueType const& rhs) + requires divide_assignable + { for (auto it = lhs.begin(); it != lhs.end(); ++it) { it.value() /= rhs; } return lhs; } - template - constexpr static ValueType get_total( - ordered_map const& map - ) requires std::is_default_constructible_v { + template + constexpr static ValueType get_total(ordered_map const& map) + requires std::is_default_constructible_v + { ValueType running_total {}; for (auto const& [key, value] : map) { running_total += value; @@ -118,14 +112,13 @@ namespace OpenVic { return running_total; } - template - constexpr static typename ordered_map::const_iterator get_largest_item( - ordered_map const& map - ) requires std::three_way_comparable_with { - constexpr auto pred = []( - typename ordered_map::value_type const& lhs, - typename ordered_map::value_type const& rhs - ) -> bool { + template + constexpr static typename ordered_map::const_iterator + get_largest_item(ordered_map const& map) + requires std::three_way_comparable_with + { + constexpr auto pred = [](typename ordered_map::value_type const& lhs, + typename ordered_map::value_type const& rhs) -> bool { return lhs.second < rhs.second; }; @@ -133,27 +126,27 @@ namespace OpenVic { } /* This function includes a key comparator to choose between entries with equal values. */ - template - constexpr static typename ordered_map::const_iterator get_largest_item_tie_break( - ordered_map const& map, const auto key_pred - ) requires std::three_way_comparable_with { + template + constexpr static typename ordered_map::const_iterator + get_largest_item_tie_break(ordered_map const& map, const auto key_pred) + requires std::three_way_comparable_with + { constexpr auto pred = [key_pred]( - typename ordered_map::value_type const& lhs, - typename ordered_map::value_type const& rhs - ) -> bool { + typename ordered_map::value_type const& lhs, + typename ordered_map::value_type const& rhs + ) -> bool { return lhs.second < rhs.second || (lhs.second == rhs.second && key_pred(lhs.first, rhs.first)); }; return std::max_element(map.begin(), map.end(), pred); } - template + template constexpr static std::pair< - typename ordered_map::const_iterator, - typename ordered_map::const_iterator - > get_largest_two_items( - ordered_map const& map - ) requires std::three_way_comparable_with { + typename ordered_map::const_iterator, typename ordered_map::const_iterator> + get_largest_two_items(ordered_map const& map) + requires std::three_way_comparable_with + { typename ordered_map::const_iterator largest = map.end(), second_largest = map.end(); for (typename ordered_map::const_iterator it = map.begin(); it != map.end(); ++it) { @@ -165,9 +158,6 @@ namespace OpenVic { } } - return std::make_pair( - std::move(largest), - std::move(second_largest) - ); + return std::make_pair(std::move(largest), std::move(second_largest)); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/PopSprite.hpp b/src/openvic-simulation/types/PopSprite.hpp index 3d086342c..7b026c992 100644 --- a/src/openvic-simulation/types/PopSprite.hpp +++ b/src/openvic-simulation/types/PopSprite.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using pop_sprite_t = uint8_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/Signal.hpp b/src/openvic-simulation/types/Signal.hpp index 882ed3d46..73527182c 100644 --- a/src/openvic-simulation/types/Signal.hpp +++ b/src/openvic-simulation/types/Signal.hpp @@ -12,11 +12,11 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/thread/NullMutex.hpp" #include "openvic-simulation/types/CowPtr.hpp" #include "openvic-simulation/types/CowVector.hpp" -#include "openvic-simulation/core/thread/NullMutex.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/Typedefs.hpp" // Based heavily on https://github.com/palacaze/sigslot and https://github.com/mousebyte/sigslot20 diff --git a/src/openvic-simulation/types/TypedIndices.hpp b/src/openvic-simulation/types/TypedIndices.hpp index a17451ed1..3c526fa7e 100644 --- a/src/openvic-simulation/types/TypedIndices.hpp +++ b/src/openvic-simulation/types/TypedIndices.hpp @@ -11,14 +11,14 @@ #define TYPED_INDEX_CUSTOM(name, base_type) \ namespace OpenVic { \ struct name : type_safe::strong_typedef, \ - type_safe::strong_typedef_op::equality_comparison, \ - type_safe::strong_typedef_op::relational_comparison, \ - type_safe::strong_typedef_op::integer_arithmetic { \ + type_safe::strong_typedef_op::equality_comparison, \ + type_safe::strong_typedef_op::relational_comparison, \ + type_safe::strong_typedef_op::integer_arithmetic { \ using strong_typedef::strong_typedef; \ }; \ } \ namespace std { \ - template <> \ + template<> \ struct hash : type_safe::hashable {}; \ } \ template<> \ @@ -54,16 +54,16 @@ TYPED_INDEX(terrain_type_index_t) namespace OpenVic { struct province_index_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } namespace std { - template <> + template<> struct hash : type_safe::hashable {}; } template<> diff --git a/src/openvic-simulation/types/TypedSpan.hpp b/src/openvic-simulation/types/TypedSpan.hpp index 5e58fbdac..9be5c61bd 100644 --- a/src/openvic-simulation/types/TypedSpan.hpp +++ b/src/openvic-simulation/types/TypedSpan.hpp @@ -4,15 +4,13 @@ #include -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/portable/ForwardableSpan.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" namespace OpenVic { template< - derived_from_specialization_of IndexType, - typename ValueType, - size_t _Extent = std::dynamic_extent - > + derived_from_specialization_of IndexType, typename ValueType, + size_t _Extent = std::dynamic_extent> struct TypedSpan : public forwardable_span { public: using forwardable_span::forwardable_span; @@ -27,7 +25,7 @@ namespace OpenVic { } constexpr operator TypedSpan() { - return TypedSpan{*this}; + return TypedSpan { *this }; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/UniqueId.hpp b/src/openvic-simulation/types/UniqueId.hpp index 27c1eed91..f72a7498c 100644 --- a/src/openvic-simulation/types/UniqueId.hpp +++ b/src/openvic-simulation/types/UniqueId.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using unique_id_t = uint64_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/UnitBranchType.hpp b/src/openvic-simulation/types/UnitBranchType.hpp index 2db89e5c3..be25b09c5 100644 --- a/src/openvic-simulation/types/UnitBranchType.hpp +++ b/src/openvic-simulation/types/UnitBranchType.hpp @@ -26,53 +26,41 @@ namespace OpenVic { using ArmyInstance = UnitInstanceGroupBranched; using NavyInstance = UnitInstanceGroupBranched; - + static constexpr std::string_view get_branch_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "land"; - case NAVAL: - return "naval"; - default: - return "INVALID BRANCH"; + case LAND: return "land"; + case NAVAL: return "naval"; + default: return "INVALID BRANCH"; } } static constexpr std::string_view get_branched_unit_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "regiment"; - case NAVAL: - return "ship"; - default: - return "INVALID UNIT BRANCH"; + case LAND: return "regiment"; + case NAVAL: return "ship"; + default: return "INVALID UNIT BRANCH"; } } static constexpr std::string_view get_branched_unit_group_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "army"; - case NAVAL: - return "navy"; - default: - return "INVALID UNIT GROUP BRANCH"; + case LAND: return "army"; + case NAVAL: return "navy"; + default: return "INVALID UNIT GROUP BRANCH"; } } static constexpr std::string_view get_branched_leader_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "general"; - case NAVAL: - return "admiral"; - default: - return "INVALID LEADER BRANCH"; + case LAND: return "general"; + case NAVAL: return "admiral"; + default: return "INVALID LEADER BRANCH"; } } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/UnitVariant.hpp b/src/openvic-simulation/types/UnitVariant.hpp index f1711281b..93533fb8f 100644 --- a/src/openvic-simulation/types/UnitVariant.hpp +++ b/src/openvic-simulation/types/UnitVariant.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using unit_variant_t = uint8_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/ValueHistory.hpp b/src/openvic-simulation/types/ValueHistory.hpp index b931d4e94..83da0e10c 100644 --- a/src/openvic-simulation/types/ValueHistory.hpp +++ b/src/openvic-simulation/types/ValueHistory.hpp @@ -11,31 +11,31 @@ namespace OpenVic { using base_type = RingBuffer; using typename base_type::allocator_type; - using typename base_type::size_type; - using typename base_type::iterator; using typename base_type::const_iterator; - using typename base_type::reverse_iterator; - using typename base_type::const_reverse_iterator; - using typename base_type::reference; - using typename base_type::const_reference; - using typename base_type::pointer; using typename base_type::const_pointer; + using typename base_type::const_reference; + using typename base_type::const_reverse_iterator; using typename base_type::difference_type; + using typename base_type::iterator; + using typename base_type::pointer; + using typename base_type::reference; + using typename base_type::reverse_iterator; + using typename base_type::size_type; using base_type::operator[]; - using base_type::size; - using base_type::capacity; - using base_type::empty; + using base_type::back; using base_type::begin; - using base_type::end; + using base_type::capacity; using base_type::cbegin; using base_type::cend; - using base_type::rbegin; - using base_type::rend; using base_type::crbegin; using base_type::crend; + using base_type::empty; + using base_type::end; using base_type::front; - using base_type::back; using base_type::push_back; + using base_type::rbegin; + using base_type::rend; + using base_type::size; constexpr ValueHistory() {}; explicit ValueHistory(size_type capacity) : base_type(capacity) {} diff --git a/src/openvic-simulation/types/Vector.hpp b/src/openvic-simulation/types/Vector.hpp index 082bd1d03..dbdacb899 100644 --- a/src/openvic-simulation/types/Vector.hpp +++ b/src/openvic-simulation/types/Vector.hpp @@ -5,11 +5,11 @@ #include -#include "openvic-simulation/types/BasicIterator.hpp" // IWYU pragma: keep -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" // IWYU pragma: keep #include "openvic-simulation/core/Math.hpp" // IWYU pragma: keep #include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep +#include "openvic-simulation/core/template/Concepts.hpp" // IWYU pragma: keep +#include "openvic-simulation/types/BasicIterator.hpp" // IWYU pragma: keep +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #define VEC_TYPE vec2_t #define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) @@ -21,7 +21,9 @@ #undef VEC_TYPE #define VEC_TYPE vec3_t -#define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) #define FOR_VEC_COMPONENTS_END(F, END_F) F(x) F(y) F(z) END_F(z) #include "VectorN.inc" @@ -30,7 +32,10 @@ #undef VEC_TYPE #define VEC_TYPE vec4_t -#define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) \ + SEP F(w) #define FOR_VEC_COMPONENTS_END(F, END_F) F(x) F(y) F(z) F(w) END_F(w) #include "VectorN.inc" diff --git a/src/openvic-simulation/types/VectorN.inc b/src/openvic-simulation/types/VectorN.inc index d1ae54312..fbab0b63b 100644 --- a/src/openvic-simulation/types/VectorN.inc +++ b/src/openvic-simulation/types/VectorN.inc @@ -14,13 +14,18 @@ // They are safe to ignore so long as they don't appear in the compiler log. #ifndef VEC_TYPE - #warning "VEC_TYPE not defined, defaulting to example: vec5_t" - #define VEC_TYPE vec5_t +#warning "VEC_TYPE not defined, defaulting to example: vec5_t" +#define VEC_TYPE vec5_t #endif #ifndef FOR_VEC_COMPONENTS - #warning "FOR_VEC_COMPONENTS not defined, defaulting to example: FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v)" - #define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v) +#warning \ + "FOR_VEC_COMPONENTS not defined, defaulting to example: FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v)" +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) \ + SEP F(w) \ + SEP F(v) #endif #define COMMA , @@ -98,8 +103,10 @@ namespace OpenVic { return rend(); } + // clang-format off #define VEC_CONSTRUCTOR_ARG(v) T new_##v #define VEC_CONSTRUCTOR_INITIALISE(v) v { new_##v } + // clang-format on OV_SPEED_INLINE constexpr VEC_TYPE(FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_ARG, COMMA)) : FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_INITIALISE, COMMA) {} #undef VEC_CONSTRUCTOR_ARG @@ -130,7 +137,9 @@ namespace OpenVic { } #undef VEC_COMPONENT_ABS + // clang-format off #define VEC_COMPONENT_SQUARE(v) v * v + // clang-format on OV_SPEED_INLINE constexpr T length_squared() const { return FOR_VEC_COMPONENTS(VEC_COMPONENT_SQUARE, +); } @@ -143,7 +152,9 @@ namespace OpenVic { } #undef VEC_COMPONENT_DIST_SQUARE + // clang-format off #define VEC_COMPONENT_DOT(v) v * vec.v + // clang-format on template OV_SPEED_INLINE constexpr T dot(VEC_TYPE const& vec) const { return FOR_VEC_COMPONENTS(VEC_COMPONENT_DOT, +); @@ -156,7 +167,9 @@ namespace OpenVic { } #undef VEC_COMPONENT_NONNEGATIVE -#define VEC_COMPONENT_COMPARE(v) if (left.v != right.v) return left.v <=> right.v; +#define VEC_COMPONENT_COMPARE(v) \ + if (left.v != right.v) \ + return left.v <=> right.v; #define VEC_COMPONENT_COMPARE_END(v) return left.v <=> right.v OV_SPEED_INLINE constexpr friend auto operator<=>(VEC_TYPE const& left, VEC_TYPE const& right) { FOR_VEC_COMPONENTS_END(VEC_COMPONENT_COMPARE, VEC_COMPONENT_COMPARE_END); @@ -164,7 +177,9 @@ namespace OpenVic { #undef VEC_COMPONENT_COMPARE #undef VEC_COMPONENT_COMPARE_END -#define VEC_COMPONENT_COMPARE(v) if (v != right.v) return v <=> right.v; +#define VEC_COMPONENT_COMPARE(v) \ + if (v != right.v) \ + return v <=> right.v; #define VEC_COMPONENT_COMPARE_END(v) return v <=> right.v template OV_SPEED_INLINE constexpr auto operator<=>(VEC_TYPE const& right) const { @@ -208,7 +223,7 @@ namespace OpenVic { #define VEC_COMPONENT_ADDEQ(v) v += right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator+=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ, ) return *this; } #undef VEC_COMPONENT_ADDEQ @@ -230,7 +245,7 @@ namespace OpenVic { #define VEC_COMPONENT_ADDEQ_RIGHT(v) v += right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator+=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ_RIGHT, ) return *this; } #undef VEC_COMPONENT_ADDEQ_RIGHT @@ -251,7 +266,7 @@ namespace OpenVic { #define VEC_COMPONENT_SUBEQ(v) v -= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator-=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ, ) return *this; } #undef VEC_COMPONENT_SUBEQ @@ -273,12 +288,14 @@ namespace OpenVic { #define VEC_COMPONENT_SUBEQ_RIGHT(v) v -= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator-=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ_RIGHT, ) return *this; } #undef VEC_COMPONENT_SUBEQ_RIGHT + // clang-format off #define VEC_COMPONENT_MUL(v) left.v * right.v + // clang-format on template OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(VEC_TYPE const& left, VEC_TYPE const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL, COMMA) }; @@ -288,19 +305,23 @@ namespace OpenVic { #define VEC_COMPONENT_MULEQ(v) v *= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator*=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ, ) return *this; } #undef VEC_COMPONENT_MULEQ + // clang-format off #define VEC_COMPONENT_MUL_RIGHT(v) left.v * right + // clang-format on template> S> OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(VEC_TYPE const& left, S const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL_RIGHT, COMMA) }; } #undef VEC_COMPONENT_MUL_RIGHT + // clang-format off #define VEC_COMPONENT_MUL_LEFT(v) left * right.v + // clang-format on template> S> OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(S const& left, VEC_TYPE const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL_LEFT, COMMA) }; @@ -310,7 +331,7 @@ namespace OpenVic { #define VEC_COMPONENT_MULEQ_RIGHT(v) v *= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator*=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ_RIGHT, ) return *this; } #undef VEC_COMPONENT_MULEQ_RIGHT @@ -325,7 +346,7 @@ namespace OpenVic { #define VEC_COMPONENT_DIVEQ(v) v /= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator/=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ, ) return *this; } #undef VEC_COMPONENT_DIVEQ @@ -347,7 +368,7 @@ namespace OpenVic { #define VEC_COMPONENT_DIVEQ_RIGHT(v) v /= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator/=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ_RIGHT, ) return *this; } #undef VEC_COMPONENT_DIVEQ_RIGHT diff --git a/src/openvic-simulation/types/fixed_point/Atomic.hpp b/src/openvic-simulation/types/fixed_point/Atomic.hpp index 1dfc91667..550206002 100644 --- a/src/openvic-simulation/types/fixed_point/Atomic.hpp +++ b/src/openvic-simulation/types/fixed_point/Atomic.hpp @@ -3,8 +3,8 @@ #include #include -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace std { template<> diff --git a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp index 764c7c4fb..9d26bd420 100644 --- a/src/openvic-simulation/types/fixed_point/FixedPoint.hpp +++ b/src/openvic-simulation/types/fixed_point/FixedPoint.hpp @@ -16,14 +16,14 @@ #include +#include "openvic-simulation/core/Math.hpp" +#include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/string/CharConv.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/types/StackString.hpp" +#include "openvic-simulation/utility/Containers.hpp" #include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/Logger.hpp" -#include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/Typedefs.hpp" -#include "openvic-simulation/core/Math.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" /* Sin lookup table */ #include "openvic-simulation/types/fixed_point/FixedPointLUT_sin.hpp" @@ -179,9 +179,7 @@ namespace OpenVic { } OV_SPEED_INLINE constexpr fixed_point_t sqrt() const { - return !is_negative() - ? parse_raw(OpenVic::sqrt(static_cast(value) << PRECISION)) - : _0; + return !is_negative() ? parse_raw(OpenVic::sqrt(static_cast(value) << PRECISION)) : _0; } OV_SPEED_INLINE constexpr bool is_integer() const { @@ -190,7 +188,7 @@ namespace OpenVic { template OV_SPEED_INLINE constexpr T unsafe_truncate() const { - if constexpr(std::unsigned_integral) { + if constexpr (std::unsigned_integral) { assert(OV_likely(!is_negative())); } return value >> PRECISION; @@ -202,9 +200,9 @@ namespace OpenVic { if (!std::is_constant_evaluated()) { if (OV_unlikely(value != 0 && abs() < fixed_point_t::_1)) { spdlog::warn_s( - "0 < abs(Fixed point) < 1, truncation will result in zero, this may be a bug. raw_value: {} as float: {}", - get_raw_value(), - static_cast(*this) + "0 < abs(Fixed point) < 1, truncation will result in zero, this may be a bug. raw_value: {} as float: " + "{}", + get_raw_value(), static_cast(*this) ); } } @@ -220,20 +218,15 @@ namespace OpenVic { OV_SPEED_INLINE constexpr T truncate() const { return static_cast(*this); } - + template OV_SPEED_INLINE static constexpr StrongType multiply_truncate(StrongType const& integer, fixed_point_t const& fp) { - return StrongType(multiply_truncate( - type_safe::get(integer), - fp - )); + return StrongType(multiply_truncate(type_safe::get(integer), fp)); } template OV_SPEED_INLINE static constexpr T multiply_truncate(T const& integer, fixed_point_t const& fp) { - return static_cast( - (static_cast(integer) * fp.get_raw_value()) >> PRECISION - ); + return static_cast((static_cast(integer) * fp.get_raw_value()) >> PRECISION); } template @@ -397,7 +390,7 @@ namespace OpenVic { } struct stack_string; - OV_SPEED_INLINE constexpr stack_string to_array(size_t decimal_places = -1) const; + OV_SPEED_INLINE constexpr stack_string to_array(size_t decimal_places = -1) const; struct stack_string final : StackString<25> { protected: @@ -432,7 +425,9 @@ namespace OpenVic { result = fixed_point_t::max; } else { if (!std::is_constant_evaluated()) { - spdlog::warn_s("parse_capped value exceeded int32 max. It still fits but exceeds fixed_point_t::usable_max"); + spdlog::warn_s( + "parse_capped value exceeded int32 max. It still fits but exceeds fixed_point_t::usable_max" + ); } result = fixed_point_t::parse_raw(value << PRECISION); } @@ -442,25 +437,27 @@ namespace OpenVic { return result; } - + template - OV_SPEED_INLINE static constexpr fixed_point_t from_fraction(StrongType const& numerator, StrongType const& denominator) { + OV_SPEED_INLINE static constexpr fixed_point_t + from_fraction(StrongType const& numerator, StrongType const& denominator) { return from_fraction(type_safe::get(numerator), type_safe::get(denominator)); } template - OV_SPEED_INLINE static constexpr fixed_point_t from_fraction(const TNumerator numerator, const TDenominator denominator) { + OV_SPEED_INLINE static constexpr fixed_point_t + from_fraction(const TNumerator numerator, const TDenominator denominator) { return parse_raw((static_cast(numerator) << PRECISION) / static_cast(denominator)); } static constexpr fixed_point_t from_fraction(const int64_t numerator, const int64_t denominator) { - assert(numerator < 140737488355328LL); //2^47 + assert(numerator < 140737488355328LL); // 2^47 assert(numerator >= -140737488355328LL); //- 2^47 return parse_raw((numerator << PRECISION) / denominator); } static constexpr fixed_point_t from_fraction(const uint64_t numerator, const uint64_t denominator) { - assert(numerator < 281474976710656ULL); //2^48 + assert(numerator < 281474976710656ULL); // 2^48 return parse_raw((numerator << PRECISION) / denominator); } @@ -491,7 +488,7 @@ namespace OpenVic { from_chars = from_chars_integer(begin, dot_pointer, result); } - if (from_chars.ec != std::errc{}) { + if (from_chars.ec != std::errc {}) { return from_chars; } @@ -502,7 +499,7 @@ namespace OpenVic { result += result.is_negative() || (*begin == '-' && result == _0) ? -adder : adder; } - if (from_chars.ec != std::errc{}) { + if (from_chars.ec != std::errc {}) { return { begin, from_chars.ec }; } @@ -690,8 +687,9 @@ namespace OpenVic { return parse_raw(value * numerator / denominator); } - //Preserves accuracy. Performing a normal multiplication of small values results in 0. - OV_SPEED_INLINE constexpr static fixed_point_t mul_div(fixed_point_t const& a, fixed_point_t const& b, fixed_point_t const& denominator) { + // Preserves accuracy. Performing a normal multiplication of small values results in 0. + OV_SPEED_INLINE constexpr static fixed_point_t + mul_div(fixed_point_t const& a, fixed_point_t const& b, fixed_point_t const& denominator) { return a.mul_div(b.value, denominator.value); } @@ -746,10 +744,11 @@ namespace OpenVic { private: // Deterministic // Can produce negative values - OV_SPEED_INLINE static constexpr std::from_chars_result from_chars_integer(char const* str, char const* const end, fixed_point_t& value) { + OV_SPEED_INLINE static constexpr std::from_chars_result + from_chars_integer(char const* str, char const* const end, fixed_point_t& value) { int64_t parsed_value = 0; std::from_chars_result result = string_to_int64(str, end, parsed_value); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { if (parsed_value > std::numeric_limits::max()) { result.ec = std::errc::value_too_large; } else { @@ -761,7 +760,8 @@ namespace OpenVic { // Deterministic // Cannot produce negative values - OV_SPEED_INLINE static constexpr std::from_chars_result from_chars_fraction(char const* begin, char const* end, fixed_point_t& value) { + OV_SPEED_INLINE static constexpr std::from_chars_result + from_chars_fraction(char const* begin, char const* end, fixed_point_t& value) { if (begin && *begin == '-') { return { begin, std::errc::invalid_argument }; } @@ -769,7 +769,7 @@ namespace OpenVic { end = end - begin > PRECISION ? begin + PRECISION : end; uint64_t parsed_value; std::from_chars_result result = string_to_uint64(begin, end, parsed_value); - if (result.ec != std::errc{}) { + if (result.ec != std::errc {}) { return result; } diff --git a/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp b/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp index 82762167f..1e7cd9f89 100644 --- a/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp +++ b/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp @@ -26,9 +26,8 @@ namespace OpenVic { } template - constexpr fixed_point_map_t& fixed_point_map_mul_add( - fixed_point_map_t& lhs, fixed_point_map_t const& rhs, fixed_point_t factor - ) { + constexpr fixed_point_map_t& + fixed_point_map_mul_add(fixed_point_map_t& lhs, fixed_point_map_t const& rhs, fixed_point_t factor) { if (factor != 0) { for (auto const& [key, value] : rhs) { lhs[key] += value * factor; @@ -90,7 +89,6 @@ namespace OpenVic { if (value_cmp != std::strong_ordering::equal) { return value_cmp == std::strong_ordering::less; } - } return rit != rhs.rcend(); diff --git a/src/openvic-simulation/types/fixed_point/Fraction.hpp b/src/openvic-simulation/types/fixed_point/Fraction.hpp index 205a18b08..98eba27db 100644 --- a/src/openvic-simulation/types/fixed_point/Fraction.hpp +++ b/src/openvic-simulation/types/fixed_point/Fraction.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" namespace OpenVic { struct Fraction { @@ -16,4 +16,4 @@ namespace OpenVic { return fixed_point_t::mul_div(lhs, rhs.numerator, rhs.denominator); } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/CompilerFeatureTesting.hpp b/src/openvic-simulation/utility/CompilerFeatureTesting.hpp index 8c9f961c8..154c23611 100644 --- a/src/openvic-simulation/utility/CompilerFeatureTesting.hpp +++ b/src/openvic-simulation/utility/CompilerFeatureTesting.hpp @@ -13,7 +13,7 @@ namespace OpenVic { std::for_each(first, last, f); #else #if defined(__linux__) || defined(__MINGW32__) - // We cannot use std::execution::par here as its implementation uses exceptions, which we have disabled + // We cannot use std::execution::par here as its implementation uses exceptions, which we have disabled std::for_each(first, last, f); #else if constexpr (__cpp_lib_execution >= 201603L) { diff --git a/src/openvic-simulation/utility/DequeMemory.hpp b/src/openvic-simulation/utility/DequeMemory.hpp index 91466539b..0a38866d7 100644 --- a/src/openvic-simulation/utility/DequeMemory.hpp +++ b/src/openvic-simulation/utility/DequeMemory.hpp @@ -12,5 +12,8 @@ namespace OpenVic::utility::memory { FOONATHAN_ALIAS_TEMPLATE(deque, OpenVic::utility::deque>); template - FOONATHAN_ALIAS_TEMPLATE(deque_scoped_alloc, OpenVic::utility::deque>>); + FOONATHAN_ALIAS_TEMPLATE( + deque_scoped_alloc, + OpenVic::utility::deque>> + ); } diff --git a/src/openvic-simulation/utility/Getters.hpp b/src/openvic-simulation/utility/Getters.hpp index 33a660caf..b19756d5a 100644 --- a/src/openvic-simulation/utility/Getters.hpp +++ b/src/openvic-simulation/utility/Getters.hpp @@ -7,10 +7,10 @@ #include #include -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" // IWYU pragma: keep for SPAN_PROPERTY #include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep -#include "openvic-simulation/utility/Containers.hpp" +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" // IWYU pragma: keep for SPAN_PROPERTY #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/utility/Containers.hpp" namespace OpenVic::utility { #if !defined(_MSC_VER) @@ -162,7 +162,7 @@ namespace OpenVic { result.emplace(property.value()); } return result; - }else { + } else { /* Return const reference */ return property; } @@ -198,7 +198,8 @@ public: \ // TODO: Special logic to decide argument type and control assignment. #define PROPERTY_RW(NAME, ...) PROPERTY_RW_ACCESS(NAME, private, __VA_ARGS__) -#define PROPERTY_RW_CUSTOM_NAME(NAME, GETTER_NAME, SETTER_NAME, ...) PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, private, __VA_ARGS__) +#define PROPERTY_RW_CUSTOM_NAME(NAME, GETTER_NAME, SETTER_NAME, ...) \ + PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, private, __VA_ARGS__) #define PROPERTY_RW_ACCESS(NAME, ACCESS, ...) PROPERTY_RW_FULL(NAME, get_##NAME, set_##NAME, ACCESS, __VA_ARGS__) #define PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, ACCESS, ...) \ PROPERTY_FULL(NAME, GETTER_NAME, ACCESS, __VA_ARGS__) \ @@ -216,6 +217,7 @@ public: \ #define PROPERTY_PTR_ACCESS(NAME, ACCESS, ...) \ NAME __VA_OPT__(=) __VA_ARGS__; \ static_assert(std::is_pointer_v && !std::is_const_v>); \ +\ public: \ [[nodiscard]] constexpr decltype(NAME) get_##NAME() { \ return NAME; \ @@ -223,14 +225,15 @@ public: \ [[nodiscard]] constexpr std::add_pointer_t>> get_##NAME() const { \ return NAME; \ } \ -ACCESS: + ACCESS: #define SPAN_PROPERTY(NAME) SPAN_PROPERTY_ACCESS(NAME, private) #define SPAN_PROPERTY_ACCESS(NAME, ACCESS) \ NAME; \ \ public: \ - [[nodiscard]] constexpr OpenVic::forwardable_span> get_##NAME() const { \ + [[nodiscard]] constexpr OpenVic::forwardable_span> get_##NAME() \ + const { \ return NAME; \ } \ ACCESS: diff --git a/src/openvic-simulation/utility/ThreadPool.cpp b/src/openvic-simulation/utility/ThreadPool.cpp index 2fc169548..a205d9c2f 100644 --- a/src/openvic-simulation/utility/ThreadPool.cpp +++ b/src/openvic-simulation/utility/ThreadPool.cpp @@ -5,23 +5,18 @@ #include "openvic-simulation/economy/GoodInstance.hpp" #include "openvic-simulation/economy/trading/GoodMarket.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/TypedSpan.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/utility/Containers.hpp" using namespace OpenVic; void ThreadPool::loop_until_cancelled( - work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - forwardable_span good_keys, - forwardable_span strata_keys, + work_t& work_type, GameRulesManager const& game_rules_manager, GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, forwardable_span country_keys, + forwardable_span good_keys, forwardable_span strata_keys, forwardable_span work_bundles ) { IndexedFlatMap reusable_goods_mask { good_keys }; @@ -33,33 +28,21 @@ void ThreadPool::loop_until_cancelled( static constexpr size_t VECTOR_COUNT = std::max( GoodMarket::VECTORS_FOR_EXECUTE_ORDERS, - std::max( - CountryInstance::VECTORS_FOR_COUNTRY_TICK, - ProvinceInstance::VECTORS_FOR_PROVINCE_TICK - ) + std::max(CountryInstance::VECTORS_FOR_COUNTRY_TICK, ProvinceInstance::VECTORS_FOR_PROVINCE_TICK) ); std::array, VECTOR_COUNT> reusable_vectors; std::span, VECTOR_COUNT> reusable_vectors_span = std::span(reusable_vectors); memory::vector reusable_good_index_vector; - PopValuesFromProvince reusable_pop_values { - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - production_type_manager, - pop_defines, - strata_keys - }; + PopValuesFromProvince reusable_pop_values { game_rules_manager, good_instance_manager, modifier_effect_cache, + production_type_manager, pop_defines, strata_keys }; while (!is_cancellation_requested) { work_t work_type_copy; { std::unique_lock thread_lock { thread_mutex }; - thread_condition.wait( - thread_lock, - [this, &work_type]() -> bool { - return is_cancellation_requested || work_type != work_t::NONE; - } - ); + thread_condition.wait(thread_lock, [this, &work_type]() -> bool { + return is_cancellation_requested || work_type != work_t::NONE; + }); if (is_cancellation_requested) { return; @@ -69,63 +52,54 @@ void ThreadPool::loop_until_cancelled( } switch (work_type_copy) { - case work_t::NONE: - break; - case work_t::GOOD_EXECUTE_ORDERS: - for (WorkBundle& work_bundle : work_bundles) { - for (GoodMarket& good : work_bundle.goods_chunk) { - good.execute_orders( - reusable_country_map_0_span, - reusable_country_map_1_span, - reusable_vectors_span.first() - ); - } + case work_t::NONE: break; + case work_t::GOOD_EXECUTE_ORDERS: + for (WorkBundle& work_bundle : work_bundles) { + for (GoodMarket& good : work_bundle.goods_chunk) { + good.execute_orders( + reusable_country_map_0_span, reusable_country_map_1_span, + reusable_vectors_span.first() + ); } - break; - case work_t::PROVINCE_TICK: - for (WorkBundle& work_bundle : work_bundles) { - for (ProvinceInstance& province : work_bundle.provinces_chunk) { - province.province_tick( - current_date, - reusable_pop_values, - work_bundle.random_number_generator, - reusable_goods_mask, - reusable_vectors_span.first() - ); - } + } + break; + case work_t::PROVINCE_TICK: + for (WorkBundle& work_bundle : work_bundles) { + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.province_tick( + current_date, reusable_pop_values, work_bundle.random_number_generator, reusable_goods_mask, + reusable_vectors_span.first() + ); } - break; - case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: - for (WorkBundle& work_bundle : work_bundles) { - for (ProvinceInstance& province : work_bundle.provinces_chunk) { - province.initialise_for_new_game( - current_date, - reusable_pop_values, - work_bundle.random_number_generator, - reusable_goods_mask, - reusable_vectors_span.first() - ); - } + } + break; + case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: + for (WorkBundle& work_bundle : work_bundles) { + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.initialise_for_new_game( + current_date, reusable_pop_values, work_bundle.random_number_generator, reusable_goods_mask, + reusable_vectors_span.first() + ); } - break; - case work_t::COUNTRY_TICK_BEFORE_MAP: - for (WorkBundle& work_bundle : work_bundles) { - for (CountryInstance& country : work_bundle.countries_chunk) { - country.country_tick_before_map( - reusable_goods_mask, - reusable_vectors_span.first(), - reusable_good_index_vector - ); - } + } + break; + case work_t::COUNTRY_TICK_BEFORE_MAP: + for (WorkBundle& work_bundle : work_bundles) { + for (CountryInstance& country : work_bundle.countries_chunk) { + country.country_tick_before_map( + reusable_goods_mask, reusable_vectors_span.first(), + reusable_good_index_vector + ); } - break; - case work_t::COUNTRY_TICK_AFTER_MAP: - for (WorkBundle& work_bundle : work_bundles) { - for (CountryInstance& country : work_bundle.countries_chunk) { - country.country_tick_after_map(current_date); - } + } + break; + case work_t::COUNTRY_TICK_AFTER_MAP: + for (WorkBundle& work_bundle : work_bundles) { + for (CountryInstance& country : work_bundle.countries_chunk) { + country.country_tick_after_map(current_date); } - break; + } + break; } { @@ -159,16 +133,12 @@ void ThreadPool::process_work(const work_t work_type) { void ThreadPool::await_completion() { std::unique_lock completed_lock { completed_mutex }; - completed_condition.wait( - completed_lock, - [this]() -> bool { - return active_work_count == 0; - } - ); + completed_condition.wait(completed_lock, [this]() -> bool { + return active_work_count == 0; + }); } -ThreadPool::ThreadPool(Date const& new_current_date) - : current_date {new_current_date} {} +ThreadPool::ThreadPool(Date const& new_current_date) : current_date { new_current_date } {} ThreadPool::~ThreadPool() { { @@ -182,23 +152,18 @@ ThreadPool::~ThreadPool() { } void ThreadPool::initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span good_keys, - forwardable_span strata_keys, - forwardable_span goods, - forwardable_span countries, - forwardable_span provinces + GameRulesManager const& game_rules_manager, GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, forwardable_span good_keys, + forwardable_span strata_keys, forwardable_span goods, + forwardable_span countries, forwardable_span provinces ) { if (threads.size() > 0) { spdlog::error_s("Attempted to initialise ThreadPool again."); return; } - RandomU32 master_rng { }; //TODO seed? + RandomU32 master_rng {}; // TODO seed? const auto [goods_quotient, goods_remainder] = std::ldiv(goods.size(), WORK_BUNDLE_COUNT); @@ -209,28 +174,20 @@ void ThreadPool::initialise_threadpool( auto provinces_begin = provinces.begin(); for (size_t i = 0; i < WORK_BUNDLE_COUNT; i++) { - const size_t goods_chunk_size = i < goods_remainder - ? goods_quotient + 1 - : goods_quotient; - const size_t countries_chunk_size = i < countries_remainder - ? countries_quotient + 1 - : countries_quotient; - const size_t provinces_chunk_size = i < provinces_remainder - ? provinces_quotient + 1 - : provinces_quotient; + const size_t goods_chunk_size = i < goods_remainder ? goods_quotient + 1 : goods_quotient; + const size_t countries_chunk_size = i < countries_remainder ? countries_quotient + 1 : countries_quotient; + const size_t provinces_chunk_size = i < provinces_remainder ? provinces_quotient + 1 : provinces_quotient; auto goods_end = goods_begin + goods_chunk_size; auto countries_end = countries_begin + countries_chunk_size; auto provinces_end = provinces_begin + provinces_chunk_size; - all_work_bundles[i] = WorkBundle { - master_rng.generator().serialize(), - std::span{ countries_begin, countries_end }, - std::span{ goods_begin, goods_end }, - std::span{ provinces_begin, provinces_end } - }; + all_work_bundles[i] = + WorkBundle { master_rng.generator().serialize(), std::span { countries_begin, countries_end }, + std::span { goods_begin, goods_end }, + std::span { provinces_begin, provinces_end } }; - //ensure different state for next WorkBundle + // ensure different state for next WorkBundle master_rng.generator().jump(); goods_begin = goods_end; @@ -242,43 +199,23 @@ void ThreadPool::initialise_threadpool( threads.reserve(max_worker_threads); work_per_thread.resize(max_worker_threads, work_t::NONE); - + const auto [work_bundles_quotient, work_bundles_remainder] = std::ldiv(WORK_BUNDLE_COUNT, max_worker_threads); auto work_bundles_begin = all_work_bundles.begin(); for (size_t i = 0; i < max_worker_threads; ++i) { - const size_t work_bundles_chunk_size = i < work_bundles_remainder - ? work_bundles_quotient + 1 - : work_bundles_quotient; + const size_t work_bundles_chunk_size = i < work_bundles_remainder ? work_bundles_quotient + 1 : work_bundles_quotient; auto work_bundles_end = work_bundles_begin + work_bundles_chunk_size; threads.emplace_back( - [ - this, - &work_for_thread = work_per_thread[i], - &game_rules_manager, - &good_instance_manager, - &modifier_effect_cache, - &pop_defines, - &production_type_manager, - countries, - good_keys, - strata_keys, - work_bundles_begin, - work_bundles_end - ]() -> void { + [this, &work_for_thread = work_per_thread[i], &game_rules_manager, &good_instance_manager, &modifier_effect_cache, + &pop_defines, &production_type_manager, countries, good_keys, strata_keys, work_bundles_begin, + work_bundles_end]() -> void { loop_until_cancelled( - work_for_thread, - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - pop_defines, - production_type_manager, - countries, - good_keys, - strata_keys, - std::span{ work_bundles_begin, work_bundles_end } + work_for_thread, game_rules_manager, good_instance_manager, modifier_effect_cache, pop_defines, + production_type_manager, countries, good_keys, strata_keys, + std::span { work_bundles_begin, work_bundles_end } ); } ); @@ -303,6 +240,6 @@ void ThreadPool::process_country_ticks_before_map() { process_work(work_t::COUNTRY_TICK_BEFORE_MAP); } -void ThreadPool::process_country_ticks_after_map(){ +void ThreadPool::process_country_ticks_after_map() { process_work(work_t::COUNTRY_TICK_AFTER_MAP); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/ThreadPool.hpp b/src/openvic-simulation/utility/ThreadPool.hpp index 5b37f0c96..86349dba2 100644 --- a/src/openvic-simulation/utility/ThreadPool.hpp +++ b/src/openvic-simulation/utility/ThreadPool.hpp @@ -5,11 +5,11 @@ #include #include +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" +#include "openvic-simulation/core/random/RandomGenerator.hpp" #include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/utility/Containers.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" -#include "openvic-simulation/core/random/RandomGenerator.hpp" namespace OpenVic { struct GameRulesManager; @@ -21,8 +21,8 @@ namespace OpenVic { struct PopsDefines; struct ProductionTypeManager; struct Strata; - - //bundle work so they always have the same rng regardless of hardware concurrency + + // bundle work so they always have the same rng regardless of hardware concurrency struct WorkBundle { public: RandomU32 random_number_generator; @@ -33,15 +33,11 @@ namespace OpenVic { constexpr WorkBundle() {} WorkBundle( - RandomU32::state_type rng_state, - forwardable_span new_countries_chunk, - forwardable_span new_goods_chunk, - forwardable_span new_provinces_chunk - ) : random_number_generator { rng_state }, - countries_chunk { new_countries_chunk }, - goods_chunk { new_goods_chunk }, - provinces_chunk { new_provinces_chunk } - {} + RandomU32::state_type rng_state, forwardable_span new_countries_chunk, + forwardable_span new_goods_chunk, forwardable_span new_provinces_chunk + ) + : random_number_generator { rng_state }, countries_chunk { new_countries_chunk }, goods_chunk { new_goods_chunk }, + provinces_chunk { new_provinces_chunk } {} }; struct ThreadPool { @@ -68,15 +64,10 @@ namespace OpenVic { bool is_province_tick_requested = false; void loop_until_cancelled( - work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - forwardable_span good_keys, - forwardable_span strata_keys, + work_t& work_type, GameRulesManager const& game_rules_manager, GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, forwardable_span country_keys, + forwardable_span good_keys, forwardable_span strata_keys, forwardable_span work_bundles ); void await_completion(); @@ -87,16 +78,11 @@ namespace OpenVic { ~ThreadPool(); void initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span good_keys, - forwardable_span strata_keys, - forwardable_span goods, - forwardable_span countries, - forwardable_span provinces + GameRulesManager const& game_rules_manager, GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, forwardable_span good_keys, + forwardable_span strata_keys, forwardable_span goods, + forwardable_span countries, forwardable_span provinces ); void process_good_execute_orders(); @@ -105,4 +91,4 @@ namespace OpenVic { void process_country_ticks_before_map(); void process_country_ticks_after_map(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/reactive/DependencyTracker.hpp b/src/openvic-simulation/utility/reactive/DependencyTracker.hpp index 1ea60b491..97210f6ce 100644 --- a/src/openvic-simulation/utility/reactive/DependencyTracker.hpp +++ b/src/openvic-simulation/utility/reactive/DependencyTracker.hpp @@ -27,11 +27,12 @@ namespace OpenVic { changed(); } + protected: signal<> changed; bool is_dirty = true; std::mutex is_dirty_lock; - + virtual ~DependencyTracker() { disconnect_all(); } @@ -44,20 +45,19 @@ namespace OpenVic { const std::lock_guard lock_guard { connections_lock }; connections.clear(); } + public: void track(signal<>& dependency_changed) { const std::lock_guard lock_guard { connections_lock }; - connections.emplace_back( - dependency_changed.connect(&DependencyTracker::mark_dirty, this) - ); + connections.emplace_back(dependency_changed.connect(&DependencyTracker::mark_dirty, this)); } template void track(signal& dependency_changed) { const std::lock_guard lock_guard { connections_lock }; - connections.emplace_back( - dependency_changed.connect([this](Args...) { mark_dirty(); }) - ); + connections.emplace_back(dependency_changed.connect([this](Args...) { + mark_dirty(); + })); } }; } diff --git a/src/openvic-simulation/utility/reactive/DerivedState.hpp b/src/openvic-simulation/utility/reactive/DerivedState.hpp index 38c9369e2..7215993c2 100644 --- a/src/openvic-simulation/utility/reactive/DerivedState.hpp +++ b/src/openvic-simulation/utility/reactive/DerivedState.hpp @@ -1,7 +1,5 @@ #pragma once -#include "DependencyTracker.hpp" - #include #include "openvic-simulation/types/Signal.hpp" @@ -9,8 +7,10 @@ #include "openvic-simulation/utility/Logger.hpp" #include "openvic-simulation/utility/reactive/DependencyTracker.hpp" +#include "DependencyTracker.hpp" + namespace OpenVic { - template + template struct DerivedState : public DependencyTracker { private: T cached_value; @@ -44,17 +44,15 @@ namespace OpenVic { public: template explicit DerivedState(Func&& new_calculate) - requires std::is_default_constructible_v - && std::is_convertible_v> - : calculate { std::forward(new_calculate) }, - cached_value() {} + requires std::is_default_constructible_v && std::is_convertible_v> + : calculate { std::forward(new_calculate) }, cached_value() {} template - requires std::is_convertible_v - && std::is_convertible_v> + requires std::is_convertible_v && + std::is_convertible_v> explicit DerivedState(Func&& new_calculate, InitialValue&& empty_initial_value) : calculate { std::forward(new_calculate) }, - cached_value { std::forward(empty_initial_value) } {} + cached_value { std::forward(empty_initial_value) } {} DerivedState(DerivedState&&) = delete; DerivedState(DerivedState const&) = delete; @@ -77,8 +75,8 @@ namespace OpenVic { recalculate_if_dirty(); return cached_value; } - - //special case where connection may be discarded as the observer handles it + + // special case where connection may be discarded as the observer handles it template requires OpenVic::_detail::signal::Callable connection connect_using_observer(Pmf&& pmf, Ptr&& ptr, OpenVic::_detail::signal::group_id gid = 0) { diff --git a/src/openvic-simulation/utility/reactive/MutableState.hpp b/src/openvic-simulation/utility/reactive/MutableState.hpp index 302dea2a8..718e6fed5 100644 --- a/src/openvic-simulation/utility/reactive/MutableState.hpp +++ b/src/openvic-simulation/utility/reactive/MutableState.hpp @@ -1,18 +1,21 @@ #pragma once -#include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/utility/reactive/DependencyTracker.hpp" namespace OpenVic { - template + template struct ReadOnlyMutableState { private: signal changed; + protected: T value; - constexpr ReadOnlyMutableState() requires std::is_default_constructible_v : value() {} + constexpr ReadOnlyMutableState() + requires std::is_default_constructible_v + : value() {} constexpr explicit ReadOnlyMutableState(T const& new_value) : value { new_value } {} constexpr explicit ReadOnlyMutableState(T&& new_value) : value { std::move(new_value) } {} ReadOnlyMutableState(ReadOnlyMutableState&&) = delete; @@ -29,6 +32,7 @@ namespace OpenVic { value = new_value; changed(value); } + public: template requires std::invocable&> @@ -43,8 +47,8 @@ namespace OpenVic { [[nodiscard]] constexpr T const& get_untracked() const { return value; } - - //special case where connection may be discarded as the observer handles it + + // special case where connection may be discarded as the observer handles it template requires OpenVic::_detail::signal::Callable connection connect_using_observer(Pmf&& pmf, Ptr&& ptr, OpenVic::_detail::signal::group_id gid = 0) { @@ -71,9 +75,11 @@ namespace OpenVic { return changed.disconnect(std::forward(args)...); } }; - template + template struct MutableState : public ReadOnlyMutableState { - constexpr MutableState() requires std::is_default_constructible_v : ReadOnlyMutableState() {} + constexpr MutableState() + requires std::is_default_constructible_v + : ReadOnlyMutableState() {} constexpr explicit MutableState(T const& new_value) : ReadOnlyMutableState(new_value) {} constexpr explicit MutableState(T&& new_value) : ReadOnlyMutableState(std::move(new_value)) {} MutableState(MutableState&&) = delete; @@ -91,21 +97,29 @@ namespace OpenVic { } using ReadOnlyMutableState::value; - MutableState& operator++() requires pre_incrementable { + MutableState& operator++() + requires pre_incrementable + { set(++value); return *this; } - void operator++(int) requires post_incrementable { + void operator++(int) + requires post_incrementable + { set(value++); } - MutableState& operator--() requires pre_decrementable { + MutableState& operator--() + requires pre_decrementable + { set(--value); return *this; } - void operator--(int) requires post_decrementable { + void operator--(int) + requires post_decrementable + { set(value--); } @@ -146,10 +160,10 @@ public: \ } \ template \ requires std::invocable&> \ - [[nodiscard]] T const& get_##NAME(ConnectTemplateType&& connect) { \ + [[nodiscard]] T const& get_##NAME(ConnectTemplateType && connect) { \ return NAME.get(std::forward(connect)); \ } \ - [[nodiscard]] T get_##NAME(DependencyTracker& tracker) { \ + [[nodiscard]] T get_##NAME(DependencyTracker & tracker) { \ return NAME.get(tracker); \ } \ [[nodiscard]] T get_##NAME##_untracked() const { \ diff --git a/tests/src/Helper.hpp b/tests/src/Helper.hpp index 264941fc3..40e9f2c83 100644 --- a/tests/src/Helper.hpp +++ b/tests/src/Helper.hpp @@ -34,11 +34,13 @@ #define _OVSIM_CHECK_FALSE(NAME, ASSIGN_VALUE, ...) _REQUIRE_IMPL("CHECK_FALSE" NAME, false, (void)0, ASSIGN_VALUE, __VA_ARGS__) // clang-format on +// clang-format off #define _OVSIM_CHECK_IF(NAME, ...) \ if (bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; [&] { _OVSIM_CHECK(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); }(), (SNITCH_MACRO_CONCAT(result_, __LINE__))) #define _OVSIM_CHECK_FALSE_IF(NAME, ...) \ if (bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; [&] { _OVSIM_CHECK_FALSE(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); }(), (!SNITCH_MACRO_CONCAT(result_, __LINE__))) +// clang-format on #define CHECK_IF(...) _OVSIM_CHECK_IF("_IF", __VA_ARGS__) diff --git a/tests/src/core/random/WeightedSampling.cpp b/tests/src/core/random/WeightedSampling.cpp index 2ccb0d963..76514db04 100644 --- a/tests/src/core/random/WeightedSampling.cpp +++ b/tests/src/core/random/WeightedSampling.cpp @@ -1,10 +1,11 @@ -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/core/random/WeightedSampling.hpp" #include #include -#include +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" + +#include #include #include @@ -14,27 +15,23 @@ constexpr uint32_t max_random_value = std::numeric_limits().max(); TEST_CASE("WeightedSampling limits", "[WeightedSampling]") { const fixed_point_t weights_sum = fixed_point_t::usable_max; - constexpr size_t perfect_divisor = 257; //4294967295 is perfectly divisible by 257 + constexpr size_t perfect_divisor = 257; // 4294967295 is perfectly divisible by 257 std::array weights {}; assert(weights.size() < std::numeric_limits::max()); constexpr uint32_t step_size = max_random_value / weights.size(); weights.fill(weights_sum / static_cast(weights.size())); for (size_t i = 0; i < weights.size(); ++i) { - CHECK(sample_weighted_index( - i * step_size, - weights, - weights_sum - ) == i); + CHECK(sample_weighted_index(i * step_size, weights, weights_sum) == i); } } TEST_CASE("WeightedSampling weights", "[WeightedSampling]") { - constexpr size_t max_length = 255; //weights_sum = (size^2+size)/2, this needs to be <= fixed_point_t::usable_max + constexpr size_t max_length = 255; // weights_sum = (size^2+size)/2, this needs to be <= fixed_point_t::usable_max std::array weights {}; - + fixed_point_t weights_sum = 0; assert(weights.size() < std::numeric_limits::max()); for (size_t i = 0; i < weights.size(); ++i) { - const fixed_point_t weight = static_cast(1+i); + const fixed_point_t weight = static_cast(1 + i); weights_sum += weight; weights[i] = weight; } @@ -48,10 +45,6 @@ TEST_CASE("WeightedSampling weights", "[WeightedSampling]") { const boost::int128::int128_t max_random_value_128 = max_random_value; const boost::int128::int128_t weights_sum_128 = weights_sum.get_raw_value(); const boost::int128::int128_t random_value = cumulative_weight_128 * max_random_value_128 / weights_sum_128; - CHECK(sample_weighted_index( - static_cast(random_value), - weights, - weights_sum - ) == i); + CHECK(sample_weighted_index(static_cast(random_value), weights, weights_sum) == i); } -} \ No newline at end of file +} diff --git a/tests/src/dataloader/NodeTools.cpp b/tests/src/dataloader/NodeTools.cpp index ca3842d42..6898075bd 100644 --- a/tests/src/dataloader/NodeTools.cpp +++ b/tests/src/dataloader/NodeTools.cpp @@ -22,10 +22,10 @@ #include #include +#include "openvic-simulation/core/string/CharConv.hpp" #include "openvic-simulation/types/Colour.hpp" #include "openvic-simulation/types/Date.hpp" #include "openvic-simulation/types/fixed_point/FixedPoint.hpp" -#include "openvic-simulation/core/string/CharConv.hpp" #include "../types/Colour.hpp" // IWYU pragma: keep #include "Helper.hpp" // IWYU pragma: keep @@ -169,7 +169,8 @@ struct Ast : ovdl::SymbolIntern { StatementList slist; for (size_t index : ranges::views::iota(static_cast(0), count)) { std::to_chars_result result = std::to_chars(hex_array.data(), hex_array.data() + hex_array.size(), index); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { continue; } @@ -188,7 +189,8 @@ struct Ast : ovdl::SymbolIntern { for (auto [index, lhs] : ranges::views::iota(static_cast(0), count) | ranges::views::enumerate) { index %= span_rhs.size(); std::to_chars_result result = std::to_chars(hex_array.data(), hex_array.data() + hex_array.size(), lhs); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { continue; } @@ -329,7 +331,8 @@ TEST_CASE("NodeTools expect integer functions", "[NodeTools][NodeTools-expect-fu decltype(val) check; std::from_chars_result result = std::from_chars(sv.data(), sv.data() + sv.size(), check); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -378,7 +381,8 @@ TEST_CASE("NodeTools expect integer functions", "[NodeTools][NodeTools-expect-fu decltype(val) check; std::from_chars_result result = string_to_uint64(sv, check, base); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -442,7 +446,8 @@ TEST_CASE( fixed_point_t check = 0; std::from_chars_result result = check.from_chars(sv.data(), sv.data() + sv.size()); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -484,7 +489,8 @@ TEST_CASE("NodeTools expect colour functions", "[NodeTools][NodeTools-expect-fun auto callback = [](ListValue const* ptr, colour_t val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == 3); + CHECK_IF (ranges::distance(list) == 3) + ; else { return false; } @@ -529,7 +535,8 @@ TEST_CASE( colour_argb_t check; std::from_chars_result result = check.from_chars_argb(sv.data(), sv.data() + sv.size()); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -595,7 +602,8 @@ TEST_CASE("NodeTools expect Date functions", "[NodeTools][NodeTools-expect-funct static auto sv_callback = [](std::string_view sv, Date val) -> bool { Date::from_chars_result result = {}; Date check = Date::from_string(sv, &result); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -633,7 +641,8 @@ TEST_CASE( int64_t check_int; std::from_chars_result result = string_to_int64(sv, check_int); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -674,7 +683,8 @@ TEST_CASE("NodeTools expect vector functions", "[NodeTools][NodeTools-expect-fun static auto callback = [](ListValue const* ptr, auto val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == val.size()); + CHECK_IF (ranges::distance(list) == val.size()) + ; else { return false; } @@ -824,8 +834,8 @@ TEST_CASE("NodeTools expect assign functions", "[NodeTools][NodeTools-expect-fun auto* value = dryad::node_cast(rhs); - CHECK_IF(ptr_lhs->value().view() == lhs) { - CHECK_IF(ptr_rhs->value().view() == value->value().view()) { + CHECK_IF (ptr_lhs->value().view() == lhs) { + CHECK_IF (ptr_rhs->value().view() == value->value().view()) { return true; } } @@ -858,7 +868,7 @@ TEST_CASE("NodeTools expect list functions", "[NodeTools][NodeTools-expect-funct auto* _24_str_list = ast.create_assign_list(24, str_value); static auto length_callback = [](size_t size, size_t check) { - CHECK_IF(size == check) { + CHECK_IF (size == check) { return true; } return false; @@ -866,7 +876,8 @@ TEST_CASE("NodeTools expect list functions", "[NodeTools][NodeTools-expect-funct static auto callback = [](ListValue const* ptr, size_t count, NodeCPtr val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == count); + CHECK_IF (ranges::distance(list) == count) + ; else { return false; } @@ -982,7 +993,8 @@ TEST_CASE("NodeTools expect length functions", "[NodeTools][NodeTools-expect-fun static auto callback = [](ListValue const* ptr, size_t count, size_t val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == count); + CHECK_IF (ranges::distance(list) == count) + ; else { return false; } @@ -1003,7 +1015,8 @@ TEST_CASE("NodeTools expect length functions", "[NodeTools][NodeTools-expect-fun static auto callback_false = [](ListValue const* ptr, size_t count, size_t val) -> bool { auto list = ptr->statements(); - CHECK_FALSE_IF(ranges::distance(list) == count); + CHECK_FALSE_IF (ranges::distance(list) == count) + ; else { return false; } @@ -1405,7 +1418,8 @@ TEST_CASE( }; static auto callback = [](string_map_t const& map, size_t expected_index, std::string_view val) { - CHECK_IF(map.size() > expected_index); + CHECK_IF (map.size() > expected_index) + ; else { return false; } diff --git a/tests/src/economy/trading/GoodMarket.cpp b/tests/src/economy/trading/GoodMarket.cpp index f8932c948..01a70c8fb 100644 --- a/tests/src/economy/trading/GoodMarket.cpp +++ b/tests/src/economy/trading/GoodMarket.cpp @@ -1,18 +1,20 @@ -#include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/economy/trading/GoodMarket.hpp" + #include + +#include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/types/Colour.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/TypedSpan.hpp" +#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" #include #include using namespace OpenVic; -GoodCategory good_category {"test_good_category"}; +GoodCategory good_category { "test_good_category" }; const fixed_point_t base_price = 16; constexpr bool is_not_available_from_start = false; @@ -23,33 +25,28 @@ constexpr bool does_not_counter_overseas_penalty = false; GoodDefinition good_definition { "test_good", colour_rgb_t {}, - good_index_t{0}, + good_index_t { 0 }, good_category, base_price, is_not_available_from_start, is_tradeable, is_not_money, - does_not_counter_overseas_penalty + does_not_counter_overseas_penalty // }; GameRulesManager game_rules_manager {}; struct Trader { public: - std::function buy_callback = []( - BuyResult const& buy_result - ) -> void { + std::function buy_callback = [](BuyResult const& buy_result) -> void { FAIL("Did not expect buy callback"); }; - std::function&)> sell_callback = []( - SellResult const& sell_result, memory::vector& reusable_vector - ) -> void { + std::function&)> sell_callback = + [](SellResult const& sell_result, memory::vector& reusable_vector) -> void { FAIL("Did not expect sell callback"); }; - static void after_buy(void* actor, BuyResult const& buy_result) { - } - static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { - } + static void after_buy(void* actor, BuyResult const& buy_result) {} + static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) {} }; TEST_CASE("GoodMarket no trading when good isn't available", "[GoodMarket]") { @@ -57,47 +54,32 @@ TEST_CASE("GoodMarket no trading when good isn't available", "[GoodMarket]") { const std::optional country_index_optional = std::nullopt; Trader buyer { - .buy_callback=[](BuyResult const& buy_result) -> void { + .buy_callback = [](BuyResult const& buy_result) -> void { CHECK(buy_result.good_definition == good_definition); CHECK(buy_result.quantity_bought == 0); CHECK(buy_result.money_spent_total == 0); CHECK(buy_result.money_spent_on_imports == 0); - } + } // }; const fixed_point_t quantity_to_buy = 1; const fixed_point_t money_to_spend = quantity_to_buy * good_market.get_max_next_price(); - good_market.add_buy_up_to_order({ - country_index_optional, - quantity_to_buy, - money_to_spend, - &buyer, - Trader::after_buy - }); + good_market.add_buy_up_to_order({ country_index_optional, quantity_to_buy, money_to_spend, &buyer, Trader::after_buy }); Trader seller { - .sell_callback=[](SellResult const& sell_result, memory::vector& reusable_vector) -> void { + .sell_callback = [](SellResult const& sell_result, memory::vector& reusable_vector) -> void { CHECK(sell_result.good_definition == good_definition); CHECK(sell_result.quantity_sold == 0); CHECK(sell_result.money_gained == 0); - } + } // }; const fixed_point_t quantity_to_sell = 1; - good_market.add_market_sell_order({ - country_index_optional, - quantity_to_sell, - &seller, - Trader::after_sell - }); + good_market.add_market_sell_order({ country_index_optional, quantity_to_sell, &seller, Trader::after_sell }); TypedSpan reusable_country_map_0 {}; TypedSpan reusable_country_map_1 {}; std::array, GoodMarket::VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors; - good_market.execute_orders( - reusable_country_map_0, - reusable_country_map_1, - reusable_vectors - ); + good_market.execute_orders(reusable_country_map_0, reusable_country_map_1, reusable_vectors); CHECK(good_market.get_price() == base_price); CHECK(good_market.get_price_change_yesterday() == 0); -} \ No newline at end of file +} diff --git a/tests/src/pathfinding/AStarPathing.cpp b/tests/src/pathfinding/AStarPathing.cpp index d73d68978..804c4a710 100644 --- a/tests/src/pathfinding/AStarPathing.cpp +++ b/tests/src/pathfinding/AStarPathing.cpp @@ -41,7 +41,7 @@ namespace { TEST_CASE("AStarPathing ABC path", "[astar-pathing][astar-pathing-abc-path]") { ABC abc; memory::vector path = abc.get_id_path(ABC::A, ABC::C); - CHECK_IF(path.size() == 3) { + CHECK_IF (path.size() == 3) { CHECK(path[0] == ABC::A); CHECK(path[1] == ABC::B); CHECK(path[2] == ABC::C); diff --git a/tests/src/pathfinding/FringePathing.cpp b/tests/src/pathfinding/FringePathing.cpp index 252330914..c396fa5ea 100644 --- a/tests/src/pathfinding/FringePathing.cpp +++ b/tests/src/pathfinding/FringePathing.cpp @@ -41,7 +41,7 @@ namespace { TEST_CASE("FringePathing ABC path", "[fringe-pathing][fringe-pathing-abc-path]") { ABC abc; memory::vector path = abc.get_id_path(ABC::A, ABC::C); - CHECK_IF(path.size() == 3) { + CHECK_IF (path.size() == 3) { CHECK(path[0] == ABC::A); CHECK(path[1] == ABC::B); CHECK(path[2] == ABC::C); diff --git a/tests/src/pathfinding/Pathing.hpp b/tests/src/pathfinding/Pathing.hpp index 61e390b45..c9a7048e7 100644 --- a/tests/src/pathfinding/Pathing.hpp +++ b/tests/src/pathfinding/Pathing.hpp @@ -125,7 +125,7 @@ namespace OpenVic::testing { // Reachable. { INFO(fmt::format("From {} to {}: Fringe did not find a path", u, v)); - CHECK_FALSE_IF(route.size() == 0) { + CHECK_FALSE_IF (route.size() == 0) { match = false; goto exit; } @@ -135,9 +135,12 @@ namespace OpenVic::testing { CAPTURE(i); { INFO( - fmt::format("From {} to {}: edge ({}, {}) does not exist", u, v, route[i - 1], route[i]) + fmt::format( + "From {} to {}: edge ({}, {}) does not exist", // + u, v, route[i - 1], route[i] + ) ); - CHECK_FALSE_IF(!adjacent[route[i - 1]][route[i]]) { + CHECK_FALSE_IF (!adjacent[route[i - 1]][route[i]]) { match = false; goto exit; } @@ -145,11 +148,13 @@ namespace OpenVic::testing { astar_dist += std::sqrt(points[route[i - 1]].distance_squared(points[route[i]])); } { - INFO(fmt::format( - "From {} to {}: Floyd-Warshall gives {:.6}, Fringe gives {:.6}", u, v, dist[u][v], - astar_dist - )); - CHECK_FALSE_IF(std::abs(astar_dist - dist[u][v]) >= accuracy_threshold) { + INFO( + fmt::format( + "From {} to {}: Floyd-Warshall gives {:.6}, Fringe gives {:.6}", // + u, v, dist[u][v], astar_dist + ) + ); + CHECK_FALSE_IF (std::abs(astar_dist - dist[u][v]) >= accuracy_threshold) { match = false; goto exit; } @@ -157,7 +162,7 @@ namespace OpenVic::testing { } else { // Unreachable. INFO(fmt::format("From {} to {}: Fringe somehow found a nonexistent path", u, v)); - CHECK_FALSE_IF(route.size() > 0) { + CHECK_FALSE_IF (route.size() > 0) { match = false; goto exit; } diff --git a/tests/src/types/Approx.hpp b/tests/src/types/Approx.hpp index 738330bc3..1b7fe16d5 100644 --- a/tests/src/types/Approx.hpp +++ b/tests/src/types/Approx.hpp @@ -5,8 +5,8 @@ #include #include -#include "openvic-simulation/types/Vector.hpp" #include "openvic-simulation/core/Math.hpp" +#include "openvic-simulation/types/Vector.hpp" #include "Vector.hpp" // IWYU pragma: keep #include diff --git a/tests/src/types/FixedPoint.cpp b/tests/src/types/FixedPoint.cpp index b0a48c47b..fadd73102 100644 --- a/tests/src/types/FixedPoint.cpp +++ b/tests/src/types/FixedPoint.cpp @@ -288,24 +288,21 @@ TEST_CASE("fixed_point_t Operators", "[fixed_point_t][fixed_point_t-operators]") CONSTEXPR_CHECK(((int32_t)decimal4) == 3); CONSTEXPR_CHECK( - fixed_point_t::mul_div( - fixed_point_t::parse_raw(2), - fixed_point_t::parse_raw(3), - fixed_point_t::parse_raw(6) - ) == fixed_point_t::parse_raw(1) + fixed_point_t::mul_div(fixed_point_t::parse_raw(2), fixed_point_t::parse_raw(3), fixed_point_t::parse_raw(6)) == + fixed_point_t::parse_raw(1) ); CONSTEXPR_CHECK( fixed_point_t::multiply_truncate( - 4294967295LL, //2^32 - 1 - fixed_point_t::usable_max //2^31 / 2^16 - ) == 140737488322560LL //2^47 - 2^15 + 4294967295LL, // 2^32 - 1 + fixed_point_t::usable_max // 2^31 / 2^16 + ) == 140737488322560LL // 2^47 - 2^15 ); CONSTEXPR_CHECK( fixed_point_t::multiply_truncate( - 281474976710655LL, //2^48 - 1 + 281474976710655LL, // 2^48 - 1 fixed_point_t::_0_50 - ) == 140737488355327LL //2^47 - 1 + ) == 140737488355327LL // 2^47 - 1 ); } diff --git a/tests/src/types/FixedVector.cpp b/tests/src/types/FixedVector.cpp index 5ead40c0e..19409e0fd 100644 --- a/tests/src/types/FixedVector.cpp +++ b/tests/src/types/FixedVector.cpp @@ -12,51 +12,55 @@ using namespace OpenVic::_detail; // It has a multi-argument constructor to test emplace_back. struct ComplexType { public: - int index; - std::string name; + int index; + std::string name; - ComplexType(int new_index, std::string name_val) : index {new_index}, name(std::move(name_val)) {} + ComplexType(int new_index, std::string name_val) : index { new_index }, name(std::move(name_val)) {} - // Equality operator for assertions - bool operator==(const ComplexType& other) const { - return index == other.index && name == other.name; - } + // Equality operator for assertions + bool operator==(const ComplexType& other) const { + return index == other.index && name == other.name; + } }; // A type that is explicitly non-copyable and non-movable. struct NonCopyableNonMovable { public: - int value; + int value; - // A simple constructor - NonCopyableNonMovable(int new_value) : value {new_value} {} + // A simple constructor + NonCopyableNonMovable(int new_value) : value { new_value } {} - // Explicitly delete copy and move operations - NonCopyableNonMovable(const NonCopyableNonMovable&) = delete; - NonCopyableNonMovable& operator=(const NonCopyableNonMovable&) = delete; - NonCopyableNonMovable(NonCopyableNonMovable&&) = delete; - NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete; + // Explicitly delete copy and move operations + NonCopyableNonMovable(const NonCopyableNonMovable&) = delete; + NonCopyableNonMovable& operator=(const NonCopyableNonMovable&) = delete; + NonCopyableNonMovable(NonCopyableNonMovable&&) = delete; + NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete; - bool operator==(const NonCopyableNonMovable& other) const { - return value == other.value; - } + bool operator==(const NonCopyableNonMovable& other) const { + return value == other.value; + } }; // A custom type to verify constructors and destructors are called correctly. struct DestructionCounter { public: - static int constructor_count; - static int destructor_count; - - DestructionCounter() { constructor_count++; } - ~DestructionCounter() { destructor_count++; } - - // Must be non-copyable/non-movable to be safe to use in a fixed vector - // and for better testing of in-place construction. - DestructionCounter(const DestructionCounter&) = delete; - DestructionCounter(DestructionCounter&&) = delete; - DestructionCounter& operator=(const DestructionCounter&) = delete; - DestructionCounter& operator=(DestructionCounter&&) = delete; + static int constructor_count; + static int destructor_count; + + DestructionCounter() { + constructor_count++; + } + ~DestructionCounter() { + destructor_count++; + } + + // Must be non-copyable/non-movable to be safe to use in a fixed vector + // and for better testing of in-place construction. + DestructionCounter(const DestructionCounter&) = delete; + DestructionCounter(DestructionCounter&&) = delete; + DestructionCounter& operator=(const DestructionCounter&) = delete; + DestructionCounter& operator=(DestructionCounter&&) = delete; }; // Define the static member variables outside the class. @@ -65,7 +69,7 @@ int DestructionCounter::constructor_count = 0; int DestructionCounter::destructor_count = 0; // A simple test case to check the basic constructor and accessors with a simple type. -TEST_CASE("FixedVector Construction and basic accessors","[FixedVector]") { +TEST_CASE("FixedVector Construction and basic accessors", "[FixedVector]") { constexpr size_t capacity = 5; FixedVector vec { capacity }; @@ -77,9 +81,9 @@ TEST_CASE("FixedVector Construction and basic accessors","[FixedVector]") { } // Test the generator constructor with a single value return. -TEST_CASE("FixedVector Generator constructor (single value)","[FixedVector]") { +TEST_CASE("FixedVector Generator constructor (single value)", "[FixedVector]") { constexpr size_t capacity = 3; - FixedVector vec(capacity, [](const size_t i)->auto { + FixedVector vec(capacity, [](const size_t i) -> auto { return std::make_tuple(static_cast(i), std::to_string(i)); }); @@ -88,14 +92,14 @@ TEST_CASE("FixedVector Generator constructor (single value)","[FixedVector]") { REQUIRE(vec.max_size() == capacity); for (size_t i = 0; i < capacity; ++i) { - CHECK(vec[i] == ComplexType{static_cast(i), std::to_string(i)}); + CHECK(vec[i] == ComplexType { static_cast(i), std::to_string(i) }); } } // Test the generator constructor with a tuple return. -TEST_CASE("FixedVector Generator constructor (tuple)","[FixedVector]") { +TEST_CASE("FixedVector Generator constructor (tuple)", "[FixedVector]") { constexpr size_t capacity = 3; - FixedVector vec(capacity, [](const size_t i)->auto { + FixedVector vec(capacity, [](const size_t i) -> auto { return std::make_tuple(static_cast(i), std::to_string(i)); }); @@ -104,41 +108,41 @@ TEST_CASE("FixedVector Generator constructor (tuple)","[FixedVector]") { REQUIRE(vec.max_size() == capacity); for (size_t i = 0; i < capacity; ++i) { - CHECK(vec[i] == ComplexType{static_cast(i), std::to_string(i)}); + CHECK(vec[i] == ComplexType { static_cast(i), std::to_string(i) }); } } // Test emplace_back, pop_back, and clear with a complex type. -TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)","[FixedVector]") { +TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)", "[FixedVector]") { constexpr size_t capacity = 4; FixedVector vec { capacity }; // Emplace elements with multiple arguments vec.emplace_back(1, "hello"); REQUIRE(vec.size() == 1); - CHECK(vec.back() == ComplexType{1, "hello"}); + CHECK(vec.back() == ComplexType { 1, "hello" }); // Emplace up to capacity vec.emplace_back(2, "world"); vec.emplace_back(3, "!"); vec.emplace_back(4, "done"); REQUIRE(vec.size() == 4); - CHECK(vec.back() == ComplexType{4, "done"}); + CHECK(vec.back() == ComplexType { 4, "done" }); // Test emplace_back on a full vector (should not change size) auto it = vec.emplace_back(5, "oops"); CHECK(vec.size() == 4); CHECK(it == vec.end()); - CHECK(vec.back() == ComplexType{4, "done"}); // The last element is unchanged + CHECK(vec.back() == ComplexType { 4, "done" }); // The last element is unchanged // Test pop_back vec.pop_back(); REQUIRE(vec.size() == 3); - CHECK(vec.back() == ComplexType{3, "!"}); + CHECK(vec.back() == ComplexType { 3, "!" }); vec.pop_back(); REQUIRE(vec.size() == 2); - CHECK(vec.back() == ComplexType{2, "world"}); + CHECK(vec.back() == ComplexType { 2, "world" }); // Test clear vec.clear(); @@ -151,7 +155,7 @@ TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)","[FixedVect } // Test that accessor methods return references to the same memory location -TEST_CASE("FixedVector Accessor reference consistency","[FixedVector]") { +TEST_CASE("FixedVector Accessor reference consistency", "[FixedVector]") { constexpr size_t capacity = 3; FixedVector vec { capacity }; @@ -169,7 +173,7 @@ TEST_CASE("FixedVector Accessor reference consistency","[FixedVector]") { } // Test with a non-copyable and non-movable type to ensure in-place construction. -TEST_CASE("FixedVector Non-copyable, non-movable type","[FixedVector]") { +TEST_CASE("FixedVector Non-copyable, non-movable type", "[FixedVector]") { constexpr size_t capacity = 2; FixedVector vec { capacity }; @@ -187,7 +191,7 @@ TEST_CASE("FixedVector Non-copyable, non-movable type","[FixedVector]") { CHECK(&vec.back() == it1); } -TEST_CASE("FixedVector Destruction, Clear, and Refill","[FixedVector]") { +TEST_CASE("FixedVector Destruction, Clear, and Refill", "[FixedVector]") { // Reset the counters for a clean test DestructionCounter::constructor_count = 0; DestructionCounter::destructor_count = 0; @@ -209,7 +213,7 @@ TEST_CASE("FixedVector Destruction, Clear, and Refill","[FixedVector]") { vec.clear(); CHECK(vec.size() == 0); CHECK(DestructionCounter::destructor_count == 2); // All elements should be destructed - + // Test refilling after a clear vec.emplace_back(); CHECK(vec.size() == 1); @@ -218,4 +222,4 @@ TEST_CASE("FixedVector Destruction, Clear, and Refill","[FixedVector]") { // After the scope, the last element should also be destructed CHECK(DestructionCounter::destructor_count == 3); -} \ No newline at end of file +} diff --git a/tests/src/utility/reactive/DerivedState.cpp b/tests/src/utility/reactive/DerivedState.cpp index fd08a8c4f..0d00ab598 100644 --- a/tests/src/utility/reactive/DerivedState.cpp +++ b/tests/src/utility/reactive/DerivedState.cpp @@ -1,6 +1,7 @@ +#include "openvic-simulation/utility/reactive/DerivedState.hpp" + #include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/utility/reactive/DependencyTracker.hpp" -#include "openvic-simulation/utility/reactive/DerivedState.hpp" #include "openvic-simulation/utility/reactive/MutableState.hpp" #include @@ -11,12 +12,12 @@ using namespace OpenVic; TEST_CASE("DerivedState untracked", "[DerivedState-untracked]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); CHECK(sum.get_untracked() == 0); mutable_state_a.set(1); @@ -28,25 +29,25 @@ TEST_CASE("DerivedState untracked", "[DerivedState-untracked]") { TEST_CASE("DerivedState reactive", "[DerivedState-reactive]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); int times_marked_dirty = 0; - connection conn = sum.connect([×_marked_dirty]()->void { + connection conn = sum.connect([×_marked_dirty]() -> void { ++times_marked_dirty; }); mutable_state_a.set(1); - CHECK(times_marked_dirty == 0); //starts dirty - CHECK(sum.get_untracked() == 1); //force update + CHECK(times_marked_dirty == 0); // starts dirty + CHECK(sum.get_untracked() == 1); // force update mutable_state_b.set(2); CHECK(times_marked_dirty == 1); - + mutable_state_a.set(2); CHECK(times_marked_dirty == 1); @@ -58,16 +59,16 @@ TEST_CASE("DerivedState reactive", "[DerivedState-reactive]") { TEST_CASE("DerivedState untracked in callback", "[DerivedState-untracked-in-callback]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); connection conn; - int sum_value = sum.get([&sum,&conn,&sum_value](OpenVic::signal<>& sum_changed) mutable -> void { - conn = sum_changed.connect([&sum,&sum_value]() mutable -> void { + int sum_value = sum.get([&sum, &conn, &sum_value](OpenVic::signal<>& sum_changed) mutable -> void { + conn = sum_changed.connect([&sum, &sum_value]() mutable -> void { sum_value = sum.get_untracked(); }); }); @@ -76,4 +77,4 @@ TEST_CASE("DerivedState untracked in callback", "[DerivedState-untracked-in-call CHECK(sum_value == 1); mutable_state_a.set(2); CHECK(sum_value == 2); -} \ No newline at end of file +} diff --git a/tests/src/utility/reactive/MutableState.cpp b/tests/src/utility/reactive/MutableState.cpp index 4e0463c7f..42e12abbe 100644 --- a/tests/src/utility/reactive/MutableState.cpp +++ b/tests/src/utility/reactive/MutableState.cpp @@ -8,7 +8,9 @@ using namespace OpenVic; TEST_CASE("MutableState", "[MutableState]") { int sum = 0; MutableState mutable_state(0); - connection conn = mutable_state.connect([&sum](const int new_value) { sum += new_value; }); + connection conn = mutable_state.connect([&sum](const int new_value) { + sum += new_value; + }); CHECK(sum == 0); mutable_state.set(1); CHECK(sum == 1); @@ -19,4 +21,4 @@ TEST_CASE("MutableState", "[MutableState]") { conn.disconnect(); mutable_state.set(3); CHECK(sum == 5); -} \ No newline at end of file +}