diff --git a/.clang-format b/.clang-format index dea31ab6..1c4a715c 100644 --- a/.clang-format +++ b/.clang-format @@ -82,7 +82,33 @@ IncludeCategories: Priority: 4 - Regex: ^ + Priority: 12 + - Regex: ^ + Priority: 17 + - Regex: ^canvas_item_add_nine_patch( - to_canvas_item, rect, { {}, size }, get_rid(), - cornered_tile_border_size, size - cornered_tile_border_size + to_canvas_item, rect, { {}, size }, get_rid(), cornered_tile_border_size, size - cornered_tile_border_size ); } } else { @@ -69,8 +68,7 @@ Ref GFXButtonStateTexture::make_gfx_button_state_texture( void GFXButtonStateTexture::set_button_state(ButtonState new_button_state) { ERR_FAIL_COND( - new_button_state != HOVER && new_button_state != PRESSED && - new_button_state != DISABLED && new_button_state != SELECTED + new_button_state != HOVER && new_button_state != PRESSED && new_button_state != DISABLED && new_button_state != SELECTED ); button_state = new_button_state; } @@ -82,9 +80,9 @@ Error GFXButtonStateTexture::generate_state_image( const Rect2i source_image_rect { {}, source_image->get_size() }; ERR_FAIL_COND_V(!region.has_area() || !source_image_rect.encloses(region), FAILED); /* Whether we've already set the ImageTexture to an image of the right dimensions and format, - * and so can update it without creating and setting a new image, or not. */ - bool can_update = state_image.is_valid() && state_image->get_size() == region.get_size() - && state_image->get_format() == source_image->get_format(); + * and so can update it without creating and setting a new image, or not. */ + bool can_update = state_image.is_valid() && state_image->get_size() == region.get_size() && + state_image->get_format() == source_image->get_format(); if (!can_update) { state_image = Image::create(region.size.width, region.size.height, false, source_image->get_format()); ERR_FAIL_NULL_V(state_image, FAILED); @@ -114,11 +112,10 @@ Error GFXButtonStateTexture::generate_state_image( return { std::max(colour.r - 0.3f, 0.0f), std::max(colour.g - 0.3f, 0.0f), std::max(colour.b - 0.3f, 0.0f), colour.a }; }; - const auto colour_func = - button_state == HOVER ? hover_colour : - button_state == PRESSED ? pressed_colour : - button_state == DISABLED ? disabled_colour : - selected_colour; + const auto colour_func = button_state == HOVER ? hover_colour + : button_state == PRESSED ? pressed_colour + : button_state == DISABLED ? disabled_colour + : selected_colour; for (Vector2i point { 0, 0 }; point.y < state_image->get_height(); ++point.y) { for (point.x = 0; point.x < state_image->get_width(); ++point.x) { @@ -141,16 +138,11 @@ StringName const& GFXButtonStateTexture::button_state_to_name(ButtonState button static const StringName name_selected = "selected"; static const StringName name_error = "INVALID BUTTON STATE"; switch (button_state) { - case HOVER: - return name_hover; - case PRESSED: - return name_pressed; - case DISABLED: - return name_disabled; - case SELECTED: - return name_selected; - default: - return name_error; + case HOVER: return name_hover; + case PRESSED: return name_pressed; + case DISABLED: return name_disabled; + case SELECTED: return name_selected; + default: return name_error; } } @@ -181,7 +173,7 @@ void GFXButtonStateHavingTexture::_clear_button_states() { GFXButtonStateHavingTexture::GFXButtonStateHavingTexture() : button_state_textures {} {} -Ref GFXButtonStateHavingTexture::get_button_state_texture( +Ref GFXButtonStateHavingTexture::get_button_state_texture( // GFXButtonStateTexture::ButtonState button_state ) { const size_t button_state_index = button_state; diff --git a/extension/src/openvic-extension/classes/GFXButtonStateTexture.hpp b/extension/src/openvic-extension/classes/GFXButtonStateTexture.hpp index 2a3a2841..daca0523 100644 --- a/extension/src/openvic-extension/classes/GFXButtonStateTexture.hpp +++ b/extension/src/openvic-extension/classes/GFXButtonStateTexture.hpp @@ -28,7 +28,7 @@ namespace OpenVic { GDCLASS(GFXButtonStateTexture, GFXCorneredTileSupportingTexture) public: - enum ButtonState { + enum ButtonState { // HOVER, PRESSED, DISABLED, diff --git a/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.cpp b/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.cpp index 2c5be7f6..f3cc3f5f 100644 --- a/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.cpp +++ b/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.cpp @@ -1,9 +1,9 @@ #include "GFXMaskedFlagTexture.hpp" +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/AssetManager.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/UITools.hpp" #include "openvic-extension/utility/Utilities.hpp" @@ -14,11 +14,11 @@ Error GFXMaskedFlagTexture::_generate_combined_image() { ERR_FAIL_NULL_V(overlay_image, FAILED); /* Whether we've already set the ImageTexture to an image of the right dimensions and format, * and so can update it without creating and setting a new image, or not. */ - bool can_update = button_image.is_valid() && button_image->get_size() == overlay_image->get_size() - && button_image->get_format() == overlay_image->get_format(); + bool can_update = button_image.is_valid() && button_image->get_size() == overlay_image->get_size() && + button_image->get_format() == overlay_image->get_format(); if (!can_update) { button_image = Image::create( - overlay_image->get_width(), overlay_image->get_height(), false, overlay_image->get_format() + overlay_image->get_width(), overlay_image->get_height(), false, overlay_image->get_format() // ); ERR_FAIL_NULL_V(button_image, FAILED); } @@ -35,21 +35,18 @@ Error GFXMaskedFlagTexture::_generate_combined_image() { const Vector2i centre_translation = (mask_image->get_size() - button_image->get_size()) / 2; for ( - Vector2i combined_image_point { 0, 0 }; - combined_image_point.y < button_image->get_height(); - ++combined_image_point.y + Vector2i combined_image_point { 0, 0 }; combined_image_point.y < button_image->get_height(); + ++combined_image_point.y // ) { - for (combined_image_point.x = 0; combined_image_point.x < button_image->get_width(); ++combined_image_point.x) { - const Color overlay_image_colour = overlay_image->get_pixelv(combined_image_point); // Translate to mask_image coordinates, keeping the centres of each image aligned. const Vector2i mask_image_point = combined_image_point + centre_translation; if ( - 0 <= mask_image_point.x && mask_image_point.x < mask_image->get_width() && - 0 <= mask_image_point.y && mask_image_point.y < mask_image->get_height() + 0 <= mask_image_point.x && mask_image_point.x < mask_image->get_width() && 0 <= mask_image_point.y && + mask_image_point.y < mask_image->get_height() // ) { const Color mask_image_colour = mask_image->get_pixelv(mask_image_point); @@ -153,9 +150,9 @@ Error GFXMaskedFlagTexture::set_gfx_masked_flag_name(String const& gfx_masked_fl GFX::MaskedFlag const* new_masked_flag = sprite->cast_to(); ERR_FAIL_NULL_V_MSG( - new_masked_flag, FAILED, Utilities::format( - "Invalid type for GFX sprite %s: %s (expected %s)", gfx_masked_flag_name, - convert_to(sprite->get_type()), + new_masked_flag, FAILED, + Utilities::format( + "Invalid type for GFX sprite %s: %s (expected %s)", gfx_masked_flag_name, convert_to(sprite->get_type()), convert_to(GFX::MaskedFlag::get_type_static()) ) ); @@ -204,11 +201,10 @@ Error GFXMaskedFlagTexture::set_flag_country_name_and_type( GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, FAILED); - CountryDefinition const* new_flag_country = game_singleton->get_definition_manager() - .get_country_definition_manager() - .get_country_definition_by_identifier( - convert_to(new_flag_country_name) - ); + CountryDefinitionManager const& manager = game_singleton->get_definition_manager().get_country_definition_manager(); + CountryDefinition const* new_flag_country = manager.get_country_definition_by_identifier( // + convert_to(new_flag_country_name) + ); ERR_FAIL_NULL_V_MSG(new_flag_country, FAILED, Utilities::format("Country not found: %s", new_flag_country_name)); return set_flag_country_and_type(new_flag_country, new_flag_type); @@ -221,7 +217,7 @@ Error GFXMaskedFlagTexture::set_flag_country(CountryInstance* new_flag_country) GovernmentType const* government_type = new_flag_country->flag_government_type.get_untracked(); - const StringName new_flag_type = government_type != nullptr + const StringName new_flag_type = government_type != nullptr // ? StringName { convert_to(government_type->get_flag_type()) } : StringName {}; @@ -239,10 +235,9 @@ Error GFXMaskedFlagTexture::set_flag_country_name(String const& new_flag_country InstanceManager* instance_manager = game_singleton->get_instance_manager(); ERR_FAIL_NULL_V(instance_manager, FAILED); - CountryInstance* new_flag_country = instance_manager->get_country_instance_manager() - .get_country_instance_by_identifier( - convert_to(new_flag_country_name) - ); + CountryInstance* new_flag_country = instance_manager->get_country_instance_manager().get_country_instance_by_identifier( + convert_to(new_flag_country_name) + ); ERR_FAIL_NULL_V_MSG(new_flag_country, FAILED, Utilities::format("Country not found: %s", new_flag_country_name)); return set_flag_country(new_flag_country); diff --git a/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.hpp b/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.hpp index 97489316..7ab72935 100644 --- a/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.hpp +++ b/extension/src/openvic-extension/classes/GFXMaskedFlagTexture.hpp @@ -45,13 +45,13 @@ namespace OpenVic { /* Set flag_country and flag_type and update the combined image to use that flag, or no flag if it doesn't exist. */ godot::Error set_flag_country_and_type( - CountryDefinition const* new_flag_country, godot::StringName const& new_flag_type + CountryDefinition const* new_flag_country, godot::StringName const& new_flag_type // ); /* Look up the country with the specified identifier, then call set_flag_country_and_type with the country and * specified flag_type as arguments. */ godot::Error set_flag_country_name_and_type( - godot::String const& new_flag_country_name, godot::StringName const& new_flag_type + godot::String const& new_flag_country_name, godot::StringName const& new_flag_type // ); /* Look up the specified country's current flag type, then call set_flag_country_and_type diff --git a/extension/src/openvic-extension/classes/GFXPieChartTexture.cpp b/extension/src/openvic-extension/classes/GFXPieChartTexture.cpp index e7467e11..5b4b8710 100644 --- a/extension/src/openvic-extension/classes/GFXPieChartTexture.cpp +++ b/extension/src/openvic-extension/classes/GFXPieChartTexture.cpp @@ -70,8 +70,8 @@ Error GFXPieChartTexture::_generate_pie_chart_image() { /* Whether we've already set the ImageTexture to an image of the right dimensions, * and so can update it without creating and setting a new image, or not. */ - const bool can_update = pie_chart_image.is_valid() && pie_chart_image->get_width() == pie_chart_diameter - && pie_chart_image->get_height() == pie_chart_diameter; + const bool can_update = pie_chart_image.is_valid() && pie_chart_image->get_width() == pie_chart_diameter && + pie_chart_image->get_height() == pie_chart_diameter; if (!can_update) { pie_chart_image = Image::create(pie_chart_diameter, pie_chart_diameter, false, Image::FORMAT_RGBA8); @@ -99,9 +99,7 @@ Error GFXPieChartTexture::_generate_pie_chart_image() { } } } else { - pie_chart_image->fill(background_colour); - } if (can_update) { @@ -124,8 +122,10 @@ Error GFXPieChartTexture::set_slices_array(godot_pie_chart_data_t const& new_sli Utilities::format("Invalid slice keys at index %d", i) ); const slice_t slice { - slice_dict[_slice_identifier_key()], slice_dict[_slice_tooltip_key()], slice_dict[_slice_colour_key()], - slice_dict[_slice_weight_key()] + slice_dict[_slice_identifier_key()], + slice_dict[_slice_tooltip_key()], // + slice_dict[_slice_colour_key()], // + slice_dict[_slice_weight_key()] // }; if (slice.weight > 0.0f) { total_weight += slice.weight; @@ -184,9 +184,9 @@ Error GFXPieChartTexture::set_gfx_pie_chart_name(String const& gfx_pie_chart_nam ERR_FAIL_NULL_V(sprite, FAILED); GFX::PieChart const* new_pie_chart = sprite->cast_to(); ERR_FAIL_NULL_V_MSG( - new_pie_chart, FAILED, Utilities::format( - "Invalid type for GFX sprite %s: %s (expected %s)", gfx_pie_chart_name, - convert_to(sprite->get_type()), + new_pie_chart, FAILED, + Utilities::format( + "Invalid type for GFX sprite %s: %s (expected %s)", gfx_pie_chart_name, convert_to(sprite->get_type()), convert_to(GFX::PieChart::get_type_static()) ) ); diff --git a/extension/src/openvic-extension/classes/GFXPieChartTexture.hpp b/extension/src/openvic-extension/classes/GFXPieChartTexture.hpp index 96906538..3d435e85 100644 --- a/extension/src/openvic-extension/classes/GFXPieChartTexture.hpp +++ b/extension/src/openvic-extension/classes/GFXPieChartTexture.hpp @@ -5,16 +5,16 @@ #include +#include #include #include #include #include +#include + #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/utility/MapHelpers.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" - -#include namespace OpenVic { template @@ -26,14 +26,14 @@ namespace OpenVic { concept IsPieChartValue = std::is_constructible_v || IsPieChartValueTypeSafe; template - concept IsPieChartDistribution = ( + concept IsPieChartDistribution = + ( /* tsl::ordered_map, KeyType derived from HasIdentifierAndColour */ specialization_of /* IndexedFlatMap, KeyType derived from HasIdentifierAndColour */ || specialization_of - ) - && IsPieChartKey> - && IsPieChartValue>; + ) && + IsPieChartKey> && IsPieChartValue>; class GFXPieChartTexture : public godot::ImageTexture { GDCLASS(GFXPieChartTexture, godot::ImageTexture) @@ -65,21 +65,20 @@ namespace OpenVic { * The resulting Array of Dictionaries can be used as an argument for set_slices_array. */ template static godot_pie_chart_data_t distribution_to_slices_array( - std::span> keys, - std::span> values, + std::span> keys, std::span> values, NodeTools::Functor< // return tooltip; args: key const*, identifier, weight, total weight - godot::String, std::add_const_t>&, godot::String const&, float, float - > auto make_tooltip, + godot::String, // + std::add_const_t>&, // + godot::String const&, // + float, // + float> auto make_tooltip, godot::String const& identifier_suffix = {} ) { assert(keys.size() == values.size()); using key_t = std::add_const_t>; using key_ref_wrap_t = std::reference_wrapper; - using entry_t = std::pair< - key_ref_wrap_t, - float - >; + using entry_t = std::pair; memory::FixedVector sorted_distribution { create_empty, keys.size() }; @@ -104,10 +103,7 @@ namespace OpenVic { total_weight += value; } else if (value < 0.0f) { - spdlog::error_s( - "Negative distribution value {} for key \"{}\"", - value, key - ); + spdlog::error_s("Negative distribution value {} for key \"{}\"", value, key); } } @@ -117,16 +113,17 @@ namespace OpenVic { } std::sort( - sorted_distribution.begin(), sorted_distribution.end(), - [](entry_t const& lhs, entry_t const& rhs) -> bool { + sorted_distribution.begin(), sorted_distribution.end(), [](entry_t const& lhs, entry_t const& rhs) -> bool { if constexpr (requires { lhs.first.get() < rhs.first.get(); }) { return lhs.first.get() < rhs.first.get(); } else if constexpr (requires { lhs.first.get().index < rhs.first.get().index; }) { return lhs.first.get().index < rhs.first.get().index; } else if constexpr (requires { lhs.first.get().get_identifier() < rhs.first.get().get_identifier(); }) { - return lhs.first.get().get_identifier() < rhs.first.get().get_identifier();; + return lhs.first.get().get_identifier() < rhs.first.get().get_identifier(); } else { - static_assert(!std::is_same_v, "distribution_to_slices_array's sorting does not support KeyType"); + static_assert( + !std::is_same_v, "distribution_to_slices_array's sorting does not support KeyType" + ); } } ); @@ -158,8 +155,12 @@ namespace OpenVic { MapType const& distribution, NodeTools::Functor< // return tooltip; args: key const*, identifier, weight, total weight - godot::String, std::add_const_t>>&, godot::String const&, float, float - > auto make_tooltip, + godot::String, // + std::add_const_t>>&, // + godot::String const&, // + float, // + float // + > auto make_tooltip, godot::String const& identifier_suffix = {} ) { memory::FixedVector> keys { create_empty, distribution.size() }; diff --git a/extension/src/openvic-extension/classes/GFXSpriteTexture.cpp b/extension/src/openvic-extension/classes/GFXSpriteTexture.cpp index 4d9661e3..4e706549 100644 --- a/extension/src/openvic-extension/classes/GFXSpriteTexture.cpp +++ b/extension/src/openvic-extension/classes/GFXSpriteTexture.cpp @@ -3,9 +3,9 @@ #include #include +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/AssetManager.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/UITools.hpp" #include "openvic-extension/utility/Utilities.hpp" @@ -31,7 +31,7 @@ void GFXSpriteTexture::_bind_methods() { GFXSpriteTexture::GFXSpriteTexture() : icon_index { GFX::NO_FRAMES }, icon_count { GFX::NO_FRAMES } {} Ref GFXSpriteTexture::make_gfx_sprite_texture( - GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon + GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon // ) { Ref texture; texture.instantiate(); @@ -97,9 +97,9 @@ Error GFXSpriteTexture::set_gfx_texture_sprite_name(String const& gfx_texture_sp ERR_FAIL_NULL_V(sprite, FAILED); GFX::TextureSprite const* new_texture_sprite = sprite->cast_to(); ERR_FAIL_NULL_V_MSG( - new_texture_sprite, FAILED, Utilities::format( - "Invalid type for GFX sprite %s: %s (expected %s)", gfx_texture_sprite_name, - convert_to(sprite->get_type()), + new_texture_sprite, FAILED, + Utilities::format( + "Invalid type for GFX sprite %s: %s (expected %s)", gfx_texture_sprite_name, convert_to(sprite->get_type()), convert_to(GFX::TextureSprite::get_type_static()) ) ); diff --git a/extension/src/openvic-extension/classes/GFXSpriteTexture.hpp b/extension/src/openvic-extension/classes/GFXSpriteTexture.hpp index cd04113f..3d216339 100644 --- a/extension/src/openvic-extension/classes/GFXSpriteTexture.hpp +++ b/extension/src/openvic-extension/classes/GFXSpriteTexture.hpp @@ -27,7 +27,7 @@ namespace OpenVic { /* Create a GFXSpriteTexture using the specified GFX::TextureSprite and icon index. Returns nullptr if * set_gfx_texture_sprite fails. */ static godot::Ref make_gfx_sprite_texture( - GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES + GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES // ); /* Discard the GFX::TextureSprite, atlas texture and icon index. */ @@ -36,13 +36,13 @@ namespace OpenVic { /* Set the GFX::TextureSprite, load its texture as an atlas, check if it is an IconTextureSprite, * and if so set its icon count and the current displayed icon. */ godot::Error set_gfx_texture_sprite( - GFX::TextureSprite const* new_gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES + GFX::TextureSprite const* new_gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES // ); /* Search for a GFX::TextureSprite with the specified name and, * if successful, call set_gfx_texture_sprite to set it and its icon. */ godot::Error set_gfx_texture_sprite_name( - godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES + godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES // ); /* Return the name of the GFX::TextureSprite, or an empty String if it's null. */ diff --git a/extension/src/openvic-extension/classes/GUIButton.cpp b/extension/src/openvic-extension/classes/GUIButton.cpp index edcaf507..2ad28c73 100644 --- a/extension/src/openvic-extension/classes/GUIButton.cpp +++ b/extension/src/openvic-extension/classes/GUIButton.cpp @@ -96,7 +96,7 @@ Error GUIButton::set_gfx_font(GFX::Font const* gfx_font) { } static const std::array button_font_themes { - "font_color", "font_hover_color", "font_hover_pressed_color", "font_pressed_color", "font_disabled_color" + "font_color", "font_hover_color", "font_hover_pressed_color", "font_pressed_color", "font_disabled_color" // }; const Color colour = convert_to(gfx_font->get_colour()); diff --git a/extension/src/openvic-extension/classes/GUIHasTooltip.hpp b/extension/src/openvic-extension/classes/GUIHasTooltip.hpp index 8c93903f..8b4d4280 100644 --- a/extension/src/openvic-extension/classes/GUIHasTooltip.hpp +++ b/extension/src/openvic-extension/classes/GUIHasTooltip.hpp @@ -5,8 +5,8 @@ #include -#include "openvic-extension/singletons/MenuSingleton.hpp" #include "openvic-extension/core/Bind.hpp" +#include "openvic-extension/singletons/MenuSingleton.hpp" /* To add tooltip functionality to a class: * - the class must be derived from Control. @@ -17,20 +17,21 @@ * - initialise tooltip_active to false in the class' constructor. */ #define GUI_TOOLTIP_DEFINITIONS \ - public: \ - void set_tooltip_string_and_substitution_dict( \ - godot::String const& new_tooltip_string, godot::Dictionary const& new_tooltip_substitution_dict \ - ); \ - void set_tooltip_string(godot::String const& new_tooltip_string); \ - void set_tooltip_substitution_dict(godot::Dictionary const& new_tooltip_substitution_dict); \ - void clear_tooltip(); \ - private: \ - godot::String PROPERTY(tooltip_string); \ - godot::Dictionary PROPERTY(tooltip_substitution_dict); \ - bool PROPERTY_CUSTOM_PREFIX(tooltip_active, is, false); \ - void _tooltip_notification(int what); \ - void _set_tooltip_active(bool new_tooltip_active); \ - void _set_tooltip_visibility(bool visible); +public: \ + void set_tooltip_string_and_substitution_dict( \ + godot::String const& new_tooltip_string, godot::Dictionary const& new_tooltip_substitution_dict \ + ); \ + void set_tooltip_string(godot::String const& new_tooltip_string); \ + void set_tooltip_substitution_dict(godot::Dictionary const& new_tooltip_substitution_dict); \ + void clear_tooltip(); \ +\ +private: \ + godot::String PROPERTY(tooltip_string); \ + godot::Dictionary PROPERTY(tooltip_substitution_dict); \ + bool PROPERTY_CUSTOM_PREFIX(tooltip_active, is, false); \ + void _tooltip_notification(int what); \ + void _set_tooltip_active(bool new_tooltip_active); \ + void _set_tooltip_visibility(bool visible); #define GUI_TOOLTIP_IMPLEMENTATIONS(CLASS) \ void CLASS::set_tooltip_string_and_substitution_dict( \ @@ -108,11 +109,11 @@ OV_BIND_METHOD(CLASS::clear_tooltip); \ OV_BIND_METHOD(CLASS::is_tooltip_active); \ ADD_PROPERTY( \ - PropertyInfo(Variant::STRING, "tooltip_string", PROPERTY_HINT_MULTILINE_TEXT), \ - "set_tooltip_string", "get_tooltip_string" \ + PropertyInfo(Variant::STRING, "tooltip_string", PROPERTY_HINT_MULTILINE_TEXT), "set_tooltip_string", \ + "get_tooltip_string" \ ); \ ADD_PROPERTY( \ - PropertyInfo(Variant::DICTIONARY, "tooltip_substitution_dict"), \ - "set_tooltip_substitution_dict", "get_tooltip_substitution_dict" \ + PropertyInfo(Variant::DICTIONARY, "tooltip_substitution_dict"), "set_tooltip_substitution_dict", \ + "get_tooltip_substitution_dict" \ ); \ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tooltip_active"), "", "is_tooltip_active"); diff --git a/extension/src/openvic-extension/classes/GUIIcon.hpp b/extension/src/openvic-extension/classes/GUIIcon.hpp index e8e3014a..3a0b1e13 100644 --- a/extension/src/openvic-extension/classes/GUIIcon.hpp +++ b/extension/src/openvic-extension/classes/GUIIcon.hpp @@ -13,14 +13,12 @@ namespace OpenVic { static void _bind_methods(); public: - godot::Error set_gfx_texture_sprite( - GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES - ); + godot::Error set_gfx_texture_sprite(GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES); godot::Ref get_gfx_sprite_texture() const; godot::Error set_gfx_texture_sprite_name( - godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES + godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES // ); godot::String get_gfx_texture_sprite_name() const; diff --git a/extension/src/openvic-extension/classes/GUIIconButton.hpp b/extension/src/openvic-extension/classes/GUIIconButton.hpp index 10fc1791..3104d966 100644 --- a/extension/src/openvic-extension/classes/GUIIconButton.hpp +++ b/extension/src/openvic-extension/classes/GUIIconButton.hpp @@ -13,14 +13,12 @@ namespace OpenVic { static void _bind_methods(); public: - godot::Error set_gfx_texture_sprite( - GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES - ); + godot::Error set_gfx_texture_sprite(GFX::TextureSprite const* gfx_texture_sprite, GFX::frame_t icon = GFX::NO_FRAMES); godot::Ref get_gfx_sprite_texture() const; godot::Error set_gfx_texture_sprite_name( - godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES + godot::String const& gfx_texture_sprite_name, GFX::frame_t icon = GFX::NO_FRAMES // ); godot::String get_gfx_texture_sprite_name() const; diff --git a/extension/src/openvic-extension/classes/GUILabel.cpp b/extension/src/openvic-extension/classes/GUILabel.cpp index 42bde925..e991e6f8 100644 --- a/extension/src/openvic-extension/classes/GUILabel.cpp +++ b/extension/src/openvic-extension/classes/GUILabel.cpp @@ -13,10 +13,10 @@ #include #include "openvic-extension/classes/GUINode.hpp" +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/AssetManager.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/Utilities.hpp" using namespace OpenVic; @@ -56,20 +56,14 @@ String const& GUILabel::get_flag_marker() { } void GUILabel::set_text_and_tooltip( - GUINode const& parent, - godot::NodePath const& path, - godot::StringName const& text_localisation_key, + GUINode const& parent, godot::NodePath const& path, godot::StringName const& text_localisation_key, godot::StringName const& tooltip_localisation_key ) { GUILabel* label_nullable = parent.get_gui_label_from_nodepath(path); if (label_nullable != nullptr) { GUILabel& label = *label_nullable; - label.set_text( - label.tr(text_localisation_key) - ); - label.set_tooltip_string( - label.tr(tooltip_localisation_key) - ); + label.set_text(label.tr(text_localisation_key)); + label.set_tooltip_string(label.tr(tooltip_localisation_key)); } } @@ -128,9 +122,7 @@ void GUILabel::_bind_methods() { ADD_PROPERTY( PropertyInfo(Variant::VECTOR2, "border_size", PROPERTY_HINT_NONE, "suffix:px"), "set_border_size", "get_border_size" ); - ADD_PROPERTY( - PropertyInfo(Variant::RECT2, "adjusted_rect", PROPERTY_HINT_NONE, "suffix:px"), "", "get_adjusted_rect" - ); + ADD_PROPERTY(PropertyInfo(Variant::RECT2, "adjusted_rect", PROPERTY_HINT_NONE, "suffix:px"), "", "get_adjusted_rect"); ADD_PROPERTY( PropertyInfo(Variant::BOOL, "auto_adjust_to_content_size"), "set_auto_adjust_to_content_size", "will_auto_adjust_to_content_size" @@ -184,8 +176,7 @@ void GUILabel::_notification(int what) { position.x += adjusted_rect.size.width - 2 * border_size.width - line.width; } break; case HORIZONTAL_ALIGNMENT_LEFT: - default: - break; + default: break; } position.y += ascent; @@ -193,22 +184,18 @@ void GUILabel::_notification(int what) { for (segment_t const& segment : line.segments) { if (string_segment_t const* string_segment = std::get_if(&segment)) { font->draw_string( - ci, position, string_segment->text, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, - string_segment->colour + ci, position, string_segment->text, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, string_segment->colour ); position.x += string_segment->width; } else if (flag_segment_t const* flag_segment = std::get_if(&segment)) { - (*flag_segment)->draw_rect(ci, Rect2 { - position - Vector2 { 1.0_real, ascent - 4.0_real }, FLAG_DRAW_DIMS - }, false); + (*flag_segment) + ->draw_rect(ci, Rect2 { position - Vector2 { 1.0_real, ascent - 4.0_real }, FLAG_DRAW_DIMS }, false); position.x += FLAG_SEGMENT_WIDTH; } else if (currency_texture.is_valid()) { currency_texture->draw( - ci, position - Vector2 { - 1.0_real, static_cast(currency_texture->get_height()) * 0.75_real - } + ci, position - Vector2 { 1.0_real, static_cast(currency_texture->get_height()) * 0.75_real } ); position.x += currency_texture->get_width(); @@ -269,9 +256,9 @@ Error GUILabel::set_gui_text(GUI::Text const* new_gui_text, GFX::Font::colour_co using enum text_format_t; static const ordered_map format_map { - { left, HORIZONTAL_ALIGNMENT_LEFT }, - { centre, HORIZONTAL_ALIGNMENT_CENTER }, - { right, HORIZONTAL_ALIGNMENT_RIGHT } + { left, HORIZONTAL_ALIGNMENT_LEFT }, // + { centre, HORIZONTAL_ALIGNMENT_CENTER }, // + { right, HORIZONTAL_ALIGNMENT_RIGHT } // }; const decltype(format_map)::const_iterator it = format_map.find(gui_text->get_format()); @@ -532,9 +519,8 @@ String GUILabel::generate_substituted_text(String const& base_text) const { while ((marker_start_pos = base_text.find(get_substitution_marker(), start_pos)) != -1) { result += base_text.substr(start_pos, marker_start_pos - start_pos); - int64_t marker_end_pos = base_text.find( - get_substitution_marker(), marker_start_pos + get_substitution_marker().length() - ); + int64_t marker_end_pos = + base_text.find(get_substitution_marker(), marker_start_pos + get_substitution_marker().length()); if (marker_end_pos == -1) { marker_end_pos = base_text.length(); } @@ -568,7 +554,7 @@ String GUILabel::generate_substituted_text(String const& base_text) const { } std::pair GUILabel::generate_display_text_and_colour_instructions( - String const& substituted_text + String const& substituted_text // ) const { String result; colour_instructions_t colour_instructions; @@ -598,7 +584,7 @@ std::pair GUILabel::generate_display_te } std::vector GUILabel::generate_lines_and_segments( - String const& display_text, colour_instructions_t const& colour_instructions + String const& display_text, colour_instructions_t const& colour_instructions // ) const { static constexpr char RESET_COLOUR_CODE = '!'; @@ -628,9 +614,7 @@ std::vector GUILabel::generate_lines_and_segments( if (current_colour != new_colour) { if (section_start < idx) { - separate_lines( - display_text.substr(section_start, idx - section_start), current_colour, unwrapped_lines - ); + separate_lines(display_text.substr(section_start, idx - section_start), current_colour, unwrapped_lines); section_start = idx; } current_colour = new_colour; @@ -644,9 +628,7 @@ std::vector GUILabel::generate_lines_and_segments( return unwrapped_lines; } -void GUILabel::separate_lines( - String const& string, Color const& colour, std::vector& unwrapped_lines -) const { +void GUILabel::separate_lines(String const& string, Color const& colour, std::vector& unwrapped_lines) const { static const String NEWLINE_MARKER = "\n"; int64_t start_pos = 0; @@ -667,9 +649,7 @@ void GUILabel::separate_lines( } } -void GUILabel::separate_currency_segments( - String const& string, Color const& colour, line_t& line -) const { +void GUILabel::separate_currency_segments(String const& string, Color const& colour, line_t& line) const { int64_t start_pos = 0; int64_t marker_pos; @@ -700,10 +680,9 @@ GUILabel::flag_segment_t GUILabel::make_flag_segment(String const& identifier) { InstanceManager* instance_manager = game_singleton.get_instance_manager(); if (instance_manager != nullptr) { - CountryInstance* country_instance = - instance_manager->get_country_instance_manager().get_country_instance_by_identifier( - convert_to(identifier) //convert_to(identifier) - ); + CountryInstance* country_instance = instance_manager->get_country_instance_manager().get_country_instance_by_identifier( + convert_to(identifier) + ); if (country_instance != nullptr) { country_index = country_instance->country_definition.index; @@ -745,9 +724,7 @@ GUILabel::flag_segment_t GUILabel::make_flag_segment(String const& identifier) { return flag_segment; } -void GUILabel::separate_flag_segments( - String const& string, Color const& colour, line_t& line -) const { +void GUILabel::separate_flag_segments(String const& string, Color const& colour, line_t& line) const { const auto push_string_segment = [this, &string, &colour, &line](int64_t start, int64_t end) -> void { String substring = string.substr(start, end - start); const real_t width = get_string_width(substring); @@ -841,9 +818,12 @@ std::vector GUILabel::wrap_lines(std::vector& unwrappe if (last_marker_pos != 0 || !current_line->segments.empty()) { if (!new_segment_string.is_empty()) { - current_line->segments.emplace_back(string_segment_t { - std::move(new_segment_string), string_segment->colour, new_segment_width - }); + current_line->segments.emplace_back( + string_segment_t { + std::move(new_segment_string), string_segment->colour, + new_segment_width // + } + ); current_line->width += new_segment_width; } @@ -854,9 +834,11 @@ std::vector GUILabel::wrap_lines(std::vector& unwrappe continue; } } - current_line->segments.emplace_back(string_segment_t { - std::move(whole_segment_string), string_segment->colour, whole_segment_width - }); + current_line->segments.emplace_back( + string_segment_t { + std::move(whole_segment_string), string_segment->colour, whole_segment_width // + } + ); current_line->width += whole_segment_width; break; } @@ -872,8 +854,7 @@ std::vector GUILabel::wrap_lines(std::vector& unwrappe } const auto is_over_max_height = [this, &wrapped_lines, &max_content_size]() -> bool { - return wrapped_lines.size() > 1 - && wrapped_lines.size() * font->get_height(font_size) > max_content_size.height; + return wrapped_lines.size() > 1 && wrapped_lines.size() * font->get_height(font_size) > max_content_size.height; }; if (is_over_max_height()) { @@ -937,8 +918,7 @@ void GUILabel::adjust_to_content_size() { adjusted_rect.position.x = max_size.width - adjusted_rect.size.width; } break; case HORIZONTAL_ALIGNMENT_LEFT: - default: - break; + default: break; } } else { adjusted_rect = { {}, max_size }; diff --git a/extension/src/openvic-extension/classes/GUILabel.hpp b/extension/src/openvic-extension/classes/GUILabel.hpp index 0cf62629..cf9b760a 100644 --- a/extension/src/openvic-extension/classes/GUILabel.hpp +++ b/extension/src/openvic-extension/classes/GUILabel.hpp @@ -74,9 +74,7 @@ namespace OpenVic { static godot::String const& get_substitution_marker(); static godot::String const& get_flag_marker(); static void set_text_and_tooltip( - GUINode const& parent, - godot::NodePath const& path, - godot::StringName const& text_localisation_key, + GUINode const& parent, godot::NodePath const& path, godot::StringName const& text_localisation_key, godot::StringName const& tooltip_localisation_key ); @@ -88,7 +86,7 @@ namespace OpenVic { godot::String get_gui_text_name() const; /* Set the GUI::Text. */ godot::Error set_gui_text( - GUI::Text const* new_gui_text, GFX::Font::colour_codes_t const* override_colour_codes = nullptr + GUI::Text const* new_gui_text, GFX::Font::colour_codes_t const* override_colour_codes = nullptr // ); void force_update_lines(); @@ -127,21 +125,15 @@ namespace OpenVic { godot::String generate_substituted_text(godot::String const& base_text) const; std::pair generate_display_text_and_colour_instructions( - godot::String const& substituted_text + godot::String const& substituted_text // ) const; std::vector generate_lines_and_segments( - godot::String const& display_text, colour_instructions_t const& colour_instructions - ) const; - void separate_lines( - godot::String const& string, godot::Color const& colour, std::vector& lines - ) const; - void separate_currency_segments( - godot::String const& string, godot::Color const& colour, line_t& line + godot::String const& display_text, colour_instructions_t const& colour_instructions // ) const; + void separate_lines(godot::String const& string, godot::Color const& colour, std::vector& lines) const; + void separate_currency_segments(godot::String const& string, godot::Color const& colour, line_t& line) const; static flag_segment_t make_flag_segment(godot::String const& identifier); - void separate_flag_segments( - godot::String const& string, godot::Color const& colour, line_t& line - ) const; + void separate_flag_segments(godot::String const& string, godot::Color const& colour, line_t& line) const; std::vector wrap_lines(std::vector& unwrapped_lines) const; void adjust_to_content_size(); }; diff --git a/extension/src/openvic-extension/classes/GUILineChart.cpp b/extension/src/openvic-extension/classes/GUILineChart.cpp index 07bb4117..60790391 100644 --- a/extension/src/openvic-extension/classes/GUILineChart.cpp +++ b/extension/src/openvic-extension/classes/GUILineChart.cpp @@ -87,9 +87,9 @@ Error GUILineChart::set_gfx_line_chart_name(String const& new_gfx_line_chart_nam GFX::LineChart const* new_gfx_line_chart = sprite->cast_to(); ERR_FAIL_NULL_V_MSG( - new_gfx_line_chart, FAILED, Utilities::format( - "Invalid type for GFX sprite %s: %s (expected %s)", new_gfx_line_chart_name, - convert_to(sprite->get_type()), + new_gfx_line_chart, FAILED, + Utilities::format( + "Invalid type for GFX sprite %s: %s (expected %s)", new_gfx_line_chart_name, convert_to(sprite->get_type()), convert_to(GFX::LineChart::get_type_static()) ) ); @@ -190,10 +190,13 @@ Error GUILineChart::add_coloured_line(PackedFloat32Array const& line_values, Col if (point_count <= 0) { point_count = line_values.size(); } else { - ERR_FAIL_COND_V_MSG(point_count != line_values.size(), FAILED, Utilities::format( - "Mismatch between number of points in GUILineChart lines: new line %d != existing lines %d", - line_values.size(), point_count - )); + ERR_FAIL_COND_V_MSG( + point_count != line_values.size(), FAILED, + Utilities::format( + "Mismatch between number of points in GUILineChart lines: new line %d != existing lines %d", line_values.size(), + point_count + ) + ); } Line2D* line = memnew(Line2D); diff --git a/extension/src/openvic-extension/classes/GUILineChart.hpp b/extension/src/openvic-extension/classes/GUILineChart.hpp index cfb48d6b..7e19c1bd 100644 --- a/extension/src/openvic-extension/classes/GUILineChart.hpp +++ b/extension/src/openvic-extension/classes/GUILineChart.hpp @@ -4,6 +4,7 @@ #include #include + #include "openvic-extension/classes/GUIHasTooltip.hpp" namespace OpenVic { diff --git a/extension/src/openvic-extension/classes/GUIMaskedFlag.hpp b/extension/src/openvic-extension/classes/GUIMaskedFlag.hpp index 4bdc6c15..42223c40 100644 --- a/extension/src/openvic-extension/classes/GUIMaskedFlag.hpp +++ b/extension/src/openvic-extension/classes/GUIMaskedFlag.hpp @@ -22,7 +22,7 @@ namespace OpenVic { godot::String get_gfx_masked_flag_name() const; godot::Error set_flag_country_name_and_type( - godot::String const& flag_country_name, godot::StringName const& flag_type + godot::String const& flag_country_name, godot::StringName const& flag_type // ) const; godot::Error set_flag_country_name(godot::String const& flag_country_name) const; diff --git a/extension/src/openvic-extension/classes/GUIMaskedFlagButton.hpp b/extension/src/openvic-extension/classes/GUIMaskedFlagButton.hpp index fd4ec2c4..c10825a9 100644 --- a/extension/src/openvic-extension/classes/GUIMaskedFlagButton.hpp +++ b/extension/src/openvic-extension/classes/GUIMaskedFlagButton.hpp @@ -24,7 +24,7 @@ namespace OpenVic { godot::String get_gfx_masked_flag_name() const; godot::Error set_flag_country_name_and_type( - godot::String const& flag_country_name, godot::StringName const& flag_type + godot::String const& flag_country_name, godot::StringName const& flag_type // ) const; godot::Error set_flag_country_name(godot::String const& flag_country_name) const; diff --git a/extension/src/openvic-extension/classes/GUINode.cpp b/extension/src/openvic-extension/classes/GUINode.cpp index 79aa724d..1c49291a 100644 --- a/extension/src/openvic-extension/classes/GUINode.cpp +++ b/extension/src/openvic-extension/classes/GUINode.cpp @@ -131,7 +131,9 @@ static T* _cast_node(Node* node) { T* result = Object::cast_to(node); ERR_FAIL_NULL_V_MSG( result, nullptr, - Utilities::format("Failed to cast node %s from type %s to %s", node->get_name(), node->get_class(), T::get_class_static()) + Utilities::format( + "Failed to cast node %s from type %s to %s", node->get_name(), node->get_class(), T::get_class_static() + ) ); return result; } @@ -157,29 +159,36 @@ Ref GUINode::get_texture_from_node(Node* node) { ERR_FAIL_NULL_V(node, nullptr); if (TextureRect const* texture_rect = Object::cast_to(node); texture_rect != nullptr) { const Ref texture = texture_rect->get_texture(); - ERR_FAIL_NULL_V_MSG(texture, nullptr, Utilities::format("Failed to get Texture2D from TextureRect %s", node->get_name())); + ERR_FAIL_NULL_V_MSG( + texture, nullptr, Utilities::format("Failed to get Texture2D from TextureRect %s", node->get_name()) + ); return texture; } else if (GUIButton const* button = Object::cast_to(node); button != nullptr) { static const StringName theme_name_normal = "normal"; const Ref stylebox = button->get_theme_stylebox(theme_name_normal); ERR_FAIL_NULL_V_MSG( - stylebox, nullptr, Utilities::format("Failed to get StyleBox %s from GUIButton %s", theme_name_normal, node->get_name()) + stylebox, nullptr, + Utilities::format("Failed to get StyleBox %s from GUIButton %s", theme_name_normal, node->get_name()) ); const Ref stylebox_texture = stylebox; ERR_FAIL_NULL_V_MSG( - stylebox_texture, nullptr, Utilities::format( + stylebox_texture, nullptr, + Utilities::format( "Failed to cast StyleBox %s from GUIButton %s to type StyleBoxTexture", theme_name_normal, node->get_name() ) ); const Ref result = stylebox_texture->get_texture(); ERR_FAIL_NULL_V_MSG( result, nullptr, - Utilities::format("Failed to get Texture2D from StyleBoxTexture %s from GUIButton %s", theme_name_normal, node->get_name()) + Utilities::format( + "Failed to get Texture2D from StyleBoxTexture %s from GUIButton %s", theme_name_normal, node->get_name() + ) ); return result; } ERR_FAIL_V_MSG( - nullptr, Utilities::format( + nullptr, + Utilities::format( "Failed to cast node %s from type %s to TextureRect or GUIButton", node->get_name(), node->get_class() ) ); diff --git a/extension/src/openvic-extension/classes/GUINode.hpp b/extension/src/openvic-extension/classes/GUINode.hpp index 538749f9..62d00cc1 100644 --- a/extension/src/openvic-extension/classes/GUINode.hpp +++ b/extension/src/openvic-extension/classes/GUINode.hpp @@ -43,11 +43,11 @@ namespace OpenVic { GUINode(); static godot::Control* generate_gui_element( - godot::String const& gui_scene, godot::String const& gui_element, godot::String const& name = "" + godot::String const& gui_scene, godot::String const& gui_element, godot::String const& name = "" // ); godot::Error add_gui_element( - godot::String const& gui_scene, godot::String const& gui_element, godot::String const& name = "" + godot::String const& gui_scene, godot::String const& gui_element, godot::String const& name = "" // ); static godot::Vector2 get_gui_position(godot::String const& gui_scene, godot::String const& gui_position); @@ -69,7 +69,7 @@ namespace OpenVic { // These expect a non-null node! static GUIIconButton* get_gui_icon_button_from_node_and_path(godot::Node* node, godot::NodePath const& path); static GUIMaskedFlagButton* get_gui_masked_flag_button_from_node_and_path( - godot::Node* node, godot::NodePath const& path + godot::Node* node, godot::NodePath const& path // ); static GUILabel* get_gui_label_from_node_and_path(godot::Node* node, godot::NodePath const& path); static godot::Panel* get_panel_from_node_and_path(godot::Node* node, godot::NodePath const& path); @@ -78,7 +78,7 @@ namespace OpenVic { static GUIMaskedFlag* get_gui_masked_flag_from_node_and_path(godot::Node* node, godot::NodePath const& path); static GUIPieChart* get_gui_pie_chart_from_node_and_path(godot::Node* node, godot::NodePath const& path); static GUIOverlappingElementsBox* get_gui_overlapping_elements_box_from_node_and_path( - godot::Node* node, godot::NodePath const& path + godot::Node* node, godot::NodePath const& path // ); static GUIScrollbar* get_gui_scrollbar_from_node_and_path(godot::Node* node, godot::NodePath const& path); static GUIListBox* get_gui_listbox_from_node_and_path(godot::Node* node, godot::NodePath const& path); diff --git a/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.cpp b/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.cpp index 81108cab..a7da9bb8 100644 --- a/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.cpp +++ b/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.cpp @@ -19,7 +19,9 @@ Error GUIOverlappingElementsBox::_update_child_positions() { return OK; } - const auto _get_child = [this](int32_t index) -> Control* { return Object::cast_to(get_child(index)); }; + const auto _get_child = [this](int32_t index) -> Control* { + return Object::cast_to(get_child(index)); + }; const float box_width = get_size().x; const float child_width = _get_child(0)->get_size().x; @@ -35,20 +37,14 @@ Error GUIOverlappingElementsBox::_update_child_positions() { Error err = OK; using enum text_format_t; switch (gui_overlapping_elements_box->get_format()) { - case left: - break; - case centre: - starting_x = (box_width - total_width) / 2; - break; - case right: - starting_x = box_width - total_width; - break; - default: - UtilityFunctions::push_error( - "Invalid GUIOverlappingElementsBox alignment: ", - static_cast(gui_overlapping_elements_box->get_format()) - ); - err = FAILED; + case left: break; + case centre: starting_x = (box_width - total_width) / 2; break; + case right: starting_x = box_width - total_width; break; + default: + UtilityFunctions::push_error( + "Invalid GUIOverlappingElementsBox alignment: ", static_cast(gui_overlapping_elements_box->get_format()) + ); + err = FAILED; } for (int32_t index = 0; index < child_count; ++index) { @@ -103,7 +99,8 @@ Error GUIOverlappingElementsBox::set_child_count(int32_t new_count) { return OK; } else { ERR_FAIL_NULL_V_MSG( - gui_child_element, FAILED, Utilities::format( + gui_child_element, FAILED, + Utilities::format( "GUIOverlappingElementsBox child element is null (child_count = %d, new_count = %d)", child_count, new_count ) ); @@ -117,9 +114,10 @@ Error GUIOverlappingElementsBox::set_child_count(int32_t new_count) { err = FAILED; } ERR_FAIL_NULL_V_MSG( - child, FAILED, Utilities::format( - "Failed to generate GUIOverlappingElementsBox child element %s (child_count = %d, new_count = %d)", - name, child_count, new_count + child, FAILED, + Utilities::format( + "Failed to generate GUIOverlappingElementsBox child element %s (child_count = %d, new_count = %d)", name, + child_count, new_count ) ); @@ -155,9 +153,7 @@ Error GUIOverlappingElementsBox::set_gui_overlapping_elements_box( } String GUIOverlappingElementsBox::get_gui_overlapping_elements_box_name() const { - return gui_overlapping_elements_box != nullptr - ? convert_to(gui_overlapping_elements_box->get_name()) - : String {}; + return gui_overlapping_elements_box != nullptr ? convert_to(gui_overlapping_elements_box->get_name()) : String {}; } Error GUIOverlappingElementsBox::set_gui_child_element(GUI::Element const* new_gui_child_element) { diff --git a/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.hpp b/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.hpp index b10c7d89..993e7167 100644 --- a/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.hpp +++ b/extension/src/openvic-extension/classes/GUIOverlappingElementsBox.hpp @@ -42,7 +42,7 @@ namespace OpenVic { /* Search for a GUI::Element with the specified name and, if successful, * set the child element to it using set_gui_child_element. */ godot::Error set_gui_child_element_name( - godot::String const& gui_child_element_file, godot::String const& gui_child_element_name + godot::String const& gui_child_element_file, godot::String const& gui_child_element_name // ); /* Return the name of the child GUI::Element, or an empty String if it's null. */ diff --git a/extension/src/openvic-extension/classes/GUIProgressBar.cpp b/extension/src/openvic-extension/classes/GUIProgressBar.cpp index ca5776e6..cded974a 100644 --- a/extension/src/openvic-extension/classes/GUIProgressBar.cpp +++ b/extension/src/openvic-extension/classes/GUIProgressBar.cpp @@ -52,9 +52,8 @@ Error GUIProgressBar::set_gfx_progress_bar(GFX::ProgressBar const* progress_bar) } if (back_texture.is_null()) { const Color back_colour = convert_to(progress_bar->get_back_colour()); - back_texture = Utilities::make_solid_colour_texture( - back_colour, progress_bar->get_size().x, progress_bar->get_size().y - ); + back_texture = + Utilities::make_solid_colour_texture(back_colour, progress_bar->get_size().x, progress_bar->get_size().y); if (back_texture.is_null()) { UtilityFunctions::push_error( "Failed to generate sprite ", back_colour, " back texture for GUIProgressBar ", get_name() @@ -65,34 +64,28 @@ Error GUIProgressBar::set_gfx_progress_bar(GFX::ProgressBar const* progress_bar) if (back_texture.is_valid()) { set_under_texture(back_texture); } else { - UtilityFunctions::push_error( - "Failed to create and set sprite back texture for GUIProgressBar ", get_name() - ); + UtilityFunctions::push_error("Failed to create and set sprite back texture for GUIProgressBar ", get_name()); err = FAILED; } Ref progress_texture; if (!progress_bar->get_progress_texture_file().empty()) { - const StringName progress_texture_file = - convert_to(progress_bar->get_progress_texture_file()); + const StringName progress_texture_file = convert_to(progress_bar->get_progress_texture_file()); progress_texture = asset_manager->get_texture(progress_texture_file, LOAD_FLAG_CACHE_TEXTURE | LOAD_FLAG_FLIP_Y); if (progress_texture.is_null()) { UtilityFunctions::push_error( - "Failed to load sprite progress texture ", progress_texture_file, " for GUIProgressBar ", - get_name() + "Failed to load sprite progress texture ", progress_texture_file, " for GUIProgressBar ", get_name() ); err = FAILED; } } if (progress_texture.is_null()) { const Color progress_colour = convert_to(progress_bar->get_progress_colour()); - progress_texture = Utilities::make_solid_colour_texture( - progress_colour, progress_bar->get_size().x, progress_bar->get_size().y - ); + progress_texture = + Utilities::make_solid_colour_texture(progress_colour, progress_bar->get_size().x, progress_bar->get_size().y); if (progress_texture.is_null()) { UtilityFunctions::push_error( - "Failed to generate sprite ", progress_colour, " progress texture for GUIProgressBar ", - get_name() + "Failed to generate sprite ", progress_colour, " progress texture for GUIProgressBar ", get_name() ); err = FAILED; } @@ -100,16 +93,12 @@ Error GUIProgressBar::set_gfx_progress_bar(GFX::ProgressBar const* progress_bar) if (progress_texture.is_valid()) { set_progress_texture(progress_texture); } else { - UtilityFunctions::push_error( - "Failed to create and set sprite progress texture for GUIProgressBar ", get_name() - ); + UtilityFunctions::push_error("Failed to create and set sprite progress texture for GUIProgressBar ", get_name()); err = FAILED; } // TODO - work out why progress bar is missing bottom border pixel (e.g. province building expansion bar) - set_custom_minimum_size( - convert_to(progress_bar->get_size()) - ); + set_custom_minimum_size(convert_to(progress_bar->get_size())); return err; } diff --git a/extension/src/openvic-extension/classes/GUIProgressBar.hpp b/extension/src/openvic-extension/classes/GUIProgressBar.hpp index 11b677ac..077b3909 100644 --- a/extension/src/openvic-extension/classes/GUIProgressBar.hpp +++ b/extension/src/openvic-extension/classes/GUIProgressBar.hpp @@ -2,7 +2,8 @@ #include -#include "openvic-simulation/interface/GFXSprite.hpp" +#include + #include "openvic-extension/classes/GUIHasTooltip.hpp" namespace OpenVic { diff --git a/extension/src/openvic-extension/classes/GUIScrollbar.cpp b/extension/src/openvic-extension/classes/GUIScrollbar.cpp index f0e65659..ad83f6b8 100644 --- a/extension/src/openvic-extension/classes/GUIScrollbar.cpp +++ b/extension/src/openvic-extension/classes/GUIScrollbar.cpp @@ -106,9 +106,7 @@ bool GUIScrollbar::_update_button_change() { } float GUIScrollbar::_value_to_ratio(int32_t val) const { - return step_count == 0 - ? 0.0f - : static_cast(val) / step_count; + return step_count == 0 ? 0.0f : static_cast(val) / step_count; } int32_t GUIScrollbar::_fp_to_value(const fixed_point_t val) const { @@ -193,8 +191,8 @@ void GUIScrollbar::_calculate_rects() { * They have a row of transparent pixels at the top to account for this, so we must also draw them * one pixel taller to avoid having a gap between the track and the more button. */ track_rect = { - { (average_button_width - track_width) / 2.0f, slider_start - 1.0f }, - { track_width, slider_distance + 1.0f } + { (average_button_width - track_width) / 2.0f, slider_start - 1.0f }, // + { track_width, slider_distance + 1.0f } // }; } else { track_rect = {}; @@ -204,8 +202,8 @@ void GUIScrollbar::_calculate_rects() { const Size2 slider_size = slider_texture->get_size(); slider_rect = { - { (average_button_width - slider_size.width) / 2.0f, 0.0f }, - slider_size + { (average_button_width - slider_size.width) / 2.0f, 0.0f }, // + slider_size // }; slider_distance -= slider_rect.size.height; @@ -232,18 +230,14 @@ void GUIScrollbar::_constrain_value() { const int32_t upper_limit = upper_range_limit.value_or(step_count); // Special case to mimic ClampedValue.hpp - if (lower_limit > upper_limit){ + if (lower_limit > upper_limit) { if (value > upper_limit) { value = lower_limit; } else { value = upper_limit; } } else { - value = std::clamp( - value, - lower_limit, - upper_limit - ); + value = std::clamp(value, lower_limit, upper_limit); } slider_rect.position[orientation == HORIZONTAL ? 0 : 1] = slider_start + slider_distance * get_value_as_ratio(); @@ -256,7 +250,7 @@ void GUIScrollbar::_constrain_range_limits() { lower_range_limit = upper_range_limit = {}; return; } - + if (lower_range_limit.has_value()) { lower_range_limit = std::clamp(lower_range_limit.value(), 0, step_count); } @@ -266,9 +260,8 @@ void GUIScrollbar::_constrain_range_limits() { const int axis = orientation == HORIZONTAL ? 0 : 1; range_limit_min_rect.position[axis] = slider_start + slider_distance * _value_to_ratio(lower_range_limit.value_or(0)); - range_limit_max_rect.position[axis] = slider_start - + slider_distance * _value_to_ratio(upper_range_limit.value_or(step_count)) - + slider_rect.size[axis] / 2.0f; + range_limit_max_rect.position[axis] = slider_start + + slider_distance * _value_to_ratio(upper_range_limit.value_or(step_count)) + slider_rect.size[axis] / 2.0f; return; } @@ -376,37 +369,50 @@ Error GUIScrollbar::set_gui_scrollbar(GUI::Scrollbar const* new_gui_scrollbar) { /* _Element is either GUI::Button or GUI::Icon, both of which have their own * separately defined get_sprite(), hence the need for a template. */ - const auto set_texture = [&gui_scrollbar_name]( - String const& target, _Element const* element, Ref& texture - ) -> bool { - ERR_FAIL_NULL_V_MSG(element, false, Utilities::format( - "Invalid %s element for GUIScrollbar %s - null!", target, gui_scrollbar_name - )); + const auto set_texture = // + [ // + &gui_scrollbar_name // + ](String const& target, _Element const* element, Ref& texture) -> bool { + ERR_FAIL_NULL_V_MSG( + element, false, Utilities::format("Invalid %s element for GUIScrollbar %s - null!", target, gui_scrollbar_name) + ); const String element_name = convert_to(element->get_name()); /* Get Sprite, convert to TextureSprite, use to make a GFXSpriteTexture. */ GFX::Sprite const* sprite = element->get_sprite(); - ERR_FAIL_NULL_V_MSG(sprite, false, Utilities::format( - "Invalid %s element %s for GUIScrollbar %s - sprite is null!", target, element_name, gui_scrollbar_name - )); + ERR_FAIL_NULL_V_MSG( + sprite, false, + Utilities::format( + "Invalid %s element %s for GUIScrollbar %s - sprite is null!", target, element_name, gui_scrollbar_name + ) + ); GFX::TextureSprite const* texture_sprite = sprite->cast_to(); - ERR_FAIL_NULL_V_MSG(texture_sprite, false, Utilities::format( - "Invalid %s element %s for GUIScrollbar %s - sprite type is %s with base type %s, expected base %s!", target, - element_name, gui_scrollbar_name, convert_to(sprite->get_type()), - convert_to(sprite->get_base_type()), - convert_to(GFX::TextureSprite::get_type_static()) - )); + ERR_FAIL_NULL_V_MSG( + texture_sprite, false, + Utilities::format( + "Invalid %s element %s for GUIScrollbar %s - sprite type is %s with base type %s, expected base %s!", target, + element_name, gui_scrollbar_name, convert_to(sprite->get_type()), + convert_to(sprite->get_base_type()), convert_to(GFX::TextureSprite::get_type_static()) + ) + ); texture = GFXSpriteTexture::make_gfx_sprite_texture(texture_sprite); - ERR_FAIL_NULL_V_MSG(texture, false, Utilities::format( - "Failed to make GFXSpriteTexture from %s element %s for GUIScrollbar %s!", target, element_name, gui_scrollbar_name - )); + ERR_FAIL_NULL_V_MSG( + texture, false, + Utilities::format( + "Failed to make GFXSpriteTexture from %s element %s for GUIScrollbar %s!", target, element_name, + gui_scrollbar_name + ) + ); if constexpr (std::is_same_v<_Element, GUI::Button>) { using enum GFXButtonStateTexture::ButtonState; for (GFXButtonStateTexture::ButtonState state : { HOVER, PRESSED }) { - ERR_FAIL_NULL_V_MSG(texture->get_button_state_texture(state), false, Utilities::format( - "Failed to generate %s texture for %s element %s for GUIScrollbar %s!", - GFXButtonStateTexture::button_state_to_name(state), target, element_name, gui_scrollbar_name - )); + ERR_FAIL_NULL_V_MSG( + texture->get_button_state_texture(state), false, + Utilities::format( + "Failed to generate %s texture for %s element %s for GUIScrollbar %s!", + GFXButtonStateTexture::button_state_to_name(state), target, element_name, gui_scrollbar_name + ) + ); } } return true; @@ -433,31 +439,24 @@ Error GUIScrollbar::set_gui_scrollbar(GUI::Scrollbar const* new_gui_scrollbar) { _calculate_rects(); - auto adjust_for_min_and_step_size = [ - min_value = gui_scrollbar->get_min_value(), - step_size = gui_scrollbar->get_step_size() - ](const int32_t val)->int32_t { + auto adjust_for_min_and_step_size = // + [ // + min_value = gui_scrollbar->get_min_value(), + step_size = gui_scrollbar->get_step_size() // + ](const int32_t val) -> int32_t { assert(step_size != 0); - return ( - (val - min_value) / step_size - ).truncate(); + return ((val - min_value) / step_size).truncate(); }; const bool was_blocking_signals = is_blocking_signals(); if (!was_blocking_signals) { - set_block_signals(true); //only emit 1 signal via set_value + set_block_signals(true); // only emit 1 signal via set_value } - set_step_count( - adjust_for_min_and_step_size(gui_scrollbar->get_max_value().truncate()) - ); + set_step_count(adjust_for_min_and_step_size(gui_scrollbar->get_max_value().truncate())); + + set_scale(gui_scrollbar->get_min_value(), gui_scrollbar->get_step_size().truncate(), 1); - set_scale( - gui_scrollbar->get_min_value(), - gui_scrollbar->get_step_size().truncate(), - 1 - ); - set_range_limits( adjust_for_min_and_step_size(gui_scrollbar->get_range_limit_min().truncate()), adjust_for_min_and_step_size(gui_scrollbar->get_range_limit_max().truncate()) @@ -467,9 +466,7 @@ Error GUIScrollbar::set_gui_scrollbar(GUI::Scrollbar const* new_gui_scrollbar) { set_block_signals(false); } - set_value( - adjust_for_min_and_step_size(gui_scrollbar->get_start_value().truncate()) - ); + set_value(adjust_for_min_and_step_size(gui_scrollbar->get_start_value().truncate())); return ERR(ret); } @@ -478,9 +475,7 @@ Error GUIScrollbar::set_gui_scrollbar_name(String const& gui_scene, String const if (gui_scene.is_empty() && gui_scrollbar_name.is_empty()) { return set_gui_scrollbar(nullptr); } - ERR_FAIL_COND_V_MSG( - gui_scene.is_empty() || gui_scrollbar_name.is_empty(), FAILED, "GUI scene or scrollbar name is empty!" - ); + ERR_FAIL_COND_V_MSG(gui_scene.is_empty() || gui_scrollbar_name.is_empty(), FAILED, "GUI scene or scrollbar name is empty!"); GUI::Element const* gui_element = UITools::get_gui_element(gui_scene, gui_scrollbar_name); ERR_FAIL_NULL_V(gui_element, FAILED); @@ -548,9 +543,7 @@ void GUIScrollbar::set_step_count(const int32_t new_step_count) { } } void GUIScrollbar::set_scale( - const fixed_point_t new_offset, - const int32_t new_scale_numerator, - const int32_t new_scale_denominator + const fixed_point_t new_offset, const int32_t new_scale_numerator, const int32_t new_scale_denominator ) { if (new_scale_numerator == 0) { spdlog::warn_s("Ignoring set_scale with numerator 0 on GUIScrollbar {}", *gui_scrollbar); @@ -566,8 +559,7 @@ void GUIScrollbar::set_scale( emit_value_changed(); } void GUIScrollbar::set_range_limits( - const std::optional new_lower_range_limit, - const std::optional new_upper_range_limit + const std::optional new_lower_range_limit, const std::optional new_upper_range_limit ) { if (!range_limited) { spdlog::warn_s("Ignoring set_range_limits of non-range-limited GUIScrollbar {}", *gui_scrollbar); @@ -584,29 +576,22 @@ void GUIScrollbar::set_range_limits( } } void GUIScrollbar::set_range_limits_fp( - const std::optional new_lower_range_limit, - const std::optional new_upper_range_limit + const std::optional new_lower_range_limit, const std::optional new_upper_range_limit ) { set_range_limits( - new_lower_range_limit.has_value() - ? _fp_to_value(new_lower_range_limit.value()) - : std::optional{}, - new_upper_range_limit.has_value() - ? _fp_to_value(new_upper_range_limit.value()) - : std::optional{} + new_lower_range_limit.has_value() ? _fp_to_value(new_lower_range_limit.value()) : std::optional {}, + new_upper_range_limit.has_value() ? _fp_to_value(new_upper_range_limit.value()) : std::optional {} ); } void GUIScrollbar::set_range_limits_and_value_from_slider_value(ReadOnlyClampedValue& slider_value) { - set_range_limits_fp( - slider_value.get_min(), - slider_value.get_max() - ); + set_range_limits_fp(slider_value.get_min(), slider_value.get_max()); set_scaled_value(slider_value.get_value_untracked()); } void GUIScrollbar::set_length_override(real_t new_length_override) { ERR_FAIL_COND_MSG( - length_override < 0, Utilities::format("Invalid GUIScrollbar length override: %f - cannot be negative!", length_override) + length_override < 0, + Utilities::format("Invalid GUIScrollbar length override: %f - cannot be negative!", length_override) ); length_override = new_length_override; @@ -700,7 +685,7 @@ void GUIScrollbar::_notification(int what) { switch (what) { case NOTIFICATION_VISIBILITY_CHANGED: - case NOTIFICATION_MOUSE_EXIT: { + case NOTIFICATION_MOUSE_EXIT: { hover_slider = false; hover_track = false; hover_less = false; diff --git a/extension/src/openvic-extension/classes/GUIScrollbar.hpp b/extension/src/openvic-extension/classes/GUIScrollbar.hpp index f20a15f6..44a9f295 100644 --- a/extension/src/openvic-extension/classes/GUIScrollbar.hpp +++ b/extension/src/openvic-extension/classes/GUIScrollbar.hpp @@ -119,22 +119,14 @@ namespace OpenVic { float get_value_scaled() const; void set_step_count(const int32_t new_step_count); - void set_scale( - const fixed_point_t new_offset, - const int32_t new_scale_numerator, - const int32_t new_scale_denominator - ); + void set_scale(const fixed_point_t new_offset, const int32_t new_scale_numerator, const int32_t new_scale_denominator); void set_range_limits( - const std::optional new_lower_range_limit, - const std::optional new_upper_range_limit + const std::optional new_lower_range_limit, const std::optional new_upper_range_limit ); void set_range_limits_fp( - const std::optional new_lower_range_limit, - const std::optional new_upper_range_limit - ); - void set_range_limits_and_value_from_slider_value( - ReadOnlyClampedValue& slider_value + const std::optional new_lower_range_limit, const std::optional new_upper_range_limit ); + void set_range_limits_and_value_from_slider_value(ReadOnlyClampedValue& slider_value); /* Override the main dimension of gui_scollbar's size with the specified length. */ void set_length_override(real_t new_length_override); diff --git a/extension/src/openvic-extension/components/budget/AdministrationBudget.cpp b/extension/src/openvic-extension/components/budget/AdministrationBudget.cpp index e5d77c0d..c03fd16f 100644 --- a/extension/src/openvic-extension/components/budget/AdministrationBudget.cpp +++ b/extension/src/openvic-extension/components/budget/AdministrationBudget.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "openvic-extension/classes/GUILabel.hpp" #include "openvic-extension/classes/GUINode.hpp" @@ -10,34 +11,21 @@ #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/PlayerSingleton.hpp" #include "openvic-extension/utility/Utilities.hpp" -#include "openvic-simulation/types/fixed_point/FixedPoint.hpp" using namespace OpenVic; -AdministrationBudget::AdministrationBudget( - GUINode const& parent, - CountryDefines const& new_country_defines -): - SliderBudgetComponent( - parent, - "BUDGET_SLIDER_ADMINISTRATION", - EXPENSES, - "./country_budget/exp_1_slider", - "./country_budget/exp_val_1" - ), - BudgetExpenseComponent("BUDGET_SLIDER_ADMINISTRATION"), - country_defines{new_country_defines}, - administrative_efficiency_label{*parent.get_gui_label_from_nodepath("./country_budget/admin_efficiency")} -{ +AdministrationBudget::AdministrationBudget(GUINode const& parent, CountryDefines const& new_country_defines) + : SliderBudgetComponent( + parent, "BUDGET_SLIDER_ADMINISTRATION", EXPENSES, "./country_budget/exp_1_slider", "./country_budget/exp_val_1" + ), + BudgetExpenseComponent("BUDGET_SLIDER_ADMINISTRATION"), country_defines { new_country_defines }, + administrative_efficiency_label { *parent.get_gui_label_from_nodepath("./country_budget/admin_efficiency") } { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); slider.set_block_signals(false); - - GUILabel::set_text_and_tooltip( - parent, "./country_budget/admin_desc", - "ADMINISTRATION","ADM_DESC" - ); + + GUILabel::set_text_and_tooltip(parent, "./country_budget/admin_desc", "ADMINISTRATION", "ADM_DESC"); administrative_efficiency_tooltip_args.resize(7); administrative_efficiency_tooltip_args[1] = administrative_efficiency_label.tr("BUDGET_ADMIN_EFFICIENCY_DESC2"); @@ -53,62 +41,54 @@ bool AdministrationBudget::was_budget_cut(CountryInstance const& country) const } fixed_point_t AdministrationBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value + CountryInstance& country, const fixed_point_t scaled_value // ) { static const godot::StringName administrative_efficiency_template = "%s\n%s%s\n--------------\n%s%s%s%s"; - const fixed_point_t administrative_efficiency_from_administrators = country.get_administrative_efficiency_from_administrators_untracked(); + const fixed_point_t administrative_efficiency_from_administrators = + country.get_administrative_efficiency_from_administrators_untracked(); administrative_efficiency_label.set_text( - Utilities::format( - "%s%%", - Utilities::fixed_point_to_string_dp( - 100 * administrative_efficiency_from_administrators, - 1 - ) - ) - ); - - administrative_efficiency_tooltip_args[0] = administrative_efficiency_label.tr( - "BUDGET_ADMIN_EFFICIENCY2" - ).replace( - Utilities::get_percentage_value_placeholder(), - Utilities::fixed_point_to_string_dp(100 * administrative_efficiency_from_administrators, 1) + Utilities::format("%s%%", Utilities::fixed_point_to_string_dp(100 * administrative_efficiency_from_administrators, 1)) ); + administrative_efficiency_tooltip_args[0] = + administrative_efficiency_label.tr("BUDGET_ADMIN_EFFICIENCY2") + .replace( + Utilities::get_percentage_value_placeholder(), + Utilities::fixed_point_to_string_dp(100 * administrative_efficiency_from_administrators, 1) + ); + if (scaled_value == 0) { administrative_efficiency_tooltip_args[2] = ""; } else { static const godot::String admin_crime_template = godot::String::utf8("\n%s §Y%s%%§! %s"); const fixed_point_t admin_spending_crime_effect = country_defines.get_admin_spending_crimefight_percent(); administrative_efficiency_tooltip_args[2] = Utilities::format( - admin_crime_template, - administrative_efficiency_label.tr("BUDGET_VIEW_CRIME_FIGHT"), + admin_crime_template, administrative_efficiency_label.tr("BUDGET_VIEW_CRIME_FIGHT"), Utilities::fixed_point_to_string_dp(100 * admin_spending_crime_effect * scaled_value, 1), - administrative_efficiency_label.tr( - "PV_CRIMEFIGHT_MAX" - ).replace( - Utilities::get_percentage_value_placeholder(), - Utilities::fixed_point_to_string_dp(100 * admin_spending_crime_effect, 1) - ) + administrative_efficiency_label.tr("PV_CRIMEFIGHT_MAX") + .replace( + Utilities::get_percentage_value_placeholder(), + Utilities::fixed_point_to_string_dp(100 * admin_spending_crime_effect, 1) + ) ); } - administrative_efficiency_tooltip_args[3] = administrative_efficiency_label.tr( - "BUDGET_ADMIN_EFFICIENCY_DESC" - ).replace( - Utilities::get_percentage_value_placeholder(), - Utilities::fixed_point_to_string_dp(100 * country.get_administrator_percentage_untracked(), 1) - ).replace( - "MAX", - Utilities::fixed_point_to_string_dp(100 * country.desired_administrator_percentage.get_untracked(), 1) - ); - administrative_efficiency_tooltip_args[5] = administrative_efficiency_label.tr( - "COMWID_BASE" - ).replace( - Utilities::get_short_value_placeholder(), - Utilities::percentage_to_string_dp(country_defines.get_max_bureaucracy_percentage(), 1) - ); + administrative_efficiency_tooltip_args[3] = + administrative_efficiency_label.tr("BUDGET_ADMIN_EFFICIENCY_DESC") + .replace( + Utilities::get_percentage_value_placeholder(), + Utilities::fixed_point_to_string_dp(100 * country.get_administrator_percentage_untracked(), 1) + ) + .replace( + "MAX", Utilities::fixed_point_to_string_dp(100 * country.desired_administrator_percentage.get_untracked(), 1) + ); + administrative_efficiency_tooltip_args[5] = + administrative_efficiency_label.tr("COMWID_BASE") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::percentage_to_string_dp(country_defines.get_max_bureaucracy_percentage(), 1) + ); godot::String reforms_part = ""; for (auto const& [group, reform] : country.get_reforms()) { @@ -120,18 +100,14 @@ fixed_point_t AdministrationBudget::calculate_budget_and_update_custom( if (administrative_multiplier == 0) { continue; } - + static const godot::String reform_template = godot::String::utf8("\n%s: %s §Y+%s%%§!"); - const fixed_point_t extra_administrator_percentage = administrative_multiplier * country_defines.get_bureaucracy_percentage_increment(); + const fixed_point_t extra_administrator_percentage = + administrative_multiplier * country_defines.get_bureaucracy_percentage_increment(); reforms_part += Utilities::format( - reform_template, - administrative_efficiency_label.tr( - convert_to(group.get_identifier()) - ), - administrative_efficiency_label.tr( - convert_to(reform->get_identifier()) - ), + reform_template, administrative_efficiency_label.tr(convert_to(group.get_identifier())), + administrative_efficiency_label.tr(convert_to(reform->get_identifier())), Utilities::fixed_point_to_string_dp(100 * extra_administrator_percentage, 2) ); } @@ -144,16 +120,16 @@ fixed_point_t AdministrationBudget::calculate_budget_and_update_custom( if (budget_label != nullptr) { budget_label->set_tooltip_string( Utilities::format( - "%s\n--------------\n%s%s", - budget_label->tr("DIST_ADMINISTRATION"), - was_budget_cut(country) - ? budget_label->tr("EXPENSE_NO_AFFORD").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp_dynamic( - static_cast(country.get_actual_administration_spending().load()) - ) - ) + "\n" - : "", + "%s\n--------------\n%s%s", budget_label->tr("DIST_ADMINISTRATION"), + was_budget_cut(country) ? budget_label->tr("EXPENSE_NO_AFFORD") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp_dynamic( + static_cast(country.get_actual_administration_spending().load()) + ) + ) + + "\n" + : "", budget_label->tr("ADM_DESC") ) ); @@ -168,4 +144,4 @@ ReadOnlyClampedValue& AdministrationBudget::get_clamped_value(CountryInstance& c void AdministrationBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_administration_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/AdministrationBudget.hpp b/extension/src/openvic-extension/components/budget/AdministrationBudget.hpp index a8aa93db..4d4dcc82 100644 --- a/extension/src/openvic-extension/components/budget/AdministrationBudget.hpp +++ b/extension/src/openvic-extension/components/budget/AdministrationBudget.hpp @@ -15,18 +15,12 @@ namespace OpenVic { GUILabel& administrative_efficiency_label; bool was_budget_cut(CountryInstance const& country) const override; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; public: - AdministrationBudget( - GUINode const& parent, - CountryDefines const& new_country_defines - ); + AdministrationBudget(GUINode const& parent, CountryDefines const& new_country_defines); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.cpp b/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.cpp index 1d75bc29..62ecf874 100644 --- a/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.cpp +++ b/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.cpp @@ -7,15 +7,9 @@ using namespace OpenVic; -ArmyStockpileBudget::ArmyStockpileBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "MILITARY_SPENDINGS_LAND", - EXPENSES, - "./country_budget/land_stockpile_slider" - ), - BudgetExpenseComponent("MILITARY_SPENDINGS_LAND") -{ +ArmyStockpileBudget::ArmyStockpileBudget(GUINode const& parent) + : SliderBudgetComponent(parent, "MILITARY_SPENDINGS_LAND", EXPENSES, "./country_budget/land_stockpile_slider"), + BudgetExpenseComponent("MILITARY_SPENDINGS_LAND") { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); @@ -27,10 +21,9 @@ fixed_point_t ArmyStockpileBudget::get_expenses() const { } fixed_point_t ArmyStockpileBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value + CountryInstance& country, const fixed_point_t scaled_value // ) { - return scaled_value * 1; //TODO connect with sim once sim has this + return scaled_value * 1; // TODO connect with sim once sim has this } ReadOnlyClampedValue& ArmyStockpileBudget::get_clamped_value(CountryInstance& country) const { @@ -39,4 +32,4 @@ ReadOnlyClampedValue& ArmyStockpileBudget::get_clamped_value(CountryInstance& co void ArmyStockpileBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_national_stockpile_army_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.hpp b/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.hpp index 97de4b6b..8343d4ca 100644 --- a/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.hpp +++ b/extension/src/openvic-extension/components/budget/ArmyStockpileBudget.hpp @@ -6,10 +6,7 @@ namespace OpenVic { struct ArmyStockpileBudget : public SliderBudgetComponent, public BudgetExpenseComponent { private: - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -17,4 +14,4 @@ namespace OpenVic { ArmyStockpileBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/BudgetMenu.cpp b/extension/src/openvic-extension/components/budget/BudgetMenu.cpp index 978c9546..40be77f8 100644 --- a/extension/src/openvic-extension/components/budget/BudgetMenu.cpp +++ b/extension/src/openvic-extension/components/budget/BudgetMenu.cpp @@ -14,63 +14,52 @@ using namespace OpenVic; BudgetMenu::BudgetMenu( - GUINode const& parent, - forwardable_span strata_keys, - ModifierEffectCache const& modifier_effect_cache, + GUINode const& parent, forwardable_span strata_keys, ModifierEffectCache const& modifier_effect_cache, CountryDefines const& country_defines -) : cash_stockpile_label{*parent.get_gui_label_from_nodepath("./country_budget/total_funds_val")}, - gold_income_label{*parent.get_gui_label_from_nodepath("./country_budget/gold_inc")}, - projected_balance_label{*parent.get_gui_label_from_nodepath("./country_budget/balance")}, - projected_expenses_label{*parent.get_gui_label_from_nodepath("./country_budget/total_exp")}, - projected_income_label{*parent.get_gui_label_from_nodepath("./country_budget/total_inc")}, - administration_budget{parent,country_defines}, - diplomatic_budget{parent}, - education_budget{parent}, - military_budget{parent}, - national_stockpile_budget{parent}, - social_budget{parent}, - tariff_budget{parent,country_defines}, - projected_income_template{generate_projected_income_template(strata_keys.size())} - { - tax_budgets.reserve(strata_keys.size()); - connections.reserve(7 + strata_keys.size()); - connections.push_back(administration_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); - connections.push_back(diplomatic_budget.balance_changed.connect(&BudgetMenu::update_all_projections, this)); - connections.push_back(education_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); - connections.push_back(military_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); - connections.push_back(national_stockpile_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); - connections.push_back(social_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); - connections.push_back(tariff_budget.balance_changed.connect(&BudgetMenu::update_all_projections, this)); - for (Strata const& strata : strata_keys) { - StrataTaxBudget& strata_tax_budget = tax_budgets.emplace_back(parent, strata, modifier_effect_cache); - connections.push_back(strata_tax_budget.balance_changed.connect(&BudgetMenu::update_projected_income_and_balance, this)); - } - - GUILabel::set_text_and_tooltip( - parent, "./country_budget/gold_desc", - "GOLD","precious_metal_desc" - ); - GUILabel::set_text_and_tooltip( - parent, "./country_budget/ind_sub_desc", - "BUDGET_INDUSTRIAL_SUBSIDIES","IND_SUP_DESC" +) + : cash_stockpile_label { *parent.get_gui_label_from_nodepath("./country_budget/total_funds_val") }, + gold_income_label { *parent.get_gui_label_from_nodepath("./country_budget/gold_inc") }, + projected_balance_label { *parent.get_gui_label_from_nodepath("./country_budget/balance") }, + projected_expenses_label { *parent.get_gui_label_from_nodepath("./country_budget/total_exp") }, + projected_income_label { *parent.get_gui_label_from_nodepath("./country_budget/total_inc") }, + administration_budget { parent, country_defines }, diplomatic_budget { parent }, education_budget { parent }, + military_budget { parent }, national_stockpile_budget { parent }, social_budget { parent }, + tariff_budget { parent, country_defines }, + projected_income_template { generate_projected_income_template(strata_keys.size()) } { + tax_budgets.reserve(strata_keys.size()); + connections.reserve(7 + strata_keys.size()); + connections.push_back( + administration_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this) + ); + connections.push_back(diplomatic_budget.balance_changed.connect(&BudgetMenu::update_all_projections, this)); + connections.push_back(education_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); + connections.push_back(military_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); + connections.push_back( + national_stockpile_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this) + ); + connections.push_back(social_budget.balance_changed.connect(&BudgetMenu::update_projected_expenses_and_balance, this)); + connections.push_back(tariff_budget.balance_changed.connect(&BudgetMenu::update_all_projections, this)); + for (Strata const& strata : strata_keys) { + StrataTaxBudget& strata_tax_budget = tax_budgets.emplace_back(parent, strata, modifier_effect_cache); + connections.push_back( + strata_tax_budget.balance_changed.connect(&BudgetMenu::update_projected_income_and_balance, this) ); - - projected_income_args.resize(5 + strata_keys.size()); - projected_expenses_args.resize(8); } + GUILabel::set_text_and_tooltip(parent, "./country_budget/gold_desc", "GOLD", "precious_metal_desc"); + GUILabel::set_text_and_tooltip(parent, "./country_budget/ind_sub_desc", "BUDGET_INDUSTRIAL_SUBSIDIES", "IND_SUP_DESC"); + + projected_income_args.resize(5 + strata_keys.size()); + projected_expenses_args.resize(8); +} + void BudgetMenu::update_projected_balance() { CountryInstance const* const country_ptr = PlayerSingleton::get_singleton()->get_player_country(); ERR_FAIL_NULL(country_ptr); CountryInstance const& country = *country_ptr; - fixed_point_t projected_balance = country.get_gold_income_untracked() - + administration_budget.get_balance() - + diplomatic_budget.get_balance() - + education_budget.get_balance() - + military_budget.get_balance() - + national_stockpile_budget.get_balance() - + social_budget.get_balance() - + tariff_budget.get_balance(); + fixed_point_t projected_balance = country.get_gold_income_untracked() + administration_budget.get_balance() + + diplomatic_budget.get_balance() + education_budget.get_balance() + military_budget.get_balance() + + national_stockpile_budget.get_balance() + social_budget.get_balance() + tariff_budget.get_balance(); for (StrataTaxBudget const& strata_tax_budget : tax_budgets) { projected_balance += strata_tax_budget.get_balance(); @@ -78,8 +67,7 @@ void BudgetMenu::update_projected_balance() { projected_balance_label.set_text( Utilities::format( - godot::String::utf8("§%s%s§!"), - Utilities::get_colour_and_sign(projected_balance), + godot::String::utf8("§%s%s§!"), Utilities::get_colour_and_sign(projected_balance), Utilities::cash_to_string_dp_dynamic(projected_balance) ) ); @@ -87,39 +75,33 @@ void BudgetMenu::update_projected_balance() { void BudgetMenu::update_projected_expenses() { static const godot::String projected_expenses_template = "%s\n--------------\n%s\n%s\n%s\n%s\n%s\n%s%s"; - const fixed_point_t projected_expenses = administration_budget.get_expenses() - + diplomatic_budget.get_expenses() - + education_budget.get_expenses() - + military_budget.get_expenses() - + national_stockpile_budget.get_expenses() - + social_budget.get_expenses() - + tariff_budget.get_expenses(); - //TODO: + import subsidies? - //TODO: + factory subsidies - //TODO: + interest + const fixed_point_t projected_expenses = administration_budget.get_expenses() + diplomatic_budget.get_expenses() + + education_budget.get_expenses() + military_budget.get_expenses() + national_stockpile_budget.get_expenses() + + social_budget.get_expenses() + tariff_budget.get_expenses(); + // TODO: + import subsidies? + // TODO: + factory subsidies + // TODO: + interest const fixed_point_t interest_expenses = 0; - projected_expenses_label.set_text( - Utilities::cash_to_string_dp_dynamic(projected_expenses) - ); + projected_expenses_label.set_text(Utilities::cash_to_string_dp_dynamic(projected_expenses)); - projected_expenses_args[0] = projected_expenses_label.tr("BUDGET_TOTAL_EXPENSE").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(projected_expenses), 3) - ); + projected_expenses_args[0] = projected_expenses_label.tr("BUDGET_TOTAL_EXPENSE") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp(static_cast(projected_expenses), 3) + ); projected_expenses_args[1] = education_budget.generate_expenses_summary_text(projected_expenses_label); projected_expenses_args[2] = administration_budget.generate_expenses_summary_text(projected_expenses_label); projected_expenses_args[3] = social_budget.generate_expenses_summary_text(projected_expenses_label); projected_expenses_args[4] = military_budget.generate_expenses_summary_text(projected_expenses_label); - projected_expenses_args[5] = projected_expenses_label.tr("BUDGET_INTEREST").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(interest_expenses), 1) - ); + projected_expenses_args[5] = projected_expenses_label.tr("BUDGET_INTEREST") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp(static_cast(interest_expenses), 1) + ); projected_expenses_args[6] = national_stockpile_budget.generate_expenses_summary_text(projected_expenses_label); projected_expenses_args[7] = diplomatic_budget.generate_expenses_summary_text(projected_expenses_label); - projected_expenses_label.set_tooltip_string( - projected_expenses_template % projected_expenses_args - ); + projected_expenses_label.set_tooltip_string(projected_expenses_template % projected_expenses_args); } void BudgetMenu::update_projected_expenses_and_balance() { @@ -141,34 +123,33 @@ void BudgetMenu::update_projected_income() { } projected_income_args[i++] = tariff_budget.generate_income_summary_text(projected_income_label); - const fixed_point_t stockpile_income = 0; //TODO stockpile sales + const fixed_point_t stockpile_income = 0; // TODO stockpile sales projected_income_excluding_tariffs += stockpile_income; - projected_income_args[i++] = projected_income_label.tr("BUDGET_EXPORTS").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(stockpile_income), 1) - ); + projected_income_args[i++] = + projected_income_label.tr("BUDGET_EXPORTS") + .replace( + Utilities::get_short_value_placeholder(), Utilities::float_to_string_dp(static_cast(stockpile_income), 1) + ); const fixed_point_t gold_income = country.get_gold_income_untracked(); projected_income_excluding_tariffs += gold_income; - projected_income_args[i++] = projected_income_label.tr("BUDGET_GOLD").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(gold_income), 1) - ); + projected_income_args[i++] = + projected_income_label.tr("BUDGET_GOLD") + .replace( + Utilities::get_short_value_placeholder(), Utilities::float_to_string_dp(static_cast(gold_income), 1) + ); projected_income_args[i++] = diplomatic_budget.generate_income_summary_text(projected_income_label); const fixed_point_t projected_income = projected_income_excluding_tariffs + tariff_budget.get_income(); - projected_income_args[0] = projected_income_label.tr("BUDGET_TOTAL_INCOME").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(projected_income), 3) - ); - projected_income_label.set_text( - Utilities::cash_to_string_dp_dynamic(projected_income_excluding_tariffs) - ); - projected_income_label.set_tooltip_string( - projected_income_template % projected_income_args - ); - - //TODO stockpile sold to construction projects + projected_income_args[0] = + projected_income_label.tr("BUDGET_TOTAL_INCOME") + .replace( + Utilities::get_short_value_placeholder(), Utilities::float_to_string_dp(static_cast(projected_income), 3) + ); + projected_income_label.set_text(Utilities::cash_to_string_dp_dynamic(projected_income_excluding_tariffs)); + projected_income_label.set_tooltip_string(projected_income_template % projected_income_args); + + // TODO stockpile sold to construction projects } void BudgetMenu::update_projected_income_and_balance() { @@ -199,7 +180,7 @@ void BudgetMenu::update() { ERR_FAIL_NULL(country_ptr); CountryInstance& country = *country_ptr; - //this will trigger a lot of signals we should ignore + // this will trigger a lot of signals we should ignore for (connection& c : connections) { c.block(); }; @@ -211,19 +192,15 @@ void BudgetMenu::update() { const fixed_point_t gold_income = country.get_gold_income_untracked(); gold_income_label.set_text( - Utilities::format_with_currency( - Utilities::float_to_string_dp(static_cast(gold_income), 1) - ) + Utilities::format_with_currency(Utilities::float_to_string_dp(static_cast(gold_income), 1)) ); gold_income_label.set_tooltip_string( gold_income_label.tr("BUDGET_GOLD_INCOME_DESC") - //TODO add separator & list all province names + income if gold_income > 0 + // TODO add separator & list all province names + income if gold_income > 0 ); const fixed_point_t cash_stockpile = country.get_cash_stockpile(); cash_stockpile_label.set_text( - Utilities::format_with_currency( - Utilities::float_to_string_suffixed(static_cast(cash_stockpile)) - ) + Utilities::format_with_currency(Utilities::float_to_string_suffixed(static_cast(cash_stockpile))) ); } @@ -233,8 +210,7 @@ godot::String BudgetMenu::generate_projected_income_template(const size_t tax_bu memory::string projected_income_template; projected_income_template.reserve( - projected_income_template_start.size() - + projected_income_template_dynamic_part.size() * (tax_budgets_size + 3) + projected_income_template_start.size() + projected_income_template_dynamic_part.size() * (tax_budgets_size + 3) ); projected_income_template.append(projected_income_template_start); @@ -245,4 +221,4 @@ godot::String BudgetMenu::generate_projected_income_template(const size_t tax_bu return projected_income_template.data(); } -#undef DO_FOR_ALL_COMPONENTS \ No newline at end of file +#undef DO_FOR_ALL_COMPONENTS diff --git a/extension/src/openvic-extension/components/budget/BudgetMenu.hpp b/extension/src/openvic-extension/components/budget/BudgetMenu.hpp index 2bb4b464..31f6da84 100644 --- a/extension/src/openvic-extension/components/budget/BudgetMenu.hpp +++ b/extension/src/openvic-extension/components/budget/BudgetMenu.hpp @@ -47,13 +47,12 @@ namespace OpenVic { void update_projected_income(); void update_projected_income_and_balance(); void update_all_projections(); + public: BudgetMenu( - GUINode const& parent, - forwardable_span strata_keys, - ModifierEffectCache const& modifier_effect_cache, + GUINode const& parent, forwardable_span strata_keys, ModifierEffectCache const& modifier_effect_cache, CountryDefines const& country_defines ); void update(); }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.cpp b/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.cpp index 6eca2cc2..02956f9c 100644 --- a/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.cpp +++ b/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.cpp @@ -7,15 +7,9 @@ using namespace OpenVic; -ConstructionStockpileBudget::ConstructionStockpileBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "MILITARY_SPENDINGS_PROJECTS", - EXPENSES, - "./country_budget/projects_stockpile_slider" - ), - BudgetExpenseComponent("MILITARY_SPENDINGS_PROJECTS") -{ +ConstructionStockpileBudget::ConstructionStockpileBudget(GUINode const& parent) + : SliderBudgetComponent(parent, "MILITARY_SPENDINGS_PROJECTS", EXPENSES, "./country_budget/projects_stockpile_slider"), + BudgetExpenseComponent("MILITARY_SPENDINGS_PROJECTS") { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); @@ -27,10 +21,9 @@ fixed_point_t ConstructionStockpileBudget::get_expenses() const { } fixed_point_t ConstructionStockpileBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value + CountryInstance& country, const fixed_point_t scaled_value // ) { - return scaled_value * 3; //TODO connect with sim once sim has this + return scaled_value * 3; // TODO connect with sim once sim has this } ReadOnlyClampedValue& ConstructionStockpileBudget::get_clamped_value(CountryInstance& country) const { @@ -39,4 +32,4 @@ ReadOnlyClampedValue& ConstructionStockpileBudget::get_clamped_value(CountryInst void ConstructionStockpileBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_national_stockpile_construction_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.hpp b/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.hpp index 643e7f5a..a5d50b30 100644 --- a/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.hpp +++ b/extension/src/openvic-extension/components/budget/ConstructionStockpileBudget.hpp @@ -6,10 +6,7 @@ namespace OpenVic { struct ConstructionStockpileBudget : public SliderBudgetComponent, public BudgetExpenseComponent { private: - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -17,4 +14,4 @@ namespace OpenVic { ConstructionStockpileBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/DiplomaticBudget.cpp b/extension/src/openvic-extension/components/budget/DiplomaticBudget.cpp index 60155a45..cecb6e3b 100644 --- a/extension/src/openvic-extension/components/budget/DiplomaticBudget.cpp +++ b/extension/src/openvic-extension/components/budget/DiplomaticBudget.cpp @@ -10,15 +10,11 @@ using namespace OpenVic; -DiplomaticBudget::DiplomaticBudget(GUINode const& parent): - BudgetIncomeComponent("WARINDEMNITIES_INCOME", decimal_places), - BudgetExpenseComponent("WARINDEMNITIES_EXPENSE", decimal_places), - balance_label{*parent.get_gui_label_from_nodepath("./country_budget/diplomatic_balance")} -{ - GUILabel::set_text_and_tooltip( - parent, "./country_budget/diplomatic_desc", - "DIPLOMATIC_BALANCE_DESC", "BUDGET_DIPL_DESC" - ); +DiplomaticBudget::DiplomaticBudget(GUINode const& parent) + : BudgetIncomeComponent("WARINDEMNITIES_INCOME", decimal_places), + BudgetExpenseComponent("WARINDEMNITIES_EXPENSE", decimal_places), + balance_label { *parent.get_gui_label_from_nodepath("./country_budget/diplomatic_balance") } { + GUILabel::set_text_and_tooltip(parent, "./country_budget/diplomatic_desc", "DIPLOMATIC_BALANCE_DESC", "BUDGET_DIPL_DESC"); } fixed_point_t DiplomaticBudget::get_income() const { @@ -28,31 +24,25 @@ fixed_point_t DiplomaticBudget::get_expenses() const { return reparations_expenses + war_subsidies_expenses; } -//no decimal values here just like Victoria 2 +// no decimal values here just like Victoria 2 #define TOOLTIP_TEXT_PART(value, localisation_key) \ - value > 0 \ - ? balance_label.tr(localisation_key).replace( \ - Utilities::get_short_value_placeholder(), \ - godot::String::num_int64(value.round()) \ - ) \ - : "" + value > 0 ? balance_label.tr(localisation_key) \ + .replace(Utilities::get_short_value_placeholder(), godot::String::num_int64(value.round())) \ + : "" void DiplomaticBudget::full_update(CountryInstance& country) { - //TODO get from sim once sim has it + // TODO get from sim once sim has it reparations_income = fixed_point_t::_0_50; war_subsidies_income = fixed_point_t::_1; reparations_expenses = fixed_point_t::_1; war_subsidies_expenses = fixed_point_t::_0_50; - const fixed_point_t diplomatic_balance = reparations_income - + war_subsidies_income - - reparations_expenses - - war_subsidies_expenses; + const fixed_point_t diplomatic_balance = + reparations_income + war_subsidies_income - reparations_expenses - war_subsidies_expenses; set_balance(diplomatic_balance); balance_label.set_text( Utilities::format( - godot::String::utf8("§%s%s§!"), - Utilities::get_colour_and_sign(diplomatic_balance), + godot::String::utf8("§%s%s§!"), Utilities::get_colour_and_sign(diplomatic_balance), Utilities::format_with_currency( Utilities::float_to_string_dp(static_cast(diplomatic_balance), decimal_places) ) @@ -61,7 +51,7 @@ void DiplomaticBudget::full_update(CountryInstance& country) { balance_label.set_tooltip_string( Utilities::format( - "%s%s%s%s", //no new lines in Victoria 2 here + "%s%s%s%s", // no new lines in Victoria 2 here TOOLTIP_TEXT_PART(war_subsidies_expenses, "WARSUBSIDIES_EXPENSE"), TOOLTIP_TEXT_PART(war_subsidies_income, "WARSUBSIDIES_INCOME"), TOOLTIP_TEXT_PART(reparations_expenses, expenses_summary_localisation_key), @@ -73,43 +63,41 @@ void DiplomaticBudget::full_update(CountryInstance& country) { #undef TOOLTIP_TEXT_PART godot::String DiplomaticBudget::generate_income_summary_text(godot::Object const& translation_object) const { - //war_subsidies_income are excluded here in Victoria 2 - return reparations_income > 0 - ? "\n"+translation_object.tr( - income_summary_localisation_key - ).replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(reparations_income), income_summary_decimal_places) - ) - : ""; + // war_subsidies_income are excluded here in Victoria 2 + return reparations_income > 0 ? "\n" + + translation_object.tr(income_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp(static_cast(reparations_income), income_summary_decimal_places) + ) + : ""; } godot::String DiplomaticBudget::generate_expenses_summary_text(godot::Object const& translation_object) const { - //war_subsidies_expenses are excluded here in Victoria 2 - return reparations_expenses > 0 - ? "\n"+translation_object.tr( - expenses_summary_localisation_key - ).replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(reparations_expenses), expenses_summary_decimal_places) - ) - : ""; + // war_subsidies_expenses are excluded here in Victoria 2 + return reparations_expenses > 0 ? "\n" + + translation_object.tr(expenses_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp(static_cast(reparations_expenses), expenses_summary_decimal_places) + ) + : ""; } godot::String DiplomaticBudget::generate_balance_summary_income_text(godot::Object const& translation_object) const { - return "\n"+translation_object.tr( - income_summary_localisation_key - ).replace( - Utilities::get_short_value_placeholder(), - "+" + Utilities::float_to_string_dp(static_cast(war_subsidies_income), income_summary_decimal_places) - ); + return "\n" + + translation_object.tr(income_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + "+" + Utilities::float_to_string_dp(static_cast(war_subsidies_income), income_summary_decimal_places) + ); } godot::String DiplomaticBudget::generate_balance_summary_expenses_text(godot::Object const& translation_object) const { - return "\n"+translation_object.tr( - expenses_summary_localisation_key - ).replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp(static_cast(war_subsidies_expenses), expenses_summary_decimal_places) - ); -} \ No newline at end of file + return "\n" + + translation_object.tr(expenses_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp(static_cast(war_subsidies_expenses), expenses_summary_decimal_places) + ); +} diff --git a/extension/src/openvic-extension/components/budget/DiplomaticBudget.hpp b/extension/src/openvic-extension/components/budget/DiplomaticBudget.hpp index bfc2a6b0..d3950571 100644 --- a/extension/src/openvic-extension/components/budget/DiplomaticBudget.hpp +++ b/extension/src/openvic-extension/components/budget/DiplomaticBudget.hpp @@ -3,17 +3,14 @@ #include #include "openvic-extension/components/budget/abstract/BudgetComponent.hpp" -#include "openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp" #include "openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp" +#include "openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp" namespace OpenVic { struct GUILabel; struct GUINode; - struct DiplomaticBudget : - public BudgetComponent, - public BudgetExpenseComponent, - public BudgetIncomeComponent { + struct DiplomaticBudget : public BudgetComponent, public BudgetExpenseComponent, public BudgetIncomeComponent { private: static const int32_t decimal_places = 1; @@ -22,6 +19,7 @@ namespace OpenVic { fixed_point_t reparations_expenses; fixed_point_t war_subsidies_income; fixed_point_t war_subsidies_expenses; + public: fixed_point_t get_income() const override; fixed_point_t get_expenses() const override; @@ -35,4 +33,4 @@ namespace OpenVic { godot::String generate_balance_summary_income_text(godot::Object const& translation_object) const; godot::String generate_balance_summary_expenses_text(godot::Object const& translation_object) const; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/EducationBudget.cpp b/extension/src/openvic-extension/components/budget/EducationBudget.cpp index 1d81a62e..cb04a65d 100644 --- a/extension/src/openvic-extension/components/budget/EducationBudget.cpp +++ b/extension/src/openvic-extension/components/budget/EducationBudget.cpp @@ -9,25 +9,17 @@ using namespace OpenVic; -EducationBudget::EducationBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "BUDGET_EXPENSE_SLIDER_EDUCATION", - EXPENSES, - "./country_budget/exp_0_slider", - "./country_budget/exp_val_0" - ), - BudgetExpenseComponent("BUDGET_EXPENSE_SLIDER_EDUCATION") -{ +EducationBudget::EducationBudget(GUINode const& parent) + : SliderBudgetComponent( + parent, "BUDGET_EXPENSE_SLIDER_EDUCATION", EXPENSES, "./country_budget/exp_0_slider", "./country_budget/exp_val_0" + ), + BudgetExpenseComponent("BUDGET_EXPENSE_SLIDER_EDUCATION") { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); slider.set_block_signals(false); - GUILabel::set_text_and_tooltip( - parent, "./country_budget/education_desc", - "EDUCATION","EDU_DESC" - ); + GUILabel::set_text_and_tooltip(parent, "./country_budget/education_desc", "EDUCATION", "EDU_DESC"); } fixed_point_t EducationBudget::get_expenses() const { @@ -38,23 +30,20 @@ bool EducationBudget::was_budget_cut(CountryInstance const& country) const { return country.get_was_education_budget_cut_yesterday(); } -fixed_point_t EducationBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value -) { +fixed_point_t EducationBudget::calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) { if (budget_label != nullptr) { budget_label->set_tooltip_string( Utilities::format( - "%s\n--------------\n%s%s", - budget_label->tr("DIST_EDUCATION"), - was_budget_cut(country) - ? budget_label->tr("EXPENSE_NO_AFFORD").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp_dynamic( - static_cast(country.get_actual_education_spending().load()) - ) - ) + "\n" - : "", + "%s\n--------------\n%s%s", budget_label->tr("DIST_EDUCATION"), + was_budget_cut(country) ? budget_label->tr("EXPENSE_NO_AFFORD") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp_dynamic( + static_cast(country.get_actual_education_spending().load()) + ) + ) + + "\n" + : "", budget_label->tr("EDU_DESC") ) ); @@ -69,4 +58,4 @@ ReadOnlyClampedValue& EducationBudget::get_clamped_value(CountryInstance& countr void EducationBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_education_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/EducationBudget.hpp b/extension/src/openvic-extension/components/budget/EducationBudget.hpp index 1837e1e8..992f7436 100644 --- a/extension/src/openvic-extension/components/budget/EducationBudget.hpp +++ b/extension/src/openvic-extension/components/budget/EducationBudget.hpp @@ -7,10 +7,7 @@ namespace OpenVic { struct EducationBudget : public SliderBudgetComponent, public BudgetExpenseComponent { private: bool was_budget_cut(CountryInstance const& country) const override; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -18,4 +15,4 @@ namespace OpenVic { EducationBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/MilitaryBudget.cpp b/extension/src/openvic-extension/components/budget/MilitaryBudget.cpp index 12b7402e..0f2b702e 100644 --- a/extension/src/openvic-extension/components/budget/MilitaryBudget.cpp +++ b/extension/src/openvic-extension/components/budget/MilitaryBudget.cpp @@ -9,25 +9,17 @@ using namespace OpenVic; -MilitaryBudget::MilitaryBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "BUDGET_SLIDER_MILITARY_SPENDING", - EXPENSES, - "./country_budget/exp_3_slider", - "./country_budget/exp_val_3" - ), - BudgetExpenseComponent("BUDGET_SLIDER_MILITARY_SPENDING") -{ +MilitaryBudget::MilitaryBudget(GUINode const& parent) + : SliderBudgetComponent( + parent, "BUDGET_SLIDER_MILITARY_SPENDING", EXPENSES, "./country_budget/exp_3_slider", "./country_budget/exp_val_3" + ), + BudgetExpenseComponent("BUDGET_SLIDER_MILITARY_SPENDING") { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); slider.set_block_signals(false); - GUILabel::set_text_and_tooltip( - parent, "./country_budget/mil_spend_desc", - "MILITARY_SPENDING","DEFENCE_DESC" - ); + GUILabel::set_text_and_tooltip(parent, "./country_budget/mil_spend_desc", "MILITARY_SPENDING", "DEFENCE_DESC"); } fixed_point_t MilitaryBudget::get_expenses() const { @@ -38,23 +30,20 @@ bool MilitaryBudget::was_budget_cut(CountryInstance const& country) const { return country.get_was_military_budget_cut_yesterday(); } -fixed_point_t MilitaryBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value -) { +fixed_point_t MilitaryBudget::calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) { if (budget_label != nullptr) { budget_label->set_tooltip_string( Utilities::format( - "%s\n--------------\n%s%s", - budget_label->tr("DIST_DEFENCE"), - was_budget_cut(country) - ? budget_label->tr("EXPENSE_NO_AFFORD").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp_dynamic( - static_cast(country.get_actual_military_spending().load()) - ) - ) + "\n" - : "", + "%s\n--------------\n%s%s", budget_label->tr("DIST_DEFENCE"), + was_budget_cut(country) ? budget_label->tr("EXPENSE_NO_AFFORD") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp_dynamic( + static_cast(country.get_actual_military_spending().load()) + ) + ) + + "\n" + : "", budget_label->tr("DEFENCE_DESC") ) ); @@ -69,4 +58,4 @@ ReadOnlyClampedValue& MilitaryBudget::get_clamped_value(CountryInstance& country void MilitaryBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_military_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/MilitaryBudget.hpp b/extension/src/openvic-extension/components/budget/MilitaryBudget.hpp index 20e127ab..e6f47ff9 100644 --- a/extension/src/openvic-extension/components/budget/MilitaryBudget.hpp +++ b/extension/src/openvic-extension/components/budget/MilitaryBudget.hpp @@ -7,10 +7,7 @@ namespace OpenVic { struct MilitaryBudget : public SliderBudgetComponent, public BudgetExpenseComponent { private: bool was_budget_cut(CountryInstance const& country) const override; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -18,4 +15,4 @@ namespace OpenVic { MilitaryBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/NationalStockpileBudget.cpp b/extension/src/openvic-extension/components/budget/NationalStockpileBudget.cpp index c371af81..f9293b8b 100644 --- a/extension/src/openvic-extension/components/budget/NationalStockpileBudget.cpp +++ b/extension/src/openvic-extension/components/budget/NationalStockpileBudget.cpp @@ -15,24 +15,19 @@ using namespace OpenVic; -NationalStockpileBudget::NationalStockpileBudget(GUINode const& parent): - BudgetExpenseComponent("BUDGET_IMPORTS"), - military_costs_label{*parent.get_gui_label_from_nodepath("./country_budget/mil_cost_val")}, - todays_actual_stockpile_spending_label{*parent.get_gui_label_from_nodepath("./country_budget/nat_stock_val")}, - overseas_costs_label{*parent.get_gui_label_from_nodepath("./country_budget/overseas_cost_val")}, - expenses_label{*parent.get_gui_label_from_nodepath("./country_budget/nat_stock_est")}, - army_stockpile_budget{parent}, - navy_stockpile_budget{parent}, - construction_stockpile_budget{parent} -{ +NationalStockpileBudget::NationalStockpileBudget(GUINode const& parent) + : BudgetExpenseComponent("BUDGET_IMPORTS"), + military_costs_label { *parent.get_gui_label_from_nodepath("./country_budget/mil_cost_val") }, + todays_actual_stockpile_spending_label { *parent.get_gui_label_from_nodepath("./country_budget/nat_stock_val") }, + overseas_costs_label { *parent.get_gui_label_from_nodepath("./country_budget/overseas_cost_val") }, + expenses_label { *parent.get_gui_label_from_nodepath("./country_budget/nat_stock_est") }, + army_stockpile_budget { parent }, navy_stockpile_budget { parent }, construction_stockpile_budget { parent } { connections[0] = army_stockpile_budget.balance_changed.connect(&NationalStockpileBudget::on_slider_value_changed, this); connections[1] = navy_stockpile_budget.balance_changed.connect(&NationalStockpileBudget::on_slider_value_changed, this); - connections[2] = construction_stockpile_budget.balance_changed.connect(&NationalStockpileBudget::on_slider_value_changed, this); - - GUILabel::set_text_and_tooltip( - parent, "./country_budget/nat_stock_desc", - "BUDGET_NATIONAL_STOCKPILE","NAT_STOCK_DESC" - ); + connections[2] = + construction_stockpile_budget.balance_changed.connect(&NationalStockpileBudget::on_slider_value_changed, this); + + GUILabel::set_text_and_tooltip(parent, "./country_budget/nat_stock_desc", "BUDGET_NATIONAL_STOCKPILE", "NAT_STOCK_DESC"); } fixed_point_t NationalStockpileBudget::get_expenses() const { @@ -45,7 +40,7 @@ void NationalStockpileBudget::on_slider_value_changed() { update_labels(*country_ptr); } -void NationalStockpileBudget::full_update(CountryInstance& country) {\ +void NationalStockpileBudget::full_update(CountryInstance& country) { for (connection& c : connections) { c.block(); }; @@ -60,36 +55,28 @@ void NationalStockpileBudget::full_update(CountryInstance& country) {\ } void NationalStockpileBudget::update_labels(CountryInstance& country) { - const fixed_point_t military_balance = army_stockpile_budget.get_balance() - + navy_stockpile_budget.get_balance(); - const fixed_point_t balance = military_balance - + construction_stockpile_budget.get_balance(); + const fixed_point_t military_balance = army_stockpile_budget.get_balance() + navy_stockpile_budget.get_balance(); + const fixed_point_t balance = military_balance + construction_stockpile_budget.get_balance(); - military_costs_label.set_text( - Utilities::cash_to_string_dp_dynamic(-military_balance) - ); + military_costs_label.set_text(Utilities::cash_to_string_dp_dynamic(-military_balance)); const fixed_point_t actual_stockpile_spending = country.get_actual_national_stockpile_spending(); - todays_actual_stockpile_spending_label.set_text( - Utilities::cash_to_string_dp_dynamic(actual_stockpile_spending) - ); + todays_actual_stockpile_spending_label.set_text(Utilities::cash_to_string_dp_dynamic(actual_stockpile_spending)); godot::String todays_actual_stockpile_spending_tooltip = todays_actual_stockpile_spending_label.tr("STOCKPILE_COST_ACTUAL"); if (actual_stockpile_spending > 0) { - todays_actual_stockpile_spending_tooltip += "\n"; //This is for a whiteline, not just a linebreak. Just like Victoria 2. + todays_actual_stockpile_spending_tooltip += "\n"; // This is for a whiteline, not just a linebreak. Just like + // Victoria 2. memory::vector> bought_goods {}; for (auto const& [good_instance, good_data] : country.get_goods_data()) { if (good_data.money_traded_yesterday < 0) { - bought_goods.push_back({&good_instance, &good_data}); + bought_goods.push_back({ &good_instance, &good_data }); } } - std::ranges::sort( - bought_goods, - [](auto const& lhs, auto const& rhs) { - return lhs.second->money_traded_yesterday < rhs.second->money_traded_yesterday; - } - ); + std::ranges::sort(bought_goods, [](auto const& lhs, auto const& rhs) { + return lhs.second->money_traded_yesterday < rhs.second->money_traded_yesterday; + }); for (auto const& [good_instance_ptr, good_data_ptr] : bought_goods) { GoodInstance const& good_instance = *good_instance_ptr; @@ -106,11 +93,9 @@ void NationalStockpileBudget::update_labels(CountryInstance& country) { todays_actual_stockpile_spending_label.set_tooltip_string(todays_actual_stockpile_spending_tooltip); overseas_costs_label.set_text( - Utilities::cash_to_string_dp_dynamic(0) //TODO - ); - expenses_label.set_text( - Utilities::cash_to_string_dp_dynamic(-balance) + Utilities::cash_to_string_dp_dynamic(0) // TODO ); + expenses_label.set_text(Utilities::cash_to_string_dp_dynamic(-balance)); set_balance(balance); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/NationalStockpileBudget.hpp b/extension/src/openvic-extension/components/budget/NationalStockpileBudget.hpp index 11cd3e51..ee53a367 100644 --- a/extension/src/openvic-extension/components/budget/NationalStockpileBudget.hpp +++ b/extension/src/openvic-extension/components/budget/NationalStockpileBudget.hpp @@ -1,9 +1,9 @@ #pragma once -#include "openvic-extension/components/budget/abstract/BudgetComponent.hpp" #include "openvic-extension/components/budget/ArmyStockpileBudget.hpp" #include "openvic-extension/components/budget/ConstructionStockpileBudget.hpp" #include "openvic-extension/components/budget/NavyStockpileBudget.hpp" +#include "openvic-extension/components/budget/abstract/BudgetComponent.hpp" namespace OpenVic { struct GUILabel; @@ -28,4 +28,4 @@ namespace OpenVic { fixed_point_t get_expenses() const override; void full_update(CountryInstance& country) override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/NavyStockpileBudget.cpp b/extension/src/openvic-extension/components/budget/NavyStockpileBudget.cpp index 1e63eebe..7f5429f9 100644 --- a/extension/src/openvic-extension/components/budget/NavyStockpileBudget.cpp +++ b/extension/src/openvic-extension/components/budget/NavyStockpileBudget.cpp @@ -7,15 +7,9 @@ using namespace OpenVic; -NavyStockpileBudget::NavyStockpileBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "MILITARY_SPENDINGS_NAVAL", - EXPENSES, - "./country_budget/naval_stockpile_slider" - ), - BudgetExpenseComponent("MILITARY_SPENDINGS_NAVAL") -{ +NavyStockpileBudget::NavyStockpileBudget(GUINode const& parent) + : SliderBudgetComponent(parent, "MILITARY_SPENDINGS_NAVAL", EXPENSES, "./country_budget/naval_stockpile_slider"), + BudgetExpenseComponent("MILITARY_SPENDINGS_NAVAL") { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); @@ -27,10 +21,9 @@ fixed_point_t NavyStockpileBudget::get_expenses() const { } fixed_point_t NavyStockpileBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value + CountryInstance& country, const fixed_point_t scaled_value // ) { - return scaled_value * 2; //TODO connect with sim once sim has this + return scaled_value * 2; // TODO connect with sim once sim has this } ReadOnlyClampedValue& NavyStockpileBudget::get_clamped_value(CountryInstance& country) const { @@ -39,4 +32,4 @@ ReadOnlyClampedValue& NavyStockpileBudget::get_clamped_value(CountryInstance& co void NavyStockpileBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_national_stockpile_navy_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/NavyStockpileBudget.hpp b/extension/src/openvic-extension/components/budget/NavyStockpileBudget.hpp index 1143f729..e64c21c6 100644 --- a/extension/src/openvic-extension/components/budget/NavyStockpileBudget.hpp +++ b/extension/src/openvic-extension/components/budget/NavyStockpileBudget.hpp @@ -6,10 +6,7 @@ namespace OpenVic { struct NavyStockpileBudget : public SliderBudgetComponent, public BudgetExpenseComponent { private: - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -17,4 +14,4 @@ namespace OpenVic { NavyStockpileBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/SocialBudget.cpp b/extension/src/openvic-extension/components/budget/SocialBudget.cpp index be5808c9..d9e80106 100644 --- a/extension/src/openvic-extension/components/budget/SocialBudget.cpp +++ b/extension/src/openvic-extension/components/budget/SocialBudget.cpp @@ -11,27 +11,21 @@ using namespace OpenVic; -SocialBudget::SocialBudget(GUINode const& parent): - SliderBudgetComponent( - parent, - "BUDGET_SLIDER_SOCIAL_SPENDING", - EXPENSES, - "./country_budget/exp_2_slider", - "./country_budget/exp_val_2" - ), - BudgetExpenseComponent("BUDGET_SLIDER_SOCIAL_SPENDING"), - pensions_label{*parent.get_gui_label_from_nodepath("./country_budget/exp_val_2")}, //TODO figure out how to get their path - unemployment_subsidies_label{*parent.get_gui_label_from_nodepath("./country_budget/exp_val_2")} -{ +SocialBudget::SocialBudget(GUINode const& parent) + : SliderBudgetComponent( + parent, "BUDGET_SLIDER_SOCIAL_SPENDING", EXPENSES, "./country_budget/exp_2_slider", "./country_budget/exp_val_2" + ), + BudgetExpenseComponent("BUDGET_SLIDER_SOCIAL_SPENDING"), + pensions_label { + *parent.get_gui_label_from_nodepath("./country_budget/exp_val_2") + }, // TODO figure out how to get their path + unemployment_subsidies_label { *parent.get_gui_label_from_nodepath("./country_budget/exp_val_2") } { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); slider.set_block_signals(false); - GUILabel::set_text_and_tooltip( - parent, "./country_budget/soc_stand_desc", - "SOCIAL_SPENDING","SOCIAL_DESC2" - ); + GUILabel::set_text_and_tooltip(parent, "./country_budget/soc_stand_desc", "SOCIAL_SPENDING", "SOCIAL_DESC2"); } fixed_point_t SocialBudget::get_expenses() const { @@ -42,37 +36,33 @@ bool SocialBudget::was_budget_cut(CountryInstance const& country) const { return country.get_was_social_budget_cut_yesterday(); } -fixed_point_t SocialBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value -) { +fixed_point_t SocialBudget::calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) { if (budget_label != nullptr) { budget_label->set_tooltip_string( Utilities::format( - "%s\n--------------\n%s%s", - budget_label->tr("DIST_SOCIAL"), - was_budget_cut(country) - ? budget_label->tr("EXPENSE_NO_AFFORD").replace( - Utilities::get_short_value_placeholder(), - Utilities::float_to_string_dp_dynamic( - static_cast(country.get_actual_pensions_spending().load() - + country.get_actual_unemployment_subsidies_spending().load()) - ) - ) + "\n" - : "", + "%s\n--------------\n%s%s", budget_label->tr("DIST_SOCIAL"), + was_budget_cut(country) ? budget_label->tr("EXPENSE_NO_AFFORD") + .replace( + Utilities::get_short_value_placeholder(), + Utilities::float_to_string_dp_dynamic( + static_cast( + country.get_actual_pensions_spending().load() + + country.get_actual_unemployment_subsidies_spending().load() + ) + ) + ) + + "\n" + : "", budget_label->tr("SOCIAL_DESC2") ) ); } const fixed_point_t pensions = scaled_value * country.get_projected_pensions_spending_unscaled_by_slider_untracked(); - pensions_label.set_text( - Utilities::cash_to_string_dp_dynamic(pensions) - ); - const fixed_point_t unemployment_subsidies = scaled_value * country.get_projected_unemployment_subsidies_spending_unscaled_by_slider_untracked(); - unemployment_subsidies_label.set_text( - Utilities::cash_to_string_dp_dynamic(unemployment_subsidies) - ); + pensions_label.set_text(Utilities::cash_to_string_dp_dynamic(pensions)); + const fixed_point_t unemployment_subsidies = + scaled_value * country.get_projected_unemployment_subsidies_spending_unscaled_by_slider_untracked(); + unemployment_subsidies_label.set_text(Utilities::cash_to_string_dp_dynamic(unemployment_subsidies)); return pensions + unemployment_subsidies; } @@ -82,4 +72,4 @@ ReadOnlyClampedValue& SocialBudget::get_clamped_value(CountryInstance& country) void SocialBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_social_spending_slider_value(scaled_value); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/SocialBudget.hpp b/extension/src/openvic-extension/components/budget/SocialBudget.hpp index ab5585a6..730cbafa 100644 --- a/extension/src/openvic-extension/components/budget/SocialBudget.hpp +++ b/extension/src/openvic-extension/components/budget/SocialBudget.hpp @@ -10,10 +10,7 @@ namespace OpenVic { GUILabel& unemployment_subsidies_label; bool was_budget_cut(CountryInstance const& country) const override; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; @@ -21,4 +18,4 @@ namespace OpenVic { SocialBudget(GUINode const& parent); fixed_point_t get_expenses() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/StrataTaxBudget.cpp b/extension/src/openvic-extension/components/budget/StrataTaxBudget.cpp index 3dd0b0ce..dab5e475 100644 --- a/extension/src/openvic-extension/components/budget/StrataTaxBudget.cpp +++ b/extension/src/openvic-extension/components/budget/StrataTaxBudget.cpp @@ -1,12 +1,13 @@ #include "StrataTaxBudget.hpp" #include -#include #include -#include "openvic-simulation/modifier/ModifierEffectCache.hpp" +#include #include +#include + #include "openvic-extension/classes/GUILabel.hpp" #include "openvic-extension/classes/GUINode.hpp" #include "openvic-extension/classes/GUIScrollbar.hpp" @@ -17,33 +18,24 @@ using namespace OpenVic; StrataTaxBudget::StrataTaxBudget( - GUINode const& parent, - Strata const& new_strata, - ModifierEffectCache const& new_modifier_effect_cache -): SliderBudgetComponent( - parent, - generate_slider_tooltip_localisation_key(new_strata), - BALANCE, - Utilities::format("./country_budget/tax_%d_slider", static_cast(type_safe::get(new_strata.index))), - Utilities::format("./country_budget/tax_%d_inc", static_cast(type_safe::get(new_strata.index))) - ), - BudgetIncomeComponent(generate_summary_localisation_key(new_strata), 1), - strata{new_strata}, - modifier_effect_cache{new_modifier_effect_cache} -{ + GUINode const& parent, Strata const& new_strata, ModifierEffectCache const& new_modifier_effect_cache +) + : SliderBudgetComponent( + parent, generate_slider_tooltip_localisation_key(new_strata), BALANCE, + Utilities::format("./country_budget/tax_%d_slider", static_cast(type_safe::get(new_strata.index))), + Utilities::format("./country_budget/tax_%d_inc", static_cast(type_safe::get(new_strata.index))) + ), + BudgetIncomeComponent(generate_summary_localisation_key(new_strata), 1), strata { new_strata }, + modifier_effect_cache { new_modifier_effect_cache } { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); slider.set_block_signals(false); GUILabel::set_text_and_tooltip( - parent, - Utilities::format("./country_budget/tax_%d_desc", static_cast(type_safe::get(new_strata.index))), + parent, Utilities::format("./country_budget/tax_%d_desc", static_cast(type_safe::get(new_strata.index))), generate_slider_tooltip_localisation_key(new_strata), - Utilities::format( - "TAX_%s_DESC", - convert_to(strata.get_identifier()).to_upper() - ) + Utilities::format("TAX_%s_DESC", convert_to(strata.get_identifier()).to_upper()) ); } @@ -51,13 +43,8 @@ fixed_point_t StrataTaxBudget::get_income() const { return std::max(fixed_point_t::_0, get_balance()); } -fixed_point_t StrataTaxBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value -) { - return scaled_value - * country.get_taxable_income_by_strata(strata) - * country.get_tax_efficiency_untracked(); +fixed_point_t StrataTaxBudget::calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) { + return scaled_value * country.get_taxable_income_by_strata(strata) * country.get_tax_efficiency_untracked(); } ReadOnlyClampedValue& StrataTaxBudget::get_clamped_value(CountryInstance& country) const { @@ -65,10 +52,7 @@ ReadOnlyClampedValue& StrataTaxBudget::get_clamped_value(CountryInstance& countr } void StrataTaxBudget::on_slider_value_changed(const fixed_point_t scaled_value) { - PlayerSingleton::get_singleton()->set_strata_tax_rate_slider_value( - strata, - scaled_value - ); + PlayerSingleton::get_singleton()->set_strata_tax_rate_slider_value(strata, scaled_value); } godot::StringName StrataTaxBudget::generate_slider_tooltip_localisation_key(Strata const& strata) { @@ -79,50 +63,49 @@ godot::StringName StrataTaxBudget::generate_summary_localisation_key(Strata cons return "TAXES_" + convert_to(strata.get_identifier()).to_upper(); } -void StrataTaxBudget::update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value -) { - //these use $VALUE$% +void StrataTaxBudget::update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value) { + // these use $VALUE$% static const godot::StringName tax_efficiency_localisation_key = "BUDGET_TAX_EFFICIENCY"; static const godot::StringName effective_tax_rate_localisation_key = "BUDGET_TAX_EFFECT"; - //this uses $VALUE$ only + // this uses $VALUE$ only static const godot::StringName tax_efficiency_from_tech_localisation_key = "BUDGET_TECH_TAX"; const godot::String localised_strata_tax = slider.tr(slider_tooltip_localisation_key); const fixed_point_t tax_efficiency = country.get_tax_efficiency_untracked(); - const godot::String tax_efficiency_text = slider.tr(tax_efficiency_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::float_to_string_dp(100 * static_cast(tax_efficiency), 2) - ); + const godot::String tax_efficiency_text = slider.tr(tax_efficiency_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::float_to_string_dp(100 * static_cast(tax_efficiency), 2) + ); const fixed_point_t tax_efficiency_from_tech = country.get_modifier_effect_value(*modifier_effect_cache.get_tax_eff()); - const godot::String tax_efficiency_from_tech_text = slider.tr(tax_efficiency_from_tech_localisation_key).replace( - Utilities::get_short_value_placeholder(), - Utilities::format( - "%s%%", - Utilities::float_to_string_dp( - static_cast(tax_efficiency_from_tech), //tax_efficiency_from_tech is already * 100 - 2 - ) - ) - ); + const godot::String tax_efficiency_from_tech_text = + slider.tr(tax_efficiency_from_tech_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::format( + "%s%%", + Utilities::float_to_string_dp( + static_cast(tax_efficiency_from_tech), // tax_efficiency_from_tech is already * 100 + 2 + ) + ) + ); const fixed_point_t effective_tax_rate = tax_efficiency * scaled_value; - const godot::String effective_tax_rate_text = slider.tr(effective_tax_rate_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::float_to_string_dp(100 * static_cast(effective_tax_rate), 2) - ); + const godot::String effective_tax_rate_text = + slider.tr(effective_tax_rate_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::float_to_string_dp(100 * static_cast(effective_tax_rate), 2) + ); const godot::String tooltip = Utilities::format( - godot::String::utf8("%s: §Y%s§!\n%s\n%s\n%s"), - localised_strata_tax, - Utilities::percentage_to_string_dp(scaled_value, 1), - tax_efficiency_text, - tax_efficiency_from_tech_text, + godot::String::utf8("%s: §Y%s§!\n%s\n%s\n%s"), localised_strata_tax, + Utilities::percentage_to_string_dp(scaled_value, 1), tax_efficiency_text, tax_efficiency_from_tech_text, effective_tax_rate_text ); slider.set_tooltip_string(tooltip); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/StrataTaxBudget.hpp b/extension/src/openvic-extension/components/budget/StrataTaxBudget.hpp index c53df96e..79e1de49 100644 --- a/extension/src/openvic-extension/components/budget/StrataTaxBudget.hpp +++ b/extension/src/openvic-extension/components/budget/StrataTaxBudget.hpp @@ -15,24 +15,14 @@ namespace OpenVic { Strata const& strata; ModifierEffectCache const& modifier_effect_cache; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; - void update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + void update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value) override; public: - StrataTaxBudget( - GUINode const& parent, - Strata const& new_strata, - ModifierEffectCache const& new_modifier_effect_cache - ); + StrataTaxBudget(GUINode const& parent, Strata const& new_strata, ModifierEffectCache const& new_modifier_effect_cache); StrataTaxBudget(StrataTaxBudget&&) = default; fixed_point_t get_income() const override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/TariffBudget.cpp b/extension/src/openvic-extension/components/budget/TariffBudget.cpp index 52c99889..3c1ebf7d 100644 --- a/extension/src/openvic-extension/components/budget/TariffBudget.cpp +++ b/extension/src/openvic-extension/components/budget/TariffBudget.cpp @@ -11,39 +11,26 @@ using namespace OpenVic; -TariffBudget::TariffBudget( - GUINode const& parent, - CountryDefines const& country_defines -) : - SliderBudgetComponent( - parent, - "TARIFFS_INCOME", - BALANCE, - "./country_budget/tariff_slider", - "./country_budget/tariff_val", - "./country_budget/tariffs_percent" - ), - BudgetExpenseComponent(""), //Victoria 2 doesn't display import subsidies - BudgetIncomeComponent("TARIFFS_INCOME", 1) -{ +TariffBudget::TariffBudget(GUINode const& parent, CountryDefines const& country_defines) + : SliderBudgetComponent( + parent, "TARIFFS_INCOME", BALANCE, "./country_budget/tariff_slider", "./country_budget/tariff_val", + "./country_budget/tariffs_percent" + ), + BudgetExpenseComponent(""), // Victoria 2 doesn't display import subsidies + BudgetIncomeComponent("TARIFFS_INCOME", 1) { slider.set_block_signals(true); slider.set_step_count(200); slider.set_scale(fixed_point_t::minus_one, 1, 100); slider.set_block_signals(false); - GUILabel::set_text_and_tooltip( - parent, "./country_budget/tariffs", - "BUDGET_TARIFFS", "TARIFFS_DESC" - ); + GUILabel::set_text_and_tooltip(parent, "./country_budget/tariffs", "BUDGET_TARIFFS", "TARIFFS_DESC"); slider_tooltip_args.resize(4); - slider_tooltip_args[2] = parent.tr("BASE_TARIFF_EFFICIENCY").replace( - Utilities::get_percentage_value_placeholder(), - //not percentage_to_string_dp as localisation text contains the % - Utilities::fixed_point_to_string_dp( - 100 * country_defines.get_base_tariff_efficiency(), - 1 - ) - ); + slider_tooltip_args[2] = parent.tr("BASE_TARIFF_EFFICIENCY") + .replace( + Utilities::get_percentage_value_placeholder(), + // not percentage_to_string_dp as localisation text contains the % + Utilities::fixed_point_to_string_dp(100 * country_defines.get_base_tariff_efficiency(), 1) + ); } fixed_point_t TariffBudget::get_expenses() const { @@ -58,13 +45,8 @@ bool TariffBudget::was_budget_cut(CountryInstance const& country) const { return country.get_was_import_subsidies_budget_cut_yesterday(); } -fixed_point_t TariffBudget::calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value -) { - return scaled_value - * country.get_yesterdays_import_value_untracked() - * country.tariff_efficiency.get_untracked(); +fixed_point_t TariffBudget::calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) { + return scaled_value * country.get_yesterdays_import_value_untracked() * country.tariff_efficiency.get_untracked(); } ReadOnlyClampedValue& TariffBudget::get_clamped_value(CountryInstance& country) const { @@ -75,42 +57,34 @@ void TariffBudget::on_slider_value_changed(const fixed_point_t scaled_value) { PlayerSingleton::get_singleton()->set_tariff_rate_slider_value(scaled_value); } -void TariffBudget::update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value -) { +void TariffBudget::update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value) { static const godot::StringName tooltip_template = "%s\n%s\n--------------\n%s\n%s"; static const godot::StringName green = "G"; static const godot::StringName red = "R"; - //Yes Victoria 2 overrides the colour specified in localisation... - godot::StringName const& prefix = scaled_value < 0 - ? red - : green; + // Yes Victoria 2 overrides the colour specified in localisation... + godot::StringName const& prefix = scaled_value < 0 ? red : green; - slider_tooltip_args[0] = slider.tr(slider_tooltip_localisation_key).replace( - "Y"+Utilities::get_short_value_placeholder(), - prefix+Utilities::percentage_to_string_dp( - scaled_value, - 1 - ) - ); - - slider_tooltip_args[1] = slider.tr("BUDGET_TARIFFS_MODIFIED").replace( - "Y"+Utilities::get_percentage_value_placeholder(), - //not percentage_to_string_dp as localisation text contains the % - prefix+Utilities::fixed_point_to_string_dp( - 100 * scaled_value * country.tariff_efficiency.get_untracked(), - 1 - ) - ); + slider_tooltip_args[0] = + slider.tr(slider_tooltip_localisation_key) + .replace( + "Y" + Utilities::get_short_value_placeholder(), prefix + Utilities::percentage_to_string_dp(scaled_value, 1) + ); - slider_tooltip_args[3] = slider.tr("BUDGET_ADMIN_EFFICIENCY").replace( - Utilities::get_percentage_value_placeholder(), - //not percentage_to_string_dp as localisation text contains the % - Utilities::fixed_point_to_string_dp( - 100 * country.get_administrative_efficiency_from_administrators_untracked(), - 1 - ) - ); + slider_tooltip_args[1] = + slider.tr("BUDGET_TARIFFS_MODIFIED") + .replace( + "Y" + Utilities::get_percentage_value_placeholder(), + // not percentage_to_string_dp as localisation text contains the % + prefix + Utilities::fixed_point_to_string_dp(100 * scaled_value * country.tariff_efficiency.get_untracked(), 1) + ); + + slider_tooltip_args[3] = slider.tr("BUDGET_ADMIN_EFFICIENCY") + .replace( + Utilities::get_percentage_value_placeholder(), + // not percentage_to_string_dp as localisation text contains the % + Utilities::fixed_point_to_string_dp( + 100 * country.get_administrative_efficiency_from_administrators_untracked(), 1 + ) + ); slider.set_tooltip_string(tooltip_template % slider_tooltip_args); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/TariffBudget.hpp b/extension/src/openvic-extension/components/budget/TariffBudget.hpp index 1d31f87f..ac94e5e2 100644 --- a/extension/src/openvic-extension/components/budget/TariffBudget.hpp +++ b/extension/src/openvic-extension/components/budget/TariffBudget.hpp @@ -2,38 +2,26 @@ #include -#include "openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp" #include "openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp" +#include "openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp" #include "openvic-extension/components/budget/abstract/SliderBudgetComponent.hpp" namespace OpenVic { struct CountryDefines; - struct TariffBudget: - public SliderBudgetComponent, - public BudgetIncomeComponent, - public BudgetExpenseComponent { + struct TariffBudget : public SliderBudgetComponent, public BudgetIncomeComponent, public BudgetExpenseComponent { private: godot::Array slider_tooltip_args; bool was_budget_cut(CountryInstance const& country) const override; - fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + fixed_point_t calculate_budget_and_update_custom(CountryInstance& country, const fixed_point_t scaled_value) override; ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const override; void on_slider_value_changed(const fixed_point_t scaled_value) override; public: - TariffBudget( - GUINode const& parent, - CountryDefines const& country_defines - ); + TariffBudget(GUINode const& parent, CountryDefines const& country_defines); fixed_point_t get_expenses() const override; fixed_point_t get_income() const override; - void update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value - ) override; + void update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value) override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.cpp b/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.cpp index 532b4b20..636b4572 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.cpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.cpp @@ -7,10 +7,10 @@ fixed_point_t BudgetComponent::get_balance() const { } void BudgetComponent::set_balance(const fixed_point_t new_balance) { - if (balance == new_balance) {; + if (balance == new_balance) { return; } balance = new_balance; balance_changed(); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.hpp b/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.hpp index 8e7b7a69..1b21af98 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.hpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetComponent.hpp @@ -1,7 +1,7 @@ #pragma once -#include #include +#include namespace OpenVic { struct CountryInstance; @@ -18,4 +18,4 @@ namespace OpenVic { fixed_point_t get_balance() const; virtual void full_update(CountryInstance& country) = 0; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.cpp b/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.cpp index d39fc487..05d37757 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.cpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.cpp @@ -5,28 +5,24 @@ using namespace OpenVic; BudgetExpenseComponent::BudgetExpenseComponent( - godot::StringName&& new_expenses_summary_localisation_key, - const int32_t new_expenses_summary_decimal_places -) : expenses_summary_localisation_key{new_expenses_summary_localisation_key}, - expenses_summary_decimal_places{new_expenses_summary_decimal_places} {} + godot::StringName&& new_expenses_summary_localisation_key, const int32_t new_expenses_summary_decimal_places +) + : expenses_summary_localisation_key { new_expenses_summary_localisation_key }, + expenses_summary_decimal_places { new_expenses_summary_decimal_places } {} -godot::String BudgetExpenseComponent::generate_expenses_summary_text( - godot::Object const& translation_object -) const { +godot::String BudgetExpenseComponent::generate_expenses_summary_text(godot::Object const& translation_object) const { const float expenses = static_cast(get_expenses()); - return translation_object.tr(expenses_summary_localisation_key).replace( - Utilities::get_short_value_placeholder(), - expenses_summary_decimal_places < 0 - ? Utilities::float_to_string_dp_dynamic(expenses) - : Utilities::float_to_string_dp(expenses, expenses_summary_decimal_places) - ); + return translation_object.tr(expenses_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + expenses_summary_decimal_places < 0 ? Utilities::float_to_string_dp_dynamic(expenses) + : Utilities::float_to_string_dp(expenses, expenses_summary_decimal_places) + ); } godot::String BudgetExpenseComponent::generate_balance_expenses_summary_text(godot::Object const& translation_object) const { static const godot::StringName red_minus = "R-"; - const float expenses = static_cast(get_expenses());//TODO use yesterdays value - return translation_object.tr(expenses_summary_localisation_key).replace( - "Y$VAL$", - red_minus + Utilities::float_to_string_dp(expenses, expenses_summary_decimal_places) - ); -} \ No newline at end of file + const float expenses = static_cast(get_expenses()); // TODO use yesterdays value + return translation_object.tr(expenses_summary_localisation_key) + .replace("Y$VAL$", red_minus + Utilities::float_to_string_dp(expenses, expenses_summary_decimal_places)); +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp b/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp index 18dab83d..93ff1950 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetExpenseComponent.hpp @@ -15,14 +15,14 @@ namespace OpenVic { protected: const godot::StringName expenses_summary_localisation_key; const int32_t expenses_summary_decimal_places; - + BudgetExpenseComponent( - godot::StringName&& new_expenses_summary_localisation_key, - const int32_t new_expenses_summary_decimal_places = -1 + godot::StringName&& new_expenses_summary_localisation_key, const int32_t new_expenses_summary_decimal_places = -1 ); + public: virtual fixed_point_t get_expenses() const = 0; virtual godot::String generate_expenses_summary_text(godot::Object const& translation_object) const; virtual godot::String generate_balance_expenses_summary_text(godot::Object const& translation_object) const; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.cpp b/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.cpp index dbcac5f8..45fe0d76 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.cpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.cpp @@ -5,28 +5,24 @@ using namespace OpenVic; BudgetIncomeComponent::BudgetIncomeComponent( - godot::StringName&& new_income_summary_localisation_key, - const int32_t new_income_summary_decimal_places -) : income_summary_localisation_key{new_income_summary_localisation_key}, - income_summary_decimal_places{new_income_summary_decimal_places} {} + godot::StringName&& new_income_summary_localisation_key, const int32_t new_income_summary_decimal_places +) + : income_summary_localisation_key { new_income_summary_localisation_key }, + income_summary_decimal_places { new_income_summary_decimal_places } {} -godot::String BudgetIncomeComponent::generate_income_summary_text( - godot::Object const& translation_object -) const { +godot::String BudgetIncomeComponent::generate_income_summary_text(godot::Object const& translation_object) const { const float income = static_cast(get_income()); - return translation_object.tr(income_summary_localisation_key).replace( - Utilities::get_short_value_placeholder(), - income_summary_decimal_places < 0 - ? Utilities::float_to_string_dp_dynamic(income) - : Utilities::float_to_string_dp(income, income_summary_decimal_places) - ); + return translation_object.tr(income_summary_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + income_summary_decimal_places < 0 ? Utilities::float_to_string_dp_dynamic(income) + : Utilities::float_to_string_dp(income, income_summary_decimal_places) + ); } godot::String BudgetIncomeComponent::generate_balance_income_summary_text(godot::Object const& translation_object) const { static const godot::StringName green_plus = "G+"; - const float income = static_cast(get_income()); //TODO use yesterdays value - return translation_object.tr(income_summary_localisation_key).replace( - "Y$VAL$", - green_plus + Utilities::float_to_string_dp(income, income_summary_decimal_places) - ); -} \ No newline at end of file + const float income = static_cast(get_income()); // TODO use yesterdays value + return translation_object.tr(income_summary_localisation_key) + .replace("Y$VAL$", green_plus + Utilities::float_to_string_dp(income, income_summary_decimal_places)); +} diff --git a/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp b/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp index 9f4bd422..d3b4fa52 100644 --- a/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp +++ b/extension/src/openvic-extension/components/budget/abstract/BudgetIncomeComponent.hpp @@ -15,14 +15,14 @@ namespace OpenVic { protected: const godot::StringName income_summary_localisation_key; int32_t income_summary_decimal_places; - + BudgetIncomeComponent( - godot::StringName&& new_income_summary_localisation_key, - const int32_t new_income_summary_decimal_places = -1 + godot::StringName&& new_income_summary_localisation_key, const int32_t new_income_summary_decimal_places = -1 ); + public: virtual fixed_point_t get_income() const = 0; virtual godot::String generate_income_summary_text(godot::Object const& translation_object) const; virtual godot::String generate_balance_income_summary_text(godot::Object const& translation_object) const; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.cpp b/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.cpp index 8c0d1038..4a24878e 100644 --- a/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.cpp +++ b/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.cpp @@ -13,26 +13,13 @@ using namespace OpenVic; SliderBudgetComponent::SliderBudgetComponent( - GUINode const& parent, - godot::String&& new_slider_tooltip_localisation_key, - const BudgetType new_budget_type, - godot::NodePath const& slider_path, - godot::NodePath const& budget_label_path, - godot::NodePath const& percent_label_path -) : budget_type{new_budget_type}, - slider_tooltip_localisation_key{std::move(new_slider_tooltip_localisation_key)}, - budget_label{ - budget_label_path.is_empty() - ? nullptr - : parent.get_gui_label_from_nodepath(budget_label_path) - }, - percent_label{ - percent_label_path.is_empty() - ? nullptr - : parent.get_gui_label_from_nodepath(percent_label_path) - }, - slider{*parent.get_gui_scrollbar_from_nodepath(slider_path)} -{ + GUINode const& parent, godot::String&& new_slider_tooltip_localisation_key, const BudgetType new_budget_type, + godot::NodePath const& slider_path, godot::NodePath const& budget_label_path, godot::NodePath const& percent_label_path +) + : budget_type { new_budget_type }, slider_tooltip_localisation_key { std::move(new_slider_tooltip_localisation_key) }, + budget_label { budget_label_path.is_empty() ? nullptr : parent.get_gui_label_from_nodepath(budget_label_path) }, + percent_label { percent_label_path.is_empty() ? nullptr : parent.get_gui_label_from_nodepath(percent_label_path) }, + slider { *parent.get_gui_scrollbar_from_nodepath(slider_path) } { slider.set_block_signals(true); slider.set_step_count(100); slider.set_scale(0, 1, 100); @@ -62,50 +49,28 @@ void SliderBudgetComponent::update_labels(CountryInstance& country, const fixed_ if (budget_label != nullptr) { const godot::String budget_text = Utilities::cash_to_string_dp_dynamic(budget); budget_label->set_text( - was_budget_cut(country) - ? Utilities::format(godot::String::utf8("§R%s§W"), budget_text) - : budget_text + was_budget_cut(country) ? Utilities::format(godot::String::utf8("§R%s§W"), budget_text) : budget_text ); }; if (percent_label != nullptr) { - percent_label->set_text( - Utilities::percentage_to_string_dp(scaled_value, 1) - ); + percent_label->set_text(Utilities::percentage_to_string_dp(scaled_value, 1)); } update_slider_tooltip(country, scaled_value); - const fixed_point_t balance = budget_type == EXPENSES - ? -budget - : budget; + const fixed_point_t balance = budget_type == EXPENSES ? -budget : budget; set_balance(balance); } -void SliderBudgetComponent::update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value -) { +void SliderBudgetComponent::update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value) { godot::String tooltip; - const godot::String percentage_text = Utilities::float_to_string_dp( - static_cast(100 * scaled_value), - 1 - ); + const godot::String percentage_text = Utilities::float_to_string_dp(static_cast(100 * scaled_value), 1); const godot::String localised = slider.tr(slider_tooltip_localisation_key); if (localised.contains(Utilities::get_short_value_placeholder())) { - tooltip = Utilities::format( - "%s%%", - localised.replace( - Utilities::get_short_value_placeholder(), - percentage_text - ) - ); + tooltip = Utilities::format("%s%%", localised.replace(Utilities::get_short_value_placeholder(), percentage_text)); } else { - tooltip = Utilities::format( - "%s%s%%", - localised, - percentage_text - ); + tooltip = Utilities::format("%s%s%%", localised, percentage_text); } slider.set_tooltip_string(tooltip); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.hpp b/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.hpp index d9c3646d..6c1f31af 100644 --- a/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.hpp +++ b/extension/src/openvic-extension/components/budget/abstract/SliderBudgetComponent.hpp @@ -12,29 +12,24 @@ namespace OpenVic { struct GUIScrollbar; struct ReadOnlyClampedValue; - enum BudgetType { - BALANCE, - EXPENSES - }; + enum BudgetType { BALANCE, EXPENSES }; struct SliderBudgetComponent : public BudgetComponent { private: - //multiplies balance by -1 for balance_label + // multiplies balance by -1 for balance_label const BudgetType budget_type; GUILabel* const percent_label; void _on_slider_value_changed(); void update_labels(CountryInstance& country, const fixed_point_t scaled_value); + protected: const godot::String slider_tooltip_localisation_key; GUIScrollbar& slider; GUILabel* const budget_label; SliderBudgetComponent( - GUINode const& parent, - godot::String&& new_slider_tooltip_localisation_key, - const BudgetType new_budget_type, - godot::NodePath const& slider_path, - godot::NodePath const& budget_label_path = {}, + GUINode const& parent, godot::String&& new_slider_tooltip_localisation_key, const BudgetType new_budget_type, + godot::NodePath const& slider_path, godot::NodePath const& budget_label_path = {}, godot::NodePath const& percent_label_path = {} ); @@ -42,17 +37,13 @@ namespace OpenVic { return false; } virtual fixed_point_t calculate_budget_and_update_custom( - CountryInstance& country, - const fixed_point_t scaled_value + CountryInstance& country, const fixed_point_t scaled_value // ) = 0; virtual ReadOnlyClampedValue& get_clamped_value(CountryInstance& country) const = 0; virtual void on_slider_value_changed(const fixed_point_t scaled_value) = 0; - virtual void update_slider_tooltip( - CountryInstance& country, - const fixed_point_t scaled_value - ); + virtual void update_slider_tooltip(CountryInstance& country, const fixed_point_t scaled_value); public: void full_update(CountryInstance& country) override; }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/overview/BudgetOverview.cpp b/extension/src/openvic-extension/components/overview/BudgetOverview.cpp index 53191245..0957bbf2 100644 --- a/extension/src/openvic-extension/components/overview/BudgetOverview.cpp +++ b/extension/src/openvic-extension/components/overview/BudgetOverview.cpp @@ -11,10 +11,9 @@ using namespace OpenVic; -BudgetOverview::BudgetOverview(GUINode const& parent): -funds_label{*parent.get_gui_label_from_nodepath("./topbar/budget_funds")}, -history_chart{*parent.get_gui_line_chart_from_nodepath("./topbar/budget_linechart")} -{ +BudgetOverview::BudgetOverview(GUINode const& parent) + : funds_label { *parent.get_gui_label_from_nodepath("./topbar/budget_funds") }, + history_chart { *parent.get_gui_line_chart_from_nodepath("./topbar/budget_linechart") } { godot::Control* node = parent.get_node("./topbar/topbarbutton_budget"); funds_label.reparent(node); history_chart.reparent(node); @@ -58,36 +57,37 @@ void BudgetOverview::update() { funds_label.set_text( Utilities::format( - godot::String::utf8("§Y%s§! (§%s%s§!)"), - Utilities::cash_to_string_dp_dynamic(cash), - Utilities::get_colour_and_sign(last_balance), - Utilities::cash_to_string_dp_dynamic(last_balance) + godot::String::utf8("§Y%s§! (§%s%s§!)"), Utilities::cash_to_string_dp_dynamic(cash), + Utilities::get_colour_and_sign(last_balance), Utilities::cash_to_string_dp_dynamic(last_balance) ) ); funds_label.set_tooltip_string( funds_label.tr("TOPBAR_FUNDS") - .replace("$YESTERDAY$", Utilities::format( - godot::String::utf8("§%s%s§!"), - Utilities::get_colour_and_sign(last_balance), + .replace( + "$YESTERDAY$", + Utilities::format( + godot::String::utf8("§%s%s§!"), Utilities::get_colour_and_sign(last_balance), Utilities::cash_to_string_dp_dynamic(last_balance) - )) - .replace("$CASH$", Utilities::format( - godot::String::utf8("§Y%s§!"), - Utilities::cash_to_string_dp_dynamic(cash) - )) + ) + ) + .replace("$CASH$", Utilities::format(godot::String::utf8("§Y%s§!"), Utilities::cash_to_string_dp_dynamic(cash))) ); history_chart.set_tooltip_string( history_chart.tr("TOPBAR_HISTORICAL_INCOME") .replace("$DAYS$", godot::String::num_int64(balance_history.size())) - .replace("$MAX$", Utilities::format( - godot::String::utf8("§%s%s§!"), - Utilities::get_colour_and_sign(maximum_balance), - Utilities::cash_to_string_dp_dynamic(maximum_balance) - )) - .replace("$MIN$", Utilities::format( - godot::String::utf8("§%s%s§!"), - Utilities::get_colour_and_sign(minimum_balance), - Utilities::cash_to_string_dp_dynamic(minimum_balance) - )) + .replace( + "$MAX$", + Utilities::format( + godot::String::utf8("§%s%s§!"), Utilities::get_colour_and_sign(maximum_balance), + Utilities::cash_to_string_dp_dynamic(maximum_balance) + ) + ) + .replace( + "$MIN$", + Utilities::format( + godot::String::utf8("§%s%s§!"), Utilities::get_colour_and_sign(minimum_balance), + Utilities::cash_to_string_dp_dynamic(minimum_balance) + ) + ) ); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/overview/BudgetOverview.hpp b/extension/src/openvic-extension/components/overview/BudgetOverview.hpp index 5f83adce..1827974c 100644 --- a/extension/src/openvic-extension/components/overview/BudgetOverview.hpp +++ b/extension/src/openvic-extension/components/overview/BudgetOverview.hpp @@ -9,8 +9,9 @@ namespace OpenVic { private: GUILabel& funds_label; GUILineChart& history_chart; + public: BudgetOverview(GUINode const& parent); void update(); }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/overview/ScoreOverview.cpp b/extension/src/openvic-extension/components/overview/ScoreOverview.cpp index f358c571..2283b4ef 100644 --- a/extension/src/openvic-extension/components/overview/ScoreOverview.cpp +++ b/extension/src/openvic-extension/components/overview/ScoreOverview.cpp @@ -4,8 +4,8 @@ #include -#include #include +#include #include #include @@ -18,19 +18,18 @@ using namespace OpenVic; -ScoreOverview::ScoreOverview(GUINode const& parent) : - flag_button{*parent.get_gui_masked_flag_button_from_nodepath("./topbar/player_flag")}, - flag_icon{*parent.get_gui_icon_from_nodepath("./topbar/topbar_flag_overlay")}, - name_label{*parent.get_gui_label_from_nodepath("./topbar/CountryName")}, - rank_label{*parent.get_gui_label_from_nodepath("./topbar/nation_totalrank")}, - prestige_label{*parent.get_gui_label_from_nodepath("./topbar/country_prestige")}, - prestige_rank_label{*parent.get_gui_label_from_nodepath("./topbar/selected_prestige_rank")}, - industrial_score_label{*parent.get_gui_label_from_nodepath("./topbar/country_economic")}, - industrial_rank_label{*parent.get_gui_label_from_nodepath("./topbar/selected_industry_rank")}, - military_score_label{*parent.get_gui_label_from_nodepath("./topbar/country_military")}, - military_rank_label{*parent.get_gui_label_from_nodepath("./topbar/selected_military_rank")}, - colonial_power_label{*parent.get_gui_label_from_nodepath("./topbar/country_colonial_power")} -{} +ScoreOverview::ScoreOverview(GUINode const& parent) + : flag_button { *parent.get_gui_masked_flag_button_from_nodepath("./topbar/player_flag") }, + flag_icon { *parent.get_gui_icon_from_nodepath("./topbar/topbar_flag_overlay") }, + name_label { *parent.get_gui_label_from_nodepath("./topbar/CountryName") }, + rank_label { *parent.get_gui_label_from_nodepath("./topbar/nation_totalrank") }, + prestige_label { *parent.get_gui_label_from_nodepath("./topbar/country_prestige") }, + prestige_rank_label { *parent.get_gui_label_from_nodepath("./topbar/selected_prestige_rank") }, + industrial_score_label { *parent.get_gui_label_from_nodepath("./topbar/country_economic") }, + industrial_rank_label { *parent.get_gui_label_from_nodepath("./topbar/selected_industry_rank") }, + military_score_label { *parent.get_gui_label_from_nodepath("./topbar/country_military") }, + military_rank_label { *parent.get_gui_label_from_nodepath("./topbar/selected_military_rank") }, + colonial_power_label { *parent.get_gui_label_from_nodepath("./topbar/country_colonial_power") } {} void ScoreOverview::update() { disconnect_all(); @@ -49,39 +48,38 @@ void ScoreOverview::update() { uint8_t status_icon_index; godot::String country_status_translation_key; switch (country_status) { - case CountryInstance::country_status_t::COUNTRY_STATUS_GREAT_POWER: - country_status_translation_key="DIPLOMACY_GREATNATION_STATUS"; - status_icon_index = 1; - break; - case CountryInstance::country_status_t::COUNTRY_STATUS_SECONDARY_POWER: - country_status_translation_key="DIPLOMACY_COLONIALNATION_STATUS"; - status_icon_index = 2; - break; - case CountryInstance::country_status_t::COUNTRY_STATUS_CIVILISED: - country_status_translation_key="DIPLOMACY_CIVILIZEDNATION_STATUS"; - status_icon_index = 3; - break; - case CountryInstance::country_status_t::COUNTRY_STATUS_PARTIALLY_CIVILISED: - country_status_translation_key="DIPLOMACY_ALMOST_WESTERN_NATION_STATUS"; - status_icon_index = 4; - break; - case CountryInstance::country_status_t::COUNTRY_STATUS_UNCIVILISED: - country_status_translation_key="DIPLOMACY_UNCIVILIZEDNATION_STATUS"; - status_icon_index = 4; - break; - case CountryInstance::country_status_t::COUNTRY_STATUS_PRIMITIVE: - country_status_translation_key="DIPLOMACY_PRIMITIVENATION_STATUS"; - status_icon_index = 4; - break; + case CountryInstance::country_status_t::COUNTRY_STATUS_GREAT_POWER: + country_status_translation_key = "DIPLOMACY_GREATNATION_STATUS"; + status_icon_index = 1; + break; + case CountryInstance::country_status_t::COUNTRY_STATUS_SECONDARY_POWER: + country_status_translation_key = "DIPLOMACY_COLONIALNATION_STATUS"; + status_icon_index = 2; + break; + case CountryInstance::country_status_t::COUNTRY_STATUS_CIVILISED: + country_status_translation_key = "DIPLOMACY_CIVILIZEDNATION_STATUS"; + status_icon_index = 3; + break; + case CountryInstance::country_status_t::COUNTRY_STATUS_PARTIALLY_CIVILISED: + country_status_translation_key = "DIPLOMACY_ALMOST_WESTERN_NATION_STATUS"; + status_icon_index = 4; + break; + case CountryInstance::country_status_t::COUNTRY_STATUS_UNCIVILISED: + country_status_translation_key = "DIPLOMACY_UNCIVILIZEDNATION_STATUS"; + status_icon_index = 4; + break; + case CountryInstance::country_status_t::COUNTRY_STATUS_PRIMITIVE: + country_status_translation_key = "DIPLOMACY_PRIMITIVENATION_STATUS"; + status_icon_index = 4; + break; } const godot::String country_name = Utilities::get_country_name(name_label, country); const godot::String country_name_rank_tooltip = Utilities::format( "%s%s%s", - flag_button.tr("PLAYER_COUNTRY_TOPBAR_RANK") + flag_button.tr("PLAYER_COUNTRY_TOPBAR_RANK") .replace("NAME", country_name) .replace("RANK", flag_button.tr(country_status_translation_key)), - MenuSingleton::get_tooltip_separator(), - flag_button.tr("RANK_TOTAL_D") + MenuSingleton::get_tooltip_separator(), flag_button.tr("RANK_TOTAL_D") ); flag_button.set_flag_country(country_ptr); @@ -95,120 +93,95 @@ void ScoreOverview::update() { const godot::String prestige_tooltip = generate_prestige_tooltip(country); prestige_rank_label.set_tooltip_string(prestige_tooltip); prestige_label.set_tooltip_string(prestige_tooltip); - on_prestige_changed( - country.get_prestige( - [this](signal& prestige_changed) mutable ->void { - prestige_changed.connect(&ScoreOverview::on_prestige_changed, this); - } - ) - ); + on_prestige_changed(country.get_prestige([this](signal& prestige_changed) mutable -> void { + prestige_changed.connect(&ScoreOverview::on_prestige_changed, this); + })); industrial_rank_label.set_text(godot::String::num_int64(country.get_industrial_rank())); const godot::String industrial_tooltip = generate_industrial_tooltip(country); industrial_rank_label.set_tooltip_string(industrial_tooltip); industrial_score_label.set_tooltip_string(industrial_tooltip); on_industrial_score_changed( - country.get_industrial_power( - [this](signal& industrial_score_changed) mutable ->void { - industrial_score_changed.connect(&ScoreOverview::on_industrial_score_changed, this); - } - ) + country.get_industrial_power([this](signal& industrial_score_changed) mutable -> void { + industrial_score_changed.connect(&ScoreOverview::on_industrial_score_changed, this); + }) ); military_rank_label.set_text(godot::String::num_int64(country.get_military_rank())); const godot::String military_tooltip = generate_military_tooltip(country); military_rank_label.set_tooltip_string(military_tooltip); military_score_label.set_tooltip_string(military_tooltip); - update_military_score( - country.military_power.get( - [this](signal<>& military_score_changed) mutable ->void { - military_score_changed.connect(&ScoreOverview::on_military_score_changed, this); - } - ) - ); - + update_military_score(country.military_power.get([this](signal<>& military_score_changed) mutable -> void { + military_score_changed.connect(&ScoreOverview::on_military_score_changed, this); + })); + colonial_power_label.set_text("TODO"); godot::String colonial_power_tooltip; if (!country.can_colonise()) { colonial_power_tooltip = Utilities::format( - "%s%s%s", - colonial_power_label.tr("COLONIAL_POINTS"), - MenuSingleton::get_tooltip_separator(), + "%s%s%s", colonial_power_label.tr("COLONIAL_POINTS"), MenuSingleton::get_tooltip_separator(), colonial_power_label.tr("NON_COLONIAL_POWER") ); } else { - //TODO get data from sim + // TODO get data from sim const long available_colonial_power = 123; const int32_t colonial_power_from_technology = 200; const fixed_point_t colonial_power_invested = 60; const fixed_point_t colonial_power_maintenance = 40; - const godot::String available_part = colonial_power_label.tr("AVAILABLE_COLONIAL_POWER") - .replace( - Utilities::get_long_value_placeholder(), - godot::String::num_int64(available_colonial_power) - ); + const godot::String available_part = + colonial_power_label.tr("AVAILABLE_COLONIAL_POWER") + .replace(Utilities::get_long_value_placeholder(), godot::String::num_int64(available_colonial_power)); InstanceManager const& instance_manager = *game_singleton.get_instance_manager(); - ModifierEffect const* const colonial_points_modifier = instance_manager - .definition_manager - .get_modifier_manager() - .get_modifier_effect_cache() - .get_colonial_points(); - const godot::String from_tech_part = colonial_power_label.tr("FROM_TECHNOLOGY")+": "+ Utilities::make_modifier_effect_value_coloured( - colonial_power_label, - *colonial_points_modifier, - colonial_power_from_technology, - false - ); + ModifierEffect const* const colonial_points_modifier = + instance_manager.definition_manager.get_modifier_manager().get_modifier_effect_cache().get_colonial_points(); + const godot::String from_tech_part = + colonial_power_label.tr("FROM_TECHNOLOGY") + ": " + + Utilities::make_modifier_effect_value_coloured( + colonial_power_label, *colonial_points_modifier, colonial_power_from_technology, false + ); - const godot::String investment_part = colonial_power_invested == 0 - ? "" - : "\n"+colonial_power_label.tr("COLONIAL_INVESTMENT") - .replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(colonial_power_invested, 1) - ); + const godot::String investment_part = colonial_power_invested == 0 ? "" + : "\n" + + colonial_power_label.tr("COLONIAL_INVESTMENT") + .replace( + Utilities::get_long_value_placeholder(), Utilities::fixed_point_to_string_dp(colonial_power_invested, 1) + ); - const godot::String maintenance_part = colonial_power_maintenance == 0 - ? "" - : "\n"+colonial_power_label.tr("COLONIAL_MAINTENANCE") - .replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(colonial_power_maintenance, 1) - ); + const godot::String maintenance_part = colonial_power_maintenance == 0 ? "" + : "\n" + + colonial_power_label.tr("COLONIAL_MAINTENANCE") + .replace( + Utilities::get_long_value_placeholder(), + Utilities::fixed_point_to_string_dp(colonial_power_maintenance, 1) + ); colonial_power_tooltip = Utilities::format( - "%s%s%s\n%s%s%s", - colonial_power_label.tr("COLONIAL_POINTS"), - MenuSingleton::get_tooltip_separator(), - available_part, - from_tech_part, - investment_part, - maintenance_part + "%s%s%s\n%s%s%s", colonial_power_label.tr("COLONIAL_POINTS"), MenuSingleton::get_tooltip_separator(), + available_part, from_tech_part, investment_part, maintenance_part ); } colonial_power_label.set_tooltip_string(colonial_power_tooltip); - //TODO colonial tooltip - // if _country_colonial_power_label: - // var available_colonial_power : int = topbar_info.get(colonial_power_available_key, 0) - // var max_colonial_power : int = topbar_info.get(colonial_power_max_key, 0) - // _country_colonial_power_label.set_text( - // "§%s%s§!/%s" % ["W" if available_colonial_power > 0 else "R", available_colonial_power, max_colonial_power] - // ) - // _country_colonial_power_label.set_tooltip_string(tr(&"COLONIAL_POINTS") + MenuSingleton.get_tooltip_separator() + ( - // topbar_info.get(colonial_power_tooltip_key, "") if country_status <= CountryStatus.SECONDARY_POWER else tr(&"NON_COLONIAL_POWER") - // )) + // TODO colonial tooltip + // if _country_colonial_power_label: + // var available_colonial_power : int = topbar_info.get(colonial_power_available_key, 0) + // var max_colonial_power : int = topbar_info.get(colonial_power_max_key, 0) + // _country_colonial_power_label.set_text( + // "§%s%s§!/%s" % ["W" if available_colonial_power > 0 else "R", available_colonial_power, max_colonial_power] + // ) + // _country_colonial_power_label.set_tooltip_string(tr(&"COLONIAL_POINTS") + MenuSingleton.get_tooltip_separator() + ( + // topbar_info.get(colonial_power_tooltip_key, "") if country_status <= CountryStatus.SECONDARY_POWER else + // tr(&"NON_COLONIAL_POWER") + // )) } godot::String ScoreOverview::generate_prestige_tooltip(CountryInstance& country) { // TODO - list prestige sources (e.g. power status) godot::String prestige_tooltip {}; - return prestige_label.tr("RANK_PRESTIGE") - + prestige_tooltip - + MenuSingleton::get_tooltip_separator() - + prestige_label.tr("RANK_PRESTIGE_D"); + return prestige_label.tr("RANK_PRESTIGE") + prestige_tooltip + MenuSingleton::get_tooltip_separator() + + prestige_label.tr("RANK_PRESTIGE_D"); } godot::String ScoreOverview::generate_industrial_tooltip(CountryInstance& country) { @@ -217,27 +190,18 @@ godot::String ScoreOverview::generate_industrial_tooltip(CountryInstance& countr // Pair: State name / Power std::vector> industrial_power_states; for (auto const& [state, power] : country.get_industrial_power_from_states()) { - industrial_power_states.emplace_back( - Utilities::get_state_name(industrial_score_label, state), - power - ); + industrial_power_states.emplace_back(Utilities::get_state_name(industrial_score_label, state), power); } - std::sort( - industrial_power_states.begin(), industrial_power_states.end(), - [](auto const& a, auto const& b) -> bool { - // Sort by greatest power, then by state name alphabetically - return a.second != b.second ? a.second > b.second : a.first < b.first; - } - ); + std::sort(industrial_power_states.begin(), industrial_power_states.end(), [](auto const& a, auto const& b) -> bool { + // Sort by greatest power, then by state name alphabetically + return a.second != b.second ? a.second > b.second : a.first < b.first; + }); for (auto const& [state_name, power] : industrial_power_states) { static const godot::String state_power_template_string = "\n%s: " + GUILabel::get_colour_marker() + "Y%s" + GUILabel::get_colour_marker() + "!"; - industrial_power_tooltip += Utilities::format( - state_power_template_string, - state_name, - Utilities::fixed_point_to_string_dp(power, 3) - ); + industrial_power_tooltip += + Utilities::format(state_power_template_string, state_name, Utilities::fixed_point_to_string_dp(power, 3)); } // Tuple: Country identifier / Country name / Power @@ -245,8 +209,7 @@ godot::String ScoreOverview::generate_industrial_tooltip(CountryInstance& countr for (auto const& [investor_ref, power] : country.get_industrial_power_from_investments()) { CountryInstance const& investor = investor_ref.get(); industrial_power_from_investments.emplace_back( - convert_to(investor.get_identifier()), - Utilities::get_country_name(industrial_score_label, investor), + convert_to(investor.get_identifier()), Utilities::get_country_name(industrial_score_label, investor), power ); } @@ -258,32 +221,23 @@ godot::String ScoreOverview::generate_industrial_tooltip(CountryInstance& countr } ); for (auto const& [country_identifier, country_name, power] : industrial_power_from_investments) { - static const godot::String investment_power_template_string = "\n" + GUILabel::get_flag_marker() + "%s %s: " + - GUILabel::get_colour_marker() + "Y%s" + GUILabel::get_colour_marker() + "!"; + static const godot::String investment_power_template_string = "\n" + GUILabel::get_flag_marker() + + "%s %s: " + GUILabel::get_colour_marker() + "Y%s" + GUILabel::get_colour_marker() + "!"; industrial_power_tooltip += Utilities::format( - investment_power_template_string, - country_identifier, - country_name, - Utilities::fixed_point_to_string_dp(power, 3) + investment_power_template_string, country_identifier, country_name, Utilities::fixed_point_to_string_dp(power, 3) ); } - return industrial_score_label.tr("RANK_INDUSTRY") - + MenuSingleton::get_tooltip_separator() - + industrial_score_label.tr("RANK_INDUSTRY_D") - + industrial_power_tooltip; + return industrial_score_label.tr("RANK_INDUSTRY") + MenuSingleton::get_tooltip_separator() + + industrial_score_label.tr("RANK_INDUSTRY_D") + industrial_power_tooltip; } void ScoreOverview::on_prestige_changed(const fixed_point_t new_prestige) { - prestige_label.set_text( - Utilities::fixed_point_to_string_dp(new_prestige, 0) - ); + prestige_label.set_text(Utilities::fixed_point_to_string_dp(new_prestige, 0)); } void ScoreOverview::on_industrial_score_changed(const fixed_point_t new_industrial_score) { - industrial_score_label.set_text( - Utilities::fixed_point_to_string_dp(new_industrial_score, 0) - ); + industrial_score_label.set_text(Utilities::fixed_point_to_string_dp(new_industrial_score, 0)); } godot::String ScoreOverview::generate_military_tooltip(CountryInstance& country) { @@ -293,22 +247,21 @@ godot::String ScoreOverview::generate_military_tooltip(CountryInstance& country) static const godot::StringName military_power_from_sea_key = "MIL_FROM_CAP_SHIPS"; static const godot::StringName military_power_from_leaders_key = "MIL_FROM_LEADERS"; - for (auto const& [source, power] : { - std::pair - { military_power_from_land_key, country.get_military_power_from_land_untracked() }, - { military_power_from_sea_key, country.get_military_power_from_sea_untracked() }, - { military_power_from_leaders_key, country.get_military_power_from_leaders_untracked() } - }) { + for ( // + auto const& [source, power] : { + std::pair { military_power_from_land_key, country.get_military_power_from_land_untracked() }, + { military_power_from_sea_key, country.get_military_power_from_sea_untracked() }, + { military_power_from_leaders_key, country.get_military_power_from_leaders_untracked() } // + } // + ) { if (power != 0) { - military_power_tooltip += "\n" + military_score_label.tr(source) + ": " + GUILabel::get_colour_marker() + "Y" - + Utilities::fixed_point_to_string_dp(power, 3) + GUILabel::get_colour_marker() + "!"; + military_power_tooltip += "\n" + military_score_label.tr(source) + ": " + GUILabel::get_colour_marker() + "Y" + + Utilities::fixed_point_to_string_dp(power, 3) + GUILabel::get_colour_marker() + "!"; } } - return military_score_label.tr("RANK_MILITARY") - + MenuSingleton::get_tooltip_separator() - + military_score_label.tr("RANK_MILITARY_D") - + military_power_tooltip; + return military_score_label.tr("RANK_MILITARY") + MenuSingleton::get_tooltip_separator() + + military_score_label.tr("RANK_MILITARY_D") + military_power_tooltip; } void ScoreOverview::on_military_score_changed() { CountryInstance* country_ptr = PlayerSingleton::get_singleton()->get_player_country(); @@ -317,10 +270,7 @@ void ScoreOverview::on_military_score_changed() { } CountryInstance& country = *country_ptr; update_military_score(country.military_power.get_untracked()); - } void ScoreOverview::update_military_score(const fixed_point_t new_military_score) { - military_score_label.set_text( - Utilities::fixed_point_to_string_dp(new_military_score, 0) - ); -} \ No newline at end of file + military_score_label.set_text(Utilities::fixed_point_to_string_dp(new_military_score, 0)); +} diff --git a/extension/src/openvic-extension/components/overview/ScoreOverview.hpp b/extension/src/openvic-extension/components/overview/ScoreOverview.hpp index aca8855c..cb1484df 100644 --- a/extension/src/openvic-extension/components/overview/ScoreOverview.hpp +++ b/extension/src/openvic-extension/components/overview/ScoreOverview.hpp @@ -37,8 +37,9 @@ namespace OpenVic { godot::String generate_military_tooltip(CountryInstance& country); void on_military_score_changed(); void update_military_score(const fixed_point_t new_military_score); + public: ScoreOverview(GUINode const& parent); void update(); }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/overview/TopBar.cpp b/extension/src/openvic-extension/components/overview/TopBar.cpp index 438ef491..7bd30618 100644 --- a/extension/src/openvic-extension/components/overview/TopBar.cpp +++ b/extension/src/openvic-extension/components/overview/TopBar.cpp @@ -2,12 +2,9 @@ using namespace OpenVic; -TopBar::TopBar(GUINode const& parent): -budget_overview{parent}, -score_overview{parent} -{} +TopBar::TopBar(GUINode const& parent) : budget_overview { parent }, score_overview { parent } {} void TopBar::update() { budget_overview.update(); score_overview.update(); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/components/overview/TopBar.hpp b/extension/src/openvic-extension/components/overview/TopBar.hpp index 2ce6d7c8..7ac71a43 100644 --- a/extension/src/openvic-extension/components/overview/TopBar.hpp +++ b/extension/src/openvic-extension/components/overview/TopBar.hpp @@ -10,8 +10,9 @@ namespace OpenVic { private: BudgetOverview budget_overview; ScoreOverview score_overview; + public: TopBar(GUINode const& parent); void update(); }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/core/ArgumentParser.cpp b/extension/src/openvic-extension/core/ArgumentParser.cpp index d7e2a628..6a0665a6 100644 --- a/extension/src/openvic-extension/core/ArgumentParser.cpp +++ b/extension/src/openvic-extension/core/ArgumentParser.cpp @@ -243,9 +243,11 @@ ArgumentParser::ArgumentParser() { options.push_back( ArgumentOption::create("base-path", Variant::STRING, "Load Victoria 2 assets from a specific path.", { "b" }, "[path]") ); - options.push_back(ArgumentOption::create( - "search-path", Variant::STRING, "Search for Victoria 2 assets at a specific path.", { "s" }, "[path]" - )); + options.push_back( + ArgumentOption::create( + "search-path", Variant::STRING, "Search for Victoria 2 assets at a specific path.", { "s" }, "[path]" + ) + ); options.push_back(ArgumentOption::create("mod", Variant::PACKED_STRING_ARRAY, "Load Victoria 2 mods.", { "m" }, "")); parse_arguments(OS::get_singleton()->get_cmdline_args(), false); @@ -339,7 +341,7 @@ String ArgumentParser::get_help(bool p_is_rich) const { PackedStringArray option_help; option_help.resize(options.size()); - for (size_t i = 0; String & help : option_help) { + for (size_t i = 0; String& help : option_help) { help = " " + options[i]->get_help_string(p_is_rich); i++; } @@ -359,8 +361,7 @@ String ArgumentParser::get_help(bool p_is_rich) const { app_description = vformat("[color=gray]%s[/color]", app_description); } - String app_copyright = - "(c) " + convert_to(GAME_COPYRIGHT_INFO[0].parts.front().copyright_statements.front()); + String app_copyright = "(c) " + convert_to(GAME_COPYRIGHT_INFO[0].parts.front().copyright_statements.front()); if (p_is_rich) { app_copyright = vformat("[color=gray]%s[/color]", app_copyright); } @@ -608,7 +609,8 @@ Error ArgumentParser::parse_arguments(PackedStringArray const& p_args, bool p_er } else if (option->get_type() == Variant::BOOL) { arguments[option->get_name()] = true; } else { - WARN_PRINT(vformat("Argument '%s' treated like a boolean but does not support a boolean value, skipping.", key) + WARN_PRINT( + vformat("Argument '%s' treated like a boolean but does not support a boolean value, skipping.", key) ); } } else if (p_error_unknown) { diff --git a/extension/src/openvic-extension/singletons/AssetManager.cpp b/extension/src/openvic-extension/singletons/AssetManager.cpp index 92f43505..43395a2c 100644 --- a/extension/src/openvic-extension/singletons/AssetManager.cpp +++ b/extension/src/openvic-extension/singletons/AssetManager.cpp @@ -2,9 +2,9 @@ #include +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/UITools.hpp" #include "openvic-extension/utility/Utilities.hpp" @@ -42,9 +42,8 @@ Ref AssetManager::_load_image(StringName const& path, bool flip_y) { GameSingleton* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, nullptr); - const String lookedup_path = convert_to( - game_singleton->get_dataloader().lookup_image_file(convert_to(path)).string() - ); + const String lookedup_path = + convert_to(game_singleton->get_dataloader().lookup_image_file(convert_to(path)).string()); ERR_FAIL_COND_V_MSG(lookedup_path.is_empty(), nullptr, Utilities::format("Failed to look up image: %s", path)); const Ref image = Utilities::load_godot_image(lookedup_path); @@ -154,16 +153,17 @@ Ref AssetManager::get_font(StringName const& name) { if (image.is_null()) { fonts.insert(name, Ref()); - ERR_FAIL_V_MSG(Ref(), Utilities::format("Failed to load font image %s for the font named %s", image_path, name)); + ERR_FAIL_V_MSG( + Ref(), Utilities::format("Failed to load font image %s for the font named %s", image_path, name) + ); } GameSingleton* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, Ref()); const String font_path = font_dir + name + font_ext; - const String lookedup_font_path = convert_to( - game_singleton->get_dataloader().lookup_file(convert_to(font_path)).string() - ); + const String lookedup_font_path = + convert_to(game_singleton->get_dataloader().lookup_file(convert_to(font_path)).string()); if (lookedup_font_path.is_empty()) { fonts.insert(name, Ref()); @@ -176,7 +176,9 @@ Ref AssetManager::get_font(StringName const& name) { ERR_FAIL_V_MSG( Ref(), - Utilities::format("Failed to load font file %s (looked up: %s) for the font named %s", font_path, lookedup_font_path, name) + Utilities::format( + "Failed to load font file %s (looked up: %s) for the font named %s", font_path, lookedup_font_path, name + ) ); } diff --git a/extension/src/openvic-extension/singletons/AssetManager.hpp b/extension/src/openvic-extension/singletons/AssetManager.hpp index 3eb50f5a..ccf56ee1 100644 --- a/extension/src/openvic-extension/singletons/AssetManager.hpp +++ b/extension/src/openvic-extension/singletons/AssetManager.hpp @@ -20,10 +20,10 @@ namespace OpenVic { public: enum LoadFlags { - LOAD_FLAG_NONE = 0, - LOAD_FLAG_CACHE_IMAGE = 1 << 0, + LOAD_FLAG_NONE = 0, + LOAD_FLAG_CACHE_IMAGE = 1 << 0, LOAD_FLAG_CACHE_TEXTURE = 1 << 1, - LOAD_FLAG_FLIP_Y = 1 << 2 + LOAD_FLAG_FLIP_Y = 1 << 2 }; private: @@ -54,7 +54,9 @@ namespace OpenVic { * load flag is set then the loaded image will be stored in the AssetManager's image cache for future access; if the * flip y load flag is set then the image will be flipped vertically before being returned (if the image is already * in the cache then no flipping will occur, regardless of whether it was originally flipped or not). */ - godot::Ref get_image(godot::StringName const& path, godot::BitField load_flags = LOAD_FLAG_CACHE_IMAGE); + godot::Ref get_image( + godot::StringName const& path, godot::BitField load_flags = LOAD_FLAG_CACHE_IMAGE // + ); /* Create a texture from an image found at the specified path relative to the game defines, fist checking the * AssetManager's texture cache in case it has already been loaded, and returning nullptr if image loading or texture @@ -64,11 +66,11 @@ namespace OpenVic { * vertically before being used to create the texture (if the image is already in the cache then no flipping will * occur, regardless of whether it was originally flipped or not). */ godot::Ref get_texture( - godot::StringName const& path, godot::BitField load_flags = LOAD_FLAG_CACHE_TEXTURE + godot::StringName const& path, godot::BitField load_flags = LOAD_FLAG_CACHE_TEXTURE // ); static godot::Ref make_stylebox_texture( - godot::Ref const& texture, godot::Vector2 const& border = {} + godot::Ref const& texture, godot::Vector2 const& border = {} // ); /* Search for and load a font with the specified name from the game defines' font directory, first checking the @@ -76,9 +78,9 @@ namespace OpenVic { godot::Ref get_font(godot::StringName const& name); private: - godot::Ref PROPERTY(currency_texture_big); // 32x32 + godot::Ref PROPERTY(currency_texture_big); // 32x32 godot::Ref PROPERTY(currency_texture_medium); // 24x24 - godot::Ref PROPERTY(currency_texture_small); // 16x16 + godot::Ref PROPERTY(currency_texture_small); // 16x16 godot::Ref PROPERTY(missing_leader_texture); diff --git a/extension/src/openvic-extension/singletons/CursorSingleton.cpp b/extension/src/openvic-extension/singletons/CursorSingleton.cpp index 0e661fa9..5d6a9e8a 100644 --- a/extension/src/openvic-extension/singletons/CursorSingleton.cpp +++ b/extension/src/openvic-extension/singletons/CursorSingleton.cpp @@ -4,42 +4,43 @@ #include #include +#include #include #include #include +#include #include #include #include #include -#include -#include #include -#include "openvic-extension/core/Bind.hpp" -#include "openvic-extension/core/Convert.hpp" -#include #include +#include "openvic-extension/core/Bind.hpp" +#include "openvic-extension/core/Convert.hpp" +#include "openvic-extension/singletons/GameSingleton.hpp" +#include "openvic-extension/utility/Utilities.hpp" + using namespace godot; using namespace OpenVic; void CursorSingleton::_bind_methods() { OV_BIND_METHOD(CursorSingleton::load_cursors); - OV_BIND_METHOD(CursorSingleton::get_frames, {"cursor_name","resolution_index"}, "normal", 0); - OV_BIND_METHOD(CursorSingleton::get_hotspots, {"cursor_name","resolution_index"}, "normal", 0); - OV_BIND_METHOD(CursorSingleton::get_animation_length, {"cursor_name"}, "normal"); - OV_BIND_METHOD(CursorSingleton::get_display_rates, {"cursor_name"}, "normal"); - OV_BIND_METHOD(CursorSingleton::get_sequence, {"cursor_name"}, "normal"); - OV_BIND_METHOD(CursorSingleton::get_resolutions, {"cursor_name"}, "normal"); - OV_BIND_METHOD(CursorSingleton::generate_resolution, {"cursor_name", "base_resolution_index", "target_resolution"}, "normal", 0, Vector2(64,64)); + OV_BIND_METHOD(CursorSingleton::get_frames, { "cursor_name", "resolution_index" }, "normal", 0); + OV_BIND_METHOD(CursorSingleton::get_hotspots, { "cursor_name", "resolution_index" }, "normal", 0); + OV_BIND_METHOD(CursorSingleton::get_animation_length, { "cursor_name" }, "normal"); + OV_BIND_METHOD(CursorSingleton::get_display_rates, { "cursor_name" }, "normal"); + OV_BIND_METHOD(CursorSingleton::get_sequence, { "cursor_name" }, "normal"); + OV_BIND_METHOD(CursorSingleton::get_resolutions, { "cursor_name" }, "normal"); + OV_BIND_METHOD( + CursorSingleton::generate_resolution, { "cursor_name", "base_resolution_index", "target_resolution" }, "normal", 0, + Vector2(64, 64) + ); OV_BIND_METHOD(CursorSingleton::get_cursor_names); - ADD_PROPERTY(PropertyInfo( - Variant::ARRAY, - "cursor_names", PROPERTY_HINT_ARRAY_TYPE, - "StringName"), - "", "get_cursor_names"); + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "cursor_names", PROPERTY_HINT_ARRAY_TYPE, "StringName"), "", "get_cursor_names"); } CursorSingleton* CursorSingleton::get_singleton() { @@ -65,7 +66,9 @@ TypedArray CursorSingleton::get_frames(StringName const& name, int ERR_FAIL_COND_V_MSG(it == cursors.end(), {}, Utilities::format("Cursor \"%s\" not found", name)); std::vector> const& images = it->value.images; - ERR_FAIL_INDEX_V_MSG(res_index, images.size(), {}, Utilities::format("Invalid image index for cursor \"%s\": %d", name, res_index)); + ERR_FAIL_INDEX_V_MSG( + res_index, images.size(), {}, Utilities::format("Invalid image index for cursor \"%s\": %d", name, res_index) + ); return images[res_index]; } @@ -75,7 +78,9 @@ PackedVector2Array CursorSingleton::get_hotspots(StringName const& name, int32_t ERR_FAIL_COND_V_MSG(it == cursors.end(), {}, Utilities::format("Cursor \"%s\" not found", name)); std::vector const& hotspots = it->value.hotspots; - ERR_FAIL_INDEX_V_MSG(res_index, hotspots.size(), {}, Utilities::format("Invalid hotspot index for cursor \"%s\": %d", name, res_index)); + ERR_FAIL_INDEX_V_MSG( + res_index, hotspots.size(), {}, Utilities::format("Invalid hotspot index for cursor \"%s\": %d", name, res_index) + ); return hotspots[res_index]; } @@ -83,7 +88,7 @@ PackedVector2Array CursorSingleton::get_hotspots(StringName const& name, int32_t int32_t CursorSingleton::get_animation_length(StringName const& name) const { const cursor_map_t::ConstIterator it = cursors.find(name); ERR_FAIL_COND_V_MSG(it == cursors.end(), {}, Utilities::format("Cursor \"%s\" not found", name)); - + return it->value.animation_length; } @@ -114,7 +119,8 @@ void CursorSingleton::generate_resolution(StringName const& name, int32_t base_r cursor_asset_t& cursor = it->value; ERR_FAIL_INDEX_MSG( - base_res_index, cursor.images.size(), Utilities::format("Invalid image index for cursor \"%s\": %d", name, base_res_index) + base_res_index, cursor.images.size(), + Utilities::format("Invalid image index for cursor \"%s\": %d", name, base_res_index) ); TypedArray const& images = cursor.images[base_res_index]; @@ -152,39 +158,39 @@ Error CursorSingleton::load_cursors() { GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V_MSG(game_singleton, FAILED, "Error retrieving GameSingleton"); - //there is also a png file in the folder we don't want to bother loading - //so don't just load everything in the directory + // there is also a png file in the folder we don't want to bother loading + // so don't just load everything in the directory - //We need to load both ".cur" and ".CUR" files - Dataloader::path_vector_t cursor_files = game_singleton->get_dataloader() - .lookup_files_in_dir_recursive(cursor_directory, ".cur"); + // We need to load both ".cur" and ".CUR" files + Dataloader::path_vector_t cursor_files = + game_singleton->get_dataloader().lookup_files_in_dir_recursive(cursor_directory, ".cur"); - Dataloader::path_vector_t CURsor_files = game_singleton->get_dataloader() - .lookup_files_in_dir_recursive(cursor_directory, ".CUR"); - cursor_files.insert(std::end(cursor_files),std::begin(CURsor_files),std::end(CURsor_files)); + Dataloader::path_vector_t CURsor_files = + game_singleton->get_dataloader().lookup_files_in_dir_recursive(cursor_directory, ".CUR"); + cursor_files.insert(std::end(cursor_files), std::begin(CURsor_files), std::end(CURsor_files)); - Dataloader::path_vector_t animated_cursor_files = game_singleton->get_dataloader() - .lookup_files_in_dir_recursive(cursor_directory, ".ani"); + Dataloader::path_vector_t animated_cursor_files = + game_singleton->get_dataloader().lookup_files_in_dir_recursive(cursor_directory, ".ani"); ERR_FAIL_COND_V_MSG(cursor_files.empty() && animated_cursor_files.empty(), FAILED, "No files in cursors directory"); Error ret = OK; - for(fs::path const& file_name : cursor_files) { + for (fs::path const& file_name : cursor_files) { String file = convert_to(file_name.string()); StringName name = _to_define_file_name(file); - if (!_load_cursor_cur(name,file)){ + if (!_load_cursor_cur(name, file)) { spdlog::error_s("Failed to load normal cursor at path {}", file_name); ret = FAILED; } } - for(fs::path const& file_name : animated_cursor_files) { + for (fs::path const& file_name : animated_cursor_files) { String file = convert_to(file_name.string()); StringName name = _to_define_file_name(file); - if (!_load_cursor_ani(name,file)){ + if (!_load_cursor_ani(name, file)) { spdlog::error_s("Failed to load animated cursor at path {}", file_name); ret = FAILED; } @@ -193,19 +199,16 @@ Error CursorSingleton::load_cursors() { return ret; } -static constexpr int32_t _reverser_lookup[] { - 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, - 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf -}; -static constexpr int32_t _reverse_bits(int32_t byte, int32_t bits_per_pixel=8) { +static constexpr int32_t _reverser_lookup[] { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf }; +static constexpr int32_t _reverse_bits(int32_t byte, int32_t bits_per_pixel = 8) { int32_t a = _reverser_lookup[(byte & 0b1111)] << 4; int32_t b = _reverser_lookup[byte >> 4]; int32_t c = b | a; - return c >> (8-bits_per_pixel); + return c >> (8 - bits_per_pixel); } -static constexpr int32_t _rotate_right(int32_t byte, int32_t size=8) { - return ((byte & 0b1) << (size-1)) | (byte >> 1); +static constexpr int32_t _rotate_right(int32_t byte, int32_t size = 8) { + return ((byte & 0b1) << (size - 1)) | (byte >> 1); } static int32_t _load_int_256(Ref const& file) { @@ -226,41 +229,43 @@ static constexpr int32_t _select_bits(uint8_t const* data, int32_t row_start, in int32_t byte_index = first_bit >> 3; int32_t bit_in_byte_index = first_bit & 0b111; ERR_FAIL_COND_V_MSG(bit_in_byte_index + bit_count > 8, 0, "Attempted to select bits outside of a byte."); - int32_t byte = _reverse_bits(*(data+row_start+byte_index)); + int32_t byte = _reverse_bits(*(data + row_start + byte_index)); int32_t selected = (byte >> bit_in_byte_index) & ((1 << bit_count) - 1); - //TODO: questionable hack, nothing in the spec suggests we should need to do this - if (bit_count > 1 && selected != 0){ - return _rotate_right(selected,4); + // TODO: questionable hack, nothing in the spec suggests we should need to do this + if (bit_count > 1 && selected != 0) { + return _rotate_right(selected, 4); } return selected; } static constexpr bool _read_AND_mask( - uint8_t const* data, int32_t pixel_x, int32_t pixel_y, int32_t x_dimension, int32_t offset) { - + uint8_t const* data, int32_t pixel_x, int32_t pixel_y, int32_t x_dimension, int32_t offset // +) { + int32_t row_start = _get_row_start(x_dimension, pixel_y, 1); - int32_t and_bit = _select_bits(data, row_start + offset,pixel_x, 1); + int32_t and_bit = _select_bits(data, row_start + offset, pixel_x, 1); return !and_bit; } static void _pixel_palette_lookup( - PackedByteArray const& data, PackedByteArray& pixel_data, uint32_t i, - PackedByteArray const& palette, int32_t coord_x, int32_t coord_y, int32_t x_dimension, - int32_t offset, bool transparent, int32_t bits_per_pixel) { - + PackedByteArray const& data, PackedByteArray& pixel_data, uint32_t i, PackedByteArray const& palette, int32_t coord_x, + int32_t coord_y, int32_t x_dimension, int32_t offset, bool transparent, int32_t bits_per_pixel +) { + int32_t row_start = _get_row_start(x_dimension, coord_y, bits_per_pixel); - int32_t pixel_bits = _select_bits(data.ptr(), row_start + offset, coord_x*bits_per_pixel, bits_per_pixel); + int32_t pixel_bits = _select_bits(data.ptr(), row_start + offset, coord_x * bits_per_pixel, bits_per_pixel); ERR_FAIL_COND_MSG( (pixel_bits + 1) * 4 > palette.size(), vformat("Attempted to select invalid colour palette entry %s", pixel_bits) ); - //pixel bits serves as an index into the colour palette. We need to multiply the index by the number of bytes per colour (4) - pixel_data[(i*4) + 0] = palette[pixel_bits*4 + 0]; - pixel_data[(i*4) + 1] = palette[pixel_bits*4 + 1]; - pixel_data[(i*4) + 2] = palette[pixel_bits*4 + 2]; - pixel_data[(i*4) + 3] = 0xFF * transparent; //a + // pixel bits serves as an index into the colour palette. We need to multiply the index by the number of bytes per colour + // (4) + pixel_data[(i * 4) + 0] = palette[pixel_bits * 4 + 0]; + pixel_data[(i * 4) + 1] = palette[pixel_bits * 4 + 1]; + pixel_data[(i * 4) + 2] = palette[pixel_bits * 4 + 2]; + pixel_data[(i * 4) + 3] = 0xFF * transparent; // a } /* @@ -270,34 +275,33 @@ but the singular example of a 24bit cursor found on the internet does things lik So emit a warning when trying to load one of these */ static void _read_24bit_pixel( - PackedByteArray const& image_data, PackedByteArray& pixel_data, - int32_t i, int32_t offset, bool opaque) { + PackedByteArray const& image_data, PackedByteArray& pixel_data, int32_t i, int32_t offset, bool opaque // +) { ERR_FAIL_COND_MSG( (i + 1) * 3 > image_data.size(), vformat("Pixel %d tried to read from a pixel data array of max size %d", i, pixel_data.size()) ); - pixel_data[(i*4) + 0] = image_data[offset + (i*3) + 2]; //r - pixel_data[(i*4) + 1] = image_data[offset + (i*3) + 1]; //g - pixel_data[(i*4) + 2] = image_data[offset + (i*3) + 0]; //b - pixel_data[(i*4) + 3] = 0xFF * opaque; //a + pixel_data[(i * 4) + 0] = image_data[offset + (i * 3) + 2]; // r + pixel_data[(i * 4) + 1] = image_data[offset + (i * 3) + 1]; // g + pixel_data[(i * 4) + 2] = image_data[offset + (i * 3) + 0]; // b + pixel_data[(i * 4) + 3] = 0xFF * opaque; // a } -static void _read_32bit_pixel( - PackedByteArray const& image_data, PackedByteArray& pixel_data, - int32_t i, int32_t offset, bool opaque) { +static void +_read_32bit_pixel(PackedByteArray const& image_data, PackedByteArray& pixel_data, int32_t i, int32_t offset, bool opaque) { ERR_FAIL_COND_MSG( (i + 1) * 4 > image_data.size(), vformat("Pixel %d tried to read from a pixel data array of max size %d", i, pixel_data.size()) ); - pixel_data[(i*4) + 0] = image_data[offset + (i*4) + 2]; //r - pixel_data[(i*4) + 1] = image_data[offset + (i*4) + 1]; //g - pixel_data[(i*4) + 2] = image_data[offset + (i*4) + 0]; //b - pixel_data[(i*4) + 3] = image_data[offset + (i*4) + 3] * opaque; //a + pixel_data[(i * 4) + 0] = image_data[offset + (i * 4) + 2]; // r + pixel_data[(i * 4) + 1] = image_data[offset + (i * 4) + 1]; // g + pixel_data[(i * 4) + 2] = image_data[offset + (i * 4) + 0]; // b + pixel_data[(i * 4) + 3] = image_data[offset + (i * 4) + 3] * opaque; // a } -//used to load a .cur file from a file (could be the a whole .cur file, or a .cur within a .ani file) +// used to load a .cur file from a file (could be the a whole .cur file, or a .cur within a .ani file) static CursorSingleton::image_hotspot_pair_asset_t _load_pair(Ref const& file) { CursorSingleton::image_hotspot_pair_asset_t pairs = {}; @@ -306,15 +310,15 @@ static CursorSingleton::image_hotspot_pair_asset_t _load_pair(Ref co //.cur header int32_t reserved = file->get_16(); - int32_t type = file->get_16(); //1=ico, 2=cur + int32_t type = file->get_16(); // 1=ico, 2=cur int32_t images_count = file->get_16(); - - //all the images - for(int32_t i=0; iget_8(); - file->get_8(); //int32_t img_reserved - + file->get_8(); // int32_t img_reserved + Vector2i hotspot = Vector2i(); hotspot.x = file->get_16(); hotspot.y = file->get_16(); @@ -322,33 +326,31 @@ static CursorSingleton::image_hotspot_pair_asset_t _load_pair(Ref co int32_t data_size = std::min(static_cast(file->get_32()), file->get_length() - file->get_position()); int32_t data_offset = file->get_32(); - //This image header information is sequential in the data, but the images aren't necessarily - // so save the current position, get the image data and return so we're ready for the next image header + // This image header information is sequential in the data, but the images aren't necessarily + // so save the current position, get the image data and return so we're ready for the next image header int32_t end_of_image_header = file->get_position(); - file->seek(data_offset+base_offset); + file->seek(data_offset + base_offset); PackedByteArray const& image_data = file->get_buffer(data_size); file->seek(end_of_image_header); Ref image = Ref(); image.instantiate(); - + // PNGs are stored in their entirety, so use Godot's internal loader - if (image_data.slice(1,4).get_string_from_ascii() == "PNG") { + if (image_data.slice(1, 4).get_string_from_ascii() == "PNG") { image->load_png_from_buffer(image_data); - } - else { //BMP based cursor, have to load this manually - //int32_t dib_header_size = image_data.decode_u32(0); + } else { // BMP based cursor, have to load this manually + // int32_t dib_header_size = image_data.decode_u32(0); - //this is the combined sized of the picture and the transparency bitmask - // (ex. 32x32 dimension image becomes 32x64 here) - //Vector2i combined_dimensions = Vector2i(image_data.decode_u32(4),image_data.decode_u32(8)); - //int32_t colour_planes = image_data.decode_u16(12); + // this is the combined sized of the picture and the transparency bitmask + // (ex. 32x32 dimension image becomes 32x64 here) + // Vector2i combined_dimensions = Vector2i(image_data.decode_u32(4),image_data.decode_u32(8)); + // int32_t colour_planes = image_data.decode_u16(12); int32_t bits_per_pixel = image_data.decode_u16(14); - if (bits_per_pixel <= 8 || bits_per_pixel == 24){ + if (bits_per_pixel <= 8 || bits_per_pixel == 24) { spdlog::warn_s("Attempting to import {} bit cursor, this isn't guaranteed to work", bits_per_pixel); - } - else if (bits_per_pixel != 32){ + } else if (bits_per_pixel != 32) { spdlog::error_s( "Unsupported bits per pixel while loading cursor image with {} bits per pixel, loading blank image", bits_per_pixel @@ -356,94 +358,85 @@ static CursorSingleton::image_hotspot_pair_asset_t _load_pair(Ref co } int32_t size = image_data.decode_u32(20); - Vector2i resolution = Vector2i(image_data.decode_s32(24),image_data.decode_s32(28)); + Vector2i resolution = Vector2i(image_data.decode_s32(24), image_data.decode_s32(28)); int32_t palette_size = image_data.decode_u32(32); - if (palette_size == 0 && bits_per_pixel <= 8){ - palette_size = 1 << bits_per_pixel; + if (palette_size == 0 && bits_per_pixel <= 8) { + palette_size = 1 << bits_per_pixel; } - //int32_t important_colours = image_data.decode_u32(36); + // int32_t important_colours = image_data.decode_u32(36); - //for BMPs with 8 bits per pixel or less, the pixel data is actually a lookup to this table here - PackedByteArray const& palette = image_data.slice(40,40+(4*palette_size)); + // for BMPs with 8 bits per pixel or less, the pixel data is actually a lookup to this table here + PackedByteArray const& palette = image_data.slice(40, 40 + (4 * palette_size)); // this is where the image data starts - int32_t offset = 40 + palette_size*4; + int32_t offset = 40 + palette_size * 4; - //where the transparency AND mask starts - int32_t mask_offset = offset + _get_row_start(dimensions.x,dimensions.y,bits_per_pixel); + // where the transparency AND mask starts + int32_t mask_offset = offset + _get_row_start(dimensions.x, dimensions.y, bits_per_pixel); PackedByteArray pixel_data = PackedByteArray(); - pixel_data.resize(dimensions.x*dimensions.y*4); + pixel_data.resize(dimensions.x * dimensions.y * 4); pixel_data.fill(255); - int32_t i=0; - for(int32_t row=0; row < dimensions.y; row++) { - for(int32_t col=0; col < dimensions.x; col++) { - Vector2i coord = Vector2i(col,row); - bool transparent = _read_AND_mask( - image_data.ptr(),coord.x,coord.y,dimensions.x,mask_offset - ); - if (bits_per_pixel <= 8){ - //mostly legacy files, these ones all use a lookup into the colour palette + int32_t i = 0; + for (int32_t row = 0; row < dimensions.y; row++) { + for (int32_t col = 0; col < dimensions.x; col++) { + Vector2i coord = Vector2i(col, row); + bool transparent = _read_AND_mask(image_data.ptr(), coord.x, coord.y, dimensions.x, mask_offset); + if (bits_per_pixel <= 8) { + // mostly legacy files, these ones all use a lookup into the colour palette _pixel_palette_lookup( - image_data, pixel_data, i, palette, coord.x, coord.y, dimensions.x, offset, transparent, bits_per_pixel + image_data, pixel_data, i, palette, coord.x, coord.y, dimensions.x, offset, transparent, + bits_per_pixel ); - }/* - else if (bits_per_pixel == 16) { //TODO - //Unsupported, error - }*/ + } /* + else if (bits_per_pixel == 16) { //TODO + //Unsupported, error + }*/ else if (bits_per_pixel == 24) { - //Support Questionable, based on 1 example on the internet as opposed to the actual spec - _read_24bit_pixel( - image_data, pixel_data, i, offset, transparent - ); - } - else if (bits_per_pixel == 32) { - //What vic actually uses - _read_32bit_pixel( - image_data, pixel_data, i, offset, transparent - ); + // Support Questionable, based on 1 example on the internet as opposed to the actual spec + _read_24bit_pixel(image_data, pixel_data, i, offset, transparent); + } else if (bits_per_pixel == 32) { + // What vic actually uses + _read_32bit_pixel(image_data, pixel_data, i, offset, transparent); } i++; } } - - image = image->create_from_data(dimensions.x,dimensions.y,false, Image::FORMAT_RGBA8,pixel_data); - //bmp images are stored bottom to top + + image = image->create_from_data(dimensions.x, dimensions.y, false, Image::FORMAT_RGBA8, pixel_data); + // bmp images are stored bottom to top image->flip_y(); } Ref image_texture = Ref(); image_texture.instantiate(); image_texture = image_texture->create_from_image(image); - - if (image_texture.is_null()){ + + if (image_texture.is_null()) { spdlog::error_s("Image Texture {} was null!", file->get_path()); } pairs.hotspots.push_back(hotspot); pairs.images.push_back(image_texture); - } return pairs; - } bool CursorSingleton::_load_cursor_ani(StringName const& name, String const& path) { const Ref file = FileAccess::open(path, FileAccess::ModeFlags::READ); const Error err = FileAccess::get_open_error(); - ERR_FAIL_COND_V_MSG( - err != OK || file.is_null(), false, Utilities::format("Failed to open ani file: \"%s\"", path) - ); + ERR_FAIL_COND_V_MSG(err != OK || file.is_null(), false, Utilities::format("Failed to open ani file: \"%s\"", path)); - //read the RIFF container - Utilities::read_riff_str(file); //riff_id - const uint64_t riff_size = std::min(static_cast(file->get_32()), file->get_length());; - Utilities::read_riff_str(file); //form_type + // read the RIFF container + Utilities::read_riff_str(file); // riff_id + const uint64_t riff_size = std::min(static_cast(file->get_32()), file->get_length()); + ; + Utilities::read_riff_str(file); // form_type - //important variables + // important variables std::vector> frames_by_resolution; std::vector hotspots_by_resolution; @@ -451,50 +444,46 @@ bool CursorSingleton::_load_cursor_ani(StringName const& name, String const& pat PackedFloat32Array display_rates; PackedInt32Array sequence; - //ani header variables + // ani header variables int32_t num_frames = 1; int32_t num_steps = 1; - Vector2i dimensions = Vector2i(1,1); + Vector2i dimensions = Vector2i(1, 1); int32_t bit_count = 1; int32_t num_planes = 1; //??? - int32_t display_rate = 1; //how long each frame should last + int32_t display_rate = 1; // how long each frame should last int32_t flags = 0; bool icon_flag = false; bool sequence_flag = false; - - while(file->get_position() < riff_size){ + while (file->get_position() < riff_size) { String id = Utilities::read_riff_str(file); int32_t size = file->get_32(); - if (id == "LIST"){ + if (id == "LIST") { String list_type = Utilities::read_riff_str(file); - } - else if (id == "anih"){ - //hack for some files, there's likely a better way - if (size == 36){ + } else if (id == "anih") { + // hack for some files, there's likely a better way + if (size == 36) { file->get_32(); // header_size } num_frames = file->get_32(); num_steps = file->get_32(); - dimensions = Vector2i(file->get_32(),file->get_32()); + dimensions = Vector2i(file->get_32(), file->get_32()); bit_count = file->get_32(); num_planes = file->get_32(); display_rate = file->get_32(); flags = file->get_32(); icon_flag = flags & 0x1; sequence_flag = flags & 0x2; - } - else if (id == "icon"){ - + } else if (id == "icon") { int32_t file_access_offset = file->get_position(); image_hotspot_pair_asset_t pair = _load_pair(file); - //basically pushback an array + // basically pushback an array + + // only store the resolutions from one frame + if (resolutions.is_empty()) { + for (int32_t i = 0; i < pair.images.size(); i++) { - //only store the resolutions from one frame - if (resolutions.is_empty()){ - for(int32_t i=0;i images; images.push_back(pair.images[i]); @@ -502,93 +491,79 @@ bool CursorSingleton::_load_cursor_ani(StringName const& name, String const& pat frames_by_resolution.push_back(images); hotspots_by_resolution.push_back(hotspots); - resolutions.push_back(Vector2(pair.images[i]->get_width(),pair.images[i]->get_height())); + resolutions.push_back(Vector2(pair.images[i]->get_width(), pair.images[i]->get_height())); } - - } - else { - if (pair.images.size() != frames_by_resolution.size()){ - spdlog::error_s( - "Malformatted .ani cursor file {} had inconsistent number of images per cursor", - name - ); + } else { + if (pair.images.size() != frames_by_resolution.size()) { + spdlog::error_s("Malformatted .ani cursor file {} had inconsistent number of images per cursor", name); } - for(int32_t i=0; iseek(file_access_offset + size); - } - else if (id == "seq "){ - for(int32_t i=0; iget_32()); } - } - else if (id == "rate"){ - for(int32_t i=0;iget_32()/60.0); + } else if (id == "rate") { + for (int32_t i = 0; i < num_steps; i++) { + display_rates.push_back(file->get_32() / 60.0); } - } - else { - //Various junk (JUNK, metadata we don't care about, ...) + } else { + // Various junk (JUNK, metadata we don't care about, ...) file->get_buffer(size); } - //align to even bytes - if ((file->get_position() & 1) != 0){ + // align to even bytes + if ((file->get_position() & 1) != 0) { file->get_8(); } } - //not all ani files have the sequence and rate chunks, if not, fill out these properties - //manually - if (sequence.is_empty()){ - for(int32_t i=0; i(sequence.size()), - display_rates, - sequence + std::move(hotspots_by_resolution), std::move(frames_by_resolution), resolutions, + static_cast(sequence.size()), display_rates, sequence // } ); cursor_names.append(name); - + return true; } bool CursorSingleton::_load_cursor_cur(StringName const& name, String const& path) { const Ref file = FileAccess::open(path, FileAccess::ModeFlags::READ); const Error err = FileAccess::get_open_error(); - ERR_FAIL_COND_V_MSG( - err != OK || file.is_null(), false, Utilities::format("Failed to open cur file: \"%s\"", path) - ); + ERR_FAIL_COND_V_MSG(err != OK || file.is_null(), false, Utilities::format("Failed to open cur file: \"%s\"", path)); image_hotspot_pair_asset_t pair = _load_pair(file); - + std::vector> frames_by_resolution; std::vector hotspots_by_resolution; PackedVector2Array resolutions; - for(int32_t i=0;iget_width(),pair.images[i]->get_height())); - + for (int32_t i = 0; i < pair.images.size(); i++) { + resolutions.push_back(Vector2(pair.images[i]->get_width(), pair.images[i]->get_height())); + TypedArray frames; frames.push_back(pair.images[i]); frames_by_resolution.push_back(frames); @@ -601,13 +576,10 @@ bool CursorSingleton::_load_cursor_cur(StringName const& name, String const& pat cursors.insert( name, cursor_asset_t { - std::move(hotspots_by_resolution), - std::move(frames_by_resolution), - resolutions, - 1 + std::move(hotspots_by_resolution), std::move(frames_by_resolution), resolutions, 1 // } ); cursor_names.append(name); return true; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/singletons/CursorSingleton.hpp b/extension/src/openvic-extension/singletons/CursorSingleton.hpp index 87fad7fc..afe87e0d 100644 --- a/extension/src/openvic-extension/singletons/CursorSingleton.hpp +++ b/extension/src/openvic-extension/singletons/CursorSingleton.hpp @@ -1,31 +1,30 @@ #pragma once -#include -#include #include #include #include +#include +#include #include #include #include #include #include -#include #include -#include #include +#include namespace OpenVic { class CursorSingleton : public godot::Object { - + GDCLASS(CursorSingleton, godot::Object); static inline CursorSingleton* _singleton = nullptr; public: - //An intermediate data type to help with loading cursors. - //The size of images/hotspots arrays corresponds to resolutions_per_cursor. + // An intermediate data type to help with loading cursors. + // The size of images/hotspots arrays corresponds to resolutions_per_cursor. struct image_hotspot_pair_asset_t { std::vector hotspots; std::vector> images; @@ -37,23 +36,23 @@ namespace OpenVic { std::vector hotspots; std::vector> images; godot::PackedVector2Array resolutions; - int32_t animation_length; //1 for static cursors + int32_t animation_length; // 1 for static cursors godot::PackedFloat32Array display_rates; godot::PackedInt32Array sequence; }; - //map of "subfolder/fileName.cur/.ani" -> cursor_asset. Subfolder comes after gfx/cursor + // map of "subfolder/fileName.cur/.ani" -> cursor_asset. Subfolder comes after gfx/cursor using cursor_map_t = godot::HashMap; cursor_map_t cursors; godot::TypedArray cursor_names; - + public: CursorSingleton(); ~CursorSingleton(); static CursorSingleton* get_singleton(); - + protected: static void _bind_methods(); @@ -64,7 +63,7 @@ namespace OpenVic { public: godot::Error load_cursors(); godot::TypedArray get_cursor_names() const; - + godot::TypedArray get_frames(godot::StringName const& name, int32_t res_index = 0) const; godot::PackedVector2Array get_hotspots(godot::StringName const& name, int32_t res_index = 0) const; int32_t get_animation_length(godot::StringName const& name) const; @@ -75,4 +74,4 @@ namespace OpenVic { void generate_resolution(godot::StringName const& name, int32_t base_res_index, godot::Vector2 target_res); }; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/singletons/GameSingleton.cpp b/extension/src/openvic-extension/singletons/GameSingleton.cpp index d4f36be5..d92d3cd1 100644 --- a/extension/src/openvic-extension/singletons/GameSingleton.cpp +++ b/extension/src/openvic-extension/singletons/GameSingleton.cpp @@ -2,36 +2,36 @@ #include #include -#include -#include #include #include #include #include -#include #include #include #include +#include #include #include #include #include +#include + +#include +#include + +#include + +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/AssetManager.hpp" #include "openvic-extension/singletons/LoadLocalisation.hpp" #include "openvic-extension/singletons/MenuSingleton.hpp" #include "openvic-extension/singletons/PlayerSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/Utilities.hpp" -#include - -#include -#include - using namespace godot; using namespace OpenVic; @@ -113,10 +113,10 @@ void GameSingleton::_on_gamestate_updated() { */ GameSingleton::GameSingleton() : game_manager { - std::bind(&GameSingleton::_on_gamestate_updated, this), - std::bind(&Time::get_ticks_usec, Time::get_singleton()), - std::bind(&Time::get_ticks_msec, Time::get_singleton()) - }, mapmode { &Mapmode::ERROR_MAPMODE } { + std::bind(&GameSingleton::_on_gamestate_updated, this), std::bind(&Time::get_ticks_usec, Time::get_singleton()), + std::bind(&Time::get_ticks_msec, Time::get_singleton()) // + }, + mapmode { &Mapmode::ERROR_MAPMODE } { ERR_FAIL_COND(singleton != nullptr); singleton = this; } @@ -132,7 +132,7 @@ void GameSingleton::setup_logger() { switch (msg.level) { using namespace spdlog::level; - case info: UtilityFunctions::print_rich("[[color=green]info[/color]] ", convert_to(payload)); break; + case info: UtilityFunctions::print_rich("[[color=green]info[/color]] ", convert_to(payload)); break; case warn: godot::_err_print_error( msg.source.funcname, msg.source.filename, msg.source.line, convert_to(payload), false, true @@ -211,19 +211,19 @@ TypedArray GameSingleton::get_bookmark_info() const { Error GameSingleton::setup_game(int32_t bookmark_index) { DefinitionManager const& definition_manager = game_manager.get_definition_manager(); - Bookmark const* bookmark = definition_manager.get_history_manager() - .get_bookmark_manager() - .get_bookmark_by_index(bookmark_index_t(bookmark_index)); + Bookmark const* bookmark = + definition_manager.get_history_manager().get_bookmark_manager().get_bookmark_by_index(bookmark_index_t(bookmark_index)); ERR_FAIL_NULL_V_MSG(bookmark, FAILED, Utilities::format("Failed to get bookmark with index: %d", bookmark_index)); bool ret = game_manager.setup_instance(*bookmark); // TODO - remove this temporary crime assignment InstanceManager* instance_manager = get_instance_manager(); ERR_FAIL_NULL_V_MSG(instance_manager, FAILED, "Failed to setup instance manager!"); - + CrimeManager const& crime_manager = definition_manager.get_crime_manager(); for (ProvinceInstance& province : instance_manager->get_map_instance().get_province_instances()) { - const crime_index_t crime_index = crime_index_t(type_safe::get(province.index) % crime_manager.get_crime_modifier_count()); + const crime_index_t crime_index = + crime_index_t(type_safe::get(province.index) % crime_manager.get_crime_modifier_count()); province.set_crime(crime_manager.get_crime_modifier_by_index(crime_index)); } @@ -326,9 +326,8 @@ Ref GameSingleton::get_flag_sheet_texture() const { int32_t GameSingleton::get_flag_sheet_index(const country_index_t country_index, StringName const& flag_type) const { const uint64_t index = static_cast(type_safe::get(country_index)); ERR_FAIL_COND_V_MSG( - index < 0 || - index >= get_definition_manager().get_country_definition_manager().get_country_definition_count(), - -1, Utilities::format("Invalid country index: %d", index) + index < 0 || index >= get_definition_manager().get_country_definition_manager().get_country_definition_count(), -1, + Utilities::format("Invalid country index: %d", index) ); const typename decltype(flag_type_index_map)::ConstIterator it = flag_type_index_map.find(flag_type); @@ -445,9 +444,8 @@ int32_t GameSingleton::get_mapmode_count() const { } String GameSingleton::get_mapmode_identifier(int32_t index) const { - Mapmode const* identifier_mapmode = get_definition_manager() - .get_mapmode_manager() - .get_mapmode_by_index(map_mode_index_t(index)); + Mapmode const* identifier_mapmode = + get_definition_manager().get_mapmode_manager().get_mapmode_by_index(map_mode_index_t(index)); if (identifier_mapmode != nullptr) { return convert_to(identifier_mapmode->get_identifier()); } @@ -455,9 +453,8 @@ String GameSingleton::get_mapmode_identifier(int32_t index) const { } String GameSingleton::get_mapmode_localisation_key(int32_t index) const { - Mapmode const* localisation_key_mapmode = get_definition_manager() - .get_mapmode_manager() - .get_mapmode_by_index(map_mode_index_t(index)); + Mapmode const* localisation_key_mapmode = + get_definition_manager().get_mapmode_manager().get_mapmode_by_index(map_mode_index_t(index)); if (localisation_key_mapmode != nullptr) { return convert_to(localisation_key_mapmode->get_localisation_key()); } @@ -469,9 +466,7 @@ int32_t GameSingleton::get_current_mapmode_index() const { } Error GameSingleton::set_mapmode(int32_t index) { - Mapmode const* new_mapmode = get_definition_manager() - .get_mapmode_manager() - .get_mapmode_by_index(map_mode_index_t(index)); + Mapmode const* new_mapmode = get_definition_manager().get_mapmode_manager().get_mapmode_by_index(map_mode_index_t(index)); ERR_FAIL_NULL_V_MSG(new_mapmode, FAILED, Utilities::format("Failed to find mapmode with index: %d", index)); mapmode = new_mapmode; const Error err = _update_colour_image(); @@ -559,7 +554,9 @@ Error GameSingleton::_load_terrain_variants() { ERR_FAIL_NULL_V(asset_manager, FAILED); // Load the terrain texture sheet and prepare to slice it up Ref terrain_sheet = asset_manager->get_image(terrain_texturesheet_path, AssetManager::LOAD_FLAG_NONE); - ERR_FAIL_NULL_V_MSG(terrain_sheet, FAILED, Utilities::format("Failed to load terrain texture sheet: %s", terrain_texturesheet_path)); + ERR_FAIL_NULL_V_MSG( + terrain_sheet, FAILED, Utilities::format("Failed to load terrain texture sheet: %s", terrain_texturesheet_path) + ); static constexpr int32_t SHEET_DIMS = 8, SHEET_SIZE = SHEET_DIMS * SHEET_DIMS; @@ -681,7 +678,8 @@ Error GameSingleton::_load_flag_sheet() { ERR_FAIL_COND_V(flag_images.size() != flag_sheet_count, FAILED); /* Calculate the width that will make the sheet as close to a square as possible (taking flag dimensions into account.) */ - flag_sheet_dims.x = fp::sqrt(fixed_point_t { static_cast(flag_images.size()) } * flag_dims.y / flag_dims.x).ceil(); + flag_sheet_dims.x = + fp::sqrt(fixed_point_t { static_cast(flag_images.size()) } * flag_dims.y / flag_dims.x).ceil(); /* Calculated corresponding height (rounded up). */ flag_sheet_dims.y = (static_cast(flag_images.size()) + flag_sheet_dims.x - 1) / flag_sheet_dims.x; diff --git a/extension/src/openvic-extension/singletons/GitInfo.hpp b/extension/src/openvic-extension/singletons/GitInfo.hpp index 899c1a38..b0e02d4b 100644 --- a/extension/src/openvic-extension/singletons/GitInfo.hpp +++ b/extension/src/openvic-extension/singletons/GitInfo.hpp @@ -4,7 +4,7 @@ #include #include -#include "openvic-simulation/utility/Getters.hpp" +#include namespace OpenVic { class GitInfo : public godot::Object { diff --git a/extension/src/openvic-extension/singletons/LoadLocalisation.cpp b/extension/src/openvic-extension/singletons/LoadLocalisation.cpp index cc5c005c..c3a93a09 100644 --- a/extension/src/openvic-extension/singletons/LoadLocalisation.cpp +++ b/extension/src/openvic-extension/singletons/LoadLocalisation.cpp @@ -35,7 +35,8 @@ Error LoadLocalisation::_load_file(String const& file_path, Ref con const Ref file = FileAccess::open(file_path, FileAccess::ModeFlags::READ); Error err = FileAccess::get_open_error(); ERR_FAIL_COND_V_MSG( - err != OK || file.is_null(), err == OK ? FAILED : err, Utilities::format("Failed to open localisation file: %s", file_path) + err != OK || file.is_null(), err == OK ? FAILED : err, + Utilities::format("Failed to open localisation file: %s", file_path) ); int line_number = 0; while (!file->eof_reached()) { @@ -93,7 +94,9 @@ Error LoadLocalisation::load_locale_dir(String const& dir_path, String const& lo */ const Ref translation = _get_translation(locale); const PackedStringArray files = DirAccess::get_files_at(dir_path); - ERR_FAIL_COND_V_MSG(files.size() < 1, FAILED, Utilities::format("Locale directory does not contain any files: %s", dir_path)); + ERR_FAIL_COND_V_MSG( + files.size() < 1, FAILED, Utilities::format("Locale directory does not contain any files: %s", dir_path) + ); Error err = OK; for (String const& file_name : files) { if (file_name.get_extension().to_lower() == "csv") { @@ -110,7 +113,8 @@ Error LoadLocalisation::load_locale_dir(String const& dir_path, String const& lo */ Error LoadLocalisation::load_localisation_dir(String const& dir_path) const { ERR_FAIL_COND_V_MSG( - !DirAccess::dir_exists_absolute(dir_path), FAILED, Utilities::format("Localisation directory does not exist: %s", dir_path) + !DirAccess::dir_exists_absolute(dir_path), FAILED, + Utilities::format("Localisation directory does not exist: %s", dir_path) ); const PackedStringArray dirs = DirAccess::get_directories_at(dir_path); ERR_FAIL_COND_V_MSG( @@ -143,8 +147,8 @@ bool LoadLocalisation::add_message(std::string_view key, Dataloader::locale_t lo const StringName old_localisation = translation->get_message(godot_key); if (!old_localisation.is_empty()) { UtilityFunctions::push_warning( - "Changing translation ", godot_key, " (", Dataloader::locale_names[locale], ") from \"", - old_localisation, "\" to \"", godot_localisation, "\"" + "Changing translation ", godot_key, " (", Dataloader::locale_names[locale], ") from \"", old_localisation, + "\" to \"", godot_localisation, "\"" ); } } diff --git a/extension/src/openvic-extension/singletons/MapItemSingleton.cpp b/extension/src/openvic-extension/singletons/MapItemSingleton.cpp index 508713d5..e129c961 100644 --- a/extension/src/openvic-extension/singletons/MapItemSingleton.cpp +++ b/extension/src/openvic-extension/singletons/MapItemSingleton.cpp @@ -1,27 +1,29 @@ #include "MapItemSingleton.hpp" -#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include -#include "godot_cpp/core/error_macros.hpp" -#include "godot_cpp/variant/packed_int32_array.hpp" -#include "godot_cpp/variant/packed_vector2_array.hpp" -#include "godot_cpp/variant/typed_array.hpp" -#include "godot_cpp/variant/vector2.hpp" +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/Utilities.hpp" -#include "openvic-simulation/country/CountryDefinition.hpp" -#include "openvic-simulation/country/CountryInstance.hpp" -#include "openvic-simulation/DefinitionManager.hpp" -#include "openvic-simulation/economy/BuildingType.hpp" -#include "openvic-simulation/interface/GFXObject.hpp" -#include "openvic-simulation/map/ProvinceDefinition.hpp" -#include "openvic-simulation/map/ProvinceInstance.hpp" -#include "openvic-simulation/map/State.hpp" -#include "openvic-simulation/types/Vector.hpp" using namespace godot; using namespace OpenVic; @@ -36,10 +38,9 @@ void MapItemSingleton::_bind_methods() { OV_BIND_METHOD(MapItemSingleton::get_rgo_icons); OV_BIND_METHOD(MapItemSingleton::get_national_focus_icons); OV_BIND_METHOD(MapItemSingleton::get_projections); - OV_BIND_METHOD(MapItemSingleton::get_unit_position_by_province_number,{"province_number"}); - OV_BIND_METHOD(MapItemSingleton::get_port_position_by_province_number,{"province_number"}); - OV_BIND_METHOD(MapItemSingleton::get_clicked_port_province_number, {"position"}); - + OV_BIND_METHOD(MapItemSingleton::get_unit_position_by_province_number, { "province_number" }); + OV_BIND_METHOD(MapItemSingleton::get_port_position_by_province_number, { "province_number" }); + OV_BIND_METHOD(MapItemSingleton::get_clicked_port_province_number, { "position" }); } MapItemSingleton* MapItemSingleton::get_singleton() { @@ -74,14 +75,15 @@ void MapItemSingleton::add_billboard_dict(GFX::Billboard const& billboard, Typed billboard_dict_array.push_back(dict); } -//get an array of all the billboard dictionaries +// get an array of all the billboard dictionaries TypedArray MapItemSingleton::get_billboards() const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); TypedArray ret; - for (memory::unique_base_ptr const& obj : game_singleton->get_definition_manager().get_ui_manager().get_objects()) { + UIManager const& manager = game_singleton->get_definition_manager().get_ui_manager(); + for (memory::unique_base_ptr const& obj : manager.get_objects()) { GFX::Billboard const* billboard = obj->cast_to(); if (billboard != nullptr) { add_billboard_dict(*billboard, ret); @@ -91,7 +93,9 @@ TypedArray MapItemSingleton::get_billboards() const { return ret; } -void MapItemSingleton::add_projection_dict(GFX::Projection const& projection, TypedArray& projection_dict_array) const { +void MapItemSingleton::add_projection_dict( + GFX::Projection const& projection, TypedArray& projection_dict_array +) const { static const StringName name_key = "name"; static const StringName texture_key = "texture"; static const StringName size_key = "size"; @@ -118,7 +122,8 @@ TypedArray MapItemSingleton::get_projections() const { TypedArray ret; - for (memory::unique_base_ptr const& obj : game_singleton->get_definition_manager().get_ui_manager().get_objects()) { + UIManager const& manager = game_singleton->get_definition_manager().get_ui_manager(); + for (memory::unique_base_ptr const& obj : manager.get_objects()) { GFX::Projection const* projection = obj->cast_to(); if (projection != nullptr) { add_projection_dict(*projection, ret); @@ -150,9 +155,11 @@ PackedVector2Array MapItemSingleton::get_province_positions() const { return billboard_pos; } -//includes non-existent countries, used for setting the billboard buffer size +// includes non-existent countries, used for setting the billboard buffer size int32_t MapItemSingleton::get_max_capital_count() const { - return GameSingleton::get_singleton()->get_definition_manager().get_country_definition_manager().get_country_definition_count(); + CountryDefinitionManager const& manager = + GameSingleton::get_singleton()->get_definition_manager().get_country_definition_manager(); + return manager.get_country_definition_count(); } PackedVector2Array MapItemSingleton::get_capital_positions() const { @@ -170,7 +177,7 @@ PackedVector2Array MapItemSingleton::get_capital_positions() const { for (CountryInstance const& country : country_instance_manager.get_country_instances()) { if (!country.exists() || country.get_capital() == nullptr) { - //skip non-existent or capital-less countries + // skip non-existent or capital-less countries continue; } @@ -228,13 +235,11 @@ PackedByteArray MapItemSingleton::get_rgo_icons() const { } GoodDefinition const* rgo_good = prov_inst.get_rgo_good(); - icons[index++] = rgo_good != nullptr - ? static_cast(type_safe::get(rgo_good->index)) + 1 - : 0; // 0 if no rgo good in the province + icons[index++] = rgo_good != nullptr ? static_cast(type_safe::get(rgo_good->index)) + 1 + : 0; // 0 if no rgo good in the province } return icons; - } /* @@ -272,64 +277,77 @@ PackedByteArray MapItemSingleton::get_national_focus_icons() const { } -Vector2 MapItemSingleton::get_unit_position_by_province_number(int32_t province_number) const { +Vector2 MapItemSingleton::get_unit_position_by_province_number(int32_t province_number) const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); - ProvinceDefinition const* province = game_singleton->get_definition_manager().get_map_definition() - .get_province_definition_from_number(province_number); - ERR_FAIL_NULL_V_MSG(province, {}, Utilities::format("Cannot get unit position - invalid province number: %d", province_number)); + ProvinceDefinition const* province = + game_singleton->get_definition_manager().get_map_definition().get_province_definition_from_number(province_number); + ERR_FAIL_NULL_V_MSG( + province, {}, Utilities::format("Cannot get unit position - invalid province number: %d", province_number) + ); return game_singleton->normalise_map_position(province->get_unit_position()); } -Vector2 MapItemSingleton::get_port_position_by_province_number(int32_t province_number) const { +Vector2 MapItemSingleton::get_port_position_by_province_number(int32_t province_number) const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); - ProvinceDefinition const* province = game_singleton->get_definition_manager().get_map_definition() - .get_province_definition_from_number(province_number); - ERR_FAIL_NULL_V_MSG(province, {}, Utilities::format("Cannot get port position - invalid province number: %d", province_number)); - ERR_FAIL_COND_V_MSG(!province->has_port(), {},Utilities::format("Cannot get port position, province has no port, number: %d", province_number) ); - - BuildingType const* port_building_type = game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager().get_port_building_type(); + ProvinceDefinition const* province = + game_singleton->get_definition_manager().get_map_definition().get_province_definition_from_number(province_number); + ERR_FAIL_NULL_V_MSG( + province, {}, Utilities::format("Cannot get port position - invalid province number: %d", province_number) + ); + ERR_FAIL_COND_V_MSG( + !province->has_port(), {}, + Utilities::format("Cannot get port position, province has no port, number: %d", province_number) + ); + + BuildingType const* port_building_type = + game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager().get_port_building_type(); fvec2_t const* port_position = province->get_building_position(port_building_type); - //no null check because province->has_port() condition passed, already verifying that this isn't null + // no null check because province->has_port() condition passed, already verifying that this isn't null return game_singleton->normalise_map_position(*port_position); } -static constexpr real_t port_radius = 0.0006_real; //how close we have to click for a detection +static constexpr real_t port_radius = 0.0006_real; // how close we have to click for a detection -//Searches provinces near the one clicked and attempts to find a port within the port_radius of the click position +// Searches provinces near the one clicked and attempts to find a port within the port_radius of the click position int32_t MapItemSingleton::get_clicked_port_province_number(Vector2 click_position) const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); int32_t initial_province_number = game_singleton->get_province_number_from_uv_coords(click_position); - ProvinceDefinition const* province = game_singleton->get_definition_manager().get_map_definition() - .get_province_definition_from_number(initial_province_number); - ERR_FAIL_NULL_V_MSG(province, {}, Utilities::format("Cannot get port position - invalid province number: %d", initial_province_number)); + ProvinceDefinition const* province = + game_singleton->get_definition_manager().get_map_definition().get_province_definition_from_number( + initial_province_number + ); + ERR_FAIL_NULL_V_MSG( + province, {}, Utilities::format("Cannot get port position - invalid province number: %d", initial_province_number) + ); + + BuildingType const* port_building_type = + game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager().get_port_building_type(); - BuildingType const* port_building_type = game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager().get_port_building_type(); - - if(province->has_port()){ + if (province->has_port()) { Vector2 port_position = game_singleton->normalise_map_position(*province->get_building_position(port_building_type)); - if(click_position.distance_to(port_position) <= port_radius){ + if (click_position.distance_to(port_position) <= port_radius) { return province->get_province_number(); } - } - else if(province->is_water()){ + } else if (province->is_water()) { // search the adjacent provinces for ones with ports - for(ProvinceDefinition::adjacency_t const& adjacency : province->get_adjacencies()) { + for (ProvinceDefinition::adjacency_t const& adjacency : province->get_adjacencies()) { ProvinceDefinition const& adjacent_province = adjacency.get_to(); - if(!adjacent_province.has_port()) { + if (!adjacent_province.has_port()) { continue; // skip provinces without ports (ie. other water provinces) } - Vector2 port_position = game_singleton->normalise_map_position(*adjacent_province.get_building_position(port_building_type)); - if(click_position.distance_to(port_position) <= port_radius){ + Vector2 port_position = + game_singleton->normalise_map_position(*adjacent_province.get_building_position(port_building_type)); + if (click_position.distance_to(port_position) <= port_radius) { return adjacent_province.get_province_number(); } } } return 0; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/singletons/MapItemSingleton.hpp b/extension/src/openvic-extension/singletons/MapItemSingleton.hpp index e2ec3b4c..fc20a3a8 100644 --- a/extension/src/openvic-extension/singletons/MapItemSingleton.hpp +++ b/extension/src/openvic-extension/singletons/MapItemSingleton.hpp @@ -2,10 +2,11 @@ #include #include + #include #include -//billboards, projections, and progress bar (no progress bar yet) +// billboards, projections, and progress bar (no progress bar yet) namespace OpenVic { class MapItemSingleton : public godot::Object { @@ -23,11 +24,15 @@ namespace OpenVic { ~MapItemSingleton(); private: - void add_billboard_dict(GFX::Billboard const& billboard, godot::TypedArray& billboard_dict_array) const; + void add_billboard_dict( + GFX::Billboard const& billboard, godot::TypedArray& billboard_dict_array // + ) const; godot::TypedArray get_billboards() const; - void add_projection_dict(GFX::Projection const& projection, godot::TypedArray& projection_dict_array) const; - godot::TypedArray get_projections() const; + void add_projection_dict( + GFX::Projection const& projection, godot::TypedArray& projection_dict_array + ) const; + godot::TypedArray get_projections() const; godot::PackedVector2Array get_province_positions() const; int32_t get_max_capital_count() const; diff --git a/extension/src/openvic-extension/singletons/MenuSingleton.cpp b/extension/src/openvic-extension/singletons/MenuSingleton.cpp index 4c1afbb2..596079fa 100644 --- a/extension/src/openvic-extension/singletons/MenuSingleton.cpp +++ b/extension/src/openvic-extension/singletons/MenuSingleton.cpp @@ -1,35 +1,34 @@ #include "MenuSingleton.hpp" #include -#include #include #include #include +#include #include #include -#include -#include #include +#include #include +#include + #include "openvic-extension/classes/GFXPieChartTexture.hpp" #include "openvic-extension/classes/GUINode.hpp" #include "openvic-extension/components/budget/BudgetMenu.hpp" +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" #include "openvic-extension/singletons/PlayerSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/Utilities.hpp" using namespace godot; using namespace OpenVic; MenuSingleton::population_menu_t::population_menu_t() -: pop_type_sort_cache { create_empty }, -province_sort_cache { create_empty }, -rebel_type_sort_cache { create_empty } {} + : pop_type_sort_cache { create_empty }, province_sort_cache { create_empty }, rebel_type_sort_cache { create_empty } {} StringName const& MenuSingleton::_signal_population_menu_province_list_changed() { static const StringName signal_population_menu_province_list_changed = "population_menu_province_list_changed"; @@ -56,23 +55,13 @@ StringName const& MenuSingleton::_signal_update_tooltip() { String MenuSingleton::_make_modifier_effect_value( ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ) const { - return Utilities::make_modifier_effect_value( - *this, - format_effect, - value, - plus_for_non_negative - ); + return Utilities::make_modifier_effect_value(*this, format_effect, value, plus_for_non_negative); } String MenuSingleton::_make_modifier_effect_value_coloured( ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ) const { - return Utilities::make_modifier_effect_value_coloured( - *this, - format_effect, - value, - plus_for_non_negative - ); + return Utilities::make_modifier_effect_value_coloured(*this, format_effect, value, plus_for_non_negative); } String MenuSingleton::_make_modifier_effects_tooltip(ModifierValue const& modifier) const { @@ -91,16 +80,16 @@ String MenuSingleton::_make_modifier_effects_tooltip(ModifierValue const& modifi template requires std::same_as || std::same_as String MenuSingleton::_make_modifier_effect_contributions_tooltip( - T const& modifier_sum, ModifierEffect const& effect, fixed_point_t* effect_value, - String const& prefix, String const& suffix + T const& modifier_sum, ModifierEffect const& effect, fixed_point_t* effect_value, String const& prefix, String const& suffix ) const { String result; modifier_sum.for_each_contributing_modifier( effect, - [this, &effect, effect_value, &prefix, &suffix, &result]( - modifier_entry_t const& modifier_entry, fixed_point_t value - ) -> void { + [ // + this, &effect, effect_value, &prefix, &suffix, + &result // + ](modifier_entry_t const& modifier_entry, fixed_point_t value) -> void { using enum Modifier::modifier_type_t; if (effect_value != nullptr) { @@ -137,15 +126,13 @@ template String OpenVic::MenuSingleton::_make_modifier_effect_contributions_tool String MenuSingleton::_make_rules_tooltip(RuleSet const& rules) const { static const StringName yes_key = "YES"; static const StringName no_key = "NO"; - static const String line_format = "\n%s: "+GUILabel::get_colour_marker()+"%s%s"+GUILabel::get_colour_marker()+"!"; + static const String line_format = "\n%s: " + GUILabel::get_colour_marker() + "%s%s" + GUILabel::get_colour_marker() + "!"; String result; for (auto const& [rule_localisation_key, is_enabled] : rules.get_localisation_keys_and_values()) { const bool is_bad_to_enable = rule_localisation_key == "RULE_SLAVERY_ALLOWED"; result += Utilities::format( - line_format, - tr(convert_to(rule_localisation_key)), - is_bad_to_enable ? "R" : "G", + line_format, tr(convert_to(rule_localisation_key)), is_bad_to_enable ? "R" : "G", tr(is_enabled ? yes_key : no_key) ); } @@ -183,26 +170,21 @@ String MenuSingleton::_make_mobilisation_impact_tooltip() const { const String impact_string = Utilities::fixed_point_to_string_dp(country.get_mobilisation_impact() * 100, 1) + "%"; - return tr( - mobilisation_impact_tooltip_localisation_key - ).replace( - mobilisation_impact_tooltip_replace_impact_key, impact_string - ).replace( - mobilisation_impact_tooltip_replace_policy_key, tr( - war_policy_issue != nullptr - ? StringName { convert_to(war_policy_issue->get_identifier()) } - : no_issue - ) - ).replace( - mobilisation_impact_tooltip_replace_units_key, - String::num_uint64(country.get_mobilisation_max_regiment_count()) - ) + "\n" + tr( - mobilisation_impact_tooltip2_localisation_key - ).replace( - mobilisation_impact_tooltip2_replace_curr_key, String::num_uint64(country.get_regiment_count()) - ).replace( - mobilisation_impact_tooltip2_replace_impact_key, impact_string - ); + return tr(mobilisation_impact_tooltip_localisation_key) + .replace(mobilisation_impact_tooltip_replace_impact_key, impact_string) + .replace( + mobilisation_impact_tooltip_replace_policy_key, + tr(war_policy_issue != nullptr ? StringName { convert_to(war_policy_issue->get_identifier()) } + : no_issue) + ) + .replace( + mobilisation_impact_tooltip_replace_units_key, + String::num_uint64(country.get_mobilisation_max_regiment_count()) + ) + + "\n" + + tr(mobilisation_impact_tooltip2_localisation_key) + .replace(mobilisation_impact_tooltip2_replace_curr_key, String::num_uint64(country.get_regiment_count())) + .replace(mobilisation_impact_tooltip2_replace_impact_key, impact_string); } void MenuSingleton::_bind_methods() { @@ -216,8 +198,8 @@ void MenuSingleton::_bind_methods() { OV_BIND_METHOD(MenuSingleton::hide_tooltip); ADD_SIGNAL(MethodInfo( - _signal_update_tooltip(), PropertyInfo(Variant::STRING, "text"), - PropertyInfo(Variant::DICTIONARY, "substitution_dict"), PropertyInfo(Variant::VECTOR2, "position") + _signal_update_tooltip(), PropertyInfo(Variant::STRING, "text"), PropertyInfo(Variant::DICTIONARY, "substitution_dict"), + PropertyInfo(Variant::VECTOR2, "position") )); /* PROVINCE OVERVIEW PANEL */ @@ -361,7 +343,7 @@ String MenuSingleton::get_country_name_from_identifier(String const& country_ide ); ERR_FAIL_NULL_V(country, {}); - return Utilities::get_country_name(*this,*country); + return Utilities::get_country_name(*this, *country); } String MenuSingleton::get_country_adjective_from_identifier(String const& country_identifier) const { @@ -380,7 +362,7 @@ String MenuSingleton::get_country_adjective_from_identifier(String const& countr ); ERR_FAIL_NULL_V(country, {}); - return Utilities::get_country_adjective(*this,*country); + return Utilities::get_country_adjective(*this, *country); } /* TOOLTIP */ @@ -404,9 +386,7 @@ void MenuSingleton::hide_tooltip() { /* PROVINCE OVERVIEW PANEL */ -static TypedArray _make_buildings_dict_array( - ProvinceInstance const* province -) { +static TypedArray _make_buildings_dict_array(ProvinceInstance const* province) { std::span buildings = province->get_buildings(); if (buildings.empty()) { @@ -438,8 +418,8 @@ static TypedArray _make_buildings_dict_array( } } else { UtilityFunctions::push_error( - "Failed to resize buildings array to the correct size (", static_cast(buildings.size()), - ") for province ", convert_to(province->get_identifier()) + "Failed to resize buildings array to the correct size (", static_cast(buildings.size()), ") for province ", + convert_to(province->get_identifier()) ); } @@ -487,7 +467,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) State const* state = province->get_state(); if (state != nullptr) { - ret[province_info_state_key] = Utilities::get_state_name(*this,*state); + ret[province_info_state_key] = Utilities::get_state_name(*this, *state); } ret[province_info_slave_status_key] = province->get_slave(); @@ -507,8 +487,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) ret[province_info_terrain_type_tooltip_key] = Utilities::format( terrain_type_template_string, tr(terrain_type_localisation_key).replace(terrain_type_replace_key, tr(terrain_type_string)), - tr(movement_cost_localisation_key), - Utilities::fixed_point_to_string_dp(terrain_type->get_movement_cost(), 2), + tr(movement_cost_localisation_key), Utilities::fixed_point_to_string_dp(terrain_type->get_movement_cost(), 2), _make_modifier_effects_tooltip(*terrain_type) ); @@ -524,9 +503,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const StringName controller_localisation_key = "PV_CONTROLLER"; static const String controller_template_string = "%s %s"; ret[province_info_controller_tooltip_key] = Utilities::format( - controller_template_string, - tr(controller_localisation_key), - Utilities::get_country_name(*this,*controller) + controller_template_string, tr(controller_localisation_key), Utilities::get_country_name(*this, *controller) ); } @@ -552,12 +529,11 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) ModifierEffectCache const& modifier_effect_cache = game_singleton->get_definition_manager().get_modifier_manager().get_modifier_effect_cache(); - fixed_point_t output_from_workers = 1, throughput_from_workers = 0, - output_multiplier = 1, throughput_multiplier = 1; + fixed_point_t output_from_workers = 1, throughput_from_workers = 0, output_multiplier = 1, throughput_multiplier = 1; String size_string, output_string, throughput_string; - static const String employee_effect_template_string = "\n -%s: " + GUILabel::get_colour_marker() + "Y%s" + - GUILabel::get_colour_marker() + "!: %s"; + static const String employee_effect_template_string = + "\n -%s: " + GUILabel::get_colour_marker() + "Y%s" + GUILabel::get_colour_marker() + "!: %s"; using enum Job::effect_t; @@ -569,17 +545,17 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) if (unlikely(state == nullptr)) { spdlog::error_s( - "Province \"{}\" has no state, preventing calculation of state-wide population proportion of RGO owner pop type \"{}\"", + "Province \"{}\" has no state, preventing calculation of state-wide population proportion of RGO owner pop " + "type \"{}\"", *province, owner_pop_type ); } else { const fixed_point_t effect_value = state->get_total_population() == 0 ? fixed_point_t::_0 : fp::mul_div( - owner_job->effect_multiplier, - state->get_population_by_type()[owner_pop_type_index], - state->get_total_population() - ); + owner_job->effect_multiplier, state->get_population_by_type()[owner_pop_type_index], + state->get_total_population() + ); static const StringName owners_localisation_key = "PRODUCTION_FACTOR_OWNER"; @@ -587,8 +563,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) case OUTPUT: output_multiplier += effect_value; output_string += Utilities::format( - employee_effect_template_string, - tr(owners_localisation_key), + employee_effect_template_string, tr(owners_localisation_key), tr(convert_to(owner_pop_type.get_identifier())), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_rgo_output_country(), effect_value, true @@ -598,35 +573,33 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) case THROUGHPUT: throughput_multiplier += effect_value; throughput_string += Utilities::format( - employee_effect_template_string, - tr(owners_localisation_key), + employee_effect_template_string, tr(owners_localisation_key), tr(convert_to(owner_pop_type.get_identifier())), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_rgo_throughput_country(), effect_value, true ) ); break; - default: - break; + default: break; } } } String amount_of_employees_by_pop_type; - for (pop_type_index_t pop_type_index {}; pop_type_index < rgo.get_employee_count_per_type_cache().size(); ++pop_type_index) { + for (pop_type_index_t pop_type_index {}; pop_type_index < rgo.get_employee_count_per_type_cache().size(); + ++pop_type_index) { const pop_size_t employees_of_type = rgo.get_employee_count_per_type_cache()[pop_type_index]; if (employees_of_type <= 0) { continue; } - static const String amount_of_employees_by_pop_type_template_string = "\n -" + GUILabel::get_colour_marker() + - "Y%s" + GUILabel::get_colour_marker() + "!:%d"; + static const String amount_of_employees_by_pop_type_template_string = + "\n -" + GUILabel::get_colour_marker() + "Y%s" + GUILabel::get_colour_marker() + "!:%d"; PopType const& pop_type = GameSingleton::get_singleton()->get_pop_type(pop_type_index); amount_of_employees_by_pop_type += Utilities::format( - amount_of_employees_by_pop_type_template_string, - tr(convert_to(pop_type.get_identifier())), + amount_of_employees_by_pop_type_template_string, tr(convert_to(pop_type.get_identifier())), type_safe::get(employees_of_type) ); @@ -644,30 +617,27 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const StringName workers_localisation_key = "PRODUCTION_FACTOR_WORKER"; switch (job.effect_type) { - case OUTPUT: - output_from_workers += effect_value; - output_string += Utilities::format( - employee_effect_template_string, - tr(workers_localisation_key), - tr(convert_to(pop_type.get_identifier())), - _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_rgo_output_country(), effect_value, true - ) - ); - break; - case THROUGHPUT: - throughput_from_workers += effect_value; - throughput_string += Utilities::format( - employee_effect_template_string, - tr(workers_localisation_key), - tr(convert_to(pop_type.get_identifier())), - _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_rgo_throughput_country(), effect_value, true - ) - ); - break; - default: - break; + case OUTPUT: + output_from_workers += effect_value; + output_string += Utilities::format( + employee_effect_template_string, tr(workers_localisation_key), + tr(convert_to(pop_type.get_identifier())), + _make_modifier_effect_value_coloured( + *modifier_effect_cache.get_rgo_output_country(), effect_value, true + ) + ); + break; + case THROUGHPUT: + throughput_from_workers += effect_value; + throughput_string += Utilities::format( + employee_effect_template_string, tr(workers_localisation_key), + tr(convert_to(pop_type.get_identifier())), + _make_modifier_effect_value_coloured( + *modifier_effect_cache.get_rgo_throughput_country(), effect_value, true + ) + ); + break; + default: break; } } } @@ -732,8 +702,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) if (size_from_terrain != fixed_point_t::_0) { size_string = Utilities::format( - size_modifier_template_string, - tr(convert_to(province->get_terrain_type()->get_identifier())), + size_modifier_template_string, tr(convert_to(province->get_terrain_type()->get_identifier())), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_farm_rgo_size_local(), size_from_terrain, false ) @@ -744,8 +713,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const StringName rgo_size_localisation_key = "RGO_SIZE"; size_string += Utilities::format( - size_modifier_template_string, - tr(rgo_size_localisation_key), + size_modifier_template_string, tr(rgo_size_localisation_key), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_farm_rgo_size_local(), size_from_province, false ) @@ -755,8 +723,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) ModifierEffectCache::good_effects_t const& good_effects = modifier_effect_cache.get_good_effects(production_type.output_good); - fixed_point_t output_from_tech = - province->get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) + + fixed_point_t output_from_tech = province->get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) + province->get_modifier_effect_value(*good_effects.get_rgo_goods_output()); fixed_point_t throughput_from_tech = province->get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_tech()) + @@ -786,9 +753,11 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) if (size_from_tech != fixed_point_t::_0) { static const StringName from_technology_localisation_key = "employ_from_tech"; - size_string += tr(from_technology_localisation_key) + _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_farm_rgo_size_global(), size_from_tech, false - ); + size_string += // + tr(from_technology_localisation_key) + + _make_modifier_effect_value_coloured( + *modifier_effect_cache.get_farm_rgo_size_global(), size_from_tech, false + ); } static const String tech_modifier_template_string = modifier_effect_contributions_prefix + String { "%s: %s" }; @@ -799,11 +768,8 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const StringName rgo_output_tech_localisation_key = "RGO_OUTPUT_TECH"; output_string += Utilities::format( - tech_modifier_template_string, - tr(rgo_output_tech_localisation_key), - _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_rgo_output_tech(), output_from_tech, true - ) + tech_modifier_template_string, tr(rgo_output_tech_localisation_key), + _make_modifier_effect_value_coloured(*modifier_effect_cache.get_rgo_output_tech(), output_from_tech, true) ); } @@ -813,8 +779,7 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const StringName rgo_throughput_tech_localisation_key = "RGO_THROUGHPUT_TECH"; throughput_string += Utilities::format( - tech_modifier_template_string, - tr(rgo_throughput_tech_localisation_key), + tech_modifier_template_string, tr(rgo_throughput_tech_localisation_key), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_rgo_throughput_tech(), throughput_from_tech, true ) @@ -845,20 +810,17 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) ret[province_info_rgo_production_tooltip_key] = Utilities::format( rgo_production_template_string, - tr(rgo_production_localisation_key).replace( - rgo_good_replace_key, tr(convert_to(rgo_good.get_identifier())) - ).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(rgo.get_revenue_yesterday(), 3) - ), + tr(rgo_production_localisation_key) + .replace(rgo_good_replace_key, tr(convert_to(rgo_good.get_identifier()))) + .replace( + Utilities::get_long_value_placeholder(), Utilities::fixed_point_to_string_dp(rgo.get_revenue_yesterday(), 3) + ), tr(max_output_localisation_key).replace(curr_replace_key, Utilities::fixed_point_to_string_dp(max_output, 2)), tr(output_explanation_localisation_key), tr(base_output_localisation_key).replace(base_replace_key, Utilities::fixed_point_to_string_dp(base_output, 2)), tr(output_efficiency_localisation_key), _make_modifier_effect_value_coloured(*modifier_effect_cache.get_rgo_output_country(), output_efficiency, false), - tr(base_localisation_key), - output_string, - tr(throughput_efficiency_localisation_key), + tr(base_localisation_key), output_string, tr(throughput_efficiency_localisation_key), _make_modifier_effect_value_coloured( *modifier_effect_cache.get_rgo_throughput_country(), throughput_efficiency, false ), @@ -871,22 +833,17 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) static const String employee_max_replace_key = "$EMPLOYEE_MAX$"; static const StringName rgo_workforce_localisation_key = "BASE_RGO_SIZE"; static const StringName province_size_localisation_key = "FROM_PROV_SIZE"; - static const String rgo_employment_template_string = "%s" + get_tooltip_separator() + "%s%s\n%s%d\n%s\n%s" + - GUILabel::get_colour_marker() + "G%d"; + static const String rgo_employment_template_string = + "%s" + get_tooltip_separator() + "%s%s\n%s%d\n%s\n%s" + GUILabel::get_colour_marker() + "G%d"; ret[province_info_rgo_employment_tooltip_key] = Utilities::format( rgo_employment_template_string, tr(employment_localisation_key).replace(Utilities::get_long_value_placeholder(), {}), - tr(employee_count_localisation_key).replace( - employee_replace_key, String::num_int64(type_safe::get(rgo.get_total_employees_count_cache())) - ).replace( - employee_max_replace_key, String::num_int64(type_safe::get(rgo.get_max_employee_count_cache())) - ), - amount_of_employees_by_pop_type, - tr(rgo_workforce_localisation_key), - type_safe::get(production_type.base_workforce_size), - size_string, - tr(province_size_localisation_key), + tr(employee_count_localisation_key) + .replace(employee_replace_key, String::num_int64(type_safe::get(rgo.get_total_employees_count_cache()))) + .replace(employee_max_replace_key, String::num_int64(type_safe::get(rgo.get_max_employee_count_cache()))), + amount_of_employees_by_pop_type, tr(rgo_workforce_localisation_key), + type_safe::get(production_type.base_workforce_size), size_string, tr(province_size_localisation_key), static_cast(rgo.get_size_multiplier()) // TODO - remove cast once variable is an int32_t ); } @@ -900,15 +857,11 @@ Dictionary MenuSingleton::get_province_info_from_number(int32_t province_number) ret[province_info_total_population_key] = type_safe::get(province->get_total_population()); const auto make_pie_chart_tooltip = // - [this]( - auto const& key, String const& identifier, float weight, float total_weight // - ) -> String { + [ // + this // + ](auto const& key, String const& identifier, float weight, float total_weight) -> String { static const String format_key = "%d%% %s"; - return Utilities::format( - format_key, - static_cast(100.0f * weight / total_weight), - tr(identifier) - ); + return Utilities::format(format_key, static_cast(100.0f * weight / total_weight), tr(identifier)); }; GFXPieChartTexture::godot_pie_chart_data_t pop_types = @@ -972,8 +925,11 @@ String MenuSingleton::get_province_building_identifier(int32_t building_index) c GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, {}); - const forwardable_span> province_building_types = game_singleton->get_definition_manager() - .get_economy_manager().get_building_type_manager().get_province_building_types(); + const forwardable_span> province_building_types = + game_singleton->get_definition_manager() + .get_economy_manager() + .get_building_type_manager() + .get_province_building_types(); ERR_FAIL_COND_V_MSG( building_index < 0 || building_index >= province_building_types.size(), {}, Utilities::format("Invalid province building index: %d", building_index) @@ -1003,7 +959,8 @@ int32_t MenuSingleton::get_rgo_owner_pop_icon_index() const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, 0); - const pop_sprite_t sprite = game_singleton->get_definition_manager().get_economy_manager().get_production_type_manager().get_rgo_owner_sprite(); + const pop_sprite_t sprite = + game_singleton->get_definition_manager().get_economy_manager().get_production_type_manager().get_rgo_owner_sprite(); ERR_FAIL_COND_V_MSG(sprite <= 0, 0, "RGO owner sprite unset!"); return sprite; } @@ -1057,13 +1014,22 @@ Dictionary MenuSingleton::get_topbar_info() const { String current_tech_localised = tr(convert_to(current_research->get_identifier())); - ret[research_tooltip_key] = tr(research_localisation_key).replace( - tech_replace_key, current_tech_localised - ).replace( - date_replace_key, Utilities::date_to_formatted_string(country.get_expected_research_completion_date_untracked(), false) - ) + "\n" + tr(research_invested_localisation_key).replace( - invested_replace_key, String::num_uint64(country.get_invested_research_points_untracked().truncate()) - ).replace(cost_replace_key, String::num_uint64(country.get_current_research_cost_untracked().truncate())); + ret[research_tooltip_key] = + tr(research_localisation_key) + .replace(tech_replace_key, current_tech_localised) + .replace( + date_replace_key, + Utilities::date_to_formatted_string(country.get_expected_research_completion_date_untracked(), false) + ) + + "\n" + + tr(research_invested_localisation_key) + .replace( + invested_replace_key, + String::num_uint64(country.get_invested_research_points_untracked().truncate()) + ) + .replace( + cost_replace_key, String::num_uint64(country.get_current_research_cost_untracked().truncate()) + ); ret[research_key] = std::move(current_tech_localised); @@ -1102,21 +1068,23 @@ Dictionary MenuSingleton::get_topbar_info() const { daily_base_research_points += research_points; - research_points_tooltip += tr(pop_type_research_localisation_key).replace( - pop_type_replace_key, tr(convert_to(pop_type->get_identifier())) - ).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(research_points, 2) - ).replace( - fraction_replace_key, Utilities::fixed_point_to_string_dp( - fp::from_fraction( - 100 * country.get_population_by_type()[pop_type->index], - country.get_total_population() - ), 2 - ) - ).replace( - optimal_replace_key, Utilities::fixed_point_to_string_dp(100 * pop_type->research_leadership_optimum, 2) - ) + "\n"; + research_points_tooltip += + tr(pop_type_research_localisation_key) + .replace(pop_type_replace_key, tr(convert_to(pop_type->get_identifier()))) + .replace(Utilities::get_long_value_placeholder(), Utilities::fixed_point_to_string_dp(research_points, 2)) + .replace( + fraction_replace_key, + Utilities::fixed_point_to_string_dp( + fp::from_fraction( + 100 * country.get_population_by_type()[pop_type->index], country.get_total_population() + ), + 2 + ) + ) + .replace( + optimal_replace_key, Utilities::fixed_point_to_string_dp(100 * pop_type->research_leadership_optimum, 2) + ) + + "\n"; } // Empty prefix, "\n" suffix, fitting with the potential trailing "\n" from the pop type contributions and the upcoming @@ -1129,40 +1097,44 @@ Dictionary MenuSingleton::get_topbar_info() const { // so this line has no newline characters of its own. Instead, potential lines above finish with newlines and // potential (and some guaranteed) lines below start with them. static const StringName daily_base_research_points_localisation_key = "TECH_DAILY_RESEARCHPOINTS_BASE_TOOLTIP"; - research_points_tooltip += tr(daily_base_research_points_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(daily_base_research_points, 2) - ); + research_points_tooltip += + tr(daily_base_research_points_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), Utilities::fixed_point_to_string_dp(daily_base_research_points, 2) + ); - research_points_tooltip += _make_modifier_effect_contributions_tooltip( - country, *modifier_effect_cache.get_research_points_modifier() - ); + research_points_tooltip += + _make_modifier_effect_contributions_tooltip(country, *modifier_effect_cache.get_research_points_modifier()); - const fixed_point_t research_points_modifier_from_tech = country.get_modifier_effect_value( - *modifier_effect_cache.get_increase_research() - ); + const fixed_point_t research_points_modifier_from_tech = + country.get_modifier_effect_value(*modifier_effect_cache.get_increase_research()); if (research_points_modifier_from_tech != fixed_point_t::_0) { static const StringName from_technology_localisation_key = "FROM_TECHNOLOGY"; - research_points_tooltip += "\n" + tr(from_technology_localisation_key) + ": " + + research_points_tooltip += + "\n" + tr(from_technology_localisation_key) + ": " + _make_modifier_effect_value_coloured( *modifier_effect_cache.get_increase_research(), research_points_modifier_from_tech, true ); } static const StringName daily_research_points_localisation_key = "TECH_DAILY_RESEARCHPOINTS_TOTAL_TOOLTIP"; - research_points_tooltip += "\n" + tr(daily_research_points_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(country.get_daily_research_points_untracked(), 2) - ); + research_points_tooltip += "\n" + + tr(daily_research_points_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::fixed_point_to_string_dp(country.get_daily_research_points_untracked(), 2) + ); // In the base game this section is only shown when no research is set, but it's useful to show it always research_points_tooltip += "\n" + get_tooltip_separator(); static const StringName accumulated_research_points_localisation_key = "RP_ACCUMULATED"; - research_points_tooltip += tr(accumulated_research_points_localisation_key).replace( - Utilities::get_short_value_placeholder(), - Utilities::fixed_point_to_string_dp(country.get_research_point_stockpile_untracked(), 1) - ); + research_points_tooltip += + tr(accumulated_research_points_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::fixed_point_to_string_dp(country.get_research_point_stockpile_untracked(), 1) + ); ret[research_points_tooltip_key] = std::move(research_points_tooltip); } @@ -1211,21 +1183,23 @@ Dictionary MenuSingleton::get_topbar_info() const { monthly_base_leadership_points += leadership_points; - leadership_tooltip += tr(pop_type_leadership_localisation_key).replace( - pop_type_replace_key, tr(convert_to(pop_type->get_identifier())) - ).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(leadership_points, 2) - ).replace( - fraction_replace_key, Utilities::fixed_point_to_string_dp( - fp::from_fraction( - 100 * country.get_population_by_type()[pop_type->index], - country.get_total_population() - ), 2 - ) - ).replace( - optimal_replace_key, Utilities::fixed_point_to_string_dp(100 * pop_type->research_leadership_optimum, 2) - ) + "\n"; + leadership_tooltip += + tr(pop_type_leadership_localisation_key) + .replace(pop_type_replace_key, tr(convert_to(pop_type->get_identifier()))) + .replace(Utilities::get_long_value_placeholder(), Utilities::fixed_point_to_string_dp(leadership_points, 2)) + .replace( + fraction_replace_key, + Utilities::fixed_point_to_string_dp( + fp::from_fraction( + 100 * country.get_population_by_type()[pop_type->index], country.get_total_population() + ), + 2 + ) + ) + .replace( + optimal_replace_key, Utilities::fixed_point_to_string_dp(100 * pop_type->research_leadership_optimum, 2) + ) + + "\n"; } // Empty prefix, "\n" suffix, fitting with the potential trailing "\n" from the pop type contributions and the upcoming @@ -1238,20 +1212,22 @@ Dictionary MenuSingleton::get_topbar_info() const { // so this line has no newline characters of its own. Instead, potential lines above finish with newlines and // potential (and some guaranteed) lines below start with them. static const StringName monthly_base_leadership_localisation_key = "TECH_DAILY_LEADERSHIP_BASE_TOOLTIP"; - leadership_tooltip += tr(monthly_base_leadership_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(monthly_base_leadership_points, 2) - ); + leadership_tooltip += tr(monthly_base_leadership_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::fixed_point_to_string_dp(monthly_base_leadership_points, 2) + ); - leadership_tooltip += _make_modifier_effect_contributions_tooltip( - country, *modifier_effect_cache.get_leadership_modifier() - ); + leadership_tooltip += + _make_modifier_effect_contributions_tooltip(country, *modifier_effect_cache.get_leadership_modifier()); static const StringName monthly_leadership_points_localisation_key = "TECH_DAILY_LEADERSHIP_TOTAL_TOOLTIP"; - leadership_tooltip += "\n" + tr(monthly_leadership_points_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp(country.get_monthly_leadership_points(), 2) - ); + leadership_tooltip += "\n" + + tr(monthly_leadership_points_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::fixed_point_to_string_dp(country.get_monthly_leadership_points(), 2) + ); const fixed_point_t max_leadership_point_stockpile = definition_manager.get_define_manager().get_military_defines().get_max_leadership_point_stockpile(); @@ -1260,9 +1236,10 @@ Dictionary MenuSingleton::get_topbar_info() const { static const StringName max_leadership_points_localisation_key = "TOPBAR_LEADERSHIP_MAX"; static const String max_replace_key = "$MAX$"; - leadership_tooltip += tr(max_leadership_points_localisation_key).trim_suffix("\n").replace( - max_replace_key, Utilities::fixed_point_to_string_dp(max_leadership_point_stockpile, 1) - ); + leadership_tooltip += + tr(max_leadership_points_localisation_key) + .trim_suffix("\n") + .replace(max_replace_key, Utilities::fixed_point_to_string_dp(max_leadership_point_stockpile, 1)); } ret[leadership_tooltip_key] = std::move(leadership_tooltip); @@ -1281,9 +1258,7 @@ void MenuSingleton::link_top_bar_to_cpp(GUINode const* const godot_top_bar) { unlink_top_bar_from_cpp(); } - top_bar = memory::make_unique( - *godot_top_bar - ); + top_bar = memory::make_unique(*godot_top_bar); GameSingleton::get_singleton()->gamestate_updated.connect(&TopBar::update, top_bar.get()); } void MenuSingleton::unlink_top_bar_from_cpp() { @@ -1358,14 +1333,10 @@ void MenuSingleton::link_budget_menu_to_cpp(GUINode const* const godot_budget_me } auto const& strata_keys = game_singleton.get_definition_manager().get_pop_manager().get_stratas(); - ModifierEffectCache const& modifier_effect_cache = game_singleton.get_definition_manager().get_modifier_manager().get_modifier_effect_cache(); + ModifierEffectCache const& modifier_effect_cache = + game_singleton.get_definition_manager().get_modifier_manager().get_modifier_effect_cache(); CountryDefines const& country_defines = game_singleton.get_definition_manager().get_define_manager().get_country_defines(); - budget_menu = memory::make_unique( - *godot_budget_menu, - strata_keys, - modifier_effect_cache, - country_defines - ); + budget_menu = memory::make_unique(*godot_budget_menu, strata_keys, modifier_effect_cache, country_defines); game_singleton.gamestate_updated.connect(&BudgetMenu::update, budget_menu.get()); } @@ -1400,33 +1371,36 @@ Error MenuSingleton::generate_search_cache() { String display_name = tr(GUINode::format_province_name(identifier)); String search_name = display_name.to_lower(); - search_panel.entry_cache.push_back({ - &province, std::move(display_name), std::move(search_name), identifier.to_lower() - }); + search_panel.entry_cache.push_back( + { &province, std::move(display_name), std::move(search_name), identifier.to_lower() } + ); } for (StateSet const& state_set : state_sets) { for (State const& state : state_set.get_states()) { - String display_name = Utilities::get_state_name(*this,state); + String display_name = Utilities::get_state_name(*this, state); String search_name = display_name.to_lower(); - search_panel.entry_cache.push_back({ - // TODO - include state identifier? (region and/or split?) - &state, std::move(display_name), std::move(search_name), {} - }); + search_panel.entry_cache.push_back( + { // TODO - include state identifier? (region and/or split?) + &state, + std::move(display_name), + std::move(search_name), + {} } + ); } } for (CountryInstance const& country : countries) { // TODO - replace with a proper "exists" check if (country.get_capital() != nullptr) { - String display_name = Utilities::get_country_name(*this,country); + String display_name = Utilities::get_country_name(*this, country); String search_name = display_name.to_lower(); - search_panel.entry_cache.push_back({ - &country, std::move(display_name), std::move(search_name), - convert_to(country.get_identifier()).to_lower() - }); + search_panel.entry_cache.push_back( + { &country, std::move(display_name), std::move(search_name), + convert_to(country.get_identifier()).to_lower() } + ); } } diff --git a/extension/src/openvic-extension/singletons/MenuSingleton.hpp b/extension/src/openvic-extension/singletons/MenuSingleton.hpp index d5cf237a..886ae613 100644 --- a/extension/src/openvic-extension/singletons/MenuSingleton.hpp +++ b/extension/src/openvic-extension/singletons/MenuSingleton.hpp @@ -9,10 +9,10 @@ #include #include -#include #include #include #include +#include #include "openvic-extension/classes/GFXPieChartTexture.hpp" #include "openvic-extension/components/budget/BudgetMenu.hpp" @@ -42,14 +42,33 @@ namespace OpenVic { static inline MenuSingleton* singleton = nullptr; public: - enum ProvinceListEntry { - LIST_ENTRY_NONE, LIST_ENTRY_COUNTRY, LIST_ENTRY_STATE, LIST_ENTRY_PROVINCE + enum ProvinceListEntry { // + LIST_ENTRY_NONE, + LIST_ENTRY_COUNTRY, + LIST_ENTRY_STATE, + LIST_ENTRY_PROVINCE }; enum PopSortKey { - SORT_NONE, SORT_SIZE, SORT_TYPE, SORT_CULTURE, SORT_RELIGION, SORT_LOCATION, SORT_MILITANCY, SORT_CONSCIOUSNESS, - SORT_IDEOLOGY, SORT_ISSUES, SORT_UNEMPLOYMENT, SORT_CASH, SORT_LIFE_NEEDS, SORT_EVERYDAY_NEEDS, - SORT_LUXURY_NEEDS, SORT_REBEL_FACTION, SORT_SIZE_CHANGE, SORT_LITERACY, MAX_SORT_KEY + SORT_NONE, + SORT_SIZE, + SORT_TYPE, + SORT_CULTURE, + SORT_RELIGION, + SORT_LOCATION, + SORT_MILITANCY, + SORT_CONSCIOUSNESS, + SORT_IDEOLOGY, + SORT_ISSUES, + SORT_UNEMPLOYMENT, + SORT_CASH, + SORT_LIFE_NEEDS, + SORT_EVERYDAY_NEEDS, + SORT_LUXURY_NEEDS, + SORT_REBEL_FACTION, + SORT_SIZE_CHANGE, + SORT_LITERACY, + MAX_SORT_KEY }; struct population_menu_t { @@ -107,7 +126,10 @@ namespace OpenVic { }; enum TradeSettingBit { - TRADE_SETTING_NONE = 0, TRADE_SETTING_AUTOMATED = 1, TRADE_SETTING_BUYING = 2, TRADE_SETTING_SELLING = 4 + TRADE_SETTING_NONE = 0, + TRADE_SETTING_AUTOMATED = 1, + TRADE_SETTING_BUYING = 2, + TRADE_SETTING_SELLING = 4 }; ordered_map cached_leader_dicts; @@ -142,7 +164,7 @@ namespace OpenVic { static godot::StringName const& _signal_update_tooltip(); godot::String _make_modifier_effect_value( - ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative + ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative // ) const; godot::String _make_modifier_effect_value_coloured( @@ -180,7 +202,7 @@ namespace OpenVic { /* TOOLTIP */ void show_tooltip( - godot::String const& text, godot::Dictionary const& substitution_dict, godot::Vector2 const& position + godot::String const& text, godot::Dictionary const& substitution_dict, godot::Vector2 const& position // ); void show_control_tooltip( godot::String const& text, godot::Dictionary const& substitution_dict, godot::Control const* control @@ -225,7 +247,8 @@ namespace OpenVic { godot::Error population_menu_select_sort_key(PopSortKey sort_key); template GFXPieChartTexture::godot_pie_chart_data_t generate_population_menu_pop_row_pie_chart_data( - std::span> keys, std::span> values, godot::String const& identifier_suffix = {} + std::span> keys, std::span> values, + godot::String const& identifier_suffix = {} ) const; template GFXPieChartTexture::godot_pie_chart_data_t generate_population_menu_pop_row_pie_chart_data( @@ -248,28 +271,23 @@ namespace OpenVic { /* TRADE MENU */ godot::Dictionary get_trade_menu_good_categories_info() const; godot::Dictionary get_trade_menu_trade_details_info( - int32_t trade_detail_good_index, GUIScrollbar* stockpile_cutoff_slider + int32_t trade_detail_good_index, GUIScrollbar* stockpile_cutoff_slider // ) const; godot::Dictionary get_trade_menu_tables_info() const; static int32_t calculate_slider_value_from_trade_menu_stockpile_cutoff( - const fixed_point_t stockpile_cutoff, - const int32_t max_slider_value + const fixed_point_t stockpile_cutoff, const int32_t max_slider_value ) { // Math.log(2)/Math.log(Math.exp(Math.log(2001)/2000)) = 182.37... constexpr fixed_point_t DOUBLES_AFTER_STEPS = fixed_point_t::parse_raw(11952029); int32_t times_halved = 0; - fixed_point_t copy_plus_one = stockpile_cutoff+1; + fixed_point_t copy_plus_one = stockpile_cutoff + 1; while (copy_plus_one >= 2) { copy_plus_one /= 2; times_halved++; } int32_t slider_value = times_halved * DOUBLES_AFTER_STEPS.truncate(); - while ( - calculate_trade_menu_stockpile_cutoff_amount_fp( - slider_value - ) < stockpile_cutoff - ) { + while (calculate_trade_menu_stockpile_cutoff_amount_fp(slider_value) < stockpile_cutoff) { if (slider_value >= max_slider_value) { return max_slider_value; } diff --git a/extension/src/openvic-extension/singletons/MilitaryMenu.cpp b/extension/src/openvic-extension/singletons/MilitaryMenu.cpp index 9f50f649..b55674b1 100644 --- a/extension/src/openvic-extension/singletons/MilitaryMenu.cpp +++ b/extension/src/openvic-extension/singletons/MilitaryMenu.cpp @@ -1,5 +1,3 @@ -#include "MenuSingleton.hpp" - #include #include @@ -13,6 +11,8 @@ #include "openvic-extension/singletons/PlayerSingleton.hpp" #include "openvic-extension/utility/Utilities.hpp" +#include "MenuSingleton.hpp" + using namespace OpenVic; using namespace godot; @@ -120,9 +120,11 @@ Dictionary MenuSingleton::make_leader_dict(LeaderInstance const& leader) { static const StringName prestige_localisation_key = "PRESTIGE_SCORE"; - String prestige_tooltip = tr(prestige_localisation_key).replace( - Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(prestige * 100, 2) + "%" - ); + String prestige_tooltip = + tr(prestige_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(prestige * 100, 2) + "%" + ); tooltip += "\n" + prestige_tooltip; @@ -135,13 +137,20 @@ Dictionary MenuSingleton::make_leader_dict(LeaderInstance const& leader) { static const StringName morale_localisation_key = "PRESTIGE_MORALE_BONUS"; static const StringName organisation_localisation_key = "PRESTIGE_MAX_ORG_BONUS"; - prestige_tooltip += "\n" + tr(morale_localisation_key).replace( - Utilities::get_short_value_placeholder(), - _make_modifier_effect_value_coloured(morale_effect, modifier_value.get_effect(morale_effect), true) - ) + "\n" + tr(organisation_localisation_key).replace( - Utilities::get_short_value_placeholder(), - _make_modifier_effect_value_coloured(organisation_effect, modifier_value.get_effect(organisation_effect), true) - ); + prestige_tooltip += "\n" + + tr(morale_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + _make_modifier_effect_value_coloured(morale_effect, modifier_value.get_effect(morale_effect), true) + ) + + "\n" + + tr(organisation_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + _make_modifier_effect_value_coloured( + organisation_effect, modifier_value.get_effect(organisation_effect), true + ) + ); leader_dict[military_info_leader_prestige_key] = static_cast(prestige); leader_dict[military_info_leader_prestige_tooltip_key] = std::move(prestige_tooltip); @@ -162,9 +171,7 @@ Dictionary MenuSingleton::make_leader_dict(LeaderInstance const& leader) { static const StringName background_localisation_key = "MILITARY_BACKGROUND"; static const String background_replace_key = "$NAME$"; - tooltip += "\n" + tr(background_localisation_key).replace( - background_replace_key, background - ); + tooltip += "\n" + tr(background_localisation_key).replace(background_replace_key, background); leader_dict[military_info_leader_background_key] = std::move(background); } @@ -184,9 +191,7 @@ Dictionary MenuSingleton::make_leader_dict(LeaderInstance const& leader) { static const StringName personality_localisation_key = "MILITARY_PERSONALITY"; static const String personality_replace_key = "$NAME$"; - tooltip += "\n" + tr(personality_localisation_key).replace( - personality_replace_key, personality - ); + tooltip += "\n" + tr(personality_localisation_key).replace(personality_replace_key, personality); leader_dict[military_info_leader_personality_key] = std::move(personality); } @@ -210,16 +215,16 @@ template Dictionary MenuSingleton::make_unit_group_dict(UnitInstanceGroupBranched const& unit_group) { static const StringName military_info_unit_group_leader_picture_key = "unit_group_leader_picture"; static const StringName military_info_unit_group_leader_tooltip_key = "unit_group_leader_tooltip"; - static const StringName military_info_unit_group_name_key = "unit_group_name"; - static const StringName military_info_unit_group_location_key = "unit_group_location"; - static const StringName military_info_unit_group_unit_count_key = "unit_group_unit_count"; - static const StringName military_info_unit_group_men_count_key = "unit_group_men_count"; // armies only - static const StringName military_info_unit_group_max_men_count_key = "unit_group_max_men_count"; // armies only - static const StringName military_info_unit_group_organisation_key = "unit_group_organisation"; - static const StringName military_info_unit_group_strength_key = "unit_group_strength"; + static const StringName military_info_unit_group_name_key = "unit_group_name"; + static const StringName military_info_unit_group_location_key = "unit_group_location"; + static const StringName military_info_unit_group_unit_count_key = "unit_group_unit_count"; + static const StringName military_info_unit_group_men_count_key = "unit_group_men_count"; // armies only + static const StringName military_info_unit_group_max_men_count_key = "unit_group_max_men_count"; // armies only + static const StringName military_info_unit_group_organisation_key = "unit_group_organisation"; + static const StringName military_info_unit_group_strength_key = "unit_group_strength"; static const StringName military_info_unit_group_moving_tooltip_key = "unit_group_moving_tooltip"; - static const StringName military_info_unit_group_dig_in_tooltip_key = "unit_group_dig_in_tooltip"; // armies only - static const StringName military_info_unit_group_combat_key = "unit_group_combat"; + static const StringName military_info_unit_group_dig_in_tooltip_key = "unit_group_dig_in_tooltip"; // armies only + static const StringName military_info_unit_group_combat_key = "unit_group_combat"; using enum unit_branch_t; @@ -251,12 +256,15 @@ Dictionary MenuSingleton::make_unit_group_dict(UnitInstanceGroupBranched ProvinceInstance const* destination = unit_group.get_movement_destination_province(); - unit_group_dict[military_info_unit_group_moving_tooltip_key] = tr(moving_localisation_key).replace( - moving_location_replace_key, - tr(GUINode::format_province_name( - destination != nullptr ? convert_to(destination->get_identifier()) : String {}, false - )) - ).replace(moving_date_replace_key, Utilities::date_to_string(unit_group.get_movement_arrival_date())); + unit_group_dict[military_info_unit_group_moving_tooltip_key] = + tr(moving_localisation_key) + .replace( + moving_location_replace_key, + tr(GUINode::format_province_name( + destination != nullptr ? convert_to(destination->get_identifier()) : String {}, false + )) + ) + .replace(moving_date_replace_key, Utilities::date_to_string(unit_group.get_movement_arrival_date())); } if constexpr (Branch == LAND) { @@ -270,9 +278,8 @@ Dictionary MenuSingleton::make_unit_group_dict(UnitInstanceGroupBranched static const StringName dig_in_localisation_key = "MILITARY_DIGIN_TOOLTIP"; static const String moving_days_replace_key = "$DAYS$"; - unit_group_dict[military_info_unit_group_dig_in_tooltip_key] = tr(dig_in_localisation_key).replace( - moving_days_replace_key, String::num_uint64(dig_in_level) - ); + unit_group_dict[military_info_unit_group_dig_in_tooltip_key] = + tr(dig_in_localisation_key).replace(moving_days_replace_key, String::num_uint64(dig_in_level)); } } @@ -304,16 +311,19 @@ Dictionary MenuSingleton::make_in_progress_unit_dict() const { const ordered_map> required_goods { { good_definition_manager.get_good_definition_by_index(good_index_t(0)), - { fixed_point_t(1234) / 100, fixed_point_t(1900) / 100 } - }, { + { fixed_point_t(1234) / 100, fixed_point_t(1900) / 100 } // + }, + { good_definition_manager.get_good_definition_by_index(good_index_t(1)), - { fixed_point_t(888) / 100, fixed_point_t(1444) / 100 } - }, { + { fixed_point_t(888) / 100, fixed_point_t(1444) / 100 } // + }, + { good_definition_manager.get_good_definition_by_index(good_index_t(2)), - { fixed_point_t(1622) / 100, fixed_point_t(1622) / 100 } - }, { + { fixed_point_t(1622) / 100, fixed_point_t(1622) / 100 } // + }, + { good_definition_manager.get_good_definition_by_index(good_index_t(3)), - { fixed_point_t(211) / 100, fixed_point_t(805) / 100 } + { fixed_point_t(211) / 100, fixed_point_t(805) / 100 } // } }; @@ -387,9 +397,8 @@ Dictionary MenuSingleton::get_military_menu_info() { static const String war_exhaustion_template_string = "%s/%s"; const String war_exhaustion_string = Utilities::fixed_point_to_string_dp(country->get_war_exhaustion(), 2); const String max_war_exhaustion_string = Utilities::fixed_point_to_string_dp(country->get_war_exhaustion_max(), 2); - ret[military_info_war_exhaustion_key] = Utilities::format( - war_exhaustion_template_string, war_exhaustion_string, max_war_exhaustion_string - ); + ret[military_info_war_exhaustion_key] = + Utilities::format(war_exhaustion_template_string, war_exhaustion_string, max_war_exhaustion_string); static const StringName war_exhaution_localisation_key = "MILITARY_WAR_EXHAUSTION_TOOLTIP"; static const StringName max_war_exhaution_localisation_key = "MILITARY_MAX_WAR_EXHAUSTION_TOOLTIP"; @@ -398,15 +407,9 @@ Dictionary MenuSingleton::get_military_menu_info() { ret[military_info_war_exhaustion_tooltip_key] = Utilities::format( war_exhaustion_tooltip_template_string, - tr(war_exhaution_localisation_key).replace( - Utilities::get_long_value_placeholder(), - war_exhaustion_string - ), + tr(war_exhaution_localisation_key).replace(Utilities::get_long_value_placeholder(), war_exhaustion_string), _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_war_exhaustion_monthly()), - tr(max_war_exhaution_localisation_key).replace( - Utilities::get_long_value_placeholder(), - max_war_exhaustion_string - ), + tr(max_war_exhaution_localisation_key).replace(Utilities::get_long_value_placeholder(), max_war_exhaustion_string), _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_max_war_exhaustion()), tr(current_effects_localisation_key), _make_modifier_effects_tooltip(static_modifier_cache.get_war_exhaustion() * country->get_war_exhaustion()) @@ -427,13 +430,11 @@ Dictionary MenuSingleton::get_military_menu_info() { String organisation_regain_tooltip = base_value_percent_tooltip; const fixed_point_t morale = country->get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); if (morale != fixed_point_t::_0) { - organisation_regain_tooltip += from_technology_tooltip + _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_morale_global(), morale, true - ); + organisation_regain_tooltip += from_technology_tooltip + + _make_modifier_effect_value_coloured(*modifier_effect_cache.get_morale_global(), morale, true); } - organisation_regain_tooltip += _make_modifier_effect_contributions_tooltip( - *country, *modifier_effect_cache.get_org_regain() - ); + organisation_regain_tooltip += + _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_org_regain()); ret[military_info_organisation_regain_tooltip_key] = std::move(organisation_regain_tooltip); } @@ -450,20 +451,19 @@ Dictionary MenuSingleton::get_military_menu_info() { { static const StringName base_value_localisation_key = "MILITARY_BASEVALUE"; String unit_start_experience_tooltip = tr(base_value_localisation_key); - const fixed_point_t regular_experience_level = country->get_modifier_effect_value( - *modifier_effect_cache.get_regular_experience_level() - ); + const fixed_point_t regular_experience_level = + country->get_modifier_effect_value(*modifier_effect_cache.get_regular_experience_level()); if (regular_experience_level != fixed_point_t::_0) { - unit_start_experience_tooltip += from_technology_tooltip + _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_regular_experience_level(), regular_experience_level, true - ); + unit_start_experience_tooltip += + from_technology_tooltip + + _make_modifier_effect_value_coloured( + *modifier_effect_cache.get_regular_experience_level(), regular_experience_level, true + ); } - const String land_unit_start_experience_tooltip = _make_modifier_effect_contributions_tooltip( - *country, *modifier_effect_cache.get_land_unit_start_experience() - ); - const String naval_unit_start_experience_tooltip = _make_modifier_effect_contributions_tooltip( - *country, *modifier_effect_cache.get_naval_unit_start_experience() - ); + const String land_unit_start_experience_tooltip = + _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_land_unit_start_experience()); + const String naval_unit_start_experience_tooltip = + _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_naval_unit_start_experience()); unit_start_experience_tooltip += land_unit_start_experience_tooltip; if (!land_unit_start_experience_tooltip.is_empty() && !naval_unit_start_experience_tooltip.is_empty()) { unit_start_experience_tooltip += "\n"; @@ -473,21 +473,22 @@ Dictionary MenuSingleton::get_military_menu_info() { } ret[military_info_recruit_time_key] = static_cast(country->get_recruit_time()); - ret[military_info_recruit_time_tooltip_key] = base_value_percent_tooltip + _make_modifier_effect_contributions_tooltip( - *country, *modifier_effect_cache.get_unit_recruitment_time() - ); + ret[military_info_recruit_time_tooltip_key] = base_value_percent_tooltip + + _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_unit_recruitment_time()); ret[military_info_combat_width_key] = type_safe::get(country->get_combat_width()); { static const StringName base_value_combat_width_localisation_key = "COMWID_BASE"; - String combat_width_tooltip = tr(base_value_combat_width_localisation_key).replace( - Utilities::get_short_value_placeholder(), String::num_uint64( - type_safe::get(definition_manager.get_define_manager().get_military_defines().get_base_combat_width()) - ) - ); - const fixed_point_t combat_width = country->get_modifier_effect_value( - *modifier_effect_cache.get_combat_width_additive() - ); + String combat_width_tooltip = + tr(base_value_combat_width_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + String::num_uint64( + type_safe::get(definition_manager.get_define_manager().get_military_defines().get_base_combat_width()) + ) + ); + const fixed_point_t combat_width = + country->get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()); if (combat_width != fixed_point_t::_0) { combat_width_tooltip += from_technology_tooltip + GUILabel::get_colour_marker() + "G" + String::num_int64(combat_width.truncate()); @@ -516,32 +517,34 @@ Dictionary MenuSingleton::get_military_menu_info() { static const StringName mobilisation_size_tooltip_localisation_key = "MOB_SIZE_IRO"; static const StringName mobilisation_size_tech_tooltip_localisation_key = "MOB_FROM_TECH"; - const fixed_point_t mobilisation_size_from_tech = country->get_modifier_effect_value( - *modifier_effect_cache.get_mobilisation_size_tech() - ); - - String military_info_mobilisation_size_tooltip = tr(mobilisation_size_tooltip_localisation_key).replace( - Utilities::get_long_value_placeholder(), - Utilities::fixed_point_to_string_dp( - ( - country->get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_size_country()) + - mobilisation_size_from_tech - ) * 100, 2 - ) - ); + const fixed_point_t mobilisation_size_from_tech = + country->get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_size_tech()); + + String military_info_mobilisation_size_tooltip = + tr(mobilisation_size_tooltip_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + Utilities::fixed_point_to_string_dp( + (country->get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_size_country()) + + mobilisation_size_from_tech) * + 100, + 2 + ) + ); if (mobilisation_size_from_tech != fixed_point_t::_0) { - military_info_mobilisation_size_tooltip += "\n" + tr(mobilisation_size_tech_tooltip_localisation_key).replace( - Utilities::get_long_value_placeholder(), - _make_modifier_effect_value_coloured( - *modifier_effect_cache.get_mobilisation_size_country(), mobilisation_size_from_tech, false - ) - ); + military_info_mobilisation_size_tooltip += "\n" + + tr(mobilisation_size_tech_tooltip_localisation_key) + .replace( + Utilities::get_long_value_placeholder(), + _make_modifier_effect_value_coloured( + *modifier_effect_cache.get_mobilisation_size_country(), mobilisation_size_from_tech, false + ) + ); } - military_info_mobilisation_size_tooltip += _make_modifier_effect_contributions_tooltip( - *country, *modifier_effect_cache.get_mobilisation_size_country() - ); + military_info_mobilisation_size_tooltip += + _make_modifier_effect_contributions_tooltip(*country, *modifier_effect_cache.get_mobilisation_size_country()); ret[military_info_mobilisation_size_tooltip_key] = std::move(military_info_mobilisation_size_tooltip); } @@ -557,24 +560,23 @@ Dictionary MenuSingleton::get_military_menu_info() { *country, *modifier_effect_cache.get_mobilisation_economy_impact_country() ); - const fixed_point_t research_contribution = country->get_modifier_effect_value( - *modifier_effect_cache.get_mobilisation_economy_impact_tech() - ); + const fixed_point_t research_contribution = + country->get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_tech()); if (research_contribution != fixed_point_t::_0) { static const StringName research_contribution_negative_key = "MOB_ECO_IMPACT"; static const StringName research_contribution_positive_key = "MOB_ECO_PENALTY"; - mobilisation_economy_impact_tooltip = tr( - research_contribution < fixed_point_t::_0 - ? research_contribution_negative_key - : research_contribution_positive_key - ).replace( - Utilities::get_long_value_placeholder(), - _make_modifier_effect_value( - *modifier_effect_cache.get_mobilisation_economy_impact_tech(), research_contribution.abs(), false - ) - ) + mobilisation_economy_impact_tooltip; + mobilisation_economy_impact_tooltip = + tr(research_contribution < fixed_point_t::_0 ? research_contribution_negative_key + : research_contribution_positive_key) + .replace( + Utilities::get_long_value_placeholder(), + _make_modifier_effect_value( + *modifier_effect_cache.get_mobilisation_economy_impact_tech(), research_contribution.abs(), false + ) + ) + + mobilisation_economy_impact_tooltip; } else if (!mobilisation_economy_impact_tooltip.is_empty()) { // Remove leading newline mobilisation_economy_impact_tooltip = mobilisation_economy_impact_tooltip.substr(1); diff --git a/extension/src/openvic-extension/singletons/ModelSingleton.cpp b/extension/src/openvic-extension/singletons/ModelSingleton.cpp index d85bf1ba..31fa9a1f 100644 --- a/extension/src/openvic-extension/singletons/ModelSingleton.cpp +++ b/extension/src/openvic-extension/singletons/ModelSingleton.cpp @@ -8,10 +8,11 @@ #include #include #include +#include +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/utility/Utilities.hpp" using namespace godot; @@ -54,15 +55,16 @@ GFX::Actor const* ModelSingleton::get_actor(std::string_view name, bool error_on } GFX::Actor const* ModelSingleton::get_cultural_actor( - std::string_view culture, std::string_view name, std::string_view fallback_name + std::string_view culture, std::string_view name, std::string_view fallback_name // ) const { GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, nullptr); ERR_FAIL_COND_V_MSG( - culture.empty() || name.empty(), nullptr, Utilities::format( - "Failed to find actor \"%s\" for culture \"%s\" - neither can be empty", - convert_to(name), convert_to(culture) + culture.empty() || name.empty(), nullptr, + Utilities::format( + "Failed to find actor \"%s\" for culture \"%s\" - neither can be empty", convert_to(name), + convert_to(culture) ) ); @@ -73,9 +75,9 @@ GFX::Actor const* ModelSingleton::get_cultural_actor( // Which should be tried first: "Generic***" or "***Infantry"? if (actor == nullptr) { + CultureManager const& manager = game_singleton->get_definition_manager().get_pop_manager().get_culture_manager(); /* If no Actor exists for the specified GraphicalCultureType then try the default instead. */ - GraphicalCultureType const* default_graphical_culture_type = game_singleton->get_definition_manager().get_pop_manager() - .get_culture_manager().get_default_graphical_culture_type(); + GraphicalCultureType const* default_graphical_culture_type = manager.get_default_graphical_culture_type(); if (default_graphical_culture_type != nullptr && default_graphical_culture_type->get_identifier() != culture) { actor_name = append_string_views(default_graphical_culture_type->get_identifier(), name); @@ -89,9 +91,9 @@ GFX::Actor const* ModelSingleton::get_cultural_actor( } ERR_FAIL_NULL_V_MSG( - actor, nullptr, Utilities::format( - "Failed to find actor \"%s\" for culture \"%s\"", convert_to(name), - convert_to(culture) + actor, nullptr, + Utilities::format( + "Failed to find actor \"%s\" for culture \"%s\"", convert_to(name), convert_to(culture) ) ); @@ -162,10 +164,10 @@ Dictionary ModelSingleton::get_model_dict(GFX::Actor const& actor) { GFX::Actor const* attachment_actor = get_actor(attachment.get_actor_name()); ERR_CONTINUE_MSG( - attachment_actor == nullptr, Utilities::format( + attachment_actor == nullptr, + Utilities::format( "Failed to find \"%s\" attachment actor for actor \"%s\"", - convert_to(attachment.get_actor_name()), - convert_to(actor.get_name()) + convert_to(attachment.get_actor_name()), convert_to(actor.get_name()) ) ); @@ -175,7 +177,6 @@ Dictionary ModelSingleton::get_model_dict(GFX::Actor const& actor) { attachment_dict[attachment_model_key] = get_model_dict(*attachment_actor); attachments_array[idx] = std::move(attachment_dict); - } if (!attachments_array.is_empty()) { @@ -199,8 +200,7 @@ Dictionary ModelSingleton::get_model_dict(GFX::Actor const& actor) { * Returning true doesn't necessarily mean a unit was added, e.g. when units is empty. */ template bool ModelSingleton::add_unit_dict( - std::span>> units, - TypedArray& unit_array + std::span>> units, TypedArray& unit_array ) { using _UnitInstanceGroup = UnitInstanceGroupBranched; @@ -234,9 +234,8 @@ bool ModelSingleton::add_unit_dict( GraphicalCultureType const& graphical_culture_type = country_definition.graphical_culture; UnitType const* display_unit_type = unit.get_display_unit_type(); ERR_FAIL_NULL_V_MSG( - display_unit_type, false, Utilities::format( - "Failed to get display unit type for unit \"%s\"", convert_to(unit.get_name()) - ) + display_unit_type, false, + Utilities::format("Failed to get display unit type for unit \"%s\"", convert_to(unit.get_name())) ); std::string_view actor_name = display_unit_type->get_sprite(); @@ -267,15 +266,14 @@ bool ModelSingleton::add_unit_dict( // TODO - default without requiring hardcoded name static constexpr std::string_view default_fallback_actor_name = "Infantry"; - GFX::Actor const* actor = get_cultural_actor( - graphical_culture_type.get_identifier(), actor_name, default_fallback_actor_name - ); + GFX::Actor const* actor = + get_cultural_actor(graphical_culture_type.get_identifier(), actor_name, default_fallback_actor_name); ERR_FAIL_NULL_V_MSG( - actor, false, Utilities::format( + actor, false, + Utilities::format( "Failed to find \"%s\" actor of graphical culture type \"%s\" for unit \"%s\"", - convert_to(display_unit_type->get_sprite()), - convert_to(graphical_culture_type.get_identifier()), + convert_to(display_unit_type->get_sprite()), convert_to(graphical_culture_type.get_identifier()), convert_to(unit.get_name()) ) ); @@ -293,12 +291,13 @@ bool ModelSingleton::add_unit_dict( dict[mount_model_key] = get_model_dict(*mount_actor); dict[mount_attach_node_key] = convert_to(mount_attach_node_name); } else { - UtilityFunctions::push_error(Utilities::format( - "Failed to find \"%s\" mount actor of graphical culture type \"%s\" for unit \"%s\"", - convert_to(mount_actor_name), - convert_to(graphical_culture_type.get_identifier()), - convert_to(unit.get_name()) - )); + UtilityFunctions::push_error( + Utilities::format( + "Failed to find \"%s\" mount actor of graphical culture type \"%s\" for unit \"%s\"", + convert_to(mount_actor_name), convert_to(graphical_culture_type.get_identifier()), + convert_to(unit.get_name()) + ) + ); ret = false; } } @@ -310,9 +309,7 @@ bool ModelSingleton::add_unit_dict( dict[flag_floating_key] = true; } - dict[position_key] = game_singleton->normalise_map_position( - unit.get_location().province_definition.get_unit_position() - ); + dict[position_key] = game_singleton->normalise_map_position(unit.get_location().province_definition.get_unit_position()); if (display_unit_type->unit_category != UnitType::unit_category_t::INFANTRY) { dict[rotation_key] = -0.25f * std::numbers::pi_v; @@ -402,10 +399,9 @@ bool ModelSingleton::add_building_dict( std::string suffix; - if ( - &building.building_type == - game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager().get_port_building_type() - ) { + BuildingTypeManager const& manager = + game_singleton->get_definition_manager().get_economy_manager().get_building_type_manager(); + if (&building.building_type == manager.get_port_building_type()) { /* Port */ if (!province_definition.has_port()) { return true; @@ -439,10 +435,10 @@ bool ModelSingleton::add_building_dict( GFX::Actor const* actor = get_actor(actor_name); ERR_FAIL_NULL_V_MSG( - actor, false, Utilities::format( - "Failed to find \"%s\" actor for building \"%s\" in province \"%s\"", - convert_to(actor_name), convert_to(building.get_identifier()), - convert_to(province.get_identifier()) + actor, false, + Utilities::format( + "Failed to find \"%s\" actor for building \"%s\" in province \"%s\"", convert_to(actor_name), + convert_to(building.get_identifier()), convert_to(province.get_identifier()) ) ); @@ -450,9 +446,8 @@ bool ModelSingleton::add_building_dict( dict[model_key] = get_model_dict(*actor); - dict[position_key] = game_singleton->normalise_map_position( - position_ptr != nullptr ? *position_ptr : province_definition.get_centre() - ); + dict[position_key] = + game_singleton->normalise_map_position(position_ptr != nullptr ? *position_ptr : province_definition.get_centre()); if (rotation != 0.0f) { dict[rotation_key] = rotation; @@ -477,8 +472,8 @@ TypedArray ModelSingleton::get_buildings() { for (BuildingInstance const& building : province.get_buildings()) { if (!add_building_dict(building, province, ret)) { UtilityFunctions::push_error( - "Error adding building \"", convert_to(building.get_identifier()), - "\" to province \"", convert_to(province.get_identifier()), "\"" + "Error adding building \"", convert_to(building.get_identifier()), "\" to province \"", + convert_to(province.get_identifier()), "\"" ); } } diff --git a/extension/src/openvic-extension/singletons/ModelSingleton.hpp b/extension/src/openvic-extension/singletons/ModelSingleton.hpp index 1517c443..4c67e4ef 100644 --- a/extension/src/openvic-extension/singletons/ModelSingleton.hpp +++ b/extension/src/openvic-extension/singletons/ModelSingleton.hpp @@ -30,7 +30,7 @@ namespace OpenVic { private: GFX::Actor const* get_actor(std::string_view name, bool error_on_fail = true) const; GFX::Actor const* get_cultural_actor( - std::string_view culture, std::string_view name, std::string_view fallback_name + std::string_view culture, std::string_view name, std::string_view fallback_name // ) const; using animation_map_t = deque_ordered_map; diff --git a/extension/src/openvic-extension/singletons/PlayerSingleton.cpp b/extension/src/openvic-extension/singletons/PlayerSingleton.cpp index 0c39f614..77285f26 100644 --- a/extension/src/openvic-extension/singletons/PlayerSingleton.cpp +++ b/extension/src/openvic-extension/singletons/PlayerSingleton.cpp @@ -7,9 +7,9 @@ #include #include "openvic-extension/classes/GUIScrollbar.hpp" +#include "openvic-extension/core/Bind.hpp" #include "openvic-extension/singletons/GameSingleton.hpp" #include "openvic-extension/singletons/MenuSingleton.hpp" -#include "openvic-extension/core/Bind.hpp" using namespace OpenVic; using namespace godot; @@ -98,17 +98,13 @@ void PlayerSingleton::set_player_country(CountryInstance* new_player_country) { ERR_FAIL_NULL(instance_manager); if (player_country != nullptr) { - instance_manager->queue_game_action( - player_country->index, true - ); + instance_manager->queue_game_action(player_country->index, true); } player_country = new_player_country; if (player_country != nullptr) { - instance_manager->queue_game_action( - player_country->index, false - ); + instance_manager->queue_game_action(player_country->index, false); } SPDLOG_INFO("Set player country to: {}", ovfmt::validate(player_country)); @@ -120,7 +116,8 @@ void PlayerSingleton::set_player_country_by_province_number(int32_t province_num InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - ProvinceInstance* province_instance = instance_manager->get_map_instance().get_province_instance_from_number(province_number); + ProvinceInstance* province_instance = + instance_manager->get_map_instance().get_province_instance_from_number(province_number); ERR_FAIL_NULL(province_instance); set_player_country(province_instance->get_owner()); @@ -174,9 +171,8 @@ void PlayerSingleton::unset_selected_province() { } int32_t PlayerSingleton::get_selected_province_number() const { - return selected_province == nullptr - ? ProvinceDefinition::NULL_PROVINCE_NUMBER - : selected_province->province_definition.get_province_number(); + return selected_province == nullptr ? ProvinceDefinition::NULL_PROVINCE_NUMBER + : selected_province->province_definition.get_province_number(); } // Core @@ -184,9 +180,7 @@ void PlayerSingleton::toggle_paused() const { InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - instance_manager->queue_game_action( - !instance_manager->get_simulation_clock().is_paused() - ); + instance_manager->queue_game_action(!instance_manager->get_simulation_clock().is_paused()); } void PlayerSingleton::increase_speed() const { @@ -216,22 +210,20 @@ void PlayerSingleton::expand_selected_province_building(int32_t province_buildin ERR_FAIL_NULL(player_country); instance_manager->queue_game_action( - player_country->index, - selected_province->index, - province_building_index_t(province_building_index) + player_country->index, selected_province->index, province_building_index_t(province_building_index) ); } // Budget #define SET_SLIDER_GAME_ACTION_EXPLICIT(value_name, argument_name) \ -void PlayerSingleton::set_##value_name##_slider_value(fixed_point_t const value) const { \ - if (player_country == nullptr) { \ - return; \ - } \ - GameSingleton::get_singleton()->get_instance_manager()->queue_game_action( \ - player_country->index, value \ - ); \ -} + void PlayerSingleton::set_##value_name##_slider_value(fixed_point_t const value) const { \ + if (player_country == nullptr) { \ + return; \ + } \ + GameSingleton::get_singleton()->get_instance_manager()->queue_game_action( \ + player_country->index, value \ + ); \ + } #define SET_SLIDER_GAME_ACTION(value_name) SET_SLIDER_GAME_ACTION_EXPLICIT(value_name, value_name) SET_SLIDER_GAME_ACTION(administration_spending) @@ -303,9 +295,7 @@ void PlayerSingleton::set_can_use_leader(uint64_t leader_id, bool can_use) const InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - instance_manager->queue_game_action( - unique_id_t(leader_id), can_use - ); + instance_manager->queue_game_action(unique_id_t(leader_id), can_use); } void PlayerSingleton::set_auto_create_leaders(bool value) const { @@ -314,9 +304,7 @@ void PlayerSingleton::set_auto_create_leaders(bool value) const { InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - instance_manager->queue_game_action( - player_country->index, value - ); + instance_manager->queue_game_action(player_country->index, value); } void PlayerSingleton::set_auto_assign_leaders(bool value) const { @@ -325,9 +313,7 @@ void PlayerSingleton::set_auto_assign_leaders(bool value) const { InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - instance_manager->queue_game_action( - player_country->index, value - ); + instance_manager->queue_game_action(player_country->index, value); } void PlayerSingleton::set_mobilise(bool value) const { @@ -336,7 +322,5 @@ void PlayerSingleton::set_mobilise(bool value) const { InstanceManager* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL(instance_manager); - instance_manager->queue_game_action( - player_country->index, value - ); + instance_manager->queue_game_action(player_country->index, value); } diff --git a/extension/src/openvic-extension/singletons/PopulationMenu.cpp b/extension/src/openvic-extension/singletons/PopulationMenu.cpp index 7d33abd0..789c6aed 100644 --- a/extension/src/openvic-extension/singletons/PopulationMenu.cpp +++ b/extension/src/openvic-extension/singletons/PopulationMenu.cpp @@ -1,20 +1,19 @@ -#include "MenuSingleton.hpp" - #include #include #include -#include #include #include #include #include #include -#include #include #include #include +#include + +#include #include "openvic-extension/classes/GFXPieChartTexture.hpp" #include "openvic-extension/classes/GUINode.hpp" @@ -23,6 +22,8 @@ #include "openvic-extension/utility/MapHelpers.hpp" #include "openvic-extension/utility/Utilities.hpp" +#include "MenuSingleton.hpp" + using namespace godot; using namespace OpenVic; @@ -40,10 +41,9 @@ Error MenuSingleton::_population_menu_update_provinces() { MapInstance const& map_instance = instance_manager->get_map_instance(); - for (CountryInstance const* country : { - // Example country - instance_manager->get_country_instance_manager().get_country_instance_by_identifier("ENG") - }) { + for (CountryInstance const* country : + { // Example country + instance_manager->get_country_instance_manager().get_country_instance_by_identifier("ENG") }) { ERR_CONTINUE(country == nullptr); population_menu.province_list_entries.emplace_back(population_menu_t::country_entry_t { *country }); @@ -176,8 +176,8 @@ TypedArray MenuSingleton::get_population_menu_province_list_rows(int } } entry_visitor { *this, start, count }; - while (entry_visitor.index < population_menu.province_list_entries.size() - && std::visit(entry_visitor, population_menu.province_list_entries[entry_visitor.index])) { + while (entry_visitor.index < population_menu.province_list_entries.size() && + std::visit(entry_visitor, population_menu.province_list_entries[entry_visitor.index])) { entry_visitor.index++; } @@ -257,23 +257,21 @@ Error MenuSingleton::population_menu_select_province_list_entry(int32_t select_i } emit_signal( - _signal_population_menu_province_list_selected_changed(), - set_scroll_index ? entry_visitor.selected_visible_index : -1 + _signal_population_menu_province_list_selected_changed(), set_scroll_index ? entry_visitor.selected_visible_index : -1 ); return _population_menu_update_pops(); } Error MenuSingleton::population_menu_select_province(int32_t province_number) { - const province_index_t province_index = ProvinceDefinition::get_index_from_province_number(province_number); + const province_index_t province_index = ProvinceDefinition::get_index_from_province_number(province_number); GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, FAILED); InstanceManager const* instance_manager = game_singleton->get_instance_manager(); ERR_FAIL_NULL_V(instance_manager, FAILED); ERR_FAIL_COND_V( - !instance_manager->get_map_instance().get_province_instance_by_definition().contains_index(province_index), - FAILED + !instance_manager->get_map_instance().get_province_instance_by_definition().contains_index(province_index), FAILED ); struct entry_visitor_t { @@ -319,8 +317,8 @@ Error MenuSingleton::population_menu_select_province(int32_t province_number) { } entry_visitor { *this, province_index }; - while (entry_visitor.index < population_menu.province_list_entries.size() - && std::visit(entry_visitor, population_menu.province_list_entries[entry_visitor.index])) { + while (entry_visitor.index < population_menu.province_list_entries.size() && + std::visit(entry_visitor, population_menu.province_list_entries[entry_visitor.index])) { entry_visitor.index++; } @@ -338,12 +336,14 @@ Error MenuSingleton::population_menu_toggle_expanded(int32_t toggle_index, bool population_menu_t::state_entry_t* state_entry = std::get_if(&population_menu.province_list_entries[toggle_index]); - ERR_FAIL_NULL_V_MSG(state_entry, FAILED, Utilities::format("Cannot toggle expansion of a non-state entry! (%d)", toggle_index)); + ERR_FAIL_NULL_V_MSG( + state_entry, FAILED, Utilities::format("Cannot toggle expansion of a non-state entry! (%d)", toggle_index) + ); int32_t provinces = 0; - while (++toggle_index < population_menu.province_list_entries.size() - && std::holds_alternative(population_menu.province_list_entries[toggle_index])) { + while (++toggle_index < population_menu.province_list_entries.size() && + std::holds_alternative(population_menu.province_list_entries[toggle_index])) { provinces++; } @@ -417,7 +417,8 @@ Error MenuSingleton::_population_menu_update_filtered_pops() { ideology_index_t ideology_index {}; for (const fixed_point_t supporter_equivalents : pop.get_supporter_equivalents_by_ideology()) { if (supporter_equivalents > 0) { - population_menu.ideology_distribution[&GameSingleton::get_singleton()->get_ideology(ideology_index)] += supporter_equivalents; + population_menu.ideology_distribution[&GameSingleton::get_singleton()->get_ideology(ideology_index)] += + supporter_equivalents; ideology_distribution_running_total += supporter_equivalents; } ++ideology_index; @@ -426,14 +427,14 @@ Error MenuSingleton::_population_menu_update_filtered_pops() { population_menu.culture_distribution[&pop.culture] += pop_size; { party_policy_index_t party_policy_index {}; - for(const fixed_point_t party_policy_support : pop.get_supporter_equivalents_by_party_policy()) { + for (const fixed_point_t party_policy_support : pop.get_supporter_equivalents_by_party_policy()) { population_menu.issue_distribution[&GameSingleton::get_singleton()->get_party_policy(party_policy_index)]; ++party_policy_index; } } { reform_index_t reform_index {}; - for(const fixed_point_t reform_support : pop.get_supporter_equivalents_by_reform()) { + for (const fixed_point_t reform_support : pop.get_supporter_equivalents_by_reform()) { population_menu.issue_distribution[&GameSingleton::get_singleton()->get_reform(reform_index)]; ++reform_index; } @@ -472,10 +473,12 @@ static bool ordered_map_lookup_less_than(ordered_map const& ma } template -static ordered_map copy_non_default_to_ordered_map(IndexedFlatMap const& indexed_flat_map) { +static ordered_map copy_non_default_to_ordered_map( + IndexedFlatMap const& indexed_flat_map // +) { ordered_map result {}; for (auto const& [key, value] : indexed_flat_map) { - if constexpr(!std::is_default_constructible_v) { + if constexpr (!std::is_default_constructible_v) { result[&key] = value; } else if (value != ValueType()) { result[&key] = value; @@ -485,8 +488,7 @@ static ordered_map copy_non_default_to_ordered_map(In } static bool sort_by_ideologies_less_than( - TypedSpan lhs, - TypedSpan rhs + TypedSpan lhs, TypedSpan rhs ) { assert(lhs.size() == rhs.size()); ideology_index_t index_of_lhs_max {}, index_of_rhs_max {}; @@ -510,8 +512,7 @@ static bool sort_by_ideologies_less_than( static bool sort_by_issues_less_than( TypedSpan lhs_party_policies, TypedSpan rhs_party_policies, - TypedSpan lhs_reforms, - TypedSpan rhs_reforms + TypedSpan lhs_reforms, TypedSpan rhs_reforms ) { assert(lhs_party_policies.size() == rhs_party_policies.size()); assert(lhs_reforms.size() == rhs_reforms.size()); @@ -615,9 +616,7 @@ MenuSingleton::sort_func_t MenuSingleton::_get_population_menu_sort_func(PopSort return [this](Pop const& a, Pop const& b) -> bool { // TODO - include country adjective for [pan-]nationalist rebels // TODO - handle social/political reform movements - return indexed_map_lookup_less_than( - population_menu.rebel_type_sort_cache, a.get_rebel_type(), b.get_rebel_type() - ); + return indexed_map_lookup_less_than(population_menu.rebel_type_sort_cache, a.get_rebel_type(), b.get_rebel_type()); }; case SORT_SIZE_CHANGE: return [](Pop const& a, Pop const& b) -> bool { @@ -629,27 +628,26 @@ MenuSingleton::sort_func_t MenuSingleton::_get_population_menu_sort_func(PopSort }; default: UtilityFunctions::push_error("Invalid population menu sort key: ", sort_key); - return [](Pop const& a, Pop const& b) -> bool { return false; }; + return [](Pop const& a, Pop const& b) -> bool { + return false; + }; } } Error MenuSingleton::_population_menu_sort_pops() { if (population_menu.sort_key != SORT_NONE) { - if ( - population_menu.pop_type_sort_cache.get_keys().empty() - || population_menu.culture_sort_cache.empty() - || population_menu.religion_sort_cache.empty() - || population_menu.province_sort_cache.get_keys().empty() - || population_menu.rebel_type_sort_cache.get_keys().empty() - ) { + if (population_menu.pop_type_sort_cache.get_keys().empty() || population_menu.culture_sort_cache.empty() || + population_menu.religion_sort_cache.empty() || population_menu.province_sort_cache.get_keys().empty() || + population_menu.rebel_type_sort_cache.get_keys().empty()) { ERR_FAIL_COND_V(population_menu_update_locale_sort_cache() != OK, FAILED); } const sort_func_t base_sort_func = _get_population_menu_sort_func(population_menu.sort_key); - const sort_func_t sort_func = population_menu.sort_descending - ? base_sort_func - : [base_sort_func](Pop const& a, Pop const& b) { return base_sort_func(b, a); }; + const sort_func_t sort_func = + population_menu.sort_descending ? base_sort_func : [base_sort_func](Pop const& a, Pop const& b) { + return base_sort_func(b, a); + }; std::sort(population_menu.filtered_pops.begin(), population_menu.filtered_pops.end(), sort_func); } @@ -668,68 +666,61 @@ Error MenuSingleton::population_menu_update_locale_sort_cache() { std::vector localised_items; std::vector sorted_items; - const auto generate_sort_cache_indexed = [this, &localised_items, &sorted_items]( - IndexedFlatMap& cache, std::span items - ) { - localised_items.resize(items.size()); - sorted_items.resize(items.size()); - - for (size_t idx = 0; idx < items.size(); ++idx) { - String identifier = convert_to(items[idx].get_identifier()); - if constexpr (std::is_same_v) { - identifier = GUINode::format_province_name(identifier); + const auto generate_sort_cache_indexed = // + [ // + this, &localised_items, &sorted_items // + ](IndexedFlatMap& cache, std::span items) { + localised_items.resize(items.size()); + sorted_items.resize(items.size()); + + for (size_t idx = 0; idx < items.size(); ++idx) { + String identifier = convert_to(items[idx].get_identifier()); + if constexpr (std::is_same_v) { + identifier = GUINode::format_province_name(identifier); + } + localised_items[idx] = tr(identifier).to_lower(); + sorted_items[idx] = idx; } - localised_items[idx] = tr(identifier).to_lower(); - sorted_items[idx] = idx; - } - std::sort( - sorted_items.begin(), sorted_items.end(), [&localised_items](size_t a, size_t b) -> bool { + std::sort(sorted_items.begin(), sorted_items.end(), [&localised_items](size_t a, size_t b) -> bool { return localised_items[a] < localised_items[b]; - } - ); + }); - IndexedFlatMap sorted_cache { items }; - for (size_t idx = 0; idx < sorted_items.size(); ++idx) { - sorted_cache.at_index( - static_cast::type>( - sorted_items[idx] - ) - ) = idx; - } - cache = std::move(sorted_cache); - }; - const auto generate_sort_cache_ordered = [this, &localised_items, &sorted_items]( - ordered_map& cache, std::span items - ) { - localised_items.resize(items.size()); - sorted_items.resize(items.size()); - - for (size_t idx = 0; idx < items.size(); ++idx) { - String identifier = convert_to(items[idx].get_identifier()); - if constexpr (std::is_same_v) { - identifier = GUINode::format_province_name(identifier); + IndexedFlatMap sorted_cache { items }; + for (size_t idx = 0; idx < sorted_items.size(); ++idx) { + sorted_cache.at_index(static_cast::type>(sorted_items[idx])) = idx; + } + cache = std::move(sorted_cache); + }; + const auto generate_sort_cache_ordered = // + [ // + this, &localised_items, &sorted_items // + ](ordered_map& cache, std::span items) { + localised_items.resize(items.size()); + sorted_items.resize(items.size()); + + for (size_t idx = 0; idx < items.size(); ++idx) { + String identifier = convert_to(items[idx].get_identifier()); + if constexpr (std::is_same_v) { + identifier = GUINode::format_province_name(identifier); + } + localised_items[idx] = tr(identifier).to_lower(); + sorted_items[idx] = idx; } - localised_items[idx] = tr(identifier).to_lower(); - sorted_items[idx] = idx; - } - std::sort( - sorted_items.begin(), sorted_items.end(), [&localised_items](size_t a, size_t b) -> bool { + std::sort(sorted_items.begin(), sorted_items.end(), [&localised_items](size_t a, size_t b) -> bool { return localised_items[a] < localised_items[b]; - } - ); + }); - cache.clear(); - for (size_t i = 0; i < sorted_items.size(); ++i) { - T const* key = &items[sorted_items[i]]; - cache[key] = i; - } - }; + cache.clear(); + for (size_t i = 0; i < sorted_items.size(); ++i) { + T const* key = &items[sorted_items[i]]; + cache[key] = i; + } + }; generate_sort_cache_indexed( - population_menu.pop_type_sort_cache, - { game_singleton->get_definition_manager().get_pop_manager().get_pop_types() } + population_menu.pop_type_sort_cache, { game_singleton->get_definition_manager().get_pop_manager().get_pop_types() } ); generate_sort_cache_ordered( population_menu.culture_sort_cache, @@ -740,8 +731,7 @@ Error MenuSingleton::population_menu_update_locale_sort_cache() { { game_singleton->get_definition_manager().get_pop_manager().get_religion_manager().get_religions() } ); generate_sort_cache_indexed( - population_menu.province_sort_cache, - { instance_manager->get_map_instance().get_province_instances() } + population_menu.province_sort_cache, { instance_manager->get_map_instance().get_province_instances() } ); generate_sort_cache_indexed( population_menu.rebel_type_sort_cache, @@ -783,26 +773,26 @@ GFXPieChartTexture::godot_pie_chart_data_t MenuSingleton::generate_population_me float total_weight = 0.0f; for (const ValueType weight : values) { - if constexpr(IsPieChartValueTypeSafe) { + if constexpr (IsPieChartValueTypeSafe) { total_weight += static_cast(type_safe::get(weight)); } else { total_weight += static_cast(weight); } } - static const String pie_chart_tooltip_format_key = "%s: " + GUILabel::get_colour_marker() + "Y%s%%" + - GUILabel::get_colour_marker() + "!"; + static const String pie_chart_tooltip_format_key = + "%s: " + GUILabel::get_colour_marker() + "Y%s%%" + GUILabel::get_colour_marker() + "!"; for (size_t i = 0; i < keys.size(); ++i) { key_t key = [&]() -> key_t { - if constexpr(requires { static_cast(keys[i]); }) { + if constexpr (requires { static_cast(keys[i]); }) { return keys[i]; } else if (requires { static_cast(*keys[i]); }) { return *keys[i]; } }(); float weight; - if constexpr(IsPieChartValueTypeSafe) { + if constexpr (IsPieChartValueTypeSafe) { weight = static_cast(type_safe::get(values[i])); } else { weight = static_cast(values[i]); @@ -810,8 +800,7 @@ GFXPieChartTexture::godot_pie_chart_data_t MenuSingleton::generate_population_me if (weight > 0.0f) { String tooltip = Utilities::format( - pie_chart_tooltip_format_key, - tr(convert_to(key.get_identifier()) + identifier_suffix), + pie_chart_tooltip_format_key, tr(convert_to(key.get_identifier()) + identifier_suffix), Utilities::float_to_string_dp(100.0f * static_cast(weight) / total_weight, 1) ); full_tooltip += "\n" + tooltip; @@ -839,14 +828,11 @@ GFXPieChartTexture::godot_pie_chart_data_t MenuSingleton::generate_population_me memory::FixedVector keys { create_empty, distribution.size() }; memory::FixedVector values { create_empty, distribution.size() }; - for (auto const& [k,v] : distribution) { + for (auto const& [k, v] : distribution) { keys.emplace_back(k); values.emplace_back(v); } - return generate_population_menu_pop_row_pie_chart_data( - keys, values, - identifier_suffix - ); + return generate_population_menu_pop_row_pie_chart_data(keys, values, identifier_suffix); } TypedArray MenuSingleton::get_population_menu_pop_rows(int32_t start, int32_t count) const { @@ -854,7 +840,8 @@ TypedArray MenuSingleton::get_population_menu_pop_rows(int32_t start return {}; } ERR_FAIL_INDEX_V_MSG( - start, population_menu.filtered_pops.size(), {}, Utilities::format("Invalid start for population menu pop rows: %d", start) + start, population_menu.filtered_pops.size(), {}, + Utilities::format("Invalid start for population menu pop rows: %d", start) ); ERR_FAIL_COND_V_MSG(count <= 0, {}, Utilities::format("Invalid count for population menu pop rows: %d", count)); @@ -923,14 +910,14 @@ TypedArray MenuSingleton::get_population_menu_pop_rows(int32_t start fixed_point_map_t supporter_equivalents_by_issue; { party_policy_index_t party_policy_index {}; - for(const fixed_point_t party_policy_support : pop.get_supporter_equivalents_by_party_policy()) { + for (const fixed_point_t party_policy_support : pop.get_supporter_equivalents_by_party_policy()) { supporter_equivalents_by_issue[&GameSingleton::get_singleton()->get_party_policy(party_policy_index)]; ++party_policy_index; } } { reform_index_t reform_index {}; - for(const fixed_point_t reform_support : pop.get_supporter_equivalents_by_reform()) { + for (const fixed_point_t reform_support : pop.get_supporter_equivalents_by_reform()) { supporter_equivalents_by_issue[&GameSingleton::get_singleton()->get_reform(reform_index)]; ++reform_index; } @@ -945,12 +932,10 @@ TypedArray MenuSingleton::get_population_menu_pop_rows(int32_t start pop_dict[pop_militancy_key] = static_cast(pop.get_militancy()); pop_dict[pop_consciousness_key] = static_cast(pop.get_consciousness()); pop_dict[pop_ideology_key] = generate_population_menu_pop_row_pie_chart_data( - GameSingleton::get_singleton()->get_ideologies(), - pop.get_supporter_equivalents_by_ideology() - ); - pop_dict[pop_issues_key] = generate_population_menu_pop_row_pie_chart_data( - supporter_equivalents_by_issue, get_issue_identifier_suffix() + GameSingleton::get_singleton()->get_ideologies(), pop.get_supporter_equivalents_by_ideology() ); + pop_dict[pop_issues_key] = + generate_population_menu_pop_row_pie_chart_data(supporter_equivalents_by_issue, get_issue_identifier_suffix()); pop_dict[pop_unemployment_key] = static_cast(pop.get_unemployment_fraction()); pop_dict[pop_cash_key] = static_cast(pop.get_cash().get_copy_of_value()); pop_dict[pop_daily_money_key] = static_cast(pop.get_income()); @@ -1026,7 +1011,8 @@ TypedArray MenuSingleton::get_population_menu_pop_filter_info() cons Error MenuSingleton::population_menu_toggle_pop_filter(int32_t index) { ERR_FAIL_COND_V_MSG( - index < 0 || index >= population_menu.pop_filters.size(), FAILED, Utilities::format("Invalid pop filter index: %d", index) + index < 0 || index >= population_menu.pop_filters.size(), FAILED, + Utilities::format("Invalid pop filter index: %d", index) ); population_menu_t::pop_filter_t& filter = mutable_iterator(population_menu.pop_filters).begin()[index].second; @@ -1071,12 +1057,12 @@ Error MenuSingleton::population_menu_deselect_all_pop_filters() { PackedStringArray MenuSingleton::get_population_menu_distribution_setup_info() const { static const PackedStringArray distribution_names = []() -> PackedStringArray { constexpr std::array NAMES { - /* Workforce (PopType) */ "WORKFORCE_DISTTITLE", - /* Religion */ "RELIGION_DISTTITLE", - /* Ideology */ "IDEOLOGY_DISTTITLE", - /* Nationality (Culture) */ "NATIONALITY_DISTTITLE", + /* Workforce (PopType) */ "WORKFORCE_DISTTITLE", + /* Religion */ "RELIGION_DISTTITLE", + /* Ideology */ "IDEOLOGY_DISTTITLE", + /* Nationality (Culture) */ "NATIONALITY_DISTTITLE", /* Issues */ "DOMINANT_ISSUES_DISTTITLE", - /* Vote */ "ELECTORATE_DISTTITLE" + /* Vote */ "ELECTORATE_DISTTITLE" }; PackedStringArray array; @@ -1096,16 +1082,13 @@ TypedArray MenuSingleton::get_population_menu_distribution_info() const { TypedArray array; ERR_FAIL_COND_V(array.resize(population_menu_t::DISTRIBUTION_COUNT) != OK, {}); - const auto make_pie_chart_tooltip = [this]( - has_get_identifier_and_colour auto const& key, String const& identifier, float weight, float total_weight - ) -> String { + const auto make_pie_chart_tooltip = // + [ // + this // + ](has_get_identifier_and_colour auto const& key, String const& identifier, float weight, float total_weight) -> String { static const String format_key = GUILabel::get_colour_marker() + String { "Y%s" } + GUILabel::get_colour_marker() + "!: %s%%"; - return Utilities::format( - format_key, - tr(identifier), - Utilities::float_to_string_dp(100.0f * weight / total_weight, 2) - ); + return Utilities::format(format_key, tr(identifier), Utilities::float_to_string_dp(100.0f * weight / total_weight, 2)); }; array[0] = GFXPieChartTexture::distribution_to_slices_array(population_menu.workforce_distribution, make_pie_chart_tooltip); diff --git a/extension/src/openvic-extension/singletons/SoundSingleton.cpp b/extension/src/openvic-extension/singletons/SoundSingleton.cpp index a9a11428..36d2702c 100644 --- a/extension/src/openvic-extension/singletons/SoundSingleton.cpp +++ b/extension/src/openvic-extension/singletons/SoundSingleton.cpp @@ -15,9 +15,9 @@ #include #include -#include "openvic-extension/singletons/GameSingleton.hpp" #include "openvic-extension/core/Bind.hpp" #include "openvic-extension/core/Convert.hpp" +#include "openvic-extension/singletons/GameSingleton.hpp" #include "openvic-extension/utility/Utilities.hpp" using namespace godot; @@ -108,7 +108,10 @@ bool SoundSingleton::load_title_theme() { String file_stem = to_define_file_name(file, music_folder); if (file_stem == title_theme_name.data()) { - ERR_BREAK_MSG(!get_song(file).is_valid(), Utilities::format("Failed to load title theme song at path %s.", convert_to(file_name.string()))); + ERR_BREAK_MSG( + !get_song(file).is_valid(), + Utilities::format("Failed to load title theme song at path %s.", convert_to(file_name.string())) + ); String name = to_define_file_name(file, music_folder); title_theme = name; @@ -180,7 +183,8 @@ Ref SoundSingleton::get_sound(String const& path) { Ref SoundSingleton::get_sound_stream(String const& path) { sfx_define_map_t::Iterator it = sfx_define.find(path); ERR_FAIL_COND_V_MSG( - it == sfx_define.end(), Ref(), Utilities::format("Attempted to retrieve sound stream at invalid index %s.", path) + it == sfx_define.end(), Ref(), + Utilities::format("Attempted to retrieve sound stream at invalid index %s.", path) ); return it->value.audio_stream; @@ -216,13 +220,22 @@ bool SoundSingleton::load_sounds() { // UI_Cavalry_Selected.wav doesn't exist (paradox mistake, UI_Cavalry_Select.wav does), just keep going // the define its associated with also isn't used in game if (full_path.empty()) { - WARN_PRINT(Utilities::format("The sound define %s points to non-existent file.", convert_to(sound_inst.get_identifier()))); + WARN_PRINT( + Utilities::format( + "The sound define %s points to non-existent file.", convert_to(sound_inst.get_identifier()) + ) + ); continue; } Ref stream = get_sound(convert_to(full_path.string())); if (stream.is_null()) { - ERR_PRINT(Utilities::format("Failed to load sound %s at path %s.", convert_to(sound_inst.get_identifier()), convert_to(full_path.string()))); + ERR_PRINT( + Utilities::format( + "Failed to load sound %s at path %s.", convert_to(sound_inst.get_identifier()), + convert_to(full_path.string()) + ) + ); ret = false; continue; // don't try to append a null pointer to the list } diff --git a/extension/src/openvic-extension/singletons/TradeMenu.cpp b/extension/src/openvic-extension/singletons/TradeMenu.cpp index 9e65b2aa..9a39aeef 100644 --- a/extension/src/openvic-extension/singletons/TradeMenu.cpp +++ b/extension/src/openvic-extension/singletons/TradeMenu.cpp @@ -1,11 +1,9 @@ -#include "MenuSingleton.hpp" - -#include - #include #include +#include + #include "openvic-extension/classes/GUILabel.hpp" #include "openvic-extension/classes/GUIScrollbar.hpp" #include "openvic-extension/core/Convert.hpp" @@ -13,6 +11,8 @@ #include "openvic-extension/singletons/PlayerSingleton.hpp" #include "openvic-extension/utility/Utilities.hpp" +#include "MenuSingleton.hpp" + using namespace OpenVic; using namespace godot; @@ -29,7 +29,8 @@ Dictionary MenuSingleton::get_trade_menu_good_categories_info() const { ERR_FAIL_NULL_V(instance_manager, {}); GoodInstanceManager const& good_instance_manager = instance_manager->get_good_instance_manager(); - GoodDefinitionManager const& good_definition_manager = instance_manager->definition_manager.get_economy_manager().get_good_definition_manager(); + GoodDefinitionManager const& good_definition_manager = + instance_manager->definition_manager.get_economy_manager().get_good_definition_manager(); CountryInstance const* country = PlayerSingleton::get_singleton()->get_player_country(); @@ -61,15 +62,20 @@ Dictionary MenuSingleton::get_trade_menu_good_categories_info() const { const fixed_point_t supply = good_instance.get_total_supply_yesterday(); const fixed_point_t demand = good_instance.get_total_demand_yesterday(); - good_dict[demand_tooltip_key] = tr( - demand > supply ? in_demand_localisation_key : not_in_demand_localisation_key - ) + get_tooltip_separator() + tr(supply_localisation_key).replace( - Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(supply, 3) - ) + "\n" + tr(demand_localisation_key).replace( - Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(demand, 3) - ) + "\n" + tr(actual_bought_localisation_key).replace( - Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(good_instance.get_quantity_traded_yesterday(), 3) - ); + good_dict[demand_tooltip_key] = + tr(demand > supply ? in_demand_localisation_key : not_in_demand_localisation_key) + + get_tooltip_separator() + + tr(supply_localisation_key) + .replace(Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(supply, 3)) + + "\n" + + tr(demand_localisation_key) + .replace(Utilities::get_short_value_placeholder(), Utilities::fixed_point_to_string_dp(demand, 3)) + + "\n" + + tr(actual_bought_localisation_key) + .replace( + Utilities::get_short_value_placeholder(), + Utilities::fixed_point_to_string_dp(good_instance.get_quantity_traded_yesterday(), 3) + ); } if (country != nullptr) { @@ -111,7 +117,7 @@ Dictionary MenuSingleton::get_trade_menu_good_categories_info() const { } Dictionary MenuSingleton::get_trade_menu_trade_details_info( - int32_t trade_detail_good_index, GUIScrollbar* stockpile_cutoff_slider + int32_t trade_detail_good_index, GUIScrollbar* stockpile_cutoff_slider // ) const { static const StringName trade_detail_good_name_key = "trade_detail_good_name"; static const StringName trade_detail_good_price_key = "trade_detail_good_price"; @@ -131,8 +137,8 @@ Dictionary MenuSingleton::get_trade_menu_trade_details_info( InstanceManager const* instance_manager = GameSingleton::get_singleton()->get_instance_manager(); ERR_FAIL_NULL_V(instance_manager, {}); - GoodInstance const* good_instance = instance_manager->get_good_instance_manager() - .get_good_instance_by_index(good_index_t(trade_detail_good_index)); + GoodInstance const* good_instance = + instance_manager->get_good_instance_manager().get_good_instance_by_index(good_index_t(trade_detail_good_index)); ERR_FAIL_NULL_V(good_instance, {}); CountryInstance const* country = PlayerSingleton::get_singleton()->get_player_country(); @@ -155,8 +161,8 @@ Dictionary MenuSingleton::get_trade_menu_trade_details_info( ret[trade_detail_price_history_key] = std::move(price_history); } else { UtilityFunctions::push_error( - "Failed to resize price history array to the correct size (", - static_cast(good_price_history.size()), ")" + "Failed to resize price history array to the correct size (", static_cast(good_price_history.size()), + ")" ); } } @@ -171,8 +177,7 @@ Dictionary MenuSingleton::get_trade_menu_trade_details_info( ret[trade_detail_is_selling_key] = good_data.is_selling; if (stockpile_cutoff_slider != nullptr) { const int32_t index = calculate_slider_value_from_trade_menu_stockpile_cutoff( - good_data.stockpile_cutoff, - stockpile_cutoff_slider->get_max_value_scaled().truncate() + good_data.stockpile_cutoff, stockpile_cutoff_slider->get_max_value_scaled().truncate() ); stockpile_cutoff_slider->set_scaled_value(index); } @@ -211,19 +216,17 @@ Dictionary MenuSingleton::get_trade_menu_tables_info() const { for (GoodInstance const& good : good_instance_manager.get_good_instances()) { static const StringName top_producers_localisation_key = "TRADE_TOP_PRODUCERS"; - String tooltip = tr(convert_to(good.get_identifier())) + get_tooltip_separator() + - tr(top_producers_localisation_key); + String tooltip = + tr(convert_to(good.get_identifier())) + get_tooltip_separator() + tr(top_producers_localisation_key); for (size_t index = 0; index < 5; ++index) { - CountryInstance const& other_country = country_instance_manager.get_country_instance_by_index( - country_index_t(index + 1) - ); + CountryInstance const& other_country = + country_instance_manager.get_country_instance_by_index(country_index_t(index + 1)); static const String top_producer_template_string = "\n" + GUILabel::get_flag_marker() + "%s %s: %s"; tooltip += Utilities::format( - top_producer_template_string, - convert_to(other_country.get_identifier()), + top_producer_template_string, convert_to(other_country.get_identifier()), Utilities::get_country_name(*this, other_country), Utilities::fixed_point_to_string_dp(fixed_point_t(1000) / static_cast(index + 1), 2) ); @@ -268,54 +271,38 @@ Dictionary MenuSingleton::get_trade_menu_tables_info() const { } good_trading_yesterday_tooltips.push_back( - tooltip.replace( - money_replace_key, Utilities::fixed_point_to_string_dp(stockpile_change_yesterday, 2) - ).replace( - units_replace_key, Utilities::fixed_point_to_string_dp(stockpile_change_yesterday * good.get_price(), 2) - ) + tooltip.replace(money_replace_key, Utilities::fixed_point_to_string_dp(stockpile_change_yesterday, 2)) + .replace( + units_replace_key, Utilities::fixed_point_to_string_dp(stockpile_change_yesterday * good.get_price(), 2) + ) ); const float good_index = type_safe::get(good.good_definition.index); if (good_data.government_needs != fixed_point_t::_0) { - government_needs.push_back({ - good_index, - static_cast(good_data.government_needs) - }); + government_needs.push_back({ good_index, static_cast(good_data.government_needs) }); } if (good_data.factory_demand != fixed_point_t::_0) { - factory_needs.push_back({ - good_index, - static_cast(good_data.factory_demand) - }); + factory_needs.push_back({ good_index, static_cast(good_data.factory_demand) }); } if (good_data.pop_demand != fixed_point_t::_0) { - pop_needs.push_back({ - good_index, static_cast(good_data.pop_demand) - }); + pop_needs.push_back({ good_index, static_cast(good_data.pop_demand) }); } - market_activity.push_back({ - good_index, - static_cast(good_data.exported_amount.abs()), - static_cast(good_data.exported_amount * good.get_price()) - }); + market_activity.push_back( + { good_index, static_cast(good_data.exported_amount.abs()), + static_cast(good_data.exported_amount * good.get_price()) } + ); - stockpile.push_back({ - good_index, - static_cast(good_data.stockpile_amount), - static_cast(good_data.stockpile_change_yesterday) - }); + stockpile.push_back( + { good_index, static_cast(good_data.stockpile_amount), + static_cast(good_data.stockpile_change_yesterday) } + ); // TODO - replace with actual common market data - common_market.push_back({ - good_index, - good_index * 100, - -good_index, - good_index * 10 - }); + common_market.push_back({ good_index, good_index * 100, -good_index, good_index * 10 }); } ret[good_trading_yesterday_tooltips_key] = std::move(good_trading_yesterday_tooltips); diff --git a/extension/src/openvic-extension/utility/MapHelpers.hpp b/extension/src/openvic-extension/utility/MapHelpers.hpp index c392afa2..468d693c 100644 --- a/extension/src/openvic-extension/utility/MapHelpers.hpp +++ b/extension/src/openvic-extension/utility/MapHelpers.hpp @@ -1,41 +1,41 @@ #pragma once -#include - #include +#include + namespace OpenVic { // Helper aliases to deduce the key and value types from the MapType. // This allows the concept and function to work with both tsl::ordered_map and IndexedFlatMap. - template + template struct key_of {}; - template + template struct key_of> { using type = KeyType; }; - template + template struct key_of> { using type = KeyType; }; - template + template using map_key_t = typename key_of::type; - template + template struct value_of {}; - template + template struct value_of> { using type = ValueType; }; - template + template struct value_of> { using type = ValueType; }; - template + template using map_value_t = typename value_of::type; -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/utility/UITools.cpp b/extension/src/openvic-extension/utility/UITools.cpp index 3611e21d..6c5bf7be 100644 --- a/extension/src/openvic-extension/utility/UITools.cpp +++ b/extension/src/openvic-extension/utility/UITools.cpp @@ -27,6 +27,7 @@ #include #include +#include #include "openvic-extension/classes/GUIButton.hpp" #include "openvic-extension/classes/GUIIcon.hpp" @@ -46,17 +47,14 @@ #include "openvic-extension/singletons/SoundSingleton.hpp" #include "openvic-extension/utility/Utilities.hpp" -#include "openvic-simulation/misc/SoundEffect.hpp" - using namespace godot; using namespace OpenVic; GFX::Sprite const* UITools::get_gfx_sprite(String const& gfx_sprite) { GameSingleton* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, nullptr); - GFX::Sprite const* sprite = game_singleton->get_definition_manager().get_ui_manager().get_sprite_by_identifier( - convert_to(gfx_sprite) - ); + GFX::Sprite const* sprite = + game_singleton->get_definition_manager().get_ui_manager().get_sprite_by_identifier(convert_to(gfx_sprite)); ERR_FAIL_NULL_V_MSG(sprite, nullptr, Utilities::format("GFX sprite not found: %s", gfx_sprite)); return sprite; } @@ -64,24 +62,26 @@ GFX::Sprite const* UITools::get_gfx_sprite(String const& gfx_sprite) { GUI::Element const* UITools::get_gui_element(String const& gui_scene, String const& gui_element) { GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, nullptr); - GUI::Scene const* scene = game_singleton->get_definition_manager().get_ui_manager().get_scene_by_identifier( - convert_to(gui_scene) - ); + GUI::Scene const* scene = + game_singleton->get_definition_manager().get_ui_manager().get_scene_by_identifier(convert_to(gui_scene)); ERR_FAIL_NULL_V_MSG(scene, nullptr, Utilities::format("Failed to find GUI scene %s", gui_scene)); GUI::Element const* element = scene->get_scene_element_by_identifier(convert_to(gui_element)); - ERR_FAIL_NULL_V_MSG(element, nullptr, Utilities::format("Failed to find GUI element %s in GUI scene %s", gui_element, gui_scene)); + ERR_FAIL_NULL_V_MSG( + element, nullptr, Utilities::format("Failed to find GUI element %s in GUI scene %s", gui_element, gui_scene) + ); return element; } GUI::Position const* UITools::get_gui_position(String const& gui_scene, String const& gui_position) { GameSingleton const* game_singleton = GameSingleton::get_singleton(); ERR_FAIL_NULL_V(game_singleton, nullptr); - GUI::Scene const* scene = game_singleton->get_definition_manager().get_ui_manager().get_scene_by_identifier( - convert_to(gui_scene) - ); + GUI::Scene const* scene = + game_singleton->get_definition_manager().get_ui_manager().get_scene_by_identifier(convert_to(gui_scene)); ERR_FAIL_NULL_V_MSG(scene, nullptr, Utilities::format("Failed to find GUI scene %s", gui_scene)); GUI::Position const* position = scene->get_scene_position_by_identifier(convert_to(gui_position)); - ERR_FAIL_NULL_V_MSG(position, nullptr, Utilities::format("Failed to find GUI position %s in GUI scene %s", gui_position, gui_scene)); + ERR_FAIL_NULL_V_MSG( + position, nullptr, Utilities::format("Failed to find GUI position %s in GUI scene %s", gui_position, gui_scene) + ); return position; } @@ -216,7 +216,8 @@ namespace OpenVic { constexpr generate_gui_args_t( GUI::Element const& new_element, String const& new_name, AssetManager& new_asset_manager, Control*& new_result - ) : element { new_element }, name { new_name }, asset_manager { new_asset_manager }, result { new_result } {} + ) + : element { new_element }, name { new_name }, asset_manager { new_asset_manager }, result { new_result } {} }; } @@ -228,8 +229,10 @@ static bool new_control(T*& node, GUI::Element const& element, String const& nam using enum GUI::Element::orientation_t; using enum Control::LayoutPreset; static const ordered_map orientation_map { - { UPPER_LEFT, PRESET_TOP_LEFT }, { LOWER_LEFT, PRESET_BOTTOM_LEFT }, - { LOWER_RIGHT, PRESET_BOTTOM_RIGHT }, { UPPER_RIGHT, PRESET_TOP_RIGHT }, + { UPPER_LEFT, PRESET_TOP_LEFT }, + { LOWER_LEFT, PRESET_BOTTOM_LEFT }, + { LOWER_RIGHT, PRESET_BOTTOM_RIGHT }, + { UPPER_RIGHT, PRESET_TOP_RIGHT }, { CENTER, PRESET_CENTER } }; @@ -244,9 +247,7 @@ static bool new_control(T*& node, GUI::Element const& element, String const& nam if (it != orientation_map.end()) { node->set_anchors_and_offsets_preset(it->second); } else { - UtilityFunctions::push_error( - "Invalid orientation for GUI element ", convert_to(element.get_name()) - ); + UtilityFunctions::push_error("Invalid orientation for GUI element ", convert_to(element.get_name())); ret = false; } @@ -271,9 +272,7 @@ static bool generate_icon(generate_gui_args_t&& args) { if (GFX::IconTextureSprite const* texture_sprite = icon.get_sprite()->cast_to()) { GUIIcon* gui_icon = nullptr; ret &= new_control(gui_icon, icon, args.name); - ERR_FAIL_NULL_V_MSG( - gui_icon, false, Utilities::format("Failed to create GUIIcon for GUI icon %s", icon_name) - ); + ERR_FAIL_NULL_V_MSG(gui_icon, false, Utilities::format("Failed to create GUIIcon for GUI icon %s", icon_name)); gui_icon->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); @@ -346,8 +345,7 @@ static bool generate_icon(generate_gui_args_t&& args) { args.result = gui_line_chart; } else { UtilityFunctions::push_error( - "Invalid sprite type ", convert_to(icon.get_sprite()->get_type()), - " for GUI icon ", icon_name + "Invalid sprite type ", convert_to(icon.get_sprite()->get_type()), " for GUI icon ", icon_name ); ret = false; } @@ -356,9 +354,9 @@ static bool generate_icon(generate_gui_args_t&& args) { const real_t rotation = static_cast(icon.get_rotation()); if (rotation != 0.0_real) { args.result->set_position( - args.result->get_position() - args.result->get_custom_minimum_size().height * Vector2 { - Math::sin(rotation), Math::cos(rotation) - 1.0_real - } + args.result->get_position() - + args.result->get_custom_minimum_size().height * + Vector2 { Math::sin(rotation), Math::cos(rotation) - 1.0_real } ); args.result->set_rotation(-rotation); } @@ -386,7 +384,9 @@ static bool generate_button(generate_gui_args_t&& args) { if (GFX::IconTextureSprite const* texture_sprite = button.get_sprite()->cast_to()) { GUIIconButton* gui_icon_button = nullptr; ret &= new_control(gui_icon_button, button, args.name); - ERR_FAIL_NULL_V_MSG(gui_icon_button, false, Utilities::format("Failed to create GUIIconButton for GUI button %s", button_name)); + ERR_FAIL_NULL_V_MSG( + gui_icon_button, false, Utilities::format("Failed to create GUIIconButton for GUI button %s", button_name) + ); if (gui_icon_button->set_gfx_texture_sprite(texture_sprite) != OK) { UtilityFunctions::push_error("Error setting up GUIIconButton for GUI button ", button_name); @@ -398,7 +398,8 @@ static bool generate_button(generate_gui_args_t&& args) { GUIMaskedFlagButton* gui_masked_flag_button = nullptr; ret &= new_control(gui_masked_flag_button, button, args.name); ERR_FAIL_NULL_V_MSG( - gui_masked_flag_button, false, Utilities::format("Failed to create GUIMaskedFlagButton for GUI button %s", button_name) + gui_masked_flag_button, false, + Utilities::format("Failed to create GUIMaskedFlagButton for GUI button %s", button_name) ); if (gui_masked_flag_button->set_gfx_masked_flag(masked_flag) != OK) { @@ -409,9 +410,9 @@ static bool generate_button(generate_gui_args_t&& args) { gui_button = gui_masked_flag_button; } else { ERR_FAIL_V_MSG( - false, Utilities::format( - "Invalid sprite type %s for GUI button %s", convert_to(button.get_sprite()->get_type()), - button_name + false, + Utilities::format( + "Invalid sprite type %s for GUI button %s", convert_to(button.get_sprite()->get_type()), button_name ) ); } @@ -477,9 +478,9 @@ static bool generate_checkbox(generate_gui_args_t&& args) { GFX::IconTextureSprite const* texture_sprite = checkbox.get_sprite()->cast_to(); ERR_FAIL_NULL_V_MSG( - texture_sprite, false, Utilities::format( - "Invalid sprite type %s for GUI checkbox %s", convert_to(checkbox.get_sprite()->get_type()), - checkbox_name + texture_sprite, false, + Utilities::format( + "Invalid sprite type %s for GUI checkbox %s", convert_to(checkbox.get_sprite()->get_type()), checkbox_name ) ); @@ -526,7 +527,8 @@ static bool generate_text(generate_gui_args_t&& args) { GameSingleton const* game_singleton = GameSingleton::get_singleton(); GFX::Font::colour_codes_t const* override_colour_codes = game_singleton != nullptr - ? &game_singleton->get_definition_manager().get_ui_manager().get_universal_colour_codes() : nullptr; + ? &game_singleton->get_definition_manager().get_ui_manager().get_universal_colour_codes() + : nullptr; if (gui_label->set_gui_text(&text, override_colour_codes) != OK) { UtilityFunctions::push_error("Error initializing GUILabel for GUI text ", text_name); @@ -546,7 +548,9 @@ static bool generate_overlapping_elements(generate_gui_args_t&& args) { bool ret = new_control(box, overlapping_elements, args.name); ERR_FAIL_NULL_V_MSG( box, false, - Utilities::format("Failed to create GUIOverlappingElementsBox for GUI overlapping elements %s", overlapping_elements_name) + Utilities::format( + "Failed to create GUIOverlappingElementsBox for GUI overlapping elements %s", overlapping_elements_name + ) ); box->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); @@ -666,7 +670,9 @@ static bool generate_scrollbar(generate_gui_args_t&& args) { GUIScrollbar* gui_scrollbar = nullptr; bool ret = new_control(gui_scrollbar, scrollbar, args.name); - ERR_FAIL_NULL_V_MSG(gui_scrollbar, false, Utilities::format("Failed to create GUIScrollbar for GUI scrollbar %s", scrollbar_name)); + ERR_FAIL_NULL_V_MSG( + gui_scrollbar, false, Utilities::format("Failed to create GUIScrollbar for GUI scrollbar %s", scrollbar_name) + ); if (gui_scrollbar->set_gui_scrollbar(&scrollbar) != OK) { UtilityFunctions::push_error("Error initializing GUIScrollbar for GUI scrollbar ", scrollbar_name); @@ -716,9 +722,7 @@ static bool generate_window(generate_gui_args_t&& args) { godot_panel->add_child(node); } if (!element_ret) { - UtilityFunctions::push_error( - "Errors generating GUI element ", convert_to(element->get_name()) - ); + UtilityFunctions::push_error("Errors generating GUI element ", convert_to(element->get_name())); ret = false; } } @@ -742,23 +746,18 @@ static bool generate_element(GUI::Element const* element, String const& name, As }; const decltype(type_map)::const_iterator it = type_map.find(element->get_type()); ERR_FAIL_COND_V_MSG( - it == type_map.end(), false, - Utilities::format("Invalid GUI element type: %s", convert_to(element->get_type())) + it == type_map.end(), false, Utilities::format("Invalid GUI element type: %s", convert_to(element->get_type())) ); return it->second({ *element, name, asset_manager, result }); } -bool UITools::generate_gui_element( - GUI::Element const* element, String const& name, Control*& result -) { +bool UITools::generate_gui_element(GUI::Element const* element, String const& name, Control*& result) { result = nullptr; AssetManager* asset_manager = AssetManager::get_singleton(); ERR_FAIL_NULL_V(asset_manager, false); return generate_element(element, name, *asset_manager, result); } -bool UITools::generate_gui_element( - String const& gui_scene, String const& gui_element, String const& name, Control*& result -) { +bool UITools::generate_gui_element(String const& gui_scene, String const& gui_element, String const& name, Control*& result) { return generate_gui_element(get_gui_element(gui_scene, gui_element), name, result); } diff --git a/extension/src/openvic-extension/utility/UITools.hpp b/extension/src/openvic-extension/utility/UITools.hpp index 566318a2..25a374bc 100644 --- a/extension/src/openvic-extension/utility/UITools.hpp +++ b/extension/src/openvic-extension/utility/UITools.hpp @@ -10,9 +10,7 @@ namespace OpenVic::UITools { GUI::Element const* get_gui_element(godot::String const& gui_scene, godot::String const& gui_element); GUI::Position const* get_gui_position(godot::String const& gui_scene, godot::String const& gui_position); - bool generate_gui_element( - GUI::Element const* element, godot::String const& name, godot::Control*& result - ); + bool generate_gui_element(GUI::Element const* element, godot::String const& name, godot::Control*& result); bool generate_gui_element( godot::String const& gui_scene, godot::String const& gui_element, godot::String const& name, godot::Control*& result ); diff --git a/extension/src/openvic-extension/utility/Utilities.cpp b/extension/src/openvic-extension/utility/Utilities.cpp index 2108aef6..3ebdd64f 100644 --- a/extension/src/openvic-extension/utility/Utilities.cpp +++ b/extension/src/openvic-extension/utility/Utilities.cpp @@ -7,14 +7,14 @@ #include #include -#include "openvic-simulation/politics/Government.hpp" -#include -#include - #include #include #include #include +#include + +#include +#include #include "openvic-extension/classes/GUINode.hpp" #include "openvic-extension/core/Convert.hpp" @@ -39,21 +39,17 @@ godot::StringName const& Utilities::get_colour_and_sign(const fixed_point_t valu static const godot::StringName red = "R"; static const godot::StringName yellow = "Y"; - return value > 0 - ? green_plus - : value < 0 - ? red - : yellow; + return value > 0 ? green_plus : value < 0 ? red : yellow; } /* Int to 2 decimal place string in terms of the largest suffix less than or equal to it, * or normal integer string if less than the smallest suffix. */ String Utilities::int_to_string_suffixed(int64_t val) { static const std::vector> suffixes { - { 1'000'000'000'000, "T" }, - { 1'000'000'000, "B" }, - { 1'000'000, "M" }, - { 1'000, "k" } + { 1'000'000'000'000, "T" }, // + { 1'000'000'000, "B" }, // + { 1'000'000, "M" }, // + { 1'000, "k" } // }; static constexpr int64_t decimal_places_multiplier = 100; const bool negative = val < 0; @@ -64,8 +60,8 @@ String Utilities::int_to_string_suffixed(int64_t val) { if (val >= suffix_val) { const int64_t whole = val / suffix_val; const int64_t frac = (val * decimal_places_multiplier / suffix_val) % decimal_places_multiplier; - return (negative ? "-" : "") + String::num_int64(whole) + "." + - (frac < 10 ? "0" : "") + String::num_int64(frac) + suffix_str; + return (negative ? "-" : "") + String::num_int64(whole) + "." + (frac < 10 ? "0" : "") + String::num_int64(frac) + + suffix_str; } } return (negative ? "-" : "") + String::num_int64(val); @@ -137,13 +133,7 @@ String Utilities::fixed_point_to_string_dp(fixed_point_t val, int32_t decimal_pl } String Utilities::percentage_to_string_dp(fixed_point_t val, int32_t decimal_places) { - return Utilities::format( - "%s%%", - Utilities::float_to_string_dp( - static_cast(100 * val), - decimal_places - ) - ); + return Utilities::format("%s%%", Utilities::float_to_string_dp(static_cast(100 * val), decimal_places)); } String Utilities::float_to_string_dp_dynamic(float val) { @@ -152,11 +142,7 @@ String Utilities::float_to_string_dp_dynamic(float val) { } String Utilities::cash_to_string_dp_dynamic(fixed_point_t val) { - return format_with_currency( - Utilities::float_to_string_suffixed( - static_cast(val) - ) - ); + return format_with_currency(Utilities::float_to_string_suffixed(static_cast(val))); } String Utilities::format_with_currency(godot::String const& text) { @@ -165,8 +151,8 @@ String Utilities::format_with_currency(godot::String const& text) { } String Utilities::date_to_string(Date date) { - static const String date_template_string = String { "%d" } + Date::SEPARATOR_CHARACTER + "%d" + - Date::SEPARATOR_CHARACTER + "%d"; + static const String date_template_string = + String { "%d" } + Date::SEPARATOR_CHARACTER + "%d" + Date::SEPARATOR_CHARACTER + "%d"; return Utilities::format(date_template_string, date.get_year(), date.get_month(), date.get_day()); } @@ -215,7 +201,9 @@ static Ref load_dds_image(String const& path) { /* Only fail if there aren't enough bytes, everything seems to work fine if there are extra bytes and we ignore them */ ERR_FAIL_COND_V_MSG( size > texture.size(), nullptr, - Utilities::format("Texture size %d mismatched with dims-based size %d for %s", static_cast(texture.size()), size, path) + Utilities::format( + "Texture size %d mismatched with dims-based size %d for %s", static_cast(texture.size()), size, path + ) ); PackedByteArray pixels; @@ -245,7 +233,9 @@ Ref Utilities::load_godot_font(String const& fnt_path, Ref cons ERR_FAIL_NULL_V(image, nullptr); Ref font; font.instantiate(); - ERR_FAIL_COND_V_MSG(font->load_bitmap_font(fnt_path) != OK, nullptr, Utilities::format("Failed to load font: %s", fnt_path)); + ERR_FAIL_COND_V_MSG( + font->load_bitmap_font(fnt_path) != OK, nullptr, Utilities::format("Failed to load font: %s", fnt_path) + ); font->set_texture_image(0, { font->get_fixed_size(), 0 }, 0, image); return font; } @@ -257,7 +247,9 @@ Ref Utilities::make_solid_colour_image(Color const& colour, int32_t width return result; } -Ref Utilities::make_solid_colour_texture(Color const& colour, int32_t width, int32_t height, Image::Format format) { +Ref Utilities::make_solid_colour_texture( + Color const& colour, int32_t width, int32_t height, Image::Format format // +) { const Ref image = make_solid_colour_image(colour, width, height, format); ERR_FAIL_NULL_V(image, nullptr); const Ref result = ImageTexture::create_from_image(image); @@ -315,9 +307,8 @@ godot::String Utilities::get_state_name(godot::Object const& translation_object, godot::String Utilities::get_country_name(godot::Object const& translation_object, CountryInstance const& country) { GovernmentType const* government_type = country.get_government_type_untracked(); if (government_type != nullptr) { - const String government_name_key = convert_to(append_string_views( - country.get_identifier(), "_", government_type->get_identifier() - )); + const String government_name_key = + convert_to(append_string_views(country.get_identifier(), "_", government_type->get_identifier())); String government_name = translation_object.tr(government_name_key); @@ -333,9 +324,9 @@ godot::String Utilities::get_country_adjective(godot::Object const& translation_ GovernmentType const* government_type = country.get_government_type_untracked(); if (government_type != nullptr) { - const String government_adjective_key = convert_to(append_string_views( - country.get_identifier(), "_", government_type->get_identifier(), adjective - )); + const String government_adjective_key = convert_to( + append_string_views(country.get_identifier(), "_", government_type->get_identifier(), adjective) + ); String government_adjective = translation_object.tr(government_adjective_key); @@ -348,9 +339,7 @@ godot::String Utilities::get_country_adjective(godot::Object const& translation_ } godot::String Utilities::make_modifier_effect_value( - godot::Object const& translation_object, - ModifierEffect const& format_effect, - fixed_point_t value, + godot::Object const& translation_object, ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ) { godot::String result; @@ -363,8 +352,8 @@ godot::String Utilities::make_modifier_effect_value( // Apply multiplier format part { - uint8_t multiplier_power = (format >> ModifierEffect::FORMAT_MULTIPLIER_BIT_OFFSET) & - ((1 << ModifierEffect::FORMAT_MULTIPLIER_BIT_COUNT) - 1); + uint8_t multiplier_power = + (format >> ModifierEffect::FORMAT_MULTIPLIER_BIT_OFFSET) & ((1 << ModifierEffect::FORMAT_MULTIPLIER_BIT_COUNT) - 1); while (multiplier_power-- > 0) { value *= 10; } @@ -414,16 +403,14 @@ godot::String Utilities::make_modifier_effect_value( return result; } godot::String Utilities::make_modifier_effect_value_coloured( - godot::Object const& translation_object, - ModifierEffect const& format_effect, - fixed_point_t value, + godot::Object const& translation_object, ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ) { godot::String result = GUILabel::get_colour_marker(); - const bool is_positive_green = ( - static_cast(format_effect.format) & (1 << ModifierEffect::FORMAT_POS_NEG_BIT_OFFSET) - ) == static_cast(ModifierEffect::format_t::FORMAT_PART_POS); + const bool is_positive_green = + (static_cast(format_effect.format) & (1 << ModifierEffect::FORMAT_POS_NEG_BIT_OFFSET)) == + static_cast(ModifierEffect::format_t::FORMAT_PART_POS); if (value == 0) { result += "Y"; @@ -454,4 +441,4 @@ fmt::format_context::iterator fmt::formatter::format(String const& str, fmt::format_context::iterator fmt::formatter::format(StringName const& str, format_context& ctx) const { return fmt::formatter::format(static_cast(str), ctx); -} \ No newline at end of file +} diff --git a/extension/src/openvic-extension/utility/Utilities.hpp b/extension/src/openvic-extension/utility/Utilities.hpp index 8775d6b1..6bf373cb 100644 --- a/extension/src/openvic-extension/utility/Utilities.hpp +++ b/extension/src/openvic-extension/utility/Utilities.hpp @@ -87,15 +87,11 @@ namespace OpenVic::Utilities { godot::String get_country_adjective(godot::Object const& translation_object, CountryInstance const& country); godot::String make_modifier_effect_value( - godot::Object const& translation_object, - ModifierEffect const& format_effect, - fixed_point_t value, + godot::Object const& translation_object, ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ); godot::String make_modifier_effect_value_coloured( - godot::Object const& translation_object, - ModifierEffect const& format_effect, - fixed_point_t value, + godot::Object const& translation_object, ModifierEffect const& format_effect, fixed_point_t value, bool plus_for_non_negative ); @@ -111,23 +107,18 @@ namespace OpenVic::Utilities { #define OPTIMISED_FORMAT_COPY(n) args_array.set(n, p_arg##n); #define OPTIMISED_FORMAT_ARRAY_INIT(count) OPTIMISED_FORMAT_EXPAND(FOR_LOOP_, count)(OPTIMISED_FORMAT_COPY) -#define OPTIMISED_FORMAT_SET_NULL(n) args_array.set(n, godot::Variant{}); +#define OPTIMISED_FORMAT_SET_NULL(n) args_array.set(n, godot::Variant {}); #define OPTIMISED_FORMAT_ARRAY_CLEAR(count) OPTIMISED_FORMAT_EXPAND(FOR_LOOP_, count)(OPTIMISED_FORMAT_SET_NULL) #define OPTIMISED_FORMAT_ARG(n) , const auto p_arg##n #define OPTIMISED_FORMAT_GET_ARGS(count) OPTIMISED_FORMAT_EXPAND(FOR_LOOP_, count)(OPTIMISED_FORMAT_ARG) #define OPTIMISED_FORMAT(count) \ - [[nodiscard]] godot::String format( \ - godot::String const& text_template \ - OPTIMISED_FORMAT_GET_ARGS(count) \ - ) { \ + [[nodiscard]] godot::String format(godot::String const& text_template OPTIMISED_FORMAT_GET_ARGS(count)) { \ extern thread_local memory::vector _formatting_array_pool_##count; \ memory::vector& array_pool = _formatting_array_pool_##count; \ const bool was_empty = array_pool.empty(); \ - godot::Array args_array = was_empty \ - ? godot::Array{} \ - : std::move(array_pool.back()); \ + godot::Array args_array = was_empty ? godot::Array {} : std::move(array_pool.back()); \ if (was_empty) { \ args_array.resize(count); \ } else { \ @@ -163,13 +154,15 @@ namespace OpenVic::Utilities { #undef OPTIMISED_FORMAT_ARG #undef OPTIMISED_FORMAT_GET_ARGS - template + template [[nodiscard]] godot::String format(godot::String const& text_template, const VarArgs... p_args) { return godot::vformat(text_template, p_args...); } namespace literals { - constexpr real_t operator""_real(long double val) { return to_real_t(val); } + constexpr real_t operator""_real(long double val) { + return to_real_t(val); + } } } @@ -181,4 +174,4 @@ struct fmt::formatter : formatter { template<> struct fmt::formatter : formatter { format_context::iterator format(godot::StringName const& str, format_context& ctx) const; -}; \ No newline at end of file +};