From c2eb43edbbeca8752c0c562f9cfbe9c3c5f19a65 Mon Sep 17 00:00:00 2001 From: Spartan322 Date: Thu, 10 Sep 2026 04:37:24 -0400 Subject: [PATCH 1/2] Add clang-format 22.1.8 to pre-commit Generally matches OpenVic repo .clang-format --- .clang-format | 35 +- .pre-commit-config.yaml | 16 +- src/headless/main.cpp | 135 +- src/openvic-simulation/DefinitionManager.hpp | 1 - src/openvic-simulation/GameManager.cpp | 32 +- src/openvic-simulation/GameManager.hpp | 10 +- src/openvic-simulation/InstanceManager.cpp | 274 ++- src/openvic-simulation/InstanceManager.hpp | 13 +- .../console/ConsoleInstance.cpp | 56 +- src/openvic-simulation/core/Assert.hpp | 49 +- .../core/FormatValidate.hpp | 2 +- src/openvic-simulation/core/Hash.hpp | 21 +- src/openvic-simulation/core/MathSqrt.hpp | 2 +- src/openvic-simulation/core/ecs/Archetype.hpp | 54 +- src/openvic-simulation/core/ecs/Checksum.cpp | 20 +- .../core/ecs/ChecksumTraits.hpp | 18 +- src/openvic-simulation/core/ecs/Chunk.hpp | 8 +- src/openvic-simulation/core/ecs/ChunkPool.cpp | 4 +- .../core/ecs/ChunkSystem.hpp | 30 +- .../core/ecs/CommandBuffer.cpp | 593 +++--- .../core/ecs/CommandBuffer.hpp | 67 +- .../core/ecs/DenseSlotAllocator.cpp | 6 +- .../core/ecs/EcsThreadPool.cpp | 8 +- .../core/ecs/QueryFilter.hpp | 5 +- .../core/ecs/Reductions.hpp | 11 +- src/openvic-simulation/core/ecs/System.hpp | 65 +- .../core/ecs/SystemAccess.hpp | 29 +- .../core/ecs/SystemImpl.hpp | 102 +- .../core/ecs/SystemPhase.hpp | 2 +- .../core/ecs/SystemScheduler.cpp | 63 +- .../core/ecs/SystemScheduler.hpp | 27 +- src/openvic-simulation/core/ecs/World.cpp | 99 +- src/openvic-simulation/core/ecs/World.hpp | 179 +- src/openvic-simulation/core/error/Error.hpp | 46 +- .../core/error/ErrorMacros.hpp | 48 +- .../core/error/ErrorSet.hpp | 2 +- src/openvic-simulation/core/io/BMP.cpp | 13 +- src/openvic-simulation/core/io/BMP.hpp | 2 +- src/openvic-simulation/core/memory/Colony.hpp | 2 +- src/openvic-simulation/core/memory/Deque.hpp | 17 +- .../core/memory/Formatting.hpp | 10 +- .../core/memory/MemoryTracker.hpp | 6 +- src/openvic-simulation/core/memory/Queue.hpp | 2 +- .../core/memory/SmartPtr.hpp | 30 +- src/openvic-simulation/core/memory/Stack.hpp | 2 +- src/openvic-simulation/core/memory/String.hpp | 9 +- .../core/memory/StringStream.hpp | 12 +- src/openvic-simulation/core/memory/Vector.hpp | 2 +- .../memory/allocators/AllocatorReference.hpp | 2 +- .../core/memory/allocators/Deleter.hpp | 4 +- .../core/memory/allocators/NewAllocator.hpp | 2 +- .../core/memory/make_tracked_allocator.hpp | 9 +- src/openvic-simulation/core/object/Colour.hpp | 139 +- src/openvic-simulation/core/object/Date.cpp | 32 +- src/openvic-simulation/core/object/Date.hpp | 187 +- .../core/object/FixedPoint.cpp | 23 +- .../core/object/FixedPoint.hpp | 27 +- .../core/object/FixedPoint/Atomic.hpp | 7 +- .../core/object/FixedPoint/Fraction.hpp | 2 +- .../core/object/FixedPoint/Math.hpp | 27 +- .../core/object/FixedPoint/String.hpp | 45 +- .../core/object/Timespan.hpp | 5 +- src/openvic-simulation/core/object/Vector.hpp | 15 +- .../core/object/VectorN.inc | 60 +- .../core/portable/Deque.hpp | 155 +- .../core/portable/ForwardableSpan.hpp | 53 +- .../core/random/RandomGenerator.hpp | 18 +- .../core/random/WeightedSampling.hpp | 8 +- .../core/stl/BasicIterator.hpp | 4 +- .../core/stl/containers/BulkInsertWrapper.hpp | 48 +- .../core/stl/containers/CowPtr.hpp | 10 +- .../core/stl/containers/CowVector.hpp | 43 +- .../core/stl/containers/FixedVector.hpp | 277 +-- .../core/stl/containers/RingBuffer.hpp | 12 +- .../core/stl/containers/StackString.hpp | 2 +- .../core/stl/containers/TypedSpan.hpp | 15 +- .../core/string/CharConv.hpp | 21 +- .../core/string/StringLiteral.hpp | 8 +- .../core/string/Utility.hpp | 2 +- .../core/template/Concepts.hpp | 27 +- .../core/template/EnumBitfield.hpp | 7 +- .../core/template/Functional.hpp | 30 +- src/openvic-simulation/core/ui/TextFormat.hpp | 5 +- .../country/CountryDefinition.cpp | 154 +- .../country/CountryDefinition.hpp | 31 +- .../country/CountryInstance.cpp | 1218 +++++++------ .../country/CountryInstance.hpp | 141 +- .../country/CountryInstanceDeps.hpp | 4 +- .../country/CountryInstanceManager.cpp | 129 +- .../country/CountryInstanceManager.hpp | 16 +- .../country/CountryParty.cpp | 21 +- .../country/CountryParty.hpp | 10 +- .../country/SharedCountryValues.cpp | 50 +- .../country/SharedCountryValues.hpp | 16 +- .../dataloader/Dataloader.cpp | 483 +++-- .../dataloader/Dataloader.hpp | 31 +- .../dataloader/ModManager.cpp | 64 +- .../dataloader/ModManager.hpp | 18 +- .../dataloader/NodeTools.cpp | 236 ++- .../dataloader/NodeTools.hpp | 295 ++- .../dataloader/Vic2PathSearch.cpp | 68 +- .../dataloader/Vic2PathSearch_Windows.hpp | 12 +- src/openvic-simulation/defines/AIDefines.cpp | 163 +- .../defines/CountryDefines.cpp | 387 ++-- .../defines/CountryDefines.hpp | 2 + src/openvic-simulation/defines/Define.cpp | 4 +- .../defines/DiplomacyDefines.cpp | 1585 +++++++++++------ .../defines/EconomyDefines.cpp | 143 +- .../defines/GraphicsDefines.cpp | 48 +- .../defines/MilitaryDefines.cpp | 281 ++- .../defines/PopsDefines.cpp | 247 ++- .../defines/PopsDefines.hpp | 2 +- .../diplomacy/CountryRelation.cpp | 8 +- .../diplomacy/CountryRelation.hpp | 43 +- .../diplomacy/DiplomaticAction.cpp | 413 ++--- .../diplomacy/DiplomaticAction.hpp | 9 +- .../economy/BuildingInstance.cpp | 26 +- .../economy/BuildingInstance.hpp | 13 +- .../economy/BuildingLevel.hpp | 13 +- .../economy/BuildingRestrictionCategory.hpp | 2 +- .../economy/BuildingType.cpp | 167 +- .../economy/BuildingType.hpp | 40 +- .../economy/EconomyManager.hpp | 11 +- .../economy/GoodDefinition.cpp | 238 +-- .../economy/GoodDefinition.hpp | 23 +- .../economy/GoodInstance.cpp | 45 +- .../economy/GoodInstance.hpp | 12 +- .../economy/production/ArtisanalProducer.cpp | 265 ++- .../economy/production/ArtisanalProducer.hpp | 105 +- .../production/ArtisanalProducerDeps.hpp | 2 +- .../economy/production/Employee.cpp | 7 +- .../economy/production/Employee.hpp | 3 +- .../economy/production/FactoryProducer.cpp | 68 +- .../economy/production/FactoryProducer.hpp | 29 +- .../economy/production/ProductionType.cpp | 460 ++--- .../economy/production/ProductionType.hpp | 116 +- .../production/ResourceGatheringOperation.cpp | 234 ++- .../production/ResourceGatheringOperation.hpp | 21 +- .../ResourceGatheringOperationDeps.hpp | 2 +- .../economy/trading/BuyResult.hpp | 17 +- .../economy/trading/BuyUpToOrder.hpp | 55 +- .../economy/trading/GoodMarket.cpp | 208 +-- .../economy/trading/GoodMarket.hpp | 26 +- .../economy/trading/MarketInstance.cpp | 34 +- .../economy/trading/MarketInstance.hpp | 17 +- .../economy/trading/MarketSellOrder.hpp | 41 +- .../economy/trading/SellResult.hpp | 10 +- src/openvic-simulation/history/Bookmark.cpp | 52 +- src/openvic-simulation/history/Bookmark.hpp | 16 +- .../history/CountryHistory.cpp | 62 +- .../history/CountryHistory.hpp | 32 +- .../history/DiplomaticHistory.cpp | 4 +- .../history/DiplomaticHistory.hpp | 5 +- .../history/HistoryManager.hpp | 1 + src/openvic-simulation/history/HistoryMap.hpp | 33 +- src/openvic-simulation/history/Period.hpp | 4 +- .../history/ProvinceHistory.cpp | 105 +- .../history/ProvinceHistory.hpp | 30 +- .../history/diplomacy/AllianceHistory.hpp | 6 +- .../history/diplomacy/ReparationsHistory.hpp | 6 +- .../history/diplomacy/SubjectHistory.hpp | 10 +- .../history/diplomacy/WarHistory.cpp | 13 +- .../history/diplomacy/WarHistory.hpp | 41 +- .../interface/GFXObject.cpp | 475 +++-- .../interface/GFXObject.hpp | 36 +- .../interface/GFXSprite.cpp | 205 ++- .../interface/GFXSprite.hpp | 10 +- src/openvic-simulation/interface/GUI.cpp | 476 +++-- src/openvic-simulation/interface/GUI.hpp | 22 +- src/openvic-simulation/interface/LoadBase.hpp | 6 +- src/openvic-simulation/interface/UI.cpp | 35 +- src/openvic-simulation/interface/UI.hpp | 10 +- src/openvic-simulation/map/Crime.cpp | 66 +- src/openvic-simulation/map/Crime.hpp | 20 +- src/openvic-simulation/map/LifeRating.hpp | 13 +- src/openvic-simulation/map/MapDefinition.cpp | 607 +++---- src/openvic-simulation/map/MapDefinition.hpp | 39 +- src/openvic-simulation/map/MapInstance.cpp | 86 +- src/openvic-simulation/map/MapInstance.hpp | 24 +- src/openvic-simulation/map/Mapmode.cpp | 389 ++-- src/openvic-simulation/map/Mapmode.hpp | 43 +- .../map/ProvinceDefinition.cpp | 56 +- .../map/ProvinceDefinition.hpp | 34 +- .../map/ProvinceInstance.cpp | 198 +- .../map/ProvinceInstance.hpp | 87 +- .../map/ProvinceInstanceDeps.hpp | 2 +- src/openvic-simulation/map/Region.cpp | 9 +- src/openvic-simulation/map/State.cpp | 97 +- src/openvic-simulation/map/State.hpp | 34 +- src/openvic-simulation/map/TerrainType.cpp | 190 +- src/openvic-simulation/map/TerrainType.hpp | 50 +- .../military/CombatWidth.hpp | 15 +- .../military/Deployment.cpp | 85 +- .../military/Deployment.hpp | 34 +- src/openvic-simulation/military/Leader.cpp | 28 +- src/openvic-simulation/military/Leader.hpp | 12 +- .../military/LeaderTrait.cpp | 34 +- .../military/LeaderTrait.hpp | 7 +- .../military/UnitInstance.cpp | 32 +- .../military/UnitInstance.hpp | 24 +- .../military/UnitInstanceGroup.cpp | 243 ++- .../military/UnitInstanceGroup.hpp | 56 +- src/openvic-simulation/military/UnitType.cpp | 403 +++-- src/openvic-simulation/military/UnitType.hpp | 81 +- src/openvic-simulation/military/Wargoal.cpp | 219 ++- src/openvic-simulation/military/Wargoal.hpp | 97 +- src/openvic-simulation/misc/Decision.cpp | 105 +- src/openvic-simulation/misc/Decision.hpp | 32 +- src/openvic-simulation/misc/Event.cpp | 298 ++-- src/openvic-simulation/misc/Event.hpp | 57 +- src/openvic-simulation/misc/GameAction.cpp | 120 +- src/openvic-simulation/misc/GameAction.hpp | 186 +- .../misc/GameRulesManager.cpp | 39 +- .../misc/GameRulesManager.hpp | 4 +- .../misc/SimulationClock.cpp | 7 +- .../misc/SimulationClock.hpp | 11 +- src/openvic-simulation/misc/SongChance.cpp | 35 +- src/openvic-simulation/misc/SongChance.hpp | 5 +- src/openvic-simulation/misc/SoundEffect.cpp | 13 +- src/openvic-simulation/misc/SoundEffect.hpp | 2 +- src/openvic-simulation/modifier/Modifier.cpp | 54 +- src/openvic-simulation/modifier/Modifier.hpp | 26 +- .../modifier/ModifierEffect.cpp | 17 +- .../modifier/ModifierEffect.hpp | 39 +- .../modifier/ModifierEffectCache.cpp | 10 +- .../modifier/ModifierEffectCache.hpp | 32 +- .../modifier/ModifierManager.cpp | 678 +++---- .../modifier/ModifierManager.hpp | 67 +- .../modifier/ModifierSum.cpp | 40 +- .../modifier/ModifierSum.hpp | 84 +- .../modifier/ModifierValue.cpp | 11 +- .../modifier/ModifierValue.hpp | 2 +- .../modifier/StaticModifierCache.cpp | 80 +- .../modifier/StaticModifierCache.hpp | 12 +- .../pathfinding/AStarPathing.cpp | 22 +- .../pathfinding/AStarPathing.hpp | 10 +- .../pathfinding/FringePathing.cpp | 4 +- .../pathfinding/PathingBase.hpp | 22 +- .../pathfinding/PointMap.cpp | 55 +- .../pathfinding/PointMap.hpp | 43 +- src/openvic-simulation/politics/BaseIssue.cpp | 19 +- src/openvic-simulation/politics/BaseIssue.hpp | 15 +- .../politics/Government.cpp | 170 +- .../politics/Government.hpp | 22 +- src/openvic-simulation/politics/Ideology.cpp | 145 +- src/openvic-simulation/politics/Ideology.hpp | 54 +- .../politics/IssueGroup.hpp | 9 +- .../politics/IssueManager.cpp | 349 ++-- .../politics/IssueManager.hpp | 77 +- .../politics/NationalFocus.cpp | 195 +- .../politics/NationalFocus.hpp | 63 +- .../politics/NationalValue.cpp | 33 +- .../politics/PartyPolicy.hpp | 38 +- .../politics/PoliticsInstanceManager.cpp | 14 +- .../politics/PoliticsInstanceManager.hpp | 9 +- .../politics/PoliticsManager.hpp | 8 +- src/openvic-simulation/politics/Rebel.cpp | 242 ++- src/openvic-simulation/politics/Rebel.hpp | 102 +- src/openvic-simulation/politics/Reform.cpp | 57 +- src/openvic-simulation/politics/Reform.hpp | 31 +- src/openvic-simulation/politics/RuleSet.hpp | 207 +-- src/openvic-simulation/population/Culture.cpp | 174 +- src/openvic-simulation/population/Culture.hpp | 51 +- src/openvic-simulation/population/Pop.cpp | 457 +++-- src/openvic-simulation/population/Pop.hpp | 138 +- src/openvic-simulation/population/PopDeps.hpp | 2 +- .../population/PopIdInProvince.hpp | 21 +- .../population/PopManager.cpp | 419 +++-- .../population/PopManager.hpp | 87 +- src/openvic-simulation/population/PopSize.hpp | 13 +- src/openvic-simulation/population/PopSum.hpp | 23 +- src/openvic-simulation/population/PopType.cpp | 126 +- src/openvic-simulation/population/PopType.hpp | 95 +- .../population/PopValuesFromProvince.cpp | 77 +- .../population/PopValuesFromProvince.hpp | 25 +- .../population/PopsAggregate.cpp | 144 +- .../population/PopsAggregate.hpp | 5 +- .../population/PopsAggregateDeps.hpp | 2 +- .../population/Religion.cpp | 61 +- .../population/Religion.hpp | 9 +- src/openvic-simulation/research/Invention.cpp | 121 +- src/openvic-simulation/research/Invention.hpp | 54 +- .../research/Technology.cpp | 154 +- .../research/Technology.hpp | 43 +- .../research/TechnologyUnlockLevel.hpp | 16 +- src/openvic-simulation/scripts/Condition.cpp | 448 +++-- src/openvic-simulation/scripts/Condition.hpp | 163 +- .../scripts/ConditionScript.cpp | 12 +- .../scripts/ConditionalWeight.cpp | 89 +- .../scripts/ConditionalWeight.hpp | 11 +- .../testing/Requirement.hpp | 1 + src/openvic-simulation/testing/TestScript.cpp | 4 +- src/openvic-simulation/testing/TestScript.hpp | 4 +- src/openvic-simulation/testing/Testing.hpp | 4 +- .../testing/test_scripts/A_001_file_tests.cpp | 109 +- .../test_scripts/A_002_economy_tests.cpp | 251 +-- src/openvic-simulation/types/ClampedValue.hpp | 12 +- src/openvic-simulation/types/ColonyStatus.hpp | 8 +- .../types/ConstructorTags.hpp | 6 +- src/openvic-simulation/types/FlagStrings.cpp | 10 +- .../types/HasIdentifier.hpp | 32 +- src/openvic-simulation/types/HasIndex.hpp | 4 +- .../types/IdentifierRegistry.hpp | 381 ++-- .../types/IndexedFlatMap.hpp | 825 ++++----- src/openvic-simulation/types/OptionalBool.hpp | 12 +- .../types/OrderedContainers.hpp | 127 +- .../types/OrderedContainersMath.hpp | 139 +- src/openvic-simulation/types/PopSprite.hpp | 2 +- src/openvic-simulation/types/Signal.hpp | 40 +- src/openvic-simulation/types/TypedIndices.hpp | 26 +- src/openvic-simulation/types/UniqueId.hpp | 2 +- .../types/UnitBranchType.hpp | 53 +- src/openvic-simulation/types/UnitVariant.hpp | 2 +- src/openvic-simulation/types/ValueHistory.hpp | 28 +- .../types/fixed_point/FixedPointMap.hpp | 3 +- .../utility/CompilerFeatureTesting.hpp | 2 +- .../utility/ConstexprIntToStr.hpp | 2 +- src/openvic-simulation/utility/Getters.hpp | 31 +- src/openvic-simulation/utility/Logger.hpp | 123 +- src/openvic-simulation/utility/ThreadPool.cpp | 276 ++- src/openvic-simulation/utility/ThreadPool.hpp | 61 +- .../utility/reactive/DependencyTracker.hpp | 14 +- .../utility/reactive/DerivedState.hpp | 29 +- .../utility/reactive/MutableState.hpp | 40 +- .../src/core/ecs/AliasingHotLoop.cpp | 20 +- tests/benchmarks/src/core/ecs/BulkCreate.cpp | 9 +- .../benchmarks/src/core/ecs/CommandBuffer.cpp | 6 +- .../src/core/ecs/ComponentAccess.cpp | 9 +- .../src/core/ecs/EntityLifecycle.cpp | 7 +- .../src/core/ecs/ImmutableEntity.cpp | 19 +- tests/benchmarks/src/core/ecs/Iteration.cpp | 25 +- tests/benchmarks/src/core/ecs/Migration.cpp | 7 +- tests/benchmarks/src/core/ecs/Reductions.cpp | 19 +- tests/benchmarks/src/core/ecs/Scheduler.cpp | 13 +- .../src/core/ecs/SystemShouldRun.cpp | 23 +- tests/benchmarks/src/core/ecs/SystemTick.cpp | 19 +- .../src/dataloading/Dataloading.cpp | 6 +- tests/src/Helper.hpp | 34 +- tests/src/SpyAllocator.hpp | 44 +- tests/src/core/BulkInsertWrapper.cpp | 86 +- tests/src/core/DualAdjacent.cpp | 28 +- tests/src/core/ecs/Archetype.cpp | 31 +- tests/src/core/ecs/BulkCreate.cpp | 71 +- tests/src/core/ecs/CachedRef.cpp | 9 +- tests/src/core/ecs/Checksum.cpp | 26 +- tests/src/core/ecs/Chunk.cpp | 17 +- tests/src/core/ecs/ChunkMigration.cpp | 20 +- tests/src/core/ecs/ChunkOverflow.cpp | 14 +- tests/src/core/ecs/ChunkPool.cpp | 13 +- tests/src/core/ecs/ChunkSystem.cpp | 2 +- tests/src/core/ecs/ChunkView.cpp | 21 +- tests/src/core/ecs/CommandBuffer.cpp | 63 +- .../src/core/ecs/CommandBufferApplyOrder.cpp | 22 +- tests/src/core/ecs/Component.cpp | 4 +- tests/src/core/ecs/Coverage.cpp | 92 +- tests/src/core/ecs/DenseSlotAllocator.cpp | 19 +- tests/src/core/ecs/EcsThreadPool.cpp | 15 +- tests/src/core/ecs/EntityID.cpp | 3 +- tests/src/core/ecs/EntityLifecycle.cpp | 6 +- tests/src/core/ecs/FNVHash.cpp | 4 +- tests/src/core/ecs/IdentitySnapshot.cpp | 9 +- .../core/ecs/IdentitySnapshotInvariance.cpp | 16 +- tests/src/core/ecs/ImmutableEntity.cpp | 82 +- tests/src/core/ecs/InTickMutationGuard.cpp | 13 +- tests/src/core/ecs/Integration.cpp | 28 +- tests/src/core/ecs/IntraSystemParallel.cpp | 26 +- tests/src/core/ecs/Iteration.cpp | 54 +- tests/src/core/ecs/KeyedReductions.cpp | 139 +- tests/src/core/ecs/MatcherHash.cpp | 40 +- tests/src/core/ecs/Migration.cpp | 4 +- tests/src/core/ecs/MultiSystemMixedStage.cpp | 82 +- tests/src/core/ecs/Query.cpp | 3 +- tests/src/core/ecs/Reductions.cpp | 28 +- tests/src/core/ecs/Singleton.cpp | 4 +- tests/src/core/ecs/System.cpp | 12 +- tests/src/core/ecs/SystemAccess.cpp | 37 +- tests/src/core/ecs/SystemFilters.cpp | 49 +- .../SystemFiltersWorkerCountInvariance.cpp | 100 +- tests/src/core/ecs/SystemPhaseAnchors.cpp | 131 +- .../ecs/SystemSchedulerDisjointWriters.cpp | 116 +- .../ecs/SystemSchedulerSingletonWrites.cpp | 69 +- .../core/ecs/SystemScheduler_Conflicts.cpp | 17 +- tests/src/core/ecs/SystemScheduler_DAG.cpp | 34 +- tests/src/core/ecs/SystemShouldRun.cpp | 192 +- tests/src/core/ecs/SystemThreadedSpawn.cpp | 25 +- tests/src/core/ecs/Tag.cpp | 18 +- tests/src/core/ecs/WorkerCountInvariance.cpp | 32 +- tests/src/core/object/Approx.hpp | 8 +- tests/src/core/object/Colour.cpp | 20 +- tests/src/core/object/FixedPoint.cpp | 33 +- tests/src/core/object/FixedPoint/Atomic.cpp | 2 +- tests/src/core/object/Timespan.cpp | 4 +- tests/src/core/object/Vector.hpp | 26 +- tests/src/core/object/Vector2.cpp | 22 +- tests/src/core/object/Vector3.cpp | 30 +- tests/src/core/object/Vector4.cpp | 42 +- tests/src/core/random/WeightedSampling.cpp | 23 +- tests/src/core/stl/containers/FixedVector.cpp | 96 +- tests/src/dataloader/NodeTools.cpp | 106 +- tests/src/economy/trading/GoodMarket.cpp | 80 +- tests/src/pathfinding/AStarPathing.cpp | 9 +- tests/src/pathfinding/FringePathing.cpp | 9 +- tests/src/pathfinding/Pathing.hpp | 23 +- tests/src/pathfinding/PointMap.cpp | 4 +- tests/src/types/IdentifierRegistry.cpp | 58 +- tests/src/types/Signal.cpp | 2 +- tests/src/utility/reactive/DerivedState.cpp | 53 +- tests/src/utility/reactive/MutableState.cpp | 6 +- 408 files changed, 15943 insertions(+), 14004 deletions(-) diff --git a/.clang-format b/.clang-format index a7d996cf5..cbfa6adb2 100644 --- a/.clang-format +++ b/.clang-format @@ -1,8 +1,7 @@ --- Language: Cpp -UseCRLF: false Standard: c++20 -UseTab: Always +UseTab: ForIndentation TabWidth: 4 IndentWidth: 4 ColumnLimit: 128 @@ -37,20 +36,20 @@ IndentRequiresClause: false IncludeBlocks: Regroup FixNamespaceComments: false EmptyLineBeforeAccessModifier: LogicalBlock -Cpp11BracedListStyle: false +Cpp11BracedListStyle: Block CompactNamespaces: false -BreakConstructorInitializers: BeforeColon +BreakConstructorInitializers: AfterColon BreakBeforeBraces: Attach AlwaysBreakTemplateDeclarations: Yes -AlwaysBreakAfterReturnType: None -PenaltyReturnTypeOnItsOwnLine: 10 +AlwaysBreakAfterReturnType: ExceptShortType +PenaltyReturnTypeOnItsOwnLine: 500 BreakBeforeConceptDeclarations: Always AllowShortLambdasOnASingleLine: Empty AllowShortIfStatementsOnASingleLine: Never -AllowShortEnumsOnASingleLine: true +AllowShortEnumsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: true AllowShortBlocksOnASingleLine: Empty -# AllowShortCompoundRequirementOnASingleLine: true +AllowShortCompoundRequirementOnASingleLine: true AllowShortFunctionsOnASingleLine: Empty AllowShortLoopsOnASingleLine: false AlignTrailingComments: @@ -58,22 +57,30 @@ AlignTrailingComments: OverEmptyLines: 0 AlignEscapedNewlines: DontAlign AlignAfterOpenBracket: BlockIndent -AlignOperands: DontAlign +AlignOperands: AlignAfterOperator AlignConsecutiveShortCaseStatements: Enabled: true AcrossEmptyLines: true AcrossComments: true AlignCaseColons: false -BinPackArguments: true -BinPackParameters: true +BinPackArguments: false +BinPackParameters: OnePerLine AccessModifierOffset: -4 InsertNewlineAtEOF: true InsertBraces: true MaxEmptyLinesToKeep: 2 RequiresClausePosition: OwnLine -SortIncludes: - Enabled: true - IgnoreCase: true +PenaltyBreakAssignment: 100 +PenaltyIndentedWhitespace: 5 +AttributeMacros: + - OV_ALWAYS_INLINE + - OV_SPEED_INLINE + - OV_NO_UNIQUE_ADDRESS + - OV_LIFETIME_BOUND + - OV_RESTRICT +IfMacros: + - CHECK_IF + - CHECK_FALSE_IF IncludeCategories: - Regex: <[[:alnum:]_]+> Priority: 1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b10e23578..39534c320 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,16 +2,12 @@ default_language_version: python: python3 repos: - # Waiting on Hop311 to approve clang-format - # - repo: https://github.com/pre-commit/mirrors-clang-format - # rev: v19.1.3 - # hooks: - # - id: clang-format - # files: \.(c|h|cpp|hpp|inc)$ - # types_or: [text] - # # exclude: | - # # (?x)^( - # # ) + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v22.1.8 + hooks: + - id: clang-format + files: \.(c|h|cpp|hpp|inc)$ + types_or: [text] - repo: https://github.com/pocc/pre-commit-hooks rev: v1.4.0 diff --git a/src/headless/main.cpp b/src/headless/main.cpp index afba914f8..32042be5a 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -12,9 +12,9 @@ #include #include +#include #include #include -#include #include #include #include @@ -33,11 +33,14 @@ inline static void print_memory_usage( // #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO spdlog::log( #ifndef SPDLOG_NO_SOURCE_LOC - spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, #else - spdlog::source_loc {}, + spdlog::source_loc {}, #endif - spdlog::level::info, "{} Memory Usage: {} Bytes", prefix, OpenVic::memory::MemoryTracker::get_memory_usage() + spdlog::level::info, + "{} Memory Usage: {} Bytes", + prefix, + OpenVic::memory::MemoryTracker::get_memory_usage() ); #endif #endif @@ -50,9 +53,9 @@ static void print_help(FILE* file, std::string_view program_name) { fmt::println(file, " -b : Use the following path as the base directory (instead of searching for one)."); fmt::println(file, " -s : Use the following path as a hint to search for a base directory."); fmt::println( - file, - "Any following paths are read as mods (/path/to/my/MODNAME.mod), with priority starting at one above the base " - "directory." + file, + "Any following paths are read as mods (/path/to/my/MODNAME.mod), with priority starting at one above the base " + "directory." ); fmt::println(file, "(Paths with spaces need to be enclosed in \"quotes\")."); } @@ -70,20 +73,20 @@ static void print_rgo(ProvinceInstance const& province) { SPDLOG_INFO("{}:", province); SPDLOG_INFO( - "\tgood: {}, " - "production_type: {}, " - "size_multiplier: {:.3}, " - "output_quantity_yesterday: {:.3}, " - "revenue_yesterday: {:.3}, " - "total owner income: {:.3}, " - "total employee income: {:.3}", - production_type.output_good, // - production_type, // - rgo.get_size_multiplier(), // - rgo.get_output_quantity_yesterday(), // - rgo.get_revenue_yesterday(), // - rgo.get_total_owner_income_cache(), // - rgo.get_total_employee_income_cache() + "\tgood: {}, " + "production_type: {}, " + "size_multiplier: {:.3}, " + "output_quantity_yesterday: {:.3}, " + "revenue_yesterday: {:.3}, " + "total owner income: {:.3}, " + "total employee income: {:.3}", + production_type.output_good, // + production_type, // + rgo.get_size_multiplier(), // + rgo.get_output_quantity_yesterday(), // + rgo.get_revenue_yesterday(), // + rgo.get_total_owner_income_cache(), // + rgo.get_total_employee_income_cache() ); bool logged_employees = false; @@ -190,11 +193,11 @@ static bool run_headless(fs::path const& root, memory::vector& m spdlog::sink_ptr counter_sink = std::make_shared([](spdlog::details::log_msg const& msg) { switch (msg.level) { using namespace spdlog::level; - case info: info_count++; break; - case warn: warning_count++; break; - case err: error_count++; break; + case info: info_count++; break; + case warn: warning_count++; break; + case err: error_count++; break; case critical: critical_count++; break; - default: break; + default: break; } }); @@ -202,9 +205,10 @@ static bool run_headless(fs::path const& root, memory::vector& m GameManager game_manager { [] { - SPDLOG_INFO("State updated"); + SPDLOG_INFO("State updated"); }, - nullptr, nullptr // + nullptr, + nullptr // }; SPDLOG_INFO("Commit hash: {}", GameManager::get_commit_hash()); @@ -220,9 +224,9 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("===== Loading definitions... ====="); ret &= game_manager.load_definitions( - [](std::string_view key, Dataloader::locale_t locale, std::string_view localisation) -> bool { - return true; - } + [](std::string_view key, Dataloader::locale_t locale, std::string_view localisation) -> bool { + return true; + } ); print_memory_usage("Definition Setup"); @@ -244,10 +248,7 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("===== Setting up instance... ====="); ret &= game_manager.setup_instance( - game_manager.get_definition_manager() - .get_history_manager() - .get_bookmark_manager() - .get_front_bookmark() + game_manager.get_definition_manager().get_history_manager().get_bookmark_manager().get_front_bookmark() ); print_memory_usage("Instance Setup"); @@ -268,20 +269,26 @@ static bool run_headless(fs::path const& root, memory::vector& m memory::string countries_str; for (CountryInstance& country : countries) { countries_str += fmt::format( - "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", // - country, // - country.get_total_rank(), country.total_score.get_untracked(), // - country.get_prestige_rank(), country.get_prestige_untracked(), - country.get_industrial_rank(), country.get_industrial_power_untracked(), - country.get_military_rank(), country.military_power.get_untracked() + "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", // + country, // + country.get_total_rank(), + country.total_score.get_untracked(), // + country.get_prestige_rank(), + country.get_prestige_untracked(), + country.get_industrial_rank(), + country.get_industrial_power_untracked(), + country.get_military_rank(), + country.military_power.get_untracked() ); } SPDLOG_INFO("{}:{}", title, countries_str); }; - CountryInstanceManager const& country_instance_manager = game_manager.get_instance_manager()->get_country_instance_manager(); + CountryInstanceManager const& country_instance_manager = + game_manager.get_instance_manager()->get_country_instance_manager(); - OpenVic::forwardable_span> great_powers = country_instance_manager.get_great_powers(); + OpenVic::forwardable_span> great_powers = + country_instance_manager.get_great_powers(); print_ranking_list("Great Powers", great_powers); print_ranking_list("Secondary Powers", country_instance_manager.get_secondary_powers()); print_ranking_list("All countries", country_instance_manager.get_total_ranking()); @@ -312,13 +319,13 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("===== Land Pathfinding test... ====="); test_duration_t duration = std::chrono::duration_cast( // - run_pathing_test(map_instance.get_land_pathing(), LAND_SEED) + run_pathing_test(map_instance.get_land_pathing(), LAND_SEED) ); SPDLOG_INFO("Ran {} land pathing tests in {}", TESTS, duration); SPDLOG_INFO("===== Sea Pathfinding test... ====="); duration = std::chrono::duration_cast( // - run_pathing_test(map_instance.get_sea_pathing(), SEA_SEED) + run_pathing_test(map_instance.get_sea_pathing(), SEA_SEED) ); SPDLOG_INFO("Ran {} sea pathing tests in {}", TESTS, duration); } @@ -329,8 +336,8 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("===== Game Tick test... ====="); size_t ticks_passed = 0; test_duration_t min_tick_duration = test_duration_t::max(), // - max_tick_duration = test_duration_t::min(), // - total_tick_duration {}; + max_tick_duration = test_duration_t::min(), // + total_tick_duration {}; const test_time_point_t start_time = testing_clock_t::now(); while (++ticks_passed < TICK_COUNT) { const test_time_point_t tick_start = testing_clock_t::now(); @@ -353,14 +360,20 @@ static bool run_headless(fs::path const& root, memory::vector& m const test_duration_t tick_tps = total_tick_duration / ticks_passed; const test_duration_t total_tps = duration / ticks_passed; spdlog::info( - "Ran {} / {} ticks, total time {} at {} per tick, tick time only {} at {} per tick. " - "Tick lengths ranged from {} to {}.", - ticks_passed, TICK_COUNT, duration, total_tps, total_tick_duration, tick_tps, // - min_tick_duration, max_tick_duration + "Ran {} / {} ticks, total time {} at {} per tick, tick time only {} at {} per tick. " + "Tick lengths ranged from {} to {}.", + ticks_passed, + TICK_COUNT, + duration, + total_tps, + total_tick_duration, + tick_tps, // + min_tick_duration, + max_tick_duration ); } else { spdlog::error_s( - "No ticks passed ({}, expected {}) or zero duration measured ({})!", ticks_passed, TICK_COUNT, duration + "No ticks passed ({}, expected {}) or zero duration measured ({})!", ticks_passed, TICK_COUNT, duration ); ret = false; } @@ -375,7 +388,7 @@ static bool run_headless(fs::path const& root, memory::vector& m } /* - $ program [-h] [-t] [-b] [path]+ + $ program [-h] [-t] [-b] [path]+ */ int main(int argc, char const* argv[]) { @@ -399,7 +412,7 @@ int main(int argc, char const* argv[]) { return true; } else { fmt::println( - stderr, "Empty path after giving \"{}\" to {} command line argument \"{}\".", path, path_use, command + stderr, "Empty path after giving \"{}\" to {} command line argument \"{}\".", path, path_use, command ); } } else { @@ -452,17 +465,19 @@ int main(int argc, char const* argv[]) { spdlog::info("Load returned: {}", ret ? "SUCCESS" : "FAILURE"); spdlog::info( - "Logger Summary: " + "Logger Summary: " #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO - "Info = {}, " + "Info = {}, " #endif - "Warning = {}, " - "Error = {}, " - "Critical = {}", + "Warning = {}, " + "Error = {}, " + "Critical = {}", #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO - info_count, + info_count, #endif - warning_count, error_count, critical_count + warning_count, + error_count, + critical_count ); return ret ? 0 : -1; diff --git a/src/openvic-simulation/DefinitionManager.hpp b/src/openvic-simulation/DefinitionManager.hpp index e30d44d5f..3a870109b 100644 --- a/src/openvic-simulation/DefinitionManager.hpp +++ b/src/openvic-simulation/DefinitionManager.hpp @@ -19,7 +19,6 @@ #include "openvic-simulation/population/PopManager.hpp" #include "openvic-simulation/research/ResearchManager.hpp" #include "openvic-simulation/scripts/ScriptManager.hpp" -#include "openvic-simulation/interface/UI.hpp" namespace OpenVic { struct DefinitionManager { diff --git a/src/openvic-simulation/GameManager.cpp b/src/openvic-simulation/GameManager.cpp index e73002310..09c091a9f 100644 --- a/src/openvic-simulation/GameManager.cpp +++ b/src/openvic-simulation/GameManager.cpp @@ -29,12 +29,12 @@ GameManager::elapsed_time_getter_func_t GameManager::get_elapsed_msec_time_callb }; GameManager::GameManager( - InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, - elapsed_time_getter_func_t new_get_elapsed_usec_callback, - elapsed_time_getter_func_t new_get_elapsed_msec_callback -) : gamestate_updated_callback { - new_gamestate_updated_callback ? std::move(new_gamestate_updated_callback) : []() {} - }, definitions_loaded { false }, mod_descriptors_loaded { false } { + InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, + elapsed_time_getter_func_t new_get_elapsed_usec_callback, + elapsed_time_getter_func_t new_get_elapsed_msec_callback +) : + gamestate_updated_callback { new_gamestate_updated_callback ? std::move(new_gamestate_updated_callback) : []() {} }, + definitions_loaded { false }, mod_descriptors_loaded { false } { if (new_get_elapsed_usec_callback) { get_elapsed_usec_time_callback = { std::move(new_get_elapsed_usec_callback) }; } @@ -50,8 +50,8 @@ GameManager::GameManager( GameManager::~GameManager() { if (instance_manager) { spdlog::error_s( - "Destroying GameManager with an active InstanceManager! " - "Calling end_game_session() to ensure proper cleanup and execute any required special end-of-session actions." + "Destroying GameManager with an active InstanceManager! " + "Calling end_game_session() to ensure proper cleanup and execute any required special end-of-session actions." ); end_game_session(); @@ -84,10 +84,10 @@ bool GameManager::load_mods(memory::vector const& mods_to_find) * (Historical Project Mod 0.4.6 or HPM both valid, for example), and load them plus their dependencies. */ for (std::string_view requested_mod : mods_to_find) { - memory::vector::const_iterator it = ranges::find_if(mod_manager.get_mods(), - [&requested_mod](Mod const& mod) -> bool { - return mod.get_identifier() == requested_mod || mod.get_user_dir() == requested_mod; - } + memory::vector::const_iterator it = ranges::find_if( + mod_manager.get_mods(), [&requested_mod](Mod const& mod) -> bool { + return mod.get_identifier() == requested_mod || mod.get_user_dir() == requested_mod; + } ); if (it == mod_manager.get_mods().end()) { @@ -98,7 +98,7 @@ bool GameManager::load_mods(memory::vector const& mods_to_find) Mod const& mod = *it; vector_ordered_set> dependencies = mod.generate_dependency_list(&ret); - if(!ret) { + if (!ret) { continue; } @@ -178,11 +178,7 @@ bool GameManager::setup_instance(Bookmark const& bookmark) { SPDLOG_INFO("Initialising new game instance."); - instance_manager.emplace( - game_rules_manager, - definition_manager, - gamestate_updated_callback - ); + instance_manager.emplace(game_rules_manager, definition_manager, gamestate_updated_callback); SPDLOG_INFO("Setting up new game instance."); diff --git a/src/openvic-simulation/GameManager.hpp b/src/openvic-simulation/GameManager.hpp index 95e37dd9b..d627eee77 100644 --- a/src/openvic-simulation/GameManager.hpp +++ b/src/openvic-simulation/GameManager.hpp @@ -5,12 +5,12 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/dataloader/ModManager.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/gen/commit_info.gen.hpp" -#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" namespace OpenVic { @@ -33,9 +33,9 @@ namespace OpenVic { public: GameManager( - InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, - elapsed_time_getter_func_t new_get_elapsed_usec_callback, - elapsed_time_getter_func_t new_get_elapsed_msec_callback + InstanceManager::gamestate_updated_func_t new_gamestate_updated_callback, + elapsed_time_getter_func_t new_get_elapsed_usec_callback, + elapsed_time_getter_func_t new_get_elapsed_msec_callback ); ~GameManager(); diff --git a/src/openvic-simulation/InstanceManager.cpp b/src/openvic-simulation/InstanceManager.cpp index cf628e40c..ace86b22c 100644 --- a/src/openvic-simulation/InstanceManager.cpp +++ b/src/openvic-simulation/InstanceManager.cpp @@ -9,139 +9,98 @@ using namespace OpenVic; InstanceManager::InstanceManager( - GameRulesManager const& new_game_rules_manager, - DefinitionManager const& new_definition_manager, - gamestate_updated_func_t gamestate_updated_callback -) : thread_pool { today }, - definition_manager { new_definition_manager }, - game_action_manager { *this }, - game_rules_manager { new_game_rules_manager }, - good_instance_manager { - new_definition_manager.get_economy_manager().get_good_definition_manager(), - new_game_rules_manager - }, - market_instance { - thread_pool, - new_definition_manager.get_define_manager().get_country_defines(), - good_instance_manager - }, - artisanal_producer_deps { - new_definition_manager.get_define_manager().get_economy_defines(), - new_definition_manager.get_economy_manager().get_good_definition_manager().get_good_definitions(), - new_definition_manager.get_modifier_manager().get_modifier_effect_cache() - }, - country_instance_deps { - new_definition_manager.get_economy_manager().get_building_type_manager().get_building_types(), - new_definition_manager.get_define_manager().get_country_defines(), - country_relation_manager, - new_definition_manager.get_crime_manager().get_crime_modifiers(), - new_definition_manager.get_define_manager().get_end_date(), - new_definition_manager.get_define_manager().get_diplomacy_defines(), - new_definition_manager.get_define_manager().get_economy_defines(), - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), - new_definition_manager.get_research_manager().get_invention_manager().get_inventions(), - new_game_rules_manager, - good_instance_manager.get_good_instances(), - good_instance_manager, - new_definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), - market_instance, - new_definition_manager.get_define_manager().get_military_defines(), - new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), - PopsAggregateDeps{ - ideology_index_t( - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideology_count() - ), - party_policy_index_t( - new_definition_manager.get_politics_manager().get_issue_manager().get_party_policy_count() - ), - pop_type_index_t( - new_definition_manager.get_pop_manager().get_pop_type_count() - ), - reform_index_t( - new_definition_manager.get_politics_manager().get_issue_manager().get_reform_count() - ), - strata_index_t( - new_definition_manager.get_pop_manager().get_strata_count() - ) - }, - new_definition_manager.get_pop_manager().get_pop_types(), - new_definition_manager.get_politics_manager().get_issue_manager().get_reform_groups(), - new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), - new_definition_manager.get_military_manager().get_unit_type_manager().get_ship_types(), - new_definition_manager.get_pop_manager().get_stratas(), - new_definition_manager.get_research_manager().get_technology_manager().get_technologies(), - new_definition_manager.get_military_manager().get_unit_type_manager() - }, - pops_aggregate_deps { - ideology_index_t( - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideology_count() - ), - party_policy_index_t( - new_definition_manager.get_politics_manager().get_issue_manager().get_party_policy_count() - ), - pop_type_index_t( - new_definition_manager.get_pop_manager().get_pop_type_count() - ), - reform_index_t( - new_definition_manager.get_politics_manager().get_issue_manager().get_reform_count() - ), - strata_index_t( - new_definition_manager.get_pop_manager().get_strata_count() - ) - }, - pop_deps { - artisanal_producer_deps, - market_instance, - pops_aggregate_deps - }, - rgo_deps { - market_instance, - new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), - pop_type_index_t(new_definition_manager.get_pop_manager().get_pop_type_count()) - }, - province_instance_deps { - new_definition_manager.get_economy_manager().get_building_type_manager(), - new_game_rules_manager, - pops_aggregate_deps, - rgo_deps, - new_definition_manager.get_pop_manager().get_stratas() - }, - global_flags { "global" }, - country_instance_manager { - new_definition_manager.get_define_manager().get_country_defines(), - new_definition_manager.get_country_definition_manager(), - country_instance_deps, - good_instance_manager, - new_definition_manager.get_define_manager().get_pops_defines(), - new_definition_manager.get_pop_manager().get_pop_types(), - new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), - thread_pool - }, - unit_instance_manager { - new_definition_manager.get_pop_manager().get_culture_manager(), - new_definition_manager.get_military_manager().get_leader_trait_manager(), - new_definition_manager.get_define_manager().get_military_defines() - }, - politics_instance_manager { - *this, - new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies() - }, - map_instance { - new_definition_manager.get_map_definition(), - province_instance_deps, - thread_pool - }, - simulation_clock { - [this]() -> void { - queue_game_action(); - }, - [this]() -> void { - execute_game_actions(); - update_gamestate(); - } - }, - console_instance { *this }, - gamestate_updated { gamestate_updated_callback ? std::move(gamestate_updated_callback) : []() {} } {} + GameRulesManager const& new_game_rules_manager, + DefinitionManager const& new_definition_manager, + gamestate_updated_func_t gamestate_updated_callback +) : + thread_pool { today }, definition_manager { new_definition_manager }, game_action_manager { *this }, + game_rules_manager { new_game_rules_manager }, + good_instance_manager { + new_definition_manager.get_economy_manager().get_good_definition_manager(), new_game_rules_manager + }, + market_instance { thread_pool, new_definition_manager.get_define_manager().get_country_defines(), good_instance_manager }, + artisanal_producer_deps { + new_definition_manager.get_define_manager().get_economy_defines(), + new_definition_manager.get_economy_manager().get_good_definition_manager().get_good_definitions(), + new_definition_manager.get_modifier_manager().get_modifier_effect_cache() + }, + country_instance_deps { + new_definition_manager.get_economy_manager().get_building_type_manager().get_building_types(), + new_definition_manager.get_define_manager().get_country_defines(), + country_relation_manager, + new_definition_manager.get_crime_manager().get_crime_modifiers(), + new_definition_manager.get_define_manager().get_end_date(), + new_definition_manager.get_define_manager().get_diplomacy_defines(), + new_definition_manager.get_define_manager().get_economy_defines(), + new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), + new_definition_manager.get_research_manager().get_invention_manager().get_inventions(), + new_game_rules_manager, + good_instance_manager.get_good_instances(), + good_instance_manager, + new_definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), + market_instance, + new_definition_manager.get_define_manager().get_military_defines(), + new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), + PopsAggregateDeps { + ideology_index_t(new_definition_manager.get_politics_manager().get_ideology_manager().get_ideology_count()), + party_policy_index_t(new_definition_manager.get_politics_manager().get_issue_manager().get_party_policy_count()), + pop_type_index_t(new_definition_manager.get_pop_manager().get_pop_type_count()), + reform_index_t(new_definition_manager.get_politics_manager().get_issue_manager().get_reform_count()), + strata_index_t(new_definition_manager.get_pop_manager().get_strata_count()) }, + new_definition_manager.get_pop_manager().get_pop_types(), + new_definition_manager.get_politics_manager().get_issue_manager().get_reform_groups(), + new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), + new_definition_manager.get_military_manager().get_unit_type_manager().get_ship_types(), + new_definition_manager.get_pop_manager().get_stratas(), + new_definition_manager.get_research_manager().get_technology_manager().get_technologies(), + new_definition_manager.get_military_manager().get_unit_type_manager() + }, + pops_aggregate_deps { + ideology_index_t(new_definition_manager.get_politics_manager().get_ideology_manager().get_ideology_count()), + party_policy_index_t(new_definition_manager.get_politics_manager().get_issue_manager().get_party_policy_count()), + pop_type_index_t(new_definition_manager.get_pop_manager().get_pop_type_count()), + reform_index_t(new_definition_manager.get_politics_manager().get_issue_manager().get_reform_count()), + strata_index_t(new_definition_manager.get_pop_manager().get_strata_count()) + }, + pop_deps { artisanal_producer_deps, market_instance, pops_aggregate_deps }, + rgo_deps { market_instance, + new_definition_manager.get_modifier_manager().get_modifier_effect_cache(), + pop_type_index_t(new_definition_manager.get_pop_manager().get_pop_type_count()) }, + province_instance_deps { + new_definition_manager.get_economy_manager().get_building_type_manager(), + new_game_rules_manager, + pops_aggregate_deps, + rgo_deps, + new_definition_manager.get_pop_manager().get_stratas() + }, + global_flags { "global" }, + country_instance_manager { + new_definition_manager.get_define_manager().get_country_defines(), + new_definition_manager.get_country_definition_manager(), + country_instance_deps, + good_instance_manager, + new_definition_manager.get_define_manager().get_pops_defines(), + new_definition_manager.get_pop_manager().get_pop_types(), + new_definition_manager.get_military_manager().get_unit_type_manager().get_regiment_types(), + thread_pool + }, + unit_instance_manager { + new_definition_manager.get_pop_manager().get_culture_manager(), + new_definition_manager.get_military_manager().get_leader_trait_manager(), + new_definition_manager.get_define_manager().get_military_defines() + }, + politics_instance_manager { *this, new_definition_manager.get_politics_manager().get_ideology_manager().get_ideologies() }, + map_instance { new_definition_manager.get_map_definition(), province_instance_deps, thread_pool }, simulation_clock { + [this]() -> void { + queue_game_action(); + }, + [this]() -> void { + execute_game_actions(); + update_gamestate(); + } + }, + console_instance { *this }, + gamestate_updated { gamestate_updated_callback ? std::move(gamestate_updated_callback) : []() {} } {} void InstanceManager::set_gamestate_needs_update() { if (!currently_updating_gamestate) { @@ -234,15 +193,15 @@ bool InstanceManager::setup() { } thread_pool.initialise_threadpool( - game_rules_manager, - good_instance_manager, - definition_manager.get_modifier_manager().get_modifier_effect_cache(), - definition_manager.get_define_manager().get_pops_defines(), - definition_manager.get_economy_manager().get_production_type_manager(), - strata_index_t(definition_manager.get_pop_manager().get_strata_count()), - good_instance_manager.get_good_instances(), - country_instance_manager.get_country_instances(), - map_instance.get_province_instances() + game_rules_manager, + good_instance_manager, + definition_manager.get_modifier_manager().get_modifier_effect_cache(), + definition_manager.get_define_manager().get_pops_defines(), + definition_manager.get_economy_manager().get_production_type_manager(), + strata_index_t(definition_manager.get_pop_manager().get_strata_count()), + good_instance_manager.get_good_instances(), + country_instance_manager.get_country_instances(), + map_instance.get_province_instances() ); game_instance_setup = true; @@ -273,12 +232,13 @@ bool InstanceManager::load_bookmark(Bookmark const& new_bookmark) { politics_instance_manager.setup_starting_ideologies(); bool ret = map_instance.apply_history_to_provinces( - definition_manager.get_history_manager().get_province_manager(), today, - country_instance_manager, - definition_manager.get_define_manager().get_military_defines(), - pop_deps, - definition_manager.get_pop_manager().get_pop_types(), - definition_manager.get_politics_manager().get_issue_manager().get_reforms() + definition_manager.get_history_manager().get_province_manager(), + today, + country_instance_manager, + definition_manager.get_define_manager().get_military_defines(), + pop_deps, + definition_manager.get_pop_manager().get_pop_types(), + definition_manager.get_politics_manager().get_issue_manager().get_reforms() ); // It is important that province history is applied before country history as province history includes @@ -287,11 +247,11 @@ bool InstanceManager::load_bookmark(Bookmark const& new_bookmark) { ret &= country_instance_manager.apply_history_to_countries(*this); ret &= map_instance.get_state_manager().generate_states( - definition_manager.get_map_definition(), - map_instance, - pops_aggregate_deps, - definition_manager.get_pop_manager().get_stratas(), - definition_manager.get_pop_manager().get_pop_types() + definition_manager.get_map_definition(), + map_instance, + pops_aggregate_deps, + definition_manager.get_pop_manager().get_stratas(), + definition_manager.get_pop_manager().get_pop_types() ); bool all_has_state = true; @@ -359,12 +319,8 @@ void InstanceManager::update_modifier_sums() { // full copy of all the modifiers affecting them in their modifier sum, but provinces only having their directly/locally // applied modifiers in their modifier sum, hence requiring owner country modifier effect values to be looked up when // determining the value of a global effect on the province. - country_instance_manager.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); - map_instance.update_modifier_sums( - today, definition_manager.get_modifier_manager().get_static_modifier_cache() - ); + country_instance_manager.update_modifier_sums(today, definition_manager.get_modifier_manager().get_static_modifier_cache()); + map_instance.update_modifier_sums(today, definition_manager.get_modifier_manager().get_static_modifier_cache()); } bool InstanceManager::queue_game_action(game_action_t&& game_action) { diff --git a/src/openvic-simulation/InstanceManager.hpp b/src/openvic-simulation/InstanceManager.hpp index 50b8e84a6..2e7797687 100644 --- a/src/openvic-simulation/InstanceManager.hpp +++ b/src/openvic-simulation/InstanceManager.hpp @@ -84,9 +84,9 @@ namespace OpenVic { DefinitionManager const& definition_manager; InstanceManager( - GameRulesManager const& new_game_rules_manager, - DefinitionManager const& new_definition_manager, - gamestate_updated_func_t gamestate_updated_callback + GameRulesManager const& new_game_rules_manager, + DefinitionManager const& new_definition_manager, + gamestate_updated_func_t gamestate_updated_callback ); inline constexpr bool is_bookmark_loaded() const { @@ -103,12 +103,7 @@ namespace OpenVic { template bool queue_game_action(Args&&... args) { - return queue_game_action( - game_action_t( - std::in_place_type, - std::forward(args)... - ) - ); + return queue_game_action(game_action_t(std::in_place_type, std::forward(args)...)); } bool queue_game_action(game_action_t&& game_action); }; diff --git a/src/openvic-simulation/console/ConsoleInstance.cpp b/src/openvic-simulation/console/ConsoleInstance.cpp index e0be3607b..6a52c5316 100644 --- a/src/openvic-simulation/console/ConsoleInstance.cpp +++ b/src/openvic-simulation/console/ConsoleInstance.cpp @@ -9,14 +9,14 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/object/Colour.hpp" #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/country/CountryInstance.hpp" -#include "openvic-simulation/DefinitionManager.hpp" -#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/military/UnitType.hpp" #include "openvic-simulation/military/Wargoal.hpp" @@ -29,8 +29,8 @@ using namespace std::string_view_literals; ConsoleInstance::ConsoleInstance(InstanceManager& instance_manager) : ConsoleInstance(instance_manager, &default_write_func) {} -ConsoleInstance::ConsoleInstance(InstanceManager& instance_manager, write_func_t&& write_func) - : instance_manager(instance_manager) { +ConsoleInstance::ConsoleInstance(InstanceManager& instance_manager, write_func_t&& write_func) : + instance_manager(instance_manager) { set_write_func(std::move(write_func)); setup_commands(); } @@ -186,11 +186,11 @@ std::optional ConsoleInstance::validate_boolean(std::string_view value_str constexpr std::string_view ON_VALUE = "on"sv; constexpr std::string_view OFF_VALUE = "off"sv; - if (value_string == TRUE_VALUE || value_string == YES_VALUE || // - value_string == ONE_VALUE || value_string == ON_VALUE) { + if (value_string == TRUE_VALUE || value_string == YES_VALUE || value_string == ONE_VALUE || value_string == ON_VALUE) { return true; - } else if (value_string == FALSE_VALUE || value_string == NO_VALUE || // - value_string == ZERO_VALUE || value_string == OFF_VALUE) { + } else if ( + value_string == FALSE_VALUE || value_string == NO_VALUE || value_string == ZERO_VALUE || value_string == OFF_VALUE + ) { return false; } @@ -255,12 +255,10 @@ UnitType const* ConsoleInstance::validate_unit(std::string_view value_string) { return nullptr; } - UnitType const* unit_type = // - instance_manager - .definition_manager // - .get_military_manager() - .get_unit_type_manager() - .get_unit_type_by_identifier(value_string); + UnitType const* unit_type = + instance_manager.definition_manager.get_military_manager().get_unit_type_manager().get_unit_type_by_identifier( + value_string + ); if (unit_type == nullptr) { write_error("Unknown unit type"); @@ -305,12 +303,10 @@ Invention const* ConsoleInstance::validate_invention(std::string_view value_stri return nullptr; } - Invention const* invention = // - instance_manager - .definition_manager // - .get_research_manager() - .get_invention_manager() - .get_invention_by_identifier(value_string); + Invention const* invention = + instance_manager.definition_manager.get_research_manager().get_invention_manager().get_invention_by_identifier( + value_string + ); if (invention == nullptr) { write_error("Unknown invention"); @@ -324,12 +320,10 @@ WargoalType const* ConsoleInstance::validate_cb_type(std::string_view value_stri return nullptr; } - WargoalType const* cb_type = // - instance_manager - .definition_manager // - .get_military_manager() - .get_wargoal_type_manager() - .get_wargoal_type_by_identifier(value_string); + WargoalType const* cb_type = + instance_manager.definition_manager.get_military_manager().get_wargoal_type_manager().get_wargoal_type_by_identifier( + value_string + ); if (cb_type == nullptr) { write_error("Unknown casus belli type"); @@ -343,12 +337,10 @@ Technology const* ConsoleInstance::validate_tech_name(std::string_view value_str return nullptr; } - Technology const* tech = // - instance_manager - .definition_manager // - .get_research_manager() - .get_technology_manager() - .get_technology_by_identifier(value_string); + Technology const* tech = + instance_manager.definition_manager.get_research_manager().get_technology_manager().get_technology_by_identifier( + value_string + ); if (tech == nullptr) { write_error("Unknown technology"); diff --git a/src/openvic-simulation/core/Assert.hpp b/src/openvic-simulation/core/Assert.hpp index bf93c8f08..40f190090 100644 --- a/src/openvic-simulation/core/Assert.hpp +++ b/src/openvic-simulation/core/Assert.hpp @@ -50,59 +50,68 @@ #define OV_HARDEN_ASSERT_VALID_ITERATOR(IT, FUNC_NAME) \ OV_HARDEN_ASSERT_VALID_RANGE_MESSAGE(IT, end(), FUNC_NAME " called with a non-dereferenceable iterator") -#else -#define OV_HARDEN_ASSERT_VALID_RANGE_MESSAGE(BEGIN, END, MSG) -#define OV_HARDEN_ASSERT_NONEMPTY_RANGE(BEGIN, END, FUNC_NAME) -#define OV_HARDEN_ASSERT_ACCESS(INDEX, FUNC_NAME) -#define OV_HARDEN_ASSERT_NONEMPTY(FUNC_NAME) -#define OV_HARDEN_ASSERT_VALID_ITERATOR(IT, FUNC_NAME) - -// clang-format off -# if defined(_GLIBCXX_ASSERTIONS) - || (defined(_LIBCPP_HARDENING_MODE) && _LIBCPP_HARDENING_MODE == _LIBCPP_HARDENING_MODE_FAST) - || _MSVC_STL_HARDENING == 1 +#else // not defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) || (defined(_MSVC_STL_VERSION) && _MSVC_STL_HARDENING == 1) +#define OV_HARDEN_ASSERT_VALID_RANGE_MESSAGE(BEGIN, END, MSG) ((void)0) +#define OV_HARDEN_ASSERT_NONEMPTY_RANGE(BEGIN, END, FUNC_NAME) ((void)0) +#define OV_HARDEN_ASSERT_ACCESS(INDEX, FUNC_NAME) ((void)0) +#define OV_HARDEN_ASSERT_NONEMPTY(FUNC_NAME) ((void)0) +#define OV_HARDEN_ASSERT_VALID_ITERATOR(IT, FUNC_NAME) ((void)0) + +#if defined(_GLIBCXX_ASSERTIONS) +|| (defined(_LIBCPP_HARDENING_MODE) && _LIBCPP_HARDENING_MODE == _LIBCPP_HARDENING_MODE_FAST) || _MSVC_STL_HARDENING == 1 #warning "Unsupported standard library for memory hardening, hardening asserts will be ignored." -# endif -// clang-format on +#endif // defined(_GLIBCXX_ASSERTIONS) -#endif +#endif // __GLIBCXX__ #ifdef __GLIBCXX__ + #if __has_include() #include #elif __has_include() #include -#else +#else // not __has_include() || __has_include() #include #warning "Unknown GLIBCXX library version" #define OV_THROW_OUT_OF_RANGE(CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE) std::abort() #define OV_THROW_LENGTH_ERROR(CLASS_NAME, FUNC_NAME) std::abort() -#endif +#endif // __has_include() #ifndef OV_THROW_OUT_OF_RANGE #define OV_THROW_OUT_OF_RANGE(CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE) \ std::__throw_out_of_range_fmt( \ - __N("%s::%s: %s (which is %zu) >= this->size() (which is %zu)"), CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE \ + __N("%s::%s: %s (which is %zu) >= this->size() (which is %zu)"), CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE \ ) -#endif +#endif // OV_THROW_OUT_OF_RANGE #ifndef OV_THROW_LENGTH_ERROR #define OV_THROW_LENGTH_ERROR(CLASS_NAME, FUNC_NAME) std::__throw_length_error(__N(CLASS_NAME "::" FUNC_NAME)) -#endif +#endif // OV_THROW_LENGTH_ERROR #elif defined(_LIBCPP_VERSION) && __has_include() #include +#ifndef OV_THROW_OUT_OF_RANGE #define OV_THROW_OUT_OF_RANGE(CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE) std::__throw_out_of_range(CLASS_NAME) +#endif // OV_THROW_OUT_OF_RANGE + +#ifndef OV_THROW_LENGTH_ERROR #define OV_THROW_LENGTH_ERROR(CLASS_NAME, FUNC_NAME) std::__throw_length_error(CLASS_NAME) +#endif // OV_THROW_LENGTH_ERROR #elif defined(_MSVC_STL_VERSION) && __has_include() #include +#ifndef OV_THROW_OUT_OF_RANGE #define OV_THROW_OUT_OF_RANGE(CLASS_NAME, FUNC_NAME, VAR_NAME, VAR, SIZE) \ std::_Xout_of_range("invalid " CLASS_NAME " subscript") +#endif // OV_THROW_OUT_OF_RANGE + +#ifndef OV_THROW_LENGTH_ERROR #define OV_THROW_LENGTH_ERROR(CLASS_NAME, FUNC_NAME) std::_Xlength_error(CLASS_NAME " too long") -#endif +#endif // OV_THROW_LENGTH_ERROR + +#endif // __GLIBCXX__ #ifndef OV_THROW_OUT_OF_RANGE #include diff --git a/src/openvic-simulation/core/FormatValidate.hpp b/src/openvic-simulation/core/FormatValidate.hpp index 07d92191f..1a188e5ae 100644 --- a/src/openvic-simulation/core/FormatValidate.hpp +++ b/src/openvic-simulation/core/FormatValidate.hpp @@ -19,6 +19,6 @@ template struct fmt::formatter> : fmt::formatter { fmt::format_context::iterator format(ovfmt::validate_view const& value, fmt::format_context& ctx) const { return value.ptr ? fmt::formatter::format(*value.ptr, ctx) - : fmt::formatter {}.format(value.invalid_string, ctx); + : fmt::formatter {}.format(value.invalid_string, ctx); } }; diff --git a/src/openvic-simulation/core/Hash.hpp b/src/openvic-simulation/core/Hash.hpp index 2224dead1..e63d54eb6 100644 --- a/src/openvic-simulation/core/Hash.hpp +++ b/src/openvic-simulation/core/Hash.hpp @@ -37,7 +37,7 @@ namespace OpenVic { template constexpr void perfect_hash(std::size_t& s, T&& v, Args&&... args) { static_assert( - sizeof(T) + (sizeof(Args) + ...) <= sizeof(std::size_t), "Perfect hashes must be able to fit into size_t" + sizeof(T) + (sizeof(Args) + ...) <= sizeof(std::size_t), "Perfect hashes must be able to fit into size_t" ); std::hash h; if constexpr (sizeof...(args) == 0) { @@ -46,16 +46,15 @@ namespace OpenVic { const std::tuple arg_tuple { args... }; s = h(v) << (sizeof(T) * CHAR_BIT); ( - [&] { - // If args is not last pointer of args - if (static_cast(&(std::get(arg_tuple))) != - static_cast(&args)) { - s <<= sizeof(Args) * CHAR_BIT; - } - s |= std::hash {}(args); - }(), - ... - ); + [&] { + // If args is not last pointer of args + if (static_cast(&(std::get(arg_tuple))) != + static_cast(&args)) { + s <<= sizeof(Args) * CHAR_BIT; + } + s |= std::hash {}(args); + }(), + ...); } } } diff --git a/src/openvic-simulation/core/MathSqrt.hpp b/src/openvic-simulation/core/MathSqrt.hpp index 4c365bf75..38604eaa7 100644 --- a/src/openvic-simulation/core/MathSqrt.hpp +++ b/src/openvic-simulation/core/MathSqrt.hpp @@ -28,4 +28,4 @@ namespace OpenVic { return c; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/ecs/Archetype.hpp b/src/openvic-simulation/core/ecs/Archetype.hpp index 4927dab74..3dc94e8ed 100644 --- a/src/openvic-simulation/core/ecs/Archetype.hpp +++ b/src/openvic-simulation/core/ecs/Archetype.hpp @@ -44,13 +44,7 @@ namespace OpenVic::ecs { inline ColumnVTable const& column_vtable_for() { if constexpr (std::is_empty_v) { static ColumnVTable const v { - 0, - 0, - [](void*, void*) {}, - [](void*) {}, - [](void*, void*, std::size_t) {}, - [](void*, std::size_t) {}, - nullptr + 0, 0, [](void*, void*) {}, [](void*) {}, [](void*, void*, std::size_t) {}, [](void*, std::size_t) {}, nullptr }; return v; } else { @@ -58,34 +52,34 @@ namespace OpenVic::ecs { sizeof(C), alignof(C), [](void* dst, void* src) { - ::new (dst) C(std::move(*static_cast(src))); - static_cast(src)->~C(); + ::new (dst) C(std::move(*static_cast(src))); + static_cast(src)->~C(); }, [](void* dst) { - static_cast(dst)->~C(); + static_cast(dst)->~C(); }, [](void* dst, void* src, std::size_t n) { - if constexpr (std::is_trivially_copyable_v) { - std::memcpy(dst, src, n * sizeof(C)); - } else { - C* d = static_cast(dst); - C* s = static_cast(src); - for (std::size_t i = 0; i < n; ++i) { - ::new (d + i) C(std::move(s[i])); - s[i].~C(); - } - } + if constexpr (std::is_trivially_copyable_v) { + std::memcpy(dst, src, n * sizeof(C)); + } else { + C* d = static_cast(dst); + C* s = static_cast(src); + for (std::size_t i = 0; i < n; ++i) { + ::new (d + i) C(std::move(s[i])); + s[i].~C(); + } + } }, [](void* dst, std::size_t n) { - if constexpr (std::is_trivially_destructible_v) { - (void) dst; - (void) n; - } else { - C* d = static_cast(dst); - for (std::size_t i = 0; i < n; ++i) { - d[i].~C(); - } - } + if constexpr (std::is_trivially_destructible_v) { + (void)dst; + (void)n; + } else { + C* d = static_cast(dst); + for (std::size_t i = 0; i < n; ++i) { + d[i].~C(); + } + } }, // Global checksum enforcement point: instantiating this thunk static_asserts // the universal hashing rule for every component type used with a World. @@ -251,7 +245,7 @@ namespace OpenVic::ecs { fresh.data = chunk_pool->acquire(); } else { fresh.data = static_cast( - ::operator new(CHUNK_BLOCK_BYTES, std::align_val_t { CHUNK_BLOCK_ALIGN }) + ::operator new(CHUNK_BLOCK_BYTES, std::align_val_t { CHUNK_BLOCK_ALIGN }) ); } chunks.push_back(std::move(fresh)); diff --git a/src/openvic-simulation/core/ecs/Checksum.cpp b/src/openvic-simulation/core/ecs/Checksum.cpp index 6637203fe..60e2fde82 100644 --- a/src/openvic-simulation/core/ecs/Checksum.cpp +++ b/src/openvic-simulation/core/ecs/Checksum.cpp @@ -49,9 +49,9 @@ namespace OpenVic::ecs { } total = fold_uint64(h, total); if (out != nullptr) { - out->archetype_entries.push_back(ArchetypeChecksumEntry { - static_cast(archetype_index), arch.signature, h - }); + out->archetype_entries.push_back( + ArchetypeChecksumEntry { static_cast(archetype_index), arch.signature, h } + ); } } @@ -62,12 +62,14 @@ namespace OpenVic::ecs { for (std::pair const& entry : world.singletons) { sorted.emplace_back(entry.first, &entry.second); } - std::sort(sorted.begin(), sorted.end(), []( - std::pair const& lhs, - std::pair const& rhs - ) { - return lhs.first < rhs.first; - }); + std::sort( + sorted.begin(), + sorted.end(), + [](std::pair const& lhs, + std::pair const& rhs) { + return lhs.first < rhs.first; + } + ); for (std::pair const& entry : sorted) { uint64_t h = fold_uint64(entry.first, CHECKSUM_SEED); h = entry.second->checksum(entry.second->ptr.get(), h); diff --git a/src/openvic-simulation/core/ecs/ChecksumTraits.hpp b/src/openvic-simulation/core/ecs/ChecksumTraits.hpp index 82c2cf5a4..77167023f 100644 --- a/src/openvic-simulation/core/ecs/ChecksumTraits.hpp +++ b/src/openvic-simulation/core/ecs/ChecksumTraits.hpp @@ -69,9 +69,8 @@ namespace OpenVic::ecs { template struct has_custom_checksum : std::false_type {}; template - struct has_custom_checksum(), std::declval()))>> - : std::true_type {}; + struct has_custom_checksum(), std::declval()))>> + : std::true_type {}; template inline constexpr bool has_custom_checksum_v = has_custom_checksum::value; @@ -80,7 +79,7 @@ namespace OpenVic::ecs { // archetype signature / singleton id fold. Custom hash takes precedence over byte path. template inline constexpr bool is_checksummable_v = - std::is_empty_v || has_custom_checksum_v || std::has_unique_object_representations_v; + std::is_empty_v || has_custom_checksum_v || std::has_unique_object_representations_v; #define OPENVIC_ECS_CHECKSUM_ENFORCE_MESSAGE \ "ECS checksum: this component/singleton type cannot be hashed. Fix one of: " \ @@ -101,13 +100,12 @@ namespace OpenVic::ecs { uint64_t checksum_value(C const& value, uint64_t seed) { static_assert(is_checksummable_v, OPENVIC_ECS_CHECKSUM_ENFORCE_MESSAGE); if constexpr (std::is_empty_v) { - (void) value; + (void)value; return seed; } else if constexpr (has_custom_checksum_v) { static_assert( - std::is_same_v< - decltype(ecs_checksum(std::declval(), std::declval())), uint64_t>, - "ecs_checksum(C const&, uint64_t seed) must return uint64_t" + std::is_same_v(), std::declval())), uint64_t>, + "ecs_checksum(C const&, uint64_t seed) must return uint64_t" ); return ecs_checksum(value, seed); } else { @@ -166,8 +164,6 @@ namespace OpenVic::ecs { // garbage and WILL produce unstable checksums), and float values produced deterministically. #define ECS_CHECKSUM_BYTES(Type) \ inline uint64_t ecs_checksum(Type const& ecs_checksum_value_, uint64_t ecs_checksum_seed_) { \ - static_assert( \ - std::is_trivially_copyable_v, "ECS_CHECKSUM_BYTES requires a trivially copyable type" \ - ); \ + static_assert(std::is_trivially_copyable_v, "ECS_CHECKSUM_BYTES requires a trivially copyable type"); \ return ::OpenVic::ecs::fnv1a_64_bytes(&ecs_checksum_value_, sizeof(Type), ecs_checksum_seed_); \ } diff --git a/src/openvic-simulation/core/ecs/Chunk.hpp b/src/openvic-simulation/core/ecs/Chunk.hpp index d52e3c334..d126c90be 100644 --- a/src/openvic-simulation/core/ecs/Chunk.hpp +++ b/src/openvic-simulation/core/ecs/Chunk.hpp @@ -25,12 +25,12 @@ namespace OpenVic::ecs { // local declaration; weaker on function returns. Not standard C++ — each target // compiler spells it differently. #if defined(_MSC_VER) -# define OV_RESTRICT __restrict +#define OV_RESTRICT __restrict #elif defined(__GNUC__) || defined(__clang__) -# define OV_RESTRICT __restrict__ +#define OV_RESTRICT __restrict__ #else -# define OV_RESTRICT -#endif +#define OV_RESTRICT +#endif // defined(_MSC_VER) // Passive holder for one chunk's 16 KB block. Lifecycle is managed explicitly at every // callsite that owns a chunk: diff --git a/src/openvic-simulation/core/ecs/ChunkPool.cpp b/src/openvic-simulation/core/ecs/ChunkPool.cpp index 379ddef07..7945503be 100644 --- a/src/openvic-simulation/core/ecs/ChunkPool.cpp +++ b/src/openvic-simulation/core/ecs/ChunkPool.cpp @@ -22,9 +22,7 @@ unsigned char* ChunkPool::acquire() { return data; } ++total_allocations_; - return static_cast( - ::operator new(CHUNK_BLOCK_BYTES, std::align_val_t { CHUNK_BLOCK_ALIGN }) - ); + return static_cast(::operator new(CHUNK_BLOCK_BYTES, std::align_val_t { CHUNK_BLOCK_ALIGN })); } void ChunkPool::release(unsigned char* data) { diff --git a/src/openvic-simulation/core/ecs/ChunkSystem.hpp b/src/openvic-simulation/core/ecs/ChunkSystem.hpp index 229b89532..b65797cd5 100644 --- a/src/openvic-simulation/core/ecs/ChunkSystem.hpp +++ b/src/openvic-simulation/core/ecs/ChunkSystem.hpp @@ -24,18 +24,25 @@ namespace OpenVic::ecs { static constexpr auto declared_access() { return std::array { ComponentAccess { component_type_id_of>(), - std::is_const_v> ? AccessMode::Read : AccessMode::Write - }... }; + std::is_const_v> ? AccessMode::Read : AccessMode::Write }... }; } static constexpr system_type_id_t type_id() { return system_type_id_of(); } - static constexpr std::array declared_run_after() { return {}; } - static constexpr std::array declared_run_before() { return {}; } - static constexpr std::array extra_reads() { return {}; } - static constexpr std::array extra_writes() { return {}; } + static constexpr std::array declared_run_after() { + return {}; + } + static constexpr std::array declared_run_before() { + return {}; + } + static constexpr std::array extra_reads() { + return {}; + } + static constexpr std::array extra_writes() { + return {}; + } static constexpr bool is_threaded = false; // Sorted-unique component ids defining the iteration query. ChunkSystem doesn't @@ -43,9 +50,7 @@ namespace OpenVic::ecs { // shape: just Cs... folded through component_type_id_of, sorted, deduped. // Consumed by the scheduler's query-cache prewarm for multi-system stages. static std::vector compute_tick_query_require_ids() { - std::vector ids = { - component_type_id_of>()... - }; + std::vector ids = { component_type_id_of>()... }; std::sort(ids.begin(), ids.end()); ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); return ids; @@ -61,10 +66,9 @@ namespace OpenVic::ecs { void tick_all(World& world, TickContext const& ctx) { Derived& self = static_cast(*this); Query const q = detail::build_tick_query(); - world.template for_each_chunk...>(q, - [&](ChunkView...> view) { - self.tick_chunk(view, ctx); - }); + world.template for_each_chunk...>(q, [&](ChunkView...> view) { + self.tick_chunk(view, ctx); + }); } }; } diff --git a/src/openvic-simulation/core/ecs/CommandBuffer.cpp b/src/openvic-simulation/core/ecs/CommandBuffer.cpp index 6ddd1bcb2..b8d1e9486 100644 --- a/src/openvic-simulation/core/ecs/CommandBuffer.cpp +++ b/src/openvic-simulation/core/ecs/CommandBuffer.cpp @@ -32,355 +32,344 @@ void CommandBuffer::apply(World& world) { for (Op& op : ops) { switch (op.kind) { - case OpKind::CreateEntity: { - // In parallel-mode-recorded ops, op.eid is a deferred placeholder. Allocate a - // real slot here (single-threaded, deterministic order) and store the mapping - // before we finalise — subsequent ops that reference this placeholder resolve - // via the map. Serial-mode ops already carry a real reserved EntityID and skip - // the allocation step. - EntityID real_eid = op.eid; - bool const was_deferred = op.eid.is_deferred(); - if (was_deferred) { - real_eid = world.reserve_entity_slot(); - if (op.eid.index < placeholder_to_real.size()) { - placeholder_to_real[op.eid.index] = real_eid; - } - } - // Hand the World move-only payload pointers; finalize_reserved_entity moves - // them into the archetype's column slabs. After the call, the payload slots - // are moved-from but still need their allocations freed. - std::vector raw_slots; - raw_slots.reserve(op.create.sorted_values.size()); - for (PayloadSlot& slot : op.create.sorted_values) { - raw_slots.push_back(slot.data); - } - world.finalize_reserved_entity( - real_eid, op.create.sorted_sig, op.create.sorted_vtables, raw_slots - ); - // Stamp immutability onto the freshly-finalised slot (covers both the deferred - // and serial create_immutable_entity paths in one place). CommandBuffer is a - // friend of World, so entity_slots is reachable here. - if (op.create.immutable && real_eid.index < world.entity_slots.size()) { - world.entity_slots[real_eid.index].immutable = true; + case OpKind::CreateEntity: { + // In parallel-mode-recorded ops, op.eid is a deferred placeholder. Allocate a + // real slot here (single-threaded, deterministic order) and store the mapping + // before we finalise — subsequent ops that reference this placeholder resolve + // via the map. Serial-mode ops already carry a real reserved EntityID and skip + // the allocation step. + EntityID real_eid = op.eid; + bool const was_deferred = op.eid.is_deferred(); + if (was_deferred) { + real_eid = world.reserve_entity_slot(); + if (op.eid.index < placeholder_to_real.size()) { + placeholder_to_real[op.eid.index] = real_eid; } - // Free the moved-from payload allocations. We don't call destroy() on them — - // the move-construct already destructively transferred the value. Capture - // `align` into a local BEFORE `release_data()` — `release_data()` clears the - // slot's `vtable` pointer, and the argument-evaluation order for the delete - // call below is unspecified, so any access to `slot.vtable->align` in the - // same expression is undefined. - for (PayloadSlot& slot : op.create.sorted_values) { - if (slot.data != nullptr && slot.vtable != nullptr && slot.vtable->size > 0) { - std::size_t const align = slot.vtable->align; - ::operator delete(slot.release_data(), std::align_val_t { align }); - slot.vtable = nullptr; - } + } + // Hand the World move-only payload pointers; finalize_reserved_entity moves + // them into the archetype's column slabs. After the call, the payload slots + // are moved-from but still need their allocations freed. + std::vector raw_slots; + raw_slots.reserve(op.create.sorted_values.size()); + for (PayloadSlot& slot : op.create.sorted_values) { + raw_slots.push_back(slot.data); + } + world.finalize_reserved_entity(real_eid, op.create.sorted_sig, op.create.sorted_vtables, raw_slots); + // Stamp immutability onto the freshly-finalised slot (covers both the deferred + // and serial create_immutable_entity paths in one place). CommandBuffer is a + // friend of World, so entity_slots is reachable here. + if (op.create.immutable && real_eid.index < world.entity_slots.size()) { + world.entity_slots[real_eid.index].immutable = true; + } + // Free the moved-from payload allocations. We don't call destroy() on them — + // the move-construct already destructively transferred the value. Capture + // `align` into a local BEFORE `release_data()` — `release_data()` clears the + // slot's `vtable` pointer, and the argument-evaluation order for the delete + // call below is unspecified, so any access to `slot.vtable->align` in the + // same expression is undefined. + for (PayloadSlot& slot : op.create.sorted_values) { + if (slot.data != nullptr && slot.vtable != nullptr && slot.vtable->size > 0) { + std::size_t const align = slot.vtable->align; + ::operator delete(slot.release_data(), std::align_val_t { align }); + slot.vtable = nullptr; } - break; } - case OpKind::CreateEntitiesBulk: { - BulkCreatePayload& bulk = *op.bulk; - std::size_t const n = bulk.count; + break; + } + case OpKind::CreateEntitiesBulk: { + BulkCreatePayload& bulk = *op.bulk; + std::size_t const n = bulk.count; - // Resolve the batch to real ids in creation order. Parallel-recorded batches - // reserve their slots HERE, at the op's position in op order — exactly what - // `n` individual CreateEntity ops would do, so id assignment matches the - // loop equivalent. Serial-recorded batches reserved at record time. - std::span ids; - std::vector resolved; - if (op.eid.is_deferred()) { - resolved.reserve(n); - for (std::size_t i = 0; i < n; ++i) { - EntityID const real = world.reserve_entity_slot(); - std::size_t const ph = static_cast(op.eid.index) + i; - if (ph < placeholder_to_real.size()) { - placeholder_to_real[ph] = real; - } - resolved.push_back(real); + // Resolve the batch to real ids in creation order. Parallel-recorded batches + // reserve their slots HERE, at the op's position in op order — exactly what + // `n` individual CreateEntity ops would do, so id assignment matches the + // loop equivalent. Serial-recorded batches reserved at record time. + std::span ids; + std::vector resolved; + if (op.eid.is_deferred()) { + resolved.reserve(n); + for (std::size_t i = 0; i < n; ++i) { + EntityID const real = world.reserve_entity_slot(); + std::size_t const ph = static_cast(op.eid.index) + i; + if (ph < placeholder_to_real.size()) { + placeholder_to_real[ph] = real; } - ids = resolved; - } else { - ids = bulk.reserved_ids; + resolved.push_back(real); } + ids = resolved; + } else { + ids = bulk.reserved_ids; + } - // Column block base pointers, parallel to sorted_sig (nullptr for tags). - std::vector blocks; - blocks.reserve(bulk.columns.size()); - for (PayloadColumn& col : bulk.columns) { - blocks.push_back(col.data); - } - world.finalize_reserved_entities_bulk(ids, bulk.sorted_sig, bulk.sorted_vtables, blocks); + // Column block base pointers, parallel to sorted_sig (nullptr for tags). + std::vector blocks; + blocks.reserve(bulk.columns.size()); + for (PayloadColumn& col : bulk.columns) { + blocks.push_back(col.data); + } + world.finalize_reserved_entities_bulk(ids, bulk.sorted_sig, bulk.sorted_vtables, blocks); - // Stamp immutability per entity. Unlike the single-create branch, re-check - // liveness + generation so a slot that was destroyed and reused between - // record and apply (serial-mode misuse) can't stamp an unrelated occupant. - if (bulk.immutable) { - for (EntityID const eid : ids) { - if (eid.index < world.entity_slots.size() - && world.entity_slots[eid.index].alive - && world.entity_slots[eid.index].generation == eid.generation) { - world.entity_slots[eid.index].immutable = true; - } + // Stamp immutability per entity. Unlike the single-create branch, re-check + // liveness + generation so a slot that was destroyed and reused between + // record and apply (serial-mode misuse) can't stamp an unrelated occupant. + if (bulk.immutable) { + for (EntityID const eid : ids) { + if (eid.index < world.entity_slots.size() && world.entity_slots[eid.index].alive && + world.entity_slots[eid.index].generation == eid.generation) { + world.entity_slots[eid.index].immutable = true; } } + } - // Free the raw blocks. Every staged value has been consumed — - // finalize_reserved_entities_bulk either move-constructed it out (sources - // destroyed by move_construct_n / move_construct) or destroyed it on the - // skip path — so release WITHOUT destroy_n. Capture `align` before - // release_data() clears the vtable (same order-of-evaluation rationale as - // the CreateEntity branch). - for (PayloadColumn& col : bulk.columns) { - if (col.data != nullptr && col.vtable != nullptr && col.vtable->size > 0) { - std::size_t const align = col.vtable->align; - ::operator delete(col.release_data(), std::align_val_t { align }); - } + // Free the raw blocks. Every staged value has been consumed — + // finalize_reserved_entities_bulk either move-constructed it out (sources + // destroyed by move_construct_n / move_construct) or destroyed it on the + // skip path — so release WITHOUT destroy_n. Capture `align` before + // release_data() clears the vtable (same order-of-evaluation rationale as + // the CreateEntity branch). + for (PayloadColumn& col : bulk.columns) { + if (col.data != nullptr && col.vtable != nullptr && col.vtable->size > 0) { + std::size_t const align = col.vtable->align; + ::operator delete(col.release_data(), std::align_val_t { align }); } + } + break; + } + case OpKind::DestroyEntity: { + // World::destroy_entity is a no-op on dead entities and on + // reserved-but-unfinalised slots (calls drop_reserved_slot internally). + world.destroy_entity(resolve(op.eid)); + break; + } + case OpKind::AddComponent: { + // Build a single-component sorted signature against the entity's current + // archetype + the new id, then dispatch through the existing template + // add_component path is awkward (requires the type at the call site). We + // instead replicate the migration logic at the type-erased level: find or + // create the target archetype and move the new component plus all existing + // components over. + // + // For simplicity this implementation goes through add_component_typeerased + // (a private World helper added below). If the entity already carries C, + // the existing slot is overwritten via move-assign… but move-assign isn't + // available type-erased. So if the component already exists, we destroy + // the existing value first then move-construct the new one in place. + EntityID const eid = resolve(op.eid); + if (!eid.is_valid() || eid.is_deferred()) { + // Unresolved placeholder (a same-buffer add referencing a placeholder whose + // CreateEntity op never ran, e.g. due to allocation failure). Drop silently. break; } - case OpKind::DestroyEntity: { - // World::destroy_entity is a no-op on dead entities and on - // reserved-but-unfinalised slots (calls drop_reserved_slot internally). - world.destroy_entity(resolve(op.eid)); + if (eid.index >= world.entity_slots.size()) { break; } - case OpKind::AddComponent: { - // Build a single-component sorted signature against the entity's current - // archetype + the new id, then dispatch through the existing template - // add_component path is awkward (requires the type at the call site). We - // instead replicate the migration logic at the type-erased level: find or - // create the target archetype and move the new component plus all existing - // components over. - // - // For simplicity this implementation goes through add_component_typeerased - // (a private World helper added below). If the entity already carries C, - // the existing slot is overwritten via move-assign… but move-assign isn't - // available type-erased. So if the component already exists, we destroy - // the existing value first then move-construct the new one in place. - EntityID const eid = resolve(op.eid); - if (!eid.is_valid() || eid.is_deferred()) { - // Unresolved placeholder (a same-buffer add referencing a placeholder whose - // CreateEntity op never ran, e.g. due to allocation failure). Drop silently. - break; - } - if (eid.index >= world.entity_slots.size()) { - break; - } - EntitySlot const& slot = world.entity_slots[eid.index]; - if (!slot.alive || slot.generation != eid.generation) { - break; - } - if (slot.archetype_index == INVALID_ARCHETYPE) { - // Entity is reserved-but-unfinalised — adding a component before the - // CreateEntity op has been applied is undefined-by-policy. Ignore. - break; - } - if (slot.immutable) { - spdlog::error_s( - "CommandBuffer::apply refused add_component: entity {}:{} is immutable " - "(component id {:#x})", - eid.index, eid.generation, op.add.id - ); - break; - } - // Immutability backstop (deferred path): apply() migrates type-erased below, - // NOT through World::add_component, so the refusal is repeated. The intact - // op.add.value payload is freed by its PayloadSlot destructor at ops.clear(). - ColumnVTable const* new_vt = op.add.value.vtable; - component_type_id_t const new_id = op.add.id; - uint32_t const src_idx = slot.archetype_index; - uint32_t const src_chunk = slot.chunk_index; - uint32_t const src_row = slot.row; + EntitySlot const& slot = world.entity_slots[eid.index]; + if (!slot.alive || slot.generation != eid.generation) { + break; + } + if (slot.archetype_index == INVALID_ARCHETYPE) { + // Entity is reserved-but-unfinalised — adding a component before the + // CreateEntity op has been applied is undefined-by-policy. Ignore. + break; + } + if (slot.immutable) { + spdlog::error_s( + "CommandBuffer::apply refused add_component: entity {}:{} is immutable " + "(component id {:#x})", + eid.index, + eid.generation, + op.add.id + ); + break; + } + // Immutability backstop (deferred path): apply() migrates type-erased below, + // NOT through World::add_component, so the refusal is repeated. The intact + // op.add.value payload is freed by its PayloadSlot destructor at ops.clear(). + ColumnVTable const* new_vt = op.add.value.vtable; + component_type_id_t const new_id = op.add.id; + uint32_t const src_idx = slot.archetype_index; + uint32_t const src_chunk = slot.chunk_index; + uint32_t const src_row = slot.row; - // In-place replace if already present. - { - Archetype& src = world.archetypes[src_idx]; - std::size_t const existing_col = src.column_index_for(new_id); - if (existing_col != NO_COLUMN_INDEX) { - if (src.column_offsets[existing_col] != NO_COLUMN_OFFSET) { - void* dst = src.row_in_column(src_chunk, existing_col, src_row); - src.vtables[existing_col]->destroy(dst); - src.vtables[existing_col]->move_construct(dst, op.add.value.data); - ++src.column_versions[existing_col]; - } - // Free the moved-from payload allocation. Capture `align` BEFORE - // `release_data()` clears the vtable pointer — see CreateEntity branch - // for the order-of-evaluation rationale. - if (op.add.value.data != nullptr && op.add.value.vtable != nullptr - && op.add.value.vtable->size > 0) { - std::size_t const align = op.add.value.vtable->align; - ::operator delete( - op.add.value.release_data(), std::align_val_t { align } - ); - op.add.value.vtable = nullptr; - } - break; + // In-place replace if already present. + { + Archetype& src = world.archetypes[src_idx]; + std::size_t const existing_col = src.column_index_for(new_id); + if (existing_col != NO_COLUMN_INDEX) { + if (src.column_offsets[existing_col] != NO_COLUMN_OFFSET) { + void* dst = src.row_in_column(src_chunk, existing_col, src_row); + src.vtables[existing_col]->destroy(dst); + src.vtables[existing_col]->move_construct(dst, op.add.value.data); + ++src.column_versions[existing_col]; + } + // Free the moved-from payload allocation. Capture `align` BEFORE + // `release_data()` clears the vtable pointer — see CreateEntity branch + // for the order-of-evaluation rationale. + if (op.add.value.data != nullptr && op.add.value.vtable != nullptr && op.add.value.vtable->size > 0) { + std::size_t const align = op.add.value.vtable->align; + ::operator delete(op.add.value.release_data(), std::align_val_t { align }); + op.add.value.vtable = nullptr; } + break; } + } - // Build target signature = src.signature ∪ {new_id}, sorted ascending. - std::vector target_sig; - std::vector target_vtables; - { - Archetype const& src = world.archetypes[src_idx]; - target_sig.reserve(src.signature.size() + 1); - target_vtables.reserve(src.signature.size() + 1); - bool inserted = false; - for (std::size_t i = 0; i < src.signature.size(); ++i) { - component_type_id_t const sid = src.signature[i]; - if (!inserted && sid > new_id) { - target_sig.push_back(new_id); - target_vtables.push_back(new_vt); - inserted = true; - } - target_sig.push_back(sid); - target_vtables.push_back(src.vtables[i]); - } - if (!inserted) { + // Build target signature = src.signature ∪ {new_id}, sorted ascending. + std::vector target_sig; + std::vector target_vtables; + { + Archetype const& src = world.archetypes[src_idx]; + target_sig.reserve(src.signature.size() + 1); + target_vtables.reserve(src.signature.size() + 1); + bool inserted = false; + for (std::size_t i = 0; i < src.signature.size(); ++i) { + component_type_id_t const sid = src.signature[i]; + if (!inserted && sid > new_id) { target_sig.push_back(new_id); target_vtables.push_back(new_vt); + inserted = true; } + target_sig.push_back(sid); + target_vtables.push_back(src.vtables[i]); } + if (!inserted) { + target_sig.push_back(new_id); + target_vtables.push_back(new_vt); + } + } - uint32_t const target_idx - = world.find_or_create_archetype(target_sig, target_vtables.data()); + uint32_t const target_idx = world.find_or_create_archetype(target_sig, target_vtables.data()); - Archetype::RowLocation target_loc = world.archetypes[target_idx].reserve_row(); - world.archetypes[target_idx].entity_array(target_loc.chunk_index)[target_loc.row] = eid; + Archetype::RowLocation target_loc = world.archetypes[target_idx].reserve_row(); + world.archetypes[target_idx].entity_array(target_loc.chunk_index)[target_loc.row] = eid; - { - Archetype& target = world.archetypes[target_idx]; - Archetype& src = world.archetypes[src_idx]; - for (std::size_t i = 0; i < target.signature.size(); ++i) { - component_type_id_t const tid = target.signature[i]; - if (target.column_offsets[i] == NO_COLUMN_OFFSET) { - continue; // tag column — no data - } - void* dst = target.row_in_column( - target_loc.chunk_index, i, target_loc.row - ); - if (tid == new_id) { - target.vtables[i]->move_construct(dst, op.add.value.data); - } else { - std::size_t const src_col_idx = src.column_index_for(tid); - void* srcp = src.row_in_column(src_chunk, src_col_idx, src_row); - target.vtables[i]->move_construct(dst, srcp); - } + { + Archetype& target = world.archetypes[target_idx]; + Archetype& src = world.archetypes[src_idx]; + for (std::size_t i = 0; i < target.signature.size(); ++i) { + component_type_id_t const tid = target.signature[i]; + if (target.column_offsets[i] == NO_COLUMN_OFFSET) { + continue; // tag column — no data + } + void* dst = target.row_in_column(target_loc.chunk_index, i, target_loc.row); + if (tid == new_id) { + target.vtables[i]->move_construct(dst, op.add.value.data); + } else { + std::size_t const src_col_idx = src.column_index_for(tid); + void* srcp = src.row_in_column(src_chunk, src_col_idx, src_row); + target.vtables[i]->move_construct(dst, srcp); } } + } - world.compact_archetype_after_external_move(src_idx, src_chunk, src_row); + world.compact_archetype_after_external_move(src_idx, src_chunk, src_row); - EntitySlot& mutable_slot = world.entity_slots[eid.index]; - mutable_slot.archetype_index = target_idx; - mutable_slot.chunk_index = static_cast(target_loc.chunk_index); - mutable_slot.row = static_cast(target_loc.row); + EntitySlot& mutable_slot = world.entity_slots[eid.index]; + mutable_slot.archetype_index = target_idx; + mutable_slot.chunk_index = static_cast(target_loc.chunk_index); + mutable_slot.row = static_cast(target_loc.row); - // Free the moved-from payload allocation. Capture `align` BEFORE - // `release_data()` clears the vtable pointer — see CreateEntity branch - // for the order-of-evaluation rationale. - if (op.add.value.data != nullptr && op.add.value.vtable != nullptr - && op.add.value.vtable->size > 0) { - std::size_t const align = op.add.value.vtable->align; - ::operator delete( - op.add.value.release_data(), std::align_val_t { align } - ); - op.add.value.vtable = nullptr; - } + // Free the moved-from payload allocation. Capture `align` BEFORE + // `release_data()` clears the vtable pointer — see CreateEntity branch + // for the order-of-evaluation rationale. + if (op.add.value.data != nullptr && op.add.value.vtable != nullptr && op.add.value.vtable->size > 0) { + std::size_t const align = op.add.value.vtable->align; + ::operator delete(op.add.value.release_data(), std::align_val_t { align }); + op.add.value.vtable = nullptr; + } + break; + } + case OpKind::RemoveComponent: { + EntityID const eid = resolve(op.eid); + if (!eid.is_valid() || eid.is_deferred()) { break; } - case OpKind::RemoveComponent: { - EntityID const eid = resolve(op.eid); - if (!eid.is_valid() || eid.is_deferred()) { - break; - } - if (eid.index >= world.entity_slots.size()) { - break; - } - EntitySlot const& slot = world.entity_slots[eid.index]; - if (!slot.alive || slot.generation != eid.generation) { - break; - } - if (slot.archetype_index == INVALID_ARCHETYPE) { - break; - } - uint32_t const src_idx = slot.archetype_index; - uint32_t const src_chunk = slot.chunk_index; - uint32_t const src_row = slot.row; + if (eid.index >= world.entity_slots.size()) { + break; + } + EntitySlot const& slot = world.entity_slots[eid.index]; + if (!slot.alive || slot.generation != eid.generation) { + break; + } + if (slot.archetype_index == INVALID_ARCHETYPE) { + break; + } + uint32_t const src_idx = slot.archetype_index; + uint32_t const src_chunk = slot.chunk_index; + uint32_t const src_row = slot.row; - if (slot.immutable) { - spdlog::error_s( - "CommandBuffer::apply refused remove_component: entity {}:{} is immutable " - "(component id {:#x})", - eid.index, eid.generation, op.remove_id - ); - break; + if (slot.immutable) { + spdlog::error_s( + "CommandBuffer::apply refused remove_component: entity {}:{} is immutable " + "(component id {:#x})", + eid.index, + eid.generation, + op.remove_id + ); + break; + } + // Immutability backstop (deferred remove path): same rationale as the + // AddComponent branch — apply() migrates type-erased, bypassing + // World::remove_component. No payload to free here. + std::size_t drop_col_idx = NO_COLUMN_INDEX; + { + Archetype const& src = world.archetypes[src_idx]; + drop_col_idx = src.column_index_for(op.remove_id); + if (drop_col_idx == NO_COLUMN_INDEX) { + break; // entity doesn't carry it — silent no-op } - // Immutability backstop (deferred remove path): same rationale as the - // AddComponent branch — apply() migrates type-erased, bypassing - // World::remove_component. No payload to free here. - std::size_t drop_col_idx = NO_COLUMN_INDEX; - { - Archetype const& src = world.archetypes[src_idx]; - drop_col_idx = src.column_index_for(op.remove_id); - if (drop_col_idx == NO_COLUMN_INDEX) { - break; // entity doesn't carry it — silent no-op - } - if (src.signature.size() == 1) { - // Removing the sole component is forbidden; mirror World::remove_component. - break; - } + if (src.signature.size() == 1) { + // Removing the sole component is forbidden; mirror World::remove_component. + break; } + } - std::vector target_sig; - std::vector target_vtables; - { - Archetype const& src = world.archetypes[src_idx]; - target_sig.reserve(src.signature.size() - 1); - target_vtables.reserve(src.signature.size() - 1); - for (std::size_t i = 0; i < src.signature.size(); ++i) { - if (src.signature[i] == op.remove_id) { - continue; - } - target_sig.push_back(src.signature[i]); - target_vtables.push_back(src.vtables[i]); + std::vector target_sig; + std::vector target_vtables; + { + Archetype const& src = world.archetypes[src_idx]; + target_sig.reserve(src.signature.size() - 1); + target_vtables.reserve(src.signature.size() - 1); + for (std::size_t i = 0; i < src.signature.size(); ++i) { + if (src.signature[i] == op.remove_id) { + continue; } + target_sig.push_back(src.signature[i]); + target_vtables.push_back(src.vtables[i]); } + } - uint32_t const target_idx - = world.find_or_create_archetype(target_sig, target_vtables.data()); + uint32_t const target_idx = world.find_or_create_archetype(target_sig, target_vtables.data()); - Archetype::RowLocation target_loc = world.archetypes[target_idx].reserve_row(); - world.archetypes[target_idx].entity_array(target_loc.chunk_index)[target_loc.row] = eid; + Archetype::RowLocation target_loc = world.archetypes[target_idx].reserve_row(); + world.archetypes[target_idx].entity_array(target_loc.chunk_index)[target_loc.row] = eid; - { - Archetype& target = world.archetypes[target_idx]; - Archetype& src = world.archetypes[src_idx]; - if (src.column_offsets[drop_col_idx] != NO_COLUMN_OFFSET) { - src.vtables[drop_col_idx]->destroy( - src.row_in_column(src_chunk, drop_col_idx, src_row) - ); - } - for (std::size_t i = 0; i < target.signature.size(); ++i) { - component_type_id_t const tid = target.signature[i]; - if (target.column_offsets[i] == NO_COLUMN_OFFSET) { - continue; - } - std::size_t const src_col_idx = src.column_index_for(tid); - void* dst = target.row_in_column(target_loc.chunk_index, i, target_loc.row); - void* srcp = src.row_in_column(src_chunk, src_col_idx, src_row); - target.vtables[i]->move_construct(dst, srcp); + { + Archetype& target = world.archetypes[target_idx]; + Archetype& src = world.archetypes[src_idx]; + if (src.column_offsets[drop_col_idx] != NO_COLUMN_OFFSET) { + src.vtables[drop_col_idx]->destroy(src.row_in_column(src_chunk, drop_col_idx, src_row)); + } + for (std::size_t i = 0; i < target.signature.size(); ++i) { + component_type_id_t const tid = target.signature[i]; + if (target.column_offsets[i] == NO_COLUMN_OFFSET) { + continue; } + std::size_t const src_col_idx = src.column_index_for(tid); + void* dst = target.row_in_column(target_loc.chunk_index, i, target_loc.row); + void* srcp = src.row_in_column(src_chunk, src_col_idx, src_row); + target.vtables[i]->move_construct(dst, srcp); } + } - world.compact_archetype_after_external_move(src_idx, src_chunk, src_row); + world.compact_archetype_after_external_move(src_idx, src_chunk, src_row); - EntitySlot& mutable_slot = world.entity_slots[eid.index]; - mutable_slot.archetype_index = target_idx; - mutable_slot.chunk_index = static_cast(target_loc.chunk_index); - mutable_slot.row = static_cast(target_loc.row); - break; - } + EntitySlot& mutable_slot = world.entity_slots[eid.index]; + mutable_slot.archetype_index = target_idx; + mutable_slot.chunk_index = static_cast(target_loc.chunk_index); + mutable_slot.row = static_cast(target_loc.row); + break; + } } } ops.clear(); diff --git a/src/openvic-simulation/core/ecs/CommandBuffer.hpp b/src/openvic-simulation/core/ecs/CommandBuffer.hpp index 2eb5af270..a47a1af56 100644 --- a/src/openvic-simulation/core/ecs/CommandBuffer.hpp +++ b/src/openvic-simulation/core/ecs/CommandBuffer.hpp @@ -97,8 +97,7 @@ namespace OpenVic::ecs { PayloadColumn(PayloadColumn const&) = delete; PayloadColumn& operator=(PayloadColumn const&) = delete; - PayloadColumn(PayloadColumn&& other) noexcept - : data { other.data }, vtable { other.vtable }, count { other.count } { + PayloadColumn(PayloadColumn&& other) noexcept : data { other.data }, vtable { other.vtable }, count { other.count } { other.data = nullptr; other.vtable = nullptr; other.count = 0; @@ -194,16 +193,12 @@ namespace OpenVic::ecs { // count == 0 records nothing. Returns false (error log, nothing recorded) on // out_ids / span length mismatch. template - bool create_entities( - World& world, std::size_t count, std::span out_ids, Spans&&... spans - ); + bool create_entities(World& world, std::size_t count, std::span out_ids, Spans&&... spans); // Bulk analogue of create_immutable_entity: apply() stamps every created entity's // slot immutable; out_ids receives ImmutableEntityID handles. template - bool create_immutable_entities( - World& world, std::size_t count, std::span out_ids, Spans&&... spans - ); + bool create_immutable_entities(World& world, std::size_t count, std::span out_ids, Spans&&... spans); inline void destroy_entity(EntityID id) { Op op; @@ -276,8 +271,7 @@ namespace OpenVic::ecs { // ImmutableEntityID. template bool record_create_entities( - bool immutable, World& world, std::size_t count, std::span out_ids, - Spans&&... spans + bool immutable, World& world, std::size_t count, std::span out_ids, Spans&&... spans ); enum class OpKind { @@ -370,9 +364,8 @@ namespace OpenVic::ecs { // `apply()` allocates the real slot at the stage barrier and rewrites the placeholder. // In serial mode, reserve a real slot up-front so callers get a usable EntityID // immediately (e.g. for `cmd.add_component(eid, ...)` later in the same recording). - EntityID const eid = parallel_mode_ - ? EntityID { deferred_count_++, DEFERRED_GENERATION_BIT } - : world.reserve_entity_slot(); + EntityID const eid = + parallel_mode_ ? EntityID { deferred_count_++, DEFERRED_GENERATION_BIT } : world.reserve_entity_slot(); Op op; op.kind = OpKind::CreateEntity; @@ -400,8 +393,8 @@ namespace OpenVic::ecs { if constexpr (!std::is_empty_v) { ::new (op.create.sorted_values[target].data) TC(std::forward(value)); } else { - (void) value; - (void) target; + (void)value; + (void)target; } }; (place(std::forward(values)), ...); @@ -423,18 +416,18 @@ namespace OpenVic::ecs { template bool CommandBuffer::record_create_entities( - bool immutable, World& world, std::size_t count, std::span out_ids, Spans&&... spans + bool immutable, World& world, std::size_t count, std::span out_ids, Spans&&... spans ) { static_assert(sizeof...(Cs) > 0, "CommandBuffer::create_entities requires at least one component"); static_assert( - (std::is_same_v> && ...), - "create_entities component types must be plain types (no const/volatile/reference)" + (std::is_same_v> && ...), + "create_entities component types must be plain types (no const/volatile/reference)" ); constexpr std::size_t const non_empty = detail::non_empty_component_count(); static_assert( - sizeof...(Spans) == non_empty || sizeof...(Spans) == 0, - "create_entities takes one span per non-empty component (matched to the non-empty " - "Cs... in pack order; tags take no span), or no spans to default-construct" + sizeof...(Spans) == non_empty || sizeof...(Spans) == 0, + "create_entities takes one span per non-empty component (matched to the non-empty " + "Cs... in pack order; tags take no span), or no spans to default-construct" ); constexpr bool const use_spans = sizeof...(Spans) > 0; @@ -449,20 +442,16 @@ namespace OpenVic::ecs { std::size_t span_sizes[non_empty]; std::size_t si = 0; std::apply( - [&](auto const&... s) { - ((span_sizes[si++] = s.size()), ...); - }, - typed_spans + [&](auto const&... s) { + ((span_sizes[si++] = s.size()), ...); + }, + typed_spans ); - if (!world.bulk_create_sizes_ok_( - count, out_ids.size(), span_sizes, non_empty, "CommandBuffer::create_entities" - )) { + if (!world.bulk_create_sizes_ok_(count, out_ids.size(), span_sizes, non_empty, "CommandBuffer::create_entities")) { return false; } } else { - if (!world.bulk_create_sizes_ok_( - count, out_ids.size(), nullptr, 0, "CommandBuffer::create_entities" - )) { + if (!world.bulk_create_sizes_ok_(count, out_ids.size(), nullptr, 0, "CommandBuffer::create_entities")) { return false; } } @@ -563,21 +552,15 @@ namespace OpenVic::ecs { } template - bool CommandBuffer::create_entities( - World& world, std::size_t count, std::span out_ids, Spans&&... spans - ) { - return record_create_entities( - false, world, count, out_ids, std::forward(spans)... - ); + bool CommandBuffer::create_entities(World& world, std::size_t count, std::span out_ids, Spans&&... spans) { + return record_create_entities(false, world, count, out_ids, std::forward(spans)...); } template bool CommandBuffer::create_immutable_entities( - World& world, std::size_t count, std::span out_ids, Spans&&... spans + World& world, std::size_t count, std::span out_ids, Spans&&... spans ) { - return record_create_entities( - true, world, count, out_ids, std::forward(spans)... - ); + return record_create_entities(true, world, count, out_ids, std::forward(spans)...); } template @@ -592,7 +575,7 @@ namespace OpenVic::ecs { if constexpr (!std::is_empty_v) { ::new (op.add.value.data) TC(std::forward(value)); } else { - (void) value; + (void)value; } ops.push_back(std::move(op)); } diff --git a/src/openvic-simulation/core/ecs/DenseSlotAllocator.cpp b/src/openvic-simulation/core/ecs/DenseSlotAllocator.cpp index 25a97ce19..47fe363a3 100644 --- a/src/openvic-simulation/core/ecs/DenseSlotAllocator.cpp +++ b/src/openvic-simulation/core/ecs/DenseSlotAllocator.cpp @@ -24,8 +24,7 @@ uint32_t DenseSlotAllocator::allocate() { void DenseSlotAllocator::release(uint32_t slot) { if (slot >= next_unallocated_) { spdlog::error_s( - "DenseSlotAllocator::release ignored: slot {} was never allocated (high water {})", - slot, next_unallocated_ + "DenseSlotAllocator::release ignored: slot {} was never allocated (high water {})", slot, next_unallocated_ ); return; } @@ -48,8 +47,7 @@ bool DenseSlotAllocator::restore(Snapshot const& snapshot) { for (std::size_t i = 0; i < sorted.size(); ++i) { if (sorted[i] >= snapshot.next_unallocated) { spdlog::error_s( - "DenseSlotAllocator::restore refused: free slot {} >= next_unallocated {}", - sorted[i], snapshot.next_unallocated + "DenseSlotAllocator::restore refused: free slot {} >= next_unallocated {}", sorted[i], snapshot.next_unallocated ); return false; } diff --git a/src/openvic-simulation/core/ecs/EcsThreadPool.cpp b/src/openvic-simulation/core/ecs/EcsThreadPool.cpp index 13e3b8f1d..5eb42e823 100644 --- a/src/openvic-simulation/core/ecs/EcsThreadPool.cpp +++ b/src/openvic-simulation/core/ecs/EcsThreadPool.cpp @@ -9,7 +9,9 @@ EcsThreadPool::EcsThreadPool(uint32_t worker_count) { uint32_t const n = std::max(1u, worker_count); workers_.reserve(n); for (uint32_t i = 0; i < n; ++i) { - workers_.emplace_back([this, i]() { worker_loop(i); }); + workers_.emplace_back([this, i]() { + worker_loop(i); + }); } } @@ -32,7 +34,9 @@ void EcsThreadPool::worker_loop(uint32_t worker_id) { bool have_job = false; { std::unique_lock lock(queue_mutex_); - cv_.wait(lock, [this]() { return stop_ || !queue_.empty(); }); + cv_.wait(lock, [this]() { + return stop_ || !queue_.empty(); + }); if (stop_ && queue_.empty()) { return; } diff --git a/src/openvic-simulation/core/ecs/QueryFilter.hpp b/src/openvic-simulation/core/ecs/QueryFilter.hpp index 7aec94441..bf77777a2 100644 --- a/src/openvic-simulation/core/ecs/QueryFilter.hpp +++ b/src/openvic-simulation/core/ecs/QueryFilter.hpp @@ -55,10 +55,7 @@ namespace OpenVic::ecs { // turns any other marker into a clear compile error rather than a silent no-op. template struct Filter { - static_assert( - (is_without::value && ...), - "ecs::Filter currently supports only ecs::Without entries." - ); + static_assert((is_without::value && ...), "ecs::Filter currently supports only ecs::Without entries."); // Sorted-unique exclude ids. Runtime (not constexpr) to mirror // System<>::compute_tick_query_require_ids — both feed Query::*_ids vectors. diff --git a/src/openvic-simulation/core/ecs/Reductions.hpp b/src/openvic-simulation/core/ecs/Reductions.hpp index f01c88d67..fb00216e5 100644 --- a/src/openvic-simulation/core/ecs/Reductions.hpp +++ b/src/openvic-simulation/core/ecs/Reductions.hpp @@ -109,8 +109,12 @@ namespace OpenVic::ecs::reductions { // keys no chunk emits keep their initial value. T needs only += (fixed_point_t works). template void parallel_keyed_sum( - EcsThreadPool& pool, std::size_t chunk_count, std::size_t key_count, - std::span out, KeyedSumScratch& scratch, Body&& body + EcsThreadPool& pool, + std::size_t chunk_count, + std::size_t key_count, + std::span out, + KeyedSumScratch& scratch, + Body&& body ) { assert(out.size() >= key_count); if (scratch.per_chunk.size() < chunk_count) { @@ -133,8 +137,7 @@ namespace OpenVic::ecs::reductions { // Convenience overload: local scratch, allocates per call. template void parallel_keyed_sum( - EcsThreadPool& pool, std::size_t chunk_count, std::size_t key_count, - std::span out, Body&& body + EcsThreadPool& pool, std::size_t chunk_count, std::size_t key_count, std::span out, Body&& body ) { KeyedSumScratch scratch; parallel_keyed_sum(pool, chunk_count, key_count, out, scratch, std::forward(body)); diff --git a/src/openvic-simulation/core/ecs/System.hpp b/src/openvic-simulation/core/ecs/System.hpp index cb8b70e9f..13594e5a5 100644 --- a/src/openvic-simulation/core/ecs/System.hpp +++ b/src/openvic-simulation/core/ecs/System.hpp @@ -10,12 +10,12 @@ #include #include -#include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/QueryFilter.hpp" #include "openvic-simulation/core/ecs/SystemAccess.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/object/Date.hpp" namespace OpenVic::ecs { struct World; @@ -121,23 +121,20 @@ namespace OpenVic::ecs { }; template - using tick_args_tuple_t = - typename fn_traits::args_tuple; + using tick_args_tuple_t = typename fn_traits::args_tuple; template - using component_pack_t = - typename strip_context_and_entity>::components; + using component_pack_t = typename strip_context_and_entity>::components; template - constexpr bool tick_takes_entity_v = - strip_context_and_entity>::takes_entity; + constexpr bool tick_takes_entity_v = strip_context_and_entity>::takes_entity; // True when Derived::tick takes an ImmutableEntityID (rather than EntityID) as its per-row // handle. The iteration path is the same with-entity path; only the handle type the driver // hands to tick() differs — see the dispatch lambdas in SystemImpl.hpp. template constexpr bool tick_takes_immutable_entity_v = - strip_context_and_entity>::takes_immutable_entity; + strip_context_and_entity>::takes_immutable_entity; // Build a static AccessSet array from a component pack tuple. template @@ -149,8 +146,7 @@ namespace OpenVic::ecs { static constexpr std::array value() { return { ComponentAccess { component_type_id_of>(), - std::is_const_v> ? AccessMode::Read : AccessMode::Write - }... }; + std::is_const_v> ? AccessMode::Read : AccessMode::Write }... }; } }; @@ -169,9 +165,7 @@ namespace OpenVic::ecs { template struct require_ids_from_tuple> { static std::vector compute() { - std::vector ids = { - component_type_id_of>()... - }; + std::vector ids = { component_type_id_of>()... }; std::sort(ids.begin(), ids.end()); ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); return ids; @@ -186,9 +180,12 @@ namespace OpenVic::ecs { template void dispatch_threaded( - Derived& self, World& world, TickContext const& ctx, - EcsThreadPool& pool, std::vector& per_chunk_cmds, - CommandBuffer& pending_cmd + Derived& self, + World& world, + TickContext const& ctx, + EcsThreadPool& pool, + std::vector& per_chunk_cmds, + CommandBuffer& pending_cmd ); } @@ -239,12 +236,11 @@ namespace OpenVic::ecs { template struct has_should_run_static_call : std::false_type {}; template - struct has_should_run_static_call()))>> : std::true_type {}; + struct has_should_run_static_call()))>> + : std::true_type {}; template - constexpr bool has_should_run_v = - has_should_run_member::value || has_should_run_static_call::value; + constexpr bool has_should_run_v = has_should_run_member::value || has_should_run_static_call::value; // Valid iff `&T::should_run` is unambiguous AND convertible to bool (*)(TickContext const&). // Convertibility (not is_same) deliberately admits the noexcept-qualified variant — a @@ -257,8 +253,7 @@ namespace OpenVic::ecs { struct should_run_signature_valid : std::false_type {}; template struct should_run_signature_valid> - : std::bool_constant< - std::is_convertible_v> {}; + : std::bool_constant> {}; template constexpr bool should_run_signature_valid_v = should_run_signature_valid::value; @@ -310,9 +305,15 @@ namespace OpenVic::ecs { // detected by trait like the optional `Filters` alias (no defaulted base // implementation — absence means "always run"). See the has_should_run_v / // should_run_signature_valid_v block above for the full determinism contract. - static constexpr std::array declared_run_after() { return {}; } - static constexpr std::array declared_run_before() { return {}; } - static constexpr std::array extra_reads() { return {}; } + static constexpr std::array declared_run_after() { + return {}; + } + static constexpr std::array declared_run_before() { + return {}; + } + static constexpr std::array extra_reads() { + return {}; + } // Cross-archetype / singleton WRITE declarations: any component (or World singleton — // singletons share component_type_id_t) the tick body mutates via ctx.world on rows it @@ -320,7 +321,9 @@ namespace OpenVic::ecs { // scheduler serialises this system against every reader/writer of the same id. // Forbidden on SystemThreaded — a chunk-parallel system would race with ITSELF on the // shared target; see the static_assert in World::register_system. - static constexpr std::array extra_writes() { return {}; } + static constexpr std::array extra_writes() { + return {}; + } // Sorted-unique component ids that define this system's iteration query — the tick // parameter pack only, NOT extra_reads. Read by the scheduler at registration time @@ -368,12 +371,13 @@ namespace OpenVic::ecs { // invokes tick_one_chunk with that chunk's per_chunk_cmds_ slot as TickContext::cmd. static std::vector collect_chunks(World& world); static void tick_one_chunk( - Derived& self, World& world, TickContext const& ctx, - uint32_t archetype_idx, uint32_t chunk_idx + Derived& self, World& world, TickContext const& ctx, uint32_t archetype_idx, uint32_t chunk_idx ); // Pooled across ticks to avoid per-tick allocator churn. - std::vector& per_chunk_buffers() { return per_chunk_cmds_; } + std::vector& per_chunk_buffers() { + return per_chunk_cmds_; + } private: std::vector per_chunk_cmds_; @@ -400,8 +404,7 @@ namespace OpenVic::ecs { // over a combined work-item list across every system in a multi-system stage. std::vector (*collect_chunks_fn)(World& world) = nullptr; void (*tick_one_chunk_fn)( - void* /*instance*/, World&, TickContext const&, - uint32_t /*archetype_idx*/, uint32_t /*chunk_idx*/ + void* /*instance*/, World&, TickContext const&, uint32_t /*archetype_idx*/, uint32_t /*chunk_idx*/ ) = nullptr; // Returns the system's per-chunk CommandBuffer pool. Scheduler resizes / clears / // flips parallel_mode through this accessor when building work items and again on diff --git a/src/openvic-simulation/core/ecs/SystemAccess.hpp b/src/openvic-simulation/core/ecs/SystemAccess.hpp index 08d682400..1c7b2f16c 100644 --- a/src/openvic-simulation/core/ecs/SystemAccess.hpp +++ b/src/openvic-simulation/core/ecs/SystemAccess.hpp @@ -45,9 +45,7 @@ namespace OpenVic::ecs { // walk. Used by the scheduler to test whether one system requires a component the other // excludes (provably-disjoint iteration). Inputs MUST be sorted ascending — both // `tick_query_require_ids` and `tick_query_exclude_ids` are stored that way. - inline bool sorted_intersects( - std::span a, std::span b - ) { + inline bool sorted_intersects(std::span a, std::span b) { std::size_t i = 0; std::size_t j = 0; while (i < a.size() && j < b.size()) { @@ -66,7 +64,7 @@ namespace OpenVic::ecs { // Returns the list of component ids that overlap (with at least one Write). For // diagnostic messages: "system X and Y conflict on component {names}". inline std::vector access_conflict_components( - std::span a, std::span b + std::span a, std::span b ) { std::vector out; for (ComponentAccess const& x : a) { @@ -88,9 +86,7 @@ namespace OpenVic::ecs { // Folds an `extra_reads` array (a list of bare component_type_id_t with implicit Read // mode) into a flat AccessSet vector. Used by the scheduler when assembling each // system's full access set. - inline void merge_extra_reads( - std::vector& dest, std::span extra - ) { + inline void merge_extra_reads(std::vector& dest, std::span extra) { for (component_type_id_t id : extra) { // If a Write entry already exists for this id, keep it (W+R coalesces to W). bool found_write = false; @@ -111,9 +107,7 @@ namespace OpenVic::ecs { // needed — a Write entry can never be masked by an existing entry. Callers MUST run // canonicalise_access_set afterwards (same contract as merge_extra_reads) so a // pre-existing Read for the same id dedupes away in favour of the Write. - inline void merge_extra_writes( - std::vector& dest, std::span extra - ) { + inline void merge_extra_writes(std::vector& dest, std::span extra) { for (component_type_id_t id : extra) { dest.push_back(ComponentAccess { id, AccessMode::Write }); } @@ -130,13 +124,14 @@ namespace OpenVic::ecs { return static_cast(a.mode) > static_cast(b.mode); }); set.erase( - std::unique( - set.begin(), set.end(), - [](ComponentAccess const& a, ComponentAccess const& b) { - return a.component_id == b.component_id; - } - ), - set.end() + std::unique( + set.begin(), + set.end(), + [](ComponentAccess const& a, ComponentAccess const& b) { + return a.component_id == b.component_id; + } + ), + set.end() ); } } diff --git a/src/openvic-simulation/core/ecs/SystemImpl.hpp b/src/openvic-simulation/core/ecs/SystemImpl.hpp index 7633c3ab2..be63dcf67 100644 --- a/src/openvic-simulation/core/ecs/SystemImpl.hpp +++ b/src/openvic-simulation/core/ecs/SystemImpl.hpp @@ -45,22 +45,23 @@ namespace OpenVic::ecs::detail { template struct dispatch_serial_impl> { static void run(Derived& self, World& world, TickContext const& ctx) { - static_assert(sizeof...(Cs) > 0, - "System::tick must have at least one component parameter after TickContext"); - world.template for_each...>(build_tick_query(), - [&self, &ctx](std::remove_cvref_t&... cs) { - self.tick(ctx, cs...); - }); + static_assert(sizeof...(Cs) > 0, "System::tick must have at least one component parameter after TickContext"); + world.template for_each...>( + build_tick_query(), [&self, &ctx](std::remove_cvref_t&... cs) { + self.tick(ctx, cs...); + } + ); } }; template struct dispatch_serial_impl> { static void run(Derived& self, World& world, TickContext const& ctx) { - world.template for_each_with_entity...>(build_tick_query(), - [&self, &ctx](EntityID eid, std::remove_cvref_t&... cs) { - invoke_tick_with_entity(self, ctx, eid, cs...); - }); + world.template for_each_with_entity...>( + build_tick_query(), [&self, &ctx](EntityID eid, std::remove_cvref_t&... cs) { + invoke_tick_with_entity(self, ctx, eid, cs...); + } + ); } }; @@ -93,8 +94,7 @@ namespace OpenVic::ecs::detail { // exclude sets identical between the main-thread collect and any worker-side dispatch. inline std::vector collect_matching_chunks(World& world, Query const& query) { QueryCacheKey key { query.require_ids, query.exclude_ids }; - std::vector const& matched - = world.resolve_query_cache_for_threaded(key).archetype_indices; + std::vector const& matched = world.resolve_query_cache_for_threaded(key).archetype_indices; std::vector out; for (uint32_t arch_idx : matched) { @@ -111,12 +111,14 @@ namespace OpenVic::ecs::detail { template struct dispatch_threaded_impl> { static void run( - Derived& self, World& world, TickContext const& ctx_template, - EcsThreadPool& pool, std::vector& per_chunk_cmds, - CommandBuffer& pending_cmd + Derived& self, + World& world, + TickContext const& ctx_template, + EcsThreadPool& pool, + std::vector& per_chunk_cmds, + CommandBuffer& pending_cmd ) { - std::vector const chunks - = collect_matching_chunks(world, build_tick_query()); + std::vector const chunks = collect_matching_chunks(world, build_tick_query()); std::size_t const N = chunks.size(); if (N == 0) { return; @@ -136,10 +138,10 @@ namespace OpenVic::ecs::detail { CommandBuffer& cmd = per_chunk_cmds[chunk_idx]; TickContext per_chunk { ctx_template.world, ctx_template.today, cmd }; world.template iterate_one_chunk_for_threaded...>( - loc.archetype_idx, loc.chunk_idx, - [&self, &per_chunk](std::remove_cvref_t&... cs) { - self.tick(per_chunk, cs...); - }); + loc.archetype_idx, loc.chunk_idx, [&self, &per_chunk](std::remove_cvref_t&... cs) { + self.tick(per_chunk, cs...); + } + ); }); // Merge in chunk_idx ascending order — deterministic regardless of worker_count. @@ -153,12 +155,14 @@ namespace OpenVic::ecs::detail { template struct dispatch_threaded_impl> { static void run( - Derived& self, World& world, TickContext const& ctx_template, - EcsThreadPool& pool, std::vector& per_chunk_cmds, - CommandBuffer& pending_cmd + Derived& self, + World& world, + TickContext const& ctx_template, + EcsThreadPool& pool, + std::vector& per_chunk_cmds, + CommandBuffer& pending_cmd ) { - std::vector const chunks - = collect_matching_chunks(world, build_tick_query()); + std::vector const chunks = collect_matching_chunks(world, build_tick_query()); std::size_t const N = chunks.size(); if (N == 0) { return; @@ -176,12 +180,11 @@ namespace OpenVic::ecs::detail { ChunkLocation const& loc = chunks[chunk_idx]; CommandBuffer& cmd = per_chunk_cmds[chunk_idx]; TickContext per_chunk { ctx_template.world, ctx_template.today, cmd }; - world.template iterate_one_chunk_with_entity_for_threaded< - std::remove_cvref_t...>( - loc.archetype_idx, loc.chunk_idx, - [&self, &per_chunk](EntityID eid, std::remove_cvref_t&... cs) { - invoke_tick_with_entity(self, per_chunk, eid, cs...); - }); + world.template iterate_one_chunk_with_entity_for_threaded...>( + loc.archetype_idx, loc.chunk_idx, [&self, &per_chunk](EntityID eid, std::remove_cvref_t&... cs) { + invoke_tick_with_entity(self, per_chunk, eid, cs...); + } + ); }); for (std::size_t i = 0; i < N; ++i) { @@ -193,14 +196,16 @@ namespace OpenVic::ecs::detail { template void dispatch_threaded( - Derived& self, World& world, TickContext const& ctx, - EcsThreadPool& pool, std::vector& per_chunk_cmds, - CommandBuffer& pending_cmd + Derived& self, + World& world, + TickContext const& ctx, + EcsThreadPool& pool, + std::vector& per_chunk_cmds, + CommandBuffer& pending_cmd ) { using Components = component_pack_t; constexpr bool with_entity = tick_takes_entity_v; - dispatch_threaded_impl::run( - self, world, ctx, pool, per_chunk_cmds, pending_cmd); + dispatch_threaded_impl::run(self, world, ctx, pool, per_chunk_cmds, pending_cmd); } } @@ -224,8 +229,7 @@ namespace OpenVic::ecs { return; } EcsThreadPool& pool = world.ecs_thread_pool(); - detail::dispatch_threaded( - static_cast(*this), world, ctx, pool, per_chunk_cmds_, *reg->pending_cmd); + detail::dispatch_threaded(static_cast(*this), world, ctx, pool, per_chunk_cmds_, *reg->pending_cmd); } // === Multi-system-stage entry points === @@ -243,27 +247,23 @@ namespace OpenVic::ecs { template void SystemThreaded::tick_one_chunk( - Derived& self, World& world, TickContext const& ctx, - uint32_t archetype_idx, uint32_t chunk_idx + Derived& self, World& world, TickContext const& ctx, uint32_t archetype_idx, uint32_t chunk_idx ) { using Components = detail::component_pack_t; constexpr bool with_entity = detail::tick_takes_entity_v; [&](std::tuple*) { if constexpr (with_entity) { - world.template iterate_one_chunk_with_entity_for_threaded< - std::remove_cvref_t...>( - archetype_idx, chunk_idx, - [&self, &ctx](EntityID eid, std::remove_cvref_t&... cs) { - invoke_tick_with_entity(self, ctx, eid, cs...); - } + world.template iterate_one_chunk_with_entity_for_threaded...>( + archetype_idx, chunk_idx, [&self, &ctx](EntityID eid, std::remove_cvref_t&... cs) { + invoke_tick_with_entity(self, ctx, eid, cs...); + } ); } else { world.template iterate_one_chunk_for_threaded...>( - archetype_idx, chunk_idx, - [&self, &ctx](std::remove_cvref_t&... cs) { - self.tick(ctx, cs...); - } + archetype_idx, chunk_idx, [&self, &ctx](std::remove_cvref_t&... cs) { + self.tick(ctx, cs...); + } ); } }(static_cast(nullptr)); diff --git a/src/openvic-simulation/core/ecs/SystemPhase.hpp b/src/openvic-simulation/core/ecs/SystemPhase.hpp index 6a74ff135..52e2ff8fe 100644 --- a/src/openvic-simulation/core/ecs/SystemPhase.hpp +++ b/src/openvic-simulation/core/ecs/SystemPhase.hpp @@ -116,7 +116,7 @@ namespace OpenVic::ecs { // not SFINAE-probeable, so there is no automated test. // - A template-id extra dep (e.g. some_system) would split on the comma at the // preprocessor level — use a type alias. -#define ECS_IN_PHASE(prev_anchor, /* next_anchor, extra_run_after_systems... */ ...) \ +#define ECS_IN_PHASE(prev_anchor, /* next_anchor, extra_run_after_systems... */...) \ static constexpr auto declared_run_after() { \ return ::OpenVic::ecs::detail::phase_run_after_array(); \ } \ diff --git a/src/openvic-simulation/core/ecs/SystemScheduler.cpp b/src/openvic-simulation/core/ecs/SystemScheduler.cpp index d174b94bd..8c069faf9 100644 --- a/src/openvic-simulation/core/ecs/SystemScheduler.cpp +++ b/src/openvic-simulation/core/ecs/SystemScheduler.cpp @@ -135,21 +135,19 @@ namespace { } bool provably_disjoint(SystemRegistration const& a, SystemRegistration const& b) { - bool const disjoint_iteration = - sorted_intersects(a.tick_query_require_ids, b.tick_query_exclude_ids) || - sorted_intersects(b.tick_query_require_ids, a.tick_query_exclude_ids); + bool const disjoint_iteration = sorted_intersects(a.tick_query_require_ids, b.tick_query_exclude_ids) || + sorted_intersects(b.tick_query_require_ids, a.tick_query_exclude_ids); if (!disjoint_iteration) { return false; } for (component_type_id_t c : access_conflict_components(a.access, b.access)) { - if (!sorted_contains(a.tick_query_require_ids, c) || - !sorted_contains(b.tick_query_require_ids, c)) { + if (!sorted_contains(a.tick_query_require_ids, c) || !sorted_contains(b.tick_query_require_ids, c)) { return false; } // Declared in an extra list on either side → the access also reaches rows the // system does not iterate; disjoint iteration cannot separate it. - if (sorted_contains(a.extra_reads, c) || sorted_contains(a.extra_writes, c) || - sorted_contains(b.extra_reads, c) || sorted_contains(b.extra_writes, c)) { + if (sorted_contains(a.extra_reads, c) || sorted_contains(a.extra_writes, c) || sorted_contains(b.extra_reads, c) || + sorted_contains(b.extra_writes, c)) { return false; } } @@ -215,8 +213,8 @@ void SystemScheduler::rebuild(std::vector& registry) { continue; } if (!access_overlaps( - std::span(registry[i].access), - std::span(registry[j].access))) { + std::span(registry[i].access), std::span(registry[j].access) + )) { continue; } // Filter-aware override: a shared Write is not a real ordering constraint when @@ -365,7 +363,7 @@ void SystemScheduler::rebuild(std::vector& registry) { } std::size_t SystemScheduler::stage_index_of( - system_type_id_t type_id, std::vector const& registry + system_type_id_t type_id, std::vector const& registry ) const noexcept { for (std::size_t s = 0; s < stages_.size(); ++s) { for (uint32_t reg_idx : stages_[s].registration_indices) { @@ -406,8 +404,7 @@ namespace { } void SystemScheduler::run( - World& world, Date today, std::vector& registry, - EcsThreadPool& pool, bool serial_mode + World& world, Date today, std::vector& registry, EcsThreadPool& pool, bool serial_mode ) { if (!built_) { return; @@ -484,7 +481,7 @@ void SystemScheduler::run( } if (!reg.tick_query_require_ids.empty()) { QueryCacheKey key { reg.tick_query_require_ids, reg.tick_query_exclude_ids }; - (void) world.resolve_query_cache_for_threaded(key); + (void)world.resolve_query_cache_for_threaded(key); } } @@ -509,9 +506,8 @@ void SystemScheduler::run( continue; } - if (reg.is_threaded && reg.collect_chunks_fn != nullptr - && reg.per_chunk_cmds_accessor != nullptr - && reg.tick_one_chunk_fn != nullptr) { + if (reg.is_threaded && reg.collect_chunks_fn != nullptr && reg.per_chunk_cmds_accessor != nullptr && + reg.tick_one_chunk_fn != nullptr) { std::vector chunks = reg.collect_chunks_fn(world); std::vector* cbs = reg.per_chunk_cmds_accessor(reg.instance); if (cbs->size() < chunks.size()) { @@ -533,9 +529,7 @@ void SystemScheduler::run( item.chunk_local_idx = static_cast(i); work_items.push_back(item); } - threaded_systems.push_back( - PerSystemThreadedInfo { reg_idx, static_cast(chunks.size()) } - ); + threaded_systems.push_back(PerSystemThreadedInfo { reg_idx, static_cast(chunks.size()) }); } else { // Plain System<> (or a SystemThreaded with no entry points — shouldn't // happen post-Phase-0). One whole-tick work item; dispatch_serial @@ -554,24 +548,19 @@ void SystemScheduler::run( // nested parallel_for, no run_concurrent — so the pool's per-call DoneState // is the only counter touched and workers never block on inner dispatches. if (!work_items.empty()) { - pool.parallel_for(work_items.size(), - [&work_items, ®istry, &world, today] - (std::size_t i, uint32_t /*worker_id*/) { - WorkItem const& item = work_items[i]; - SystemRegistration& reg = registry[item.reg_idx]; - if (item.kind == WorkKind::ThreadedChunk) { - std::vector* cbs - = reg.per_chunk_cmds_accessor(reg.instance); - TickContext ctx { world, today, (*cbs)[item.chunk_local_idx] }; - reg.tick_one_chunk_fn( - reg.instance, world, ctx, - item.archetype_idx, item.chunk_idx - ); - } else { - TickContext ctx { world, today, *reg.pending_cmd }; - reg.tick_all_fn(reg.instance, world, ctx); - } - } + pool.parallel_for( + work_items.size(), [&work_items, ®istry, &world, today](std::size_t i, uint32_t /*worker_id*/) { + WorkItem const& item = work_items[i]; + SystemRegistration& reg = registry[item.reg_idx]; + if (item.kind == WorkKind::ThreadedChunk) { + std::vector* cbs = reg.per_chunk_cmds_accessor(reg.instance); + TickContext ctx { world, today, (*cbs)[item.chunk_local_idx] }; + reg.tick_one_chunk_fn(reg.instance, world, ctx, item.archetype_idx, item.chunk_idx); + } else { + TickContext ctx { world, today, *reg.pending_cmd }; + reg.tick_all_fn(reg.instance, world, ctx); + } + } ); } diff --git a/src/openvic-simulation/core/ecs/SystemScheduler.hpp b/src/openvic-simulation/core/ecs/SystemScheduler.hpp index d3f716613..5013113ac 100644 --- a/src/openvic-simulation/core/ecs/SystemScheduler.hpp +++ b/src/openvic-simulation/core/ecs/SystemScheduler.hpp @@ -4,9 +4,9 @@ #include #include -#include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/ecs/System.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/object/Date.hpp" namespace OpenVic::ecs { struct World; @@ -34,29 +34,32 @@ namespace OpenVic::ecs { // stage has only one system). After each stage joins, applies each system's // pending CommandBuffer in the stage's deterministic emit order — ascending // system_type_id_t within the stage, independent of registration order. - void run( - World& world, Date today, std::vector& registry, - EcsThreadPool& pool, bool serial_mode - ); + void run(World& world, Date today, std::vector& registry, EcsThreadPool& pool, bool serial_mode); // FNV-1a hash over the (stage_index, system_type_id_t) pairs of the schedule. - uint64_t schedule_hash() const noexcept { return schedule_hash_; } + uint64_t schedule_hash() const noexcept { + return schedule_hash_; + } // Drop the built state — next `run` call will rebuild. - void invalidate() noexcept { built_ = false; } + void invalidate() noexcept { + built_ = false; + } - bool built() const noexcept { return built_; } + bool built() const noexcept { + return built_; + } // Test/introspection only. Number of stages in the built schedule (0 if not built). - std::size_t stage_count() const noexcept { return stages_.size(); } + std::size_t stage_count() const noexcept { + return stages_.size(); + } // Test/introspection only. Stage index of the system registered with `type_id`, or // SIZE_MAX if it isn't scheduled. Walks `registry` to map a stage's registration // indices back to type ids — lets tests assert two systems do (or do not) share a // stage, which is exactly what the disjoint-iteration conflict override changes. - std::size_t stage_index_of( - system_type_id_t type_id, std::vector const& registry - ) const noexcept; + std::size_t stage_index_of(system_type_id_t type_id, std::vector const& registry) const noexcept; private: bool built_ = false; diff --git a/src/openvic-simulation/core/ecs/World.cpp b/src/openvic-simulation/core/ecs/World.cpp index b4d2e8234..045117ce8 100644 --- a/src/openvic-simulation/core/ecs/World.cpp +++ b/src/openvic-simulation/core/ecs/World.cpp @@ -26,9 +26,9 @@ bool World::in_tick_or_log_(char const* fn_name) { // logged so the misuse doesn't hide behind a surprise nullptr/false/invalid-id // return. spdlog::error_s( - "{} refused: direct structural mutation during tick_systems — queue the op on " - "ctx.cmd instead (applies at the stage barrier)", - fn_name + "{} refused: direct structural mutation during tick_systems — queue the op on " + "ctx.cmd instead (applies at the stage barrier)", + fn_name ); return true; } @@ -42,8 +42,11 @@ bool World::immutable_or_log_(EntityID id, char const* fn_name, std::string_view // an error. This is the runtime backstop for plain EntityIDs that surface for an immutable // entity (for_each_with_entity, or a laundered unsafe_mutable_id()). spdlog::error_s( - "{} refused: entity {}:{} is immutable — its archetype cannot change (component '{}')", - fn_name, id.index, id.generation, component_name + "{} refused: entity {}:{} is immutable — its archetype cannot change (component '{}')", + fn_name, + id.index, + id.generation, + component_name ); return true; } @@ -137,9 +140,8 @@ void World::compute_chunk_layout(Archetype& arch) { total_align_overhead += (vt->align - 1); } } - std::size_t const usable = (CHUNK_BLOCK_BYTES > total_align_overhead) - ? (CHUNK_BLOCK_BYTES - total_align_overhead) - : CHUNK_BLOCK_BYTES; + std::size_t const usable = + (CHUNK_BLOCK_BYTES > total_align_overhead) ? (CHUNK_BLOCK_BYTES - total_align_overhead) : CHUNK_BLOCK_BYTES; std::size_t capacity = std::max(1, usable / total_per_row); // Compute slab offsets at this capacity. If the result happens to overflow (only @@ -170,9 +172,7 @@ void World::compute_chunk_layout(Archetype& arch) { arch.chunk_capacity = capacity; } -uint32_t World::find_or_create_archetype( - std::vector const& sig, ColumnVTable const* const* vtables -) { +uint32_t World::find_or_create_archetype(std::vector const& sig, ColumnVTable const* const* vtables) { auto it = archetype_by_signature.find(sig); if (it != archetype_by_signature.end()) { return it->second; @@ -224,9 +224,7 @@ bool World::is_alive(EntityID id) const { return true; } -void World::compact_archetype_after_external_move( - uint32_t archetype_index, std::size_t chunk_index, std::size_t row -) { +void World::compact_archetype_after_external_move(uint32_t archetype_index, std::size_t chunk_index, std::size_t row) { Archetype& arch = archetypes[archetype_index]; for (uint64_t& v : arch.column_versions) { ++v; @@ -348,9 +346,9 @@ bool World::snapshot_identity(WorldIdentitySnapshot& out) const { EntitySlot const& slot = entity_slots[i]; if (slot.alive && slot.archetype_index == INVALID_ARCHETYPE) { spdlog::error_s( - "World::snapshot_identity refused: slot {} is reserved-but-unfinalised (a CommandBuffer " - "holds un-applied creates) — apply every buffer before snapshotting", - i + "World::snapshot_identity refused: slot {} is reserved-but-unfinalised (a CommandBuffer " + "holds un-applied creates) — apply every buffer before snapshotting", + i ); out.slots.clear(); return false; @@ -372,9 +370,7 @@ bool World::snapshot_identity(WorldIdentitySnapshot& out) const { std::size_t steps = 0; while (true) { if (cur >= entity_slots.size() || entity_slots[cur].alive || steps >= entity_slots.size()) { - spdlog::error_s( - "World::snapshot_identity refused: corrupt free chain at slot {} (step {})", cur, steps - ); + spdlog::error_s("World::snapshot_identity refused: corrupt free chain at slot {} (step {})", cur, steps); out.slots.clear(); out.free_list.clear(); return false; @@ -392,8 +388,9 @@ bool World::snapshot_identity(WorldIdentitySnapshot& out) const { // Every dead slot must be chain-reachable — a mismatch means a leaked or doubly-linked slot. if (out.free_list.size() != dead_count) { spdlog::error_s( - "World::snapshot_identity refused: free chain holds {} slots but {} slots are dead", - out.free_list.size(), dead_count + "World::snapshot_identity refused: free chain holds {} slots but {} slots are dead", + out.free_list.size(), + dead_count ); out.slots.clear(); out.free_list.clear(); @@ -410,8 +407,7 @@ bool World::restore_identity(WorldIdentitySnapshot const& snapshot) { } if (!entity_slots.empty()) { spdlog::error_s( - "World::restore_identity refused: target World is not fresh ({} slots already allocated)", - entity_slots.size() + "World::restore_identity refused: target World is not fresh ({} slots already allocated)", entity_slots.size() ); return false; } @@ -421,8 +417,7 @@ bool World::restore_identity(WorldIdentitySnapshot const& snapshot) { uint32_t const gen = snapshot.slots[i].generation; if (gen == 0 || (gen & DEFERRED_GENERATION_BIT) != 0) { spdlog::error_s( - "World::restore_identity refused: slot {} has invalid generation {:#x} (must be in [1, 0x7FFFFFFF])", - i, gen + "World::restore_identity refused: slot {} has invalid generation {:#x} (must be in [1, 0x7FFFFFFF])", i, gen ); return false; } @@ -432,8 +427,9 @@ bool World::restore_identity(WorldIdentitySnapshot const& snapshot) { for (uint32_t const free_index : snapshot.free_list) { if (free_index >= snapshot.slots.size()) { spdlog::error_s( - "World::restore_identity refused: free-list index {} out of range ({} slots)", - free_index, snapshot.slots.size() + "World::restore_identity refused: free-list index {} out of range ({} slots)", + free_index, + snapshot.slots.size() ); return false; } @@ -479,9 +475,7 @@ bool World::restore_entity_precheck_(EntityID eid) const { return false; } if (eid.index >= entity_slots.size()) { - spdlog::error_s( - "World::restore_entity refused: slot index {} out of range ({} slots)", eid.index, entity_slots.size() - ); + spdlog::error_s("World::restore_entity refused: slot index {} out of range ({} slots)", eid.index, entity_slots.size()); return false; } EntitySlot const& slot = entity_slots[eid.index]; @@ -491,25 +485,25 @@ bool World::restore_entity_precheck_(EntityID eid) const { } if (slot.generation != eid.generation) { spdlog::error_s( - "World::restore_entity refused: stale generation for entity {}:{} (slot holds {})", - eid.index, eid.generation, slot.generation + "World::restore_entity refused: stale generation for entity {}:{} (slot holds {})", + eid.index, + eid.generation, + slot.generation ); return false; } if (slot.archetype_index != INVALID_ARCHETYPE) { - spdlog::error_s( - "World::restore_entity refused: entity {}:{} is already finalised", eid.index, eid.generation - ); + spdlog::error_s("World::restore_entity refused: entity {}:{} is already finalised", eid.index, eid.generation); return false; } return true; } void World::finalize_reserved_entity( - EntityID eid, - std::vector const& sorted_sig, - std::vector const& sorted_vtables, - std::vector const& sorted_value_slots + EntityID eid, + std::vector const& sorted_sig, + std::vector const& sorted_vtables, + std::vector const& sorted_value_slots ) { if (eid.index >= entity_slots.size()) { return; @@ -541,8 +535,7 @@ void World::finalize_reserved_entity( } bool World::bulk_create_sizes_ok_( - std::size_t count, std::size_t out_ids_size, std::size_t const* span_sizes, - std::size_t span_count, char const* fn_name + std::size_t count, std::size_t out_ids_size, std::size_t const* span_sizes, std::size_t span_count, char const* fn_name ) const { if (out_ids_size != count) { spdlog::error_s("{} refused: out_ids length {} != count {}", fn_name, out_ids_size, count); @@ -550,9 +543,7 @@ bool World::bulk_create_sizes_ok_( } for (std::size_t i = 0; i < span_count; ++i) { if (span_sizes[i] != count) { - spdlog::error_s( - "{} refused: input span {} has length {} != count {}", fn_name, i, span_sizes[i], count - ); + spdlog::error_s("{} refused: input span {} has length {} != count {}", fn_name, i, span_sizes[i], count); return false; } } @@ -560,10 +551,10 @@ bool World::bulk_create_sizes_ok_( } void World::finalize_reserved_entities_bulk( - std::span ids, - std::vector const& sorted_sig, - std::vector const& sorted_vtables, - std::span column_blocks + std::span ids, + std::vector const& sorted_sig, + std::vector const& sorted_vtables, + std::span column_blocks ) { std::size_t const count = ids.size(); if (count == 0) { @@ -598,13 +589,11 @@ void World::finalize_reserved_entities_bulk( element_slots[c] = nullptr; continue; } - element_slots[c] - = static_cast(column_blocks[c]) + i * sorted_vtables[c]->size; + element_slots[c] = static_cast(column_blocks[c]) + i * sorted_vtables[c]->size; } - bool const valid = eid.index < entity_slots.size() - && entity_slots[eid.index].alive - && entity_slots[eid.index].generation == eid.generation - && entity_slots[eid.index].archetype_index == INVALID_ARCHETYPE; + bool const valid = eid.index < entity_slots.size() && entity_slots[eid.index].alive && + entity_slots[eid.index].generation == eid.generation && + entity_slots[eid.index].archetype_index == INVALID_ARCHETYPE; if (valid) { finalize_reserved_entity(eid, sorted_sig, sorted_vtables, element_slots); } else { diff --git a/src/openvic-simulation/core/ecs/World.hpp b/src/openvic-simulation/core/ecs/World.hpp index 424e4be1f..336ab40ca 100644 --- a/src/openvic-simulation/core/ecs/World.hpp +++ b/src/openvic-simulation/core/ecs/World.hpp @@ -184,9 +184,7 @@ namespace OpenVic::ecs { // are ImmutableEntityID (same compile-time structural-mutation guarantee as the // single-entity API). template - bool create_immutable_entities( - std::size_t count, std::span out_ids, Spans&&... spans - ); + bool create_immutable_entities(std::size_t count, std::span out_ids, Spans&&... spans); void destroy_entity(EntityID id); bool is_alive(EntityID id) const; @@ -407,8 +405,7 @@ namespace OpenVic::ecs { void iterate_one_chunk_for_threaded(uint32_t archetype_idx, uint32_t chunk_idx, Body&& body); template - void iterate_one_chunk_with_entity_for_threaded( - uint32_t archetype_idx, uint32_t chunk_idx, Body&& body); + void iterate_one_chunk_with_entity_for_threaded(uint32_t archetype_idx, uint32_t chunk_idx, Body&& body); // === Reserved-but-unfinalised slot === // Reserves an entity slot without placing it in any archetype. The returned EntityID @@ -425,10 +422,10 @@ namespace OpenVic::ecs { // Caller is responsible for ensuring `eid` is a reserved slot (alive but // archetype_index == INVALID_ARCHETYPE). void finalize_reserved_entity( - EntityID eid, - std::vector const& sorted_sig, - std::vector const& sorted_vtables, - std::vector const& sorted_value_slots + EntityID eid, + std::vector const& sorted_sig, + std::vector const& sorted_vtables, + std::vector const& sorted_value_slots ); // Bulk analogue of finalize_reserved_entity, used by CommandBuffer::apply for batch @@ -448,10 +445,10 @@ namespace OpenVic::ecs { // values are destroyed here. Immutability stamping is the caller's job (as with // finalize_reserved_entity). void finalize_reserved_entities_bulk( - std::span ids, - std::vector const& sorted_sig, - std::vector const& sorted_vtables, - std::span column_blocks + std::span ids, + std::vector const& sorted_sig, + std::vector const& sorted_vtables, + std::span column_blocks ); // Drops a reserved-but-unfinalised slot (used when CommandBuffer records a destroy @@ -632,16 +629,17 @@ namespace OpenVic::ecs { // Shared body of create_entities / create_immutable_entities. OutIdT is EntityID or // ImmutableEntityID (both aggregate-init from { index, generation }). template - bool create_entities_impl( - bool immutable, std::size_t count, std::span out_ids, Spans&&... spans - ); + bool create_entities_impl(bool immutable, std::size_t count, std::span out_ids, Spans&&... spans); // Out-of-line validation + logging for the bulk-create entry points, so the header // template stays free of the Logger include. True iff out_ids_size == count and every // span_sizes[0..span_count) == count; logs an error naming the mismatch otherwise. bool bulk_create_sizes_ok_( - std::size_t count, std::size_t out_ids_size, std::size_t const* span_sizes, - std::size_t span_count, char const* fn_name + std::size_t count, + std::size_t out_ids_size, + std::size_t const* span_sizes, + std::size_t span_count, + char const* fn_name ) const; // Reused scratch for bulk row reservation (create_entities_impl / @@ -668,9 +666,7 @@ namespace OpenVic::ecs { // Looks up an existing archetype matching `sig` (sorted) or creates one with empty // chunks (none allocated until `reserve_row` is called). Returns the archetype's // index in `archetypes`. Bumps `archetype_epoch` if a new archetype was created. - uint32_t find_or_create_archetype( - std::vector const& sig, ColumnVTable const* const* vtables - ); + uint32_t find_or_create_archetype(std::vector const& sig, ColumnVTable const* const* vtables); // Computes column_offsets and chunk_capacity for an archetype. Tag columns receive // NO_COLUMN_OFFSET. Returns the per-row total bytes (used internally; callers don't @@ -749,8 +745,8 @@ namespace OpenVic::ecs { void* slot = archetypes[archetype_idx].row_in_column(loc.chunk_index, col, loc.row); ::new (slot) TC(std::forward(value)); } else { - (void) col; - (void) value; + (void)col; + (void)value; } }; (place(std::forward(values)), ...); @@ -798,25 +794,23 @@ namespace OpenVic::ecs { // Element types are non-const so a std::span (or const container) argument // fails to convert — the moved-from input contract cannot silently become a copy. template - using BulkSpanTuple = decltype(std::tuple_cat(std::declval< - std::conditional_t, std::tuple<>, std::tuple>> - >()...)); + using BulkSpanTuple = decltype(std::tuple_cat( + std::declval, std::tuple<>, std::tuple>>>()... + )); } template - bool World::create_entities_impl( - bool immutable, std::size_t count, std::span out_ids, Spans&&... spans - ) { + bool World::create_entities_impl(bool immutable, std::size_t count, std::span out_ids, Spans&&... spans) { static_assert(sizeof...(Cs) > 0, "create_entities requires at least one component"); static_assert( - (std::is_same_v> && ...), - "create_entities component types must be plain types (no const/volatile/reference)" + (std::is_same_v> && ...), + "create_entities component types must be plain types (no const/volatile/reference)" ); constexpr std::size_t const non_empty = detail::non_empty_component_count(); static_assert( - sizeof...(Spans) == non_empty || sizeof...(Spans) == 0, - "create_entities takes one span per non-empty component (matched to the non-empty " - "Cs... in pack order; tags take no span), or no spans to default-construct" + sizeof...(Spans) == non_empty || sizeof...(Spans) == 0, + "create_entities takes one span per non-empty component (matched to the non-empty " + "Cs... in pack order; tags take no span), or no spans to default-construct" ); constexpr bool const use_spans = sizeof...(Spans) > 0; @@ -838,10 +832,10 @@ namespace OpenVic::ecs { std::size_t span_sizes[non_empty]; std::size_t si = 0; std::apply( - [&](auto const&... s) { - ((span_sizes[si++] = s.size()), ...); - }, - typed_spans + [&](auto const&... s) { + ((span_sizes[si++] = s.size()), ...); + }, + typed_spans ); if (!bulk_create_sizes_ok_(count, out_ids.size(), span_sizes, non_empty, "World::create_entities")) { return false; @@ -918,9 +912,7 @@ namespace OpenVic::ecs { std::size_t const col = arch.column_index_for(component_type_id_of()); std::size_t offset = 0; for (Archetype::RowRange const& range : bulk_rows_scratch_) { - TC* const dst = static_cast( - arch.row_in_column(range.chunk_index, col, range.row_begin) - ); + TC* const dst = static_cast(arch.row_in_column(range.chunk_index, col, range.row_begin)); if constexpr (use_spans) { std::span const src = std::get(typed_spans); for (std::size_t k = 0; k < range.count; ++k) { @@ -947,9 +939,7 @@ namespace OpenVic::ecs { } template - bool World::create_immutable_entities( - std::size_t count, std::span out_ids, Spans&&... spans - ) { + bool World::create_immutable_entities(std::size_t count, std::span out_ids, Spans&&... spans) { return create_entities_impl(true, count, out_ids, std::forward(spans)...); } @@ -1097,7 +1087,7 @@ namespace OpenVic::ecs { std::size_t const existing_col = src.column_index_for(new_id); if (existing_col != NO_COLUMN_INDEX) { if constexpr (std::is_empty_v) { - (void) value; + (void)value; return nullptr; // tag types have no data — no pointer to return. } else { TC* dst_ptr = static_cast(src.row_in_column(src_chunk, existing_col, src_row)); @@ -1152,7 +1142,7 @@ namespace OpenVic::ecs { placed_ptr = static_cast(slot); ::new (slot) TC(std::forward(value)); } else { - (void) value; + (void)value; } } else { std::size_t const src_col_idx = src.column_index_for(tid); @@ -1276,10 +1266,10 @@ namespace OpenVic::ecs { C& deref_chunk_row(Archetype& arch, std::size_t col_idx, std::size_t chunk_idx, std::size_t row) { if constexpr (std::is_empty_v) { static C instance {}; - (void) arch; - (void) col_idx; - (void) chunk_idx; - (void) row; + (void)arch; + (void)col_idx; + (void)chunk_idx; + (void)row; return instance; } else { return *static_cast(arch.row_in_column(chunk_idx, col_idx, row)); @@ -1292,9 +1282,9 @@ namespace OpenVic::ecs { template C* chunk_array_for(Archetype& arch, std::size_t col_idx, std::size_t chunk_idx) { if constexpr (std::is_empty_v) { - (void) arch; - (void) col_idx; - (void) chunk_idx; + (void)arch; + (void)col_idx; + (void)chunk_idx; return nullptr; } else { return static_cast(arch.column_array(chunk_idx, col_idx)); @@ -1311,8 +1301,8 @@ namespace OpenVic::ecs { C& row_ref_from_array(C* OV_RESTRICT arr, std::size_t row) { if constexpr (std::is_empty_v) { static C instance {}; - (void) arr; - (void) row; + (void)arr; + (void)row; return instance; } else { return arr[row]; @@ -1358,11 +1348,9 @@ namespace OpenVic::ecs { // loop indexes these directly; per-row pointer rederivation through // row_in_column is eliminated. row_ref_from_array's OV_RESTRICT param // carries the non-aliasing promise into the inlined body. - auto arrs = std::tuple { detail::chunk_array_for( - arch, cols[Is], chunk_idx)... }; + auto arrs = std::tuple { detail::chunk_array_for(arch, cols[Is], chunk_idx)... }; for (std::size_t row = 0; row < row_count; ++row) { - fn(detail::row_ref_from_array( - std::get(arrs), row)...); + fn(detail::row_ref_from_array(std::get(arrs), row)...); } }(std::index_sequence_for {}); } @@ -1386,11 +1374,9 @@ namespace OpenVic::ecs { std::size_t const row_count = arch.chunks[chunk_idx].count; EntityID const* OV_RESTRICT eids = arch.entity_array(chunk_idx); [&](std::index_sequence) { - auto arrs = std::tuple { detail::chunk_array_for( - arch, cols[Is], chunk_idx)... }; + auto arrs = std::tuple { detail::chunk_array_for(arch, cols[Is], chunk_idx)... }; for (std::size_t row = 0; row < row_count; ++row) { - fn(eids[row], detail::row_ref_from_array( - std::get(arrs), row)...); + fn(eids[row], detail::row_ref_from_array(std::get(arrs), row)...); } }(std::index_sequence_for {}); } @@ -1425,9 +1411,7 @@ namespace OpenVic::ecs { } [&](std::index_sequence) { ChunkView view { - row_count, - arch.entity_array(chunk_idx), - { detail::chunk_array_for(arch, cols[Is], chunk_idx)... } + row_count, arch.entity_array(chunk_idx), { detail::chunk_array_for(arch, cols[Is], chunk_idx)... } }; fn(view); }(std::index_sequence_for {}); @@ -1449,9 +1433,9 @@ namespace OpenVic::ecs { return existing; } TC* fresh = new TC(std::forward(value)); - singletons.emplace(id, SingletonRecord { - SingletonPtr { static_cast(fresh), deleter }, checksum_singleton_thunk_for() - }); + singletons.emplace( + id, SingletonRecord { SingletonPtr { static_cast(fresh), deleter }, checksum_singleton_thunk_for() } + ); return fresh; } @@ -1469,9 +1453,9 @@ namespace OpenVic::ecs { return existing; } TC* fresh = new TC {}; - singletons.emplace(id, SingletonRecord { - SingletonPtr { static_cast(fresh), deleter }, checksum_singleton_thunk_for() - }); + singletons.emplace( + id, SingletonRecord { SingletonPtr { static_cast(fresh), deleter }, checksum_singleton_thunk_for() } + ); return fresh; } @@ -1511,19 +1495,19 @@ namespace OpenVic::ecs { template SystemHandle World::register_system(Args&&... args) { static_assert( - !(S::is_threaded && S::extra_writes().size() > 0), - "SystemThreaded must not declare extra_writes(): its chunks run concurrently, so a " - "cross-archetype/singleton write races the system with ITSELF — no scheduler edge " - "can fix that. Use a serial System<> (with Reductions::* for parallel folds) instead." + !(S::is_threaded && S::extra_writes().size() > 0), + "SystemThreaded must not declare extra_writes(): its chunks run concurrently, so a " + "cross-archetype/singleton write races the system with ITSELF — no scheduler edge " + "can fix that. Use a serial System<> (with Reductions::* for parallel folds) instead." ); static_assert( - !has_should_run_v || should_run_signature_valid_v, - "S declares `should_run`, but not as `static bool should_run(TickContext const&)`. " - "It must be a single, non-overloaded STATIC function with exactly that signature " - "(noexcept allowed) — systems are stateless by project rule. A member function, " - "data member, overload set, or wrong-signature variant would otherwise be silently " - "ignored; this assert makes it a hard error instead." + !has_should_run_v || should_run_signature_valid_v, + "S declares `should_run`, but not as `static bool should_run(TickContext const&)`. " + "It must be a single, non-overloaded STATIC function with exactly that signature " + "(noexcept allowed) — systems are stateless by project rule. A member function, " + "data member, overload set, or wrong-signature variant would otherwise be silently " + "ignored; this assert makes it a hard error instead." ); // Build a SystemRegistration from S's static metadata. The system's per-row tick @@ -1536,7 +1520,9 @@ namespace OpenVic::ecs { auto instance_owned = std::make_unique(std::forward(args)...); void* instance_raw = instance_owned.get(); - auto deleter = +[](void* p) { delete static_cast(p); }; + auto deleter = +[](void* p) { + delete static_cast(p); + }; auto tick_all_fn = +[](void* inst, World& w, TickContext const& tc) { static_cast(inst)->tick_all(w, tc); }; @@ -1567,13 +1553,9 @@ namespace OpenVic::ecs { // tick_query_require_ids). Declaration order is not meaningful — these only ever // fold into the access set and gate the disjoint-iteration override. std::sort(reg.extra_reads.begin(), reg.extra_reads.end()); - reg.extra_reads.erase( - std::unique(reg.extra_reads.begin(), reg.extra_reads.end()), reg.extra_reads.end() - ); + reg.extra_reads.erase(std::unique(reg.extra_reads.begin(), reg.extra_reads.end()), reg.extra_reads.end()); std::sort(reg.extra_writes.begin(), reg.extra_writes.end()); - reg.extra_writes.erase( - std::unique(reg.extra_writes.begin(), reg.extra_writes.end()), reg.extra_writes.end() - ); + reg.extra_writes.erase(std::unique(reg.extra_writes.begin(), reg.extra_writes.end()), reg.extra_writes.end()); merge_extra_reads(reg.access, reg.extra_reads); merge_extra_writes(reg.access, reg.extra_writes); canonicalise_access_set(reg.access); @@ -1595,10 +1577,7 @@ namespace OpenVic::ecs { reg.collect_chunks_fn = +[](World& w) -> std::vector { return S::collect_chunks(w); }; - reg.tick_one_chunk_fn = +[]( - void* inst, World& w, TickContext const& tc, - uint32_t arch_idx, uint32_t chunk_idx - ) { + reg.tick_one_chunk_fn = +[](void* inst, World& w, TickContext const& tc, uint32_t arch_idx, uint32_t chunk_idx) { S::tick_one_chunk(*static_cast(inst), w, tc, arch_idx, chunk_idx); }; reg.per_chunk_cmds_accessor = +[](void* inst) -> std::vector* { @@ -1624,7 +1603,7 @@ namespace OpenVic::ecs { // Move the instance ownership into the registration last, so partial-failure paths // don't leak. (`instance_raw` was already captured.) - (void) instance_owned.release(); + (void)instance_owned.release(); system_registry_.push_back(std::move(reg)); scheduler_dirty_ = true; @@ -1641,11 +1620,9 @@ namespace OpenVic::ecs { ((cols[i++] = arch.column_index_for(component_type_id_of())), ...); std::size_t const row_count = arch.chunks[chunk_idx].count; [&](std::index_sequence) { - auto arrs = std::tuple { detail::chunk_array_for( - arch, cols[Is], chunk_idx)... }; + auto arrs = std::tuple { detail::chunk_array_for(arch, cols[Is], chunk_idx)... }; for (std::size_t row = 0; row < row_count; ++row) { - body(detail::row_ref_from_array( - std::get(arrs), row)...); + body(detail::row_ref_from_array(std::get(arrs), row)...); } }(std::index_sequence_for {}); } @@ -1659,11 +1636,9 @@ namespace OpenVic::ecs { std::size_t const row_count = arch.chunks[chunk_idx].count; EntityID const* OV_RESTRICT eids = arch.entity_array(chunk_idx); [&](std::index_sequence) { - auto arrs = std::tuple { detail::chunk_array_for( - arch, cols[Is], chunk_idx)... }; + auto arrs = std::tuple { detail::chunk_array_for(arch, cols[Is], chunk_idx)... }; for (std::size_t row = 0; row < row_count; ++row) { - body(eids[row], detail::row_ref_from_array( - std::get(arrs), row)...); + body(eids[row], detail::row_ref_from_array(std::get(arrs), row)...); } }(std::index_sequence_for {}); } diff --git a/src/openvic-simulation/core/error/Error.hpp b/src/openvic-simulation/core/error/Error.hpp index d28ca1ad6..beb6e2865 100644 --- a/src/openvic-simulation/core/error/Error.hpp +++ b/src/openvic-simulation/core/error/Error.hpp @@ -37,31 +37,31 @@ namespace OpenVic { static constexpr std::string_view as_string(Error err) { switch (err) { using enum Error; - case OK: return "OK"; - case FAILED: return "Failed"; - case UNAVAILABLE: return "Unavailable"; - case UNCONFIGURED: return "Unconfigured"; - case UNAUTHORIZED: return "Unauthorized"; - case FILE_NOT_FOUND: return "File not found"; - case FILE_BAD_PATH: return "File: Bad path"; + case OK: return "OK"; + case FAILED: return "Failed"; + case UNAVAILABLE: return "Unavailable"; + case UNCONFIGURED: return "Unconfigured"; + case UNAUTHORIZED: return "Unauthorized"; + case FILE_NOT_FOUND: return "File not found"; + case FILE_BAD_PATH: return "File: Bad path"; case FILE_NO_PERMISSION: return "File: Permission Denied"; case FILE_ALREADY_IN_USE: return "File already in use"; - case FILE_CANT_OPEN: return "Can't open file"; - case FILE_CAN_WRITE: return "Can't write file"; - case FILE_CANT_READ: return "Can't read file"; - case LOCKED: return "Locked"; - case TIMEOUT: return "Timeout"; - case CANT_CONNECT: return "Can't connect"; - case CANT_RESOLVE: return "Can't resolve"; - case CONNECTION_ERROR: return "Connection error"; - case INVALID_DATA: return "Invalid data"; - case INVALID_PARAMETER: return "Invalid parameter"; - case ALREADY_EXISTS: return "Already exists"; - case DOES_NOT_EXIST: return "Does not exist"; - case BUSY: return "Busy"; - case SKIP: return "Skip"; - case BUG: return "Bug"; - case MAX: return ""; + case FILE_CANT_OPEN: return "Can't open file"; + case FILE_CAN_WRITE: return "Can't write file"; + case FILE_CANT_READ: return "Can't read file"; + case LOCKED: return "Locked"; + case TIMEOUT: return "Timeout"; + case CANT_CONNECT: return "Can't connect"; + case CANT_RESOLVE: return "Can't resolve"; + case CONNECTION_ERROR: return "Connection error"; + case INVALID_DATA: return "Invalid data"; + case INVALID_PARAMETER: return "Invalid parameter"; + case ALREADY_EXISTS: return "Already exists"; + case DOES_NOT_EXIST: return "Does not exist"; + case BUSY: return "Busy"; + case SKIP: return "Skip"; + case BUG: return "Bug"; + case MAX: return ""; } OpenVic::unreachable(); diff --git a/src/openvic-simulation/core/error/ErrorMacros.hpp b/src/openvic-simulation/core/error/ErrorMacros.hpp index 0b1163abf..7d345b208 100644 --- a/src/openvic-simulation/core/error/ErrorMacros.hpp +++ b/src/openvic-simulation/core/error/ErrorMacros.hpp @@ -5,8 +5,8 @@ #include // IWYU pragma: keep -#include "openvic-simulation/core/error/Error.hpp" // IWYU pragma: keep for error #include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep for macros +#include "openvic-simulation/core/error/Error.hpp" // IWYU pragma: keep for error // Based heavily on https://github.com/godotengine/godot/blob/34d06658a85845111a50db9e485ec4a0701d4298/core/error/error_macros.h @@ -46,8 +46,8 @@ #define OV_RETURN_IF_ERROR(m_exp) \ if (::OpenVic::Error _err_propagate_error = (m_exp); OV_unlikely(_err_propagate_error != ::OpenVic::Error::OK)) { \ static_assert( \ - std::same_as, ::OpenVic::Error>, \ - "OV_RETURN_IF_ERROR expects an Error-returning expression" \ + std::same_as, ::OpenVic::Error>, \ + "OV_RETURN_IF_ERROR expects an Error-returning expression" \ ); \ return _err_propagate_error; \ } else \ @@ -79,7 +79,7 @@ #define OV_ERR_FAIL_INDEX_MSG(m_index, m_size, m_msg) \ if (OV_unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ ); \ return; \ } else \ @@ -95,8 +95,12 @@ #define OV_ERR_FAIL_INDEX_V(m_index, m_size, m_retval) \ if (OV_unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "Index {} = {} is out of bounds ({} = {}). Returning: {}", _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size), \ - _OV_STR(m_retval) \ + "Index {} = {} is out of bounds ({} = {}). Returning: {}", \ + _OV_STR(m_index), \ + (m_index), \ + _OV_STR(m_size), \ + (m_size), \ + _OV_STR(m_retval) \ ); \ return m_retval; \ } else \ @@ -109,8 +113,13 @@ #define OV_ERR_FAIL_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ if (OV_unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}). Returning: {}", (m_msg), _OV_STR(m_index), (m_index), \ - _OV_STR(m_size), (m_size), _OV_STR(m_retval) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}). Returning: {}", \ + (m_msg), \ + _OV_STR(m_index), \ + (m_index), \ + _OV_STR(m_size), \ + (m_size), \ + _OV_STR(m_retval) \ ); \ return m_retval; \ } else \ @@ -142,7 +151,7 @@ #define OV_CRASH_BAD_INDEX_MSG(m_index, m_size, m_msg) \ if (OV_unlikely((m_index) < 0 || (m_index) >= (m_size))) { \ SPDLOG_CRITICAL( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ ); \ spdlog::shutdown(); \ OV_GENERATE_TRAP(); \ @@ -172,7 +181,7 @@ #define OV_ERR_FAIL_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ if (OV_unlikely((m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ ); \ return; \ } else \ @@ -188,8 +197,12 @@ #define OV_ERR_FAIL_UNSIGNED_INDEX_V(m_index, m_size, m_retval) \ if (OV_unlikely((m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "Index {} = {} is out of bounds ({} = {}). Returning: {}", _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size), \ - _OV_STR(m_retval) \ + "Index {} = {} is out of bounds ({} = {}). Returning: {}", \ + _OV_STR(m_index), \ + (m_index), \ + _OV_STR(m_size), \ + (m_size), \ + _OV_STR(m_retval) \ ); \ return m_retval; \ } else \ @@ -202,8 +215,13 @@ #define OV_ERR_FAIL_UNSIGNED_INDEX_V_MSG(m_index, m_size, m_retval, m_msg) \ if (OV_unlikely((m_index) >= (m_size))) { \ SPDLOG_ERROR( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}). Returning: {}", (m_msg), _OV_STR(m_index), (m_index), \ - _OV_STR(m_size), (m_size), _OV_STR(m_retval) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}). Returning: {}", \ + (m_msg), \ + _OV_STR(m_index), \ + (m_index), \ + _OV_STR(m_size), \ + (m_size), \ + _OV_STR(m_retval) \ ); \ return m_retval; \ } else \ @@ -235,7 +253,7 @@ #define OV_CRASH_BAD_UNSIGNED_INDEX_MSG(m_index, m_size, m_msg) \ if (OV_unlikely((m_index) >= (m_size))) { \ SPDLOG_CRITICAL( \ - "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ + "{}\n\tIndex {} = {} is out of bounds ({} = {}).", (m_msg), _OV_STR(m_index), (m_index), _OV_STR(m_size), (m_size) \ ); \ spdlog::shutdown(); \ OV_GENERATE_TRAP(); \ diff --git a/src/openvic-simulation/core/error/ErrorSet.hpp b/src/openvic-simulation/core/error/ErrorSet.hpp index 8fb2d66af..6083a2961 100644 --- a/src/openvic-simulation/core/error/ErrorSet.hpp +++ b/src/openvic-simulation/core/error/ErrorSet.hpp @@ -99,7 +99,7 @@ namespace OpenVic { memory::string to_bitset_string(memory::string::value_type zero = '0', memory::string::value_type one = '1') const { return bitset::to_string( - zero, one + zero, one ); } diff --git a/src/openvic-simulation/core/io/BMP.cpp b/src/openvic-simulation/core/io/BMP.cpp index 54aa19c94..76ac23d20 100644 --- a/src/openvic-simulation/core/io/BMP.cpp +++ b/src/openvic-simulation/core/io/BMP.cpp @@ -72,8 +72,11 @@ bool BMP::read_header() { // Validate sizes and dimensions if (header.image_size_bytes > 0 && header.file_size != header.offset + header.image_size_bytes) { spdlog::error_s( - "Invalid BMP memory sizes: file size = {} != {} = {} + {} = image data offset + image data size", header.file_size, - header.offset + header.image_size_bytes, header.offset, header.image_size_bytes + "Invalid BMP memory sizes: file size = {} != {} = {} + {} = image data offset + image data size", + header.file_size, + header.offset + header.image_size_bytes, + header.offset, + header.image_size_bytes ); header_validated = false; } @@ -103,8 +106,10 @@ bool BMP::read_header() { static constexpr uint16_t PALETTE_BITS_PER_PIXEL_LIMIT = 8; if (header.num_colours != 0 && header.bits_per_pixel > PALETTE_BITS_PER_PIXEL_LIMIT) { spdlog::error_s( - "Invalid BMP palette size: {} (should be 0 as bits per pixel is {} > {})", header.num_colours, - header.bits_per_pixel, PALETTE_BITS_PER_PIXEL_LIMIT + "Invalid BMP palette size: {} (should be 0 as bits per pixel is {} > {})", + header.num_colours, + header.bits_per_pixel, + PALETTE_BITS_PER_PIXEL_LIMIT ); header_validated = false; } diff --git a/src/openvic-simulation/core/io/BMP.hpp b/src/openvic-simulation/core/io/BMP.hpp index 2b60c21c8..ecbc579da 100644 --- a/src/openvic-simulation/core/io/BMP.hpp +++ b/src/openvic-simulation/core/io/BMP.hpp @@ -4,8 +4,8 @@ #include #include -#include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/memory/Vector.hpp" namespace OpenVic { namespace fs = std::filesystem; diff --git a/src/openvic-simulation/core/memory/Colony.hpp b/src/openvic-simulation/core/memory/Colony.hpp index 4c43400ae..d0481a232 100644 --- a/src/openvic-simulation/core/memory/Colony.hpp +++ b/src/openvic-simulation/core/memory/Colony.hpp @@ -10,4 +10,4 @@ namespace OpenVic::memory { template using colony = plf::colony>>; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/Deque.hpp b/src/openvic-simulation/core/memory/Deque.hpp index 106b25cde..f3c5285a4 100644 --- a/src/openvic-simulation/core/memory/Deque.hpp +++ b/src/openvic-simulation/core/memory/Deque.hpp @@ -10,20 +10,11 @@ namespace OpenVic::memory { template - FOONATHAN_ALIAS_TEMPLATE( - deque, - OpenVic::utility::deque< - T, - foonathan::memory::std_allocator> - > - ); + FOONATHAN_ALIAS_TEMPLATE(deque, OpenVic::utility::deque>>); template FOONATHAN_ALIAS_TEMPLATE( - deque_scoped_alloc, - OpenVic::utility::deque< - T, - std::scoped_allocator_adaptor>> - > + deque_scoped_alloc, + OpenVic::utility::deque>>> ); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/Formatting.hpp b/src/openvic-simulation/core/memory/Formatting.hpp index 2e229ee18..5ebe280e1 100644 --- a/src/openvic-simulation/core/memory/Formatting.hpp +++ b/src/openvic-simulation/core/memory/Formatting.hpp @@ -14,13 +14,9 @@ namespace OpenVic::memory { namespace fmt { template using basic_memory_buffer = ::fmt::basic_memory_buffer< - T, - ::fmt::inline_buffer_size, - foonathan::memory::std_allocator< - T, - OpenVic::memory::tracker - > - >; + T, + ::fmt::inline_buffer_size, + foonathan::memory::std_allocator>>; inline static memory::string vformat(::fmt::string_view fmt, ::fmt::format_args args) { memory::fmt::basic_memory_buffer buf {}; diff --git a/src/openvic-simulation/core/memory/MemoryTracker.hpp b/src/openvic-simulation/core/memory/MemoryTracker.hpp index b96942e75..b970825dd 100644 --- a/src/openvic-simulation/core/memory/MemoryTracker.hpp +++ b/src/openvic-simulation/core/memory/MemoryTracker.hpp @@ -53,9 +53,9 @@ namespace OpenVic::memory { template using tracker = #ifdef DEBUG_ENABLED - foonathan::memory::tracked_allocator + foonathan::memory::tracked_allocator #else - RawAllocator + RawAllocator #endif - ; + ; } diff --git a/src/openvic-simulation/core/memory/Queue.hpp b/src/openvic-simulation/core/memory/Queue.hpp index a75272c24..bd88965a9 100644 --- a/src/openvic-simulation/core/memory/Queue.hpp +++ b/src/openvic-simulation/core/memory/Queue.hpp @@ -7,4 +7,4 @@ namespace OpenVic::memory { template> using queue = std::queue; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/SmartPtr.hpp b/src/openvic-simulation/core/memory/SmartPtr.hpp index 6605e883f..b808d14cf 100644 --- a/src/openvic-simulation/core/memory/SmartPtr.hpp +++ b/src/openvic-simulation/core/memory/SmartPtr.hpp @@ -7,8 +7,8 @@ #include #include -#include "openvic-simulation/core/memory/make_tracked_allocator.hpp" #include "openvic-simulation/core/memory/MemoryTracker.hpp" +#include "openvic-simulation/core/memory/make_tracked_allocator.hpp" namespace OpenVic::memory { template @@ -35,7 +35,7 @@ namespace OpenVic::memory { requires(!std::is_array_v) unique_ptr> allocate_unique(RawAllocator&& alloc, Args&&... args) { return foonathan::memory::allocate_unique( - OpenVic::memory::make_tracked_allocator(std::forward(alloc)), std::forward(args)... + OpenVic::memory::make_tracked_allocator(std::forward(alloc)), std::forward(args)... ); } @@ -43,19 +43,21 @@ namespace OpenVic::memory { requires(std::is_array_v) unique_ptr> allocate_unique(RawAllocator&& alloc, std::size_t size) { return foonathan::memory::allocate_unique>( - OpenVic::memory::make_tracked_allocator(std::forward(alloc)), size + OpenVic::memory::make_tracked_allocator(std::forward(alloc)), size ); } #else template using unique_ptr = std::conditional_t< - will_optimize_deleter_for::value, std::unique_ptr, - foonathan::memory::unique_ptr>>; + will_optimize_deleter_for::value, + std::unique_ptr, + foonathan::memory::unique_ptr>>; template using unique_base_ptr = std::conditional_t< - will_optimize_deleter_for::value, std::unique_ptr, - foonathan::memory::unique_base_ptr>>; + will_optimize_deleter_for::value, + std::unique_ptr, + foonathan::memory::unique_base_ptr>>; template requires(!std::is_array_v) @@ -64,7 +66,7 @@ namespace OpenVic::memory { return std::make_unique(std::forward(args)...); } else { return foonathan::memory::allocate_unique( - OpenVic::memory::make_tracked_allocator(std::forward(alloc)), std::forward(args)... + OpenVic::memory::make_tracked_allocator(std::forward(alloc)), std::forward(args)... ); } } @@ -76,7 +78,7 @@ namespace OpenVic::memory { return std::make_unique(size); } else { return foonathan::memory::allocate_unique>( - OpenVic::memory::make_tracked_allocator(std::forward(alloc)), size + OpenVic::memory::make_tracked_allocator(std::forward(alloc)), size ); } } @@ -91,10 +93,7 @@ namespace OpenVic::memory { template requires(std::is_unbounded_array_v) static inline unique_ptr make_unique(size_t n) { - return allocate_unique( - OpenVic::memory::make_tracked_allocator(RawAllocator {}), - n - ); + return allocate_unique(OpenVic::memory::make_tracked_allocator(RawAllocator {}), n); } template @@ -126,10 +125,7 @@ namespace OpenVic::memory { template std::shared_ptr allocate_shared(RawAllocator&& alloc, Args&&... args) { return foonathan::memory::allocate_shared( - OpenVic::memory::make_tracked_allocator( - std::forward(alloc) - ), - std::forward(args)... + OpenVic::memory::make_tracked_allocator(std::forward(alloc)), std::forward(args)... ); } diff --git a/src/openvic-simulation/core/memory/Stack.hpp b/src/openvic-simulation/core/memory/Stack.hpp index 2411b7094..1bc458d20 100644 --- a/src/openvic-simulation/core/memory/Stack.hpp +++ b/src/openvic-simulation/core/memory/Stack.hpp @@ -7,4 +7,4 @@ namespace OpenVic::memory { template> using stack = std::stack; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/String.hpp b/src/openvic-simulation/core/memory/String.hpp index d53ecb205..3235fa142 100644 --- a/src/openvic-simulation/core/memory/String.hpp +++ b/src/openvic-simulation/core/memory/String.hpp @@ -9,11 +9,8 @@ namespace OpenVic::memory { template - using basic_string = std::basic_string< - CharT, - std::char_traits, - foonathan::memory::std_allocator> - >; + using basic_string = + std::basic_string, foonathan::memory::std_allocator>>; template using string_alloc = basic_string; @@ -24,4 +21,4 @@ namespace OpenVic::memory { using wstring_alloc = basic_string; using wstring = wstring_alloc<>; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/StringStream.hpp b/src/openvic-simulation/core/memory/StringStream.hpp index cec91ec8a..de48d04f9 100644 --- a/src/openvic-simulation/core/memory/StringStream.hpp +++ b/src/openvic-simulation/core/memory/StringStream.hpp @@ -9,12 +9,12 @@ #include "openvic-simulation/core/memory/MemoryTracker.hpp" namespace OpenVic::memory { - template, class RawAllocator = foonathan::memory::default_allocator> - using basic_stringstream = std::basic_stringstream< - CharT, - CharTraits, - foonathan::memory::std_allocator> - >; + template< + typename CharT, + typename CharTraits = std::char_traits, + class RawAllocator = foonathan::memory::default_allocator> + using basic_stringstream = + std::basic_stringstream>>; template using stringstream_alloc = basic_stringstream, RawAllocator>; diff --git a/src/openvic-simulation/core/memory/Vector.hpp b/src/openvic-simulation/core/memory/Vector.hpp index cbf9cdaf2..02674c361 100644 --- a/src/openvic-simulation/core/memory/Vector.hpp +++ b/src/openvic-simulation/core/memory/Vector.hpp @@ -8,4 +8,4 @@ namespace OpenVic::memory { template using vector = foonathan::memory::vector>; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/allocators/AllocatorReference.hpp b/src/openvic-simulation/core/memory/allocators/AllocatorReference.hpp index 59481f8a7..e6ab4f6b4 100644 --- a/src/openvic-simulation/core/memory/allocators/AllocatorReference.hpp +++ b/src/openvic-simulation/core/memory/allocators/AllocatorReference.hpp @@ -5,4 +5,4 @@ namespace OpenVic::memory { template using allocator_reference = foonathan::memory::allocator_reference; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/allocators/Deleter.hpp b/src/openvic-simulation/core/memory/allocators/Deleter.hpp index 3418aa952..a7bae4919 100644 --- a/src/openvic-simulation/core/memory/allocators/Deleter.hpp +++ b/src/openvic-simulation/core/memory/allocators/Deleter.hpp @@ -9,7 +9,7 @@ namespace OpenVic::memory { template using allocator_deleter = foonathan::memory::allocator_deleter; - + template requires(!std::is_array_v) static inline void dealloc_delete(RawAllocator&& alloc, T* ptr) { @@ -37,4 +37,4 @@ namespace OpenVic::memory { static inline void delete_at(T* ptr, size_t n) { dealloc_delete(OpenVic::memory::make_tracked_allocator(RawAllocator {}), ptr, n); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/allocators/NewAllocator.hpp b/src/openvic-simulation/core/memory/allocators/NewAllocator.hpp index 7e0f7e3ad..32f6eacd5 100644 --- a/src/openvic-simulation/core/memory/allocators/NewAllocator.hpp +++ b/src/openvic-simulation/core/memory/allocators/NewAllocator.hpp @@ -35,4 +35,4 @@ namespace OpenVic::memory { static inline T* make_new(size_t n) { return allocate_new(OpenVic::memory::make_tracked_allocator(RawAllocator {}), n); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/memory/make_tracked_allocator.hpp b/src/openvic-simulation/core/memory/make_tracked_allocator.hpp index 03dc3b0ef..0d9f2e844 100644 --- a/src/openvic-simulation/core/memory/make_tracked_allocator.hpp +++ b/src/openvic-simulation/core/memory/make_tracked_allocator.hpp @@ -6,16 +6,13 @@ namespace OpenVic::memory { template - tracker make_tracked_allocator( - RawAllocator&& alloc - ) { + tracker make_tracked_allocator(RawAllocator&& alloc) { #ifdef DEBUG_ENABLED return foonathan::memory::make_tracked_allocator( - typename tracker::tracker {}, - std::forward(alloc) + typename tracker::tracker {}, std::forward(alloc) ); #else return std::forward(alloc); #endif } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/object/Colour.hpp b/src/openvic-simulation/core/object/Colour.hpp index 4e98f2fef..8be725f2a 100644 --- a/src/openvic-simulation/core/object/Colour.hpp +++ b/src/openvic-simulation/core/object/Colour.hpp @@ -20,10 +20,10 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/stl/containers/StackString.hpp" #include "openvic-simulation/core/string/CharConv.hpp" #include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/Typedefs.hpp" namespace OpenVic { template @@ -52,10 +52,14 @@ namespace OpenVic { OV_SPEED_INLINE static constexpr integer_type make_rgb_integer(value_type red, value_type green, value_type blue) { return (red << red_shift) | (green << green_shift) | (blue << blue_shift); } - OV_SPEED_INLINE static constexpr integer_type make_rgba_integer(value_type red, value_type green, value_type blue, value_type alpha) { + OV_SPEED_INLINE static constexpr integer_type make_rgba_integer( + value_type red, value_type green, value_type blue, value_type alpha + ) { return (make_rgb_integer(red, green, blue) << component_bit_size) | (alpha << rgba_alpha_shift); } - OV_SPEED_INLINE static constexpr integer_type make_argb_integer(value_type red, value_type green, value_type blue, value_type alpha) { + OV_SPEED_INLINE static constexpr integer_type make_argb_integer( + value_type red, value_type green, value_type blue, value_type alpha + ) { return make_rgb_integer(red, green, blue) | static_cast(alpha << argb_alpha_shift); } @@ -188,39 +192,34 @@ namespace OpenVic { } } - OV_SPEED_INLINE static constexpr basic_colour_t from_argb(integer_type integer) - { + OV_SPEED_INLINE static constexpr basic_colour_t from_argb(integer_type integer) { if constexpr (colour_traits::has_alpha) { - return { - colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), - colour_traits::blue_from_argb(integer), colour_traits::alpha_from_argb(integer) - }; + return { colour_traits::red_from_argb(integer), + colour_traits::green_from_argb(integer), + colour_traits::blue_from_argb(integer), + colour_traits::alpha_from_argb(integer) }; } else { return from_rgb(integer); } } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgba(integer_type integer) - { + OV_SPEED_INLINE static constexpr basic_colour_t from_rgba(integer_type integer) { if constexpr (colour_traits::has_alpha) { - return { - colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), - colour_traits::blue_from_rgb(integer), colour_traits::alpha_from_rgba(integer) - }; + return { colour_traits::red_from_rgb(integer), + colour_traits::green_from_rgb(integer), + colour_traits::blue_from_rgb(integer), + colour_traits::alpha_from_rgba(integer) }; } else { - return { - colour_traits::red_from_rgb(integer), colour_traits::green_from_rgb(integer), - colour_traits::blue_from_rgb(integer) - }; + return { colour_traits::red_from_rgb(integer), + colour_traits::green_from_rgb(integer), + colour_traits::blue_from_rgb(integer) }; } } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgb(integer_type integer) - { - return { - colour_traits::red_from_argb(integer), colour_traits::green_from_argb(integer), - colour_traits::blue_from_argb(integer) - }; + OV_SPEED_INLINE static constexpr basic_colour_t from_rgb(integer_type integer) { + return { colour_traits::red_from_argb(integer), + colour_traits::green_from_argb(integer), + colour_traits::blue_from_argb(integer) }; } OV_SPEED_INLINE static constexpr basic_colour_t from_floats( // @@ -228,10 +227,10 @@ namespace OpenVic { ) requires(colour_traits::has_alpha) { - return { - colour_traits::red_from_float(r), colour_traits::green_from_float(g), colour_traits::blue_from_float(b), - colour_traits::alpha_from_float(a) - }; + return { colour_traits::red_from_float(r), + colour_traits::green_from_float(g), + colour_traits::blue_from_float(b), + colour_traits::alpha_from_float(a) }; } OV_SPEED_INLINE static constexpr basic_colour_t from_floats(float r, float g, float b) @@ -263,7 +262,9 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t from_string( + std::string_view str, std::from_chars_result* from_chars = nullptr + ) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars(str.data(), str.data() + str.size()); @@ -283,7 +284,9 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgba_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t from_rgba_string( + std::string_view str, std::from_chars_result* from_chars = nullptr + ) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_rgba(str.data(), str.data() + str.size()); @@ -303,7 +306,9 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_argb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t from_argb_string( + std::string_view str, std::from_chars_result* from_chars = nullptr + ) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_argb(str.data(), str.data() + str.size()); @@ -323,7 +328,9 @@ namespace OpenVic { return result; } - OV_SPEED_INLINE static constexpr basic_colour_t from_rgb_string(std::string_view str, std::from_chars_result* from_chars = nullptr) { + OV_SPEED_INLINE static constexpr basic_colour_t from_rgb_string( + std::string_view str, std::from_chars_result* from_chars = nullptr + ) { basic_colour_t result {}; if (from_chars == nullptr) { result.from_chars_rgb(str.data(), str.data() + str.size()); @@ -350,40 +357,40 @@ namespace OpenVic { OV_SPEED_INLINE constexpr basic_colour_t(value_type r, value_type g, value_type b, value_type a = max_value) requires(colour_traits::has_alpha) - : red(r), green(g), blue(b), alpha(a) {} + : red(r), green(g), blue(b), alpha(a) {} OV_SPEED_INLINE constexpr basic_colour_t(value_type r, value_type g, value_type b) requires(!colour_traits::has_alpha) - : red(r), green(g), blue(b) {} + : red(r), green(g), blue(b) {} template requires( - _ColourTraits::has_alpha && std::same_as && - std::same_as + _ColourTraits::has_alpha && std::same_as && + std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t(basic_colour_t const& colour) requires(colour_traits::has_alpha) - : basic_colour_t { colour.red, colour.green, colour.blue, colour.alpha } {} + : basic_colour_t { colour.red, colour.green, colour.blue, colour.alpha } {} template requires( - !_ColourTraits::has_alpha && std::same_as && - std::same_as + !_ColourTraits::has_alpha && std::same_as && + std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t( - basic_colour_t const& colour, value_type a = max_value + basic_colour_t const& colour, value_type a = max_value ) requires(colour_traits::has_alpha) - : basic_colour_t { colour.red, colour.green, colour.blue, a } {} + : basic_colour_t { colour.red, colour.green, colour.blue, a } {} template requires( - std::same_as && - std::same_as + std::same_as && + std::same_as ) OV_SPEED_INLINE explicit constexpr basic_colour_t(basic_colour_t const& colour) requires(!colour_traits::has_alpha) - : basic_colour_t { colour.red, colour.green, colour.blue } {} + : basic_colour_t { colour.red, colour.green, colour.blue } {} OV_SPEED_INLINE constexpr explicit operator integer_type() const { if constexpr (colour_traits::has_alpha) { @@ -439,7 +446,9 @@ namespace OpenVic { return colour_traits::alpha_to_float(alpha); } - OV_SPEED_INLINE constexpr std::to_chars_result to_hex_chars(char* first, char* last, bool alpha = colour_traits::has_alpha) const { + OV_SPEED_INLINE constexpr std::to_chars_result to_hex_chars( + char* first, char* last, bool alpha = colour_traits::has_alpha + ) const { constexpr size_t component_str_width = (std::bit_width(max_value) + 3) / 4; std::to_chars_result result = OpenVic::to_chars(first, last, alpha ? as_rgba() : as_rgb(), 16); @@ -562,7 +571,9 @@ namespace OpenVic { return new_colour; } - OV_SPEED_INLINE constexpr basic_colour_t full_invert() const requires(colour_traits::has_alpha) { + OV_SPEED_INLINE constexpr basic_colour_t full_invert() const + requires(colour_traits::has_alpha) + { basic_colour_t new_colour = *this; new_colour.red = max_value - new_colour.red; new_colour.green = max_value - new_colour.green; @@ -585,7 +596,7 @@ namespace OpenVic { constexpr double BLUE_MULTIPLIER = 0.0721750; double luminance = std::pow(red / max_value, POWER) * RED_MULTIPLIER + - std::pow(green / max_value, POWER) * GREEN_MULTIPLIER + std::pow(blue, POWER) * BLUE_MULTIPLIER; + std::pow(green / max_value, POWER) * GREEN_MULTIPLIER + std::pow(blue, POWER) * BLUE_MULTIPLIER; return luminance >= LUMINANCE_FLIP ? basic_colour_t::from_floats(0, 0, 0) : basic_colour_t::from_floats(1, 1, 1); } @@ -815,8 +826,8 @@ struct fmt::formatter { ctx.advance_to(it); switch (_value_format_type) { - case value_format_type::none: _value_format_type = value_format_type::value; [[fallthrough]]; - case value_format_type::value: return _colour_value.parse(ctx); + case value_format_type::none: _value_format_type = value_format_type::value; [[fallthrough]]; + case value_format_type::value: return _colour_value.parse(ctx); case value_format_type::integer: return _integer.parse(ctx); case value_format_type::floating: return _floating.parse(ctx); } @@ -842,9 +853,9 @@ struct fmt::formatter { switch (_alpha_handle_type) { default: case alpha_handle_type::follow_type: return colour.to_hex_array(); - case alpha_handle_type::no_alpha: return colour.to_hex_array(false); - case alpha_handle_type::argb: return colour.to_argb_hex_array(); - case alpha_handle_type::rgba: return colour.to_hex_array(true); + case alpha_handle_type::no_alpha: return colour.to_hex_array(false); + case alpha_handle_type::argb: return colour.to_argb_hex_array(); + case alpha_handle_type::rgba: return colour.to_hex_array(true); } }(); @@ -884,8 +895,8 @@ struct fmt::formatter { auto write_value = [&](T::value_type const& comp) { ctx.advance_to(out); switch (_value_format_type) { - case value_format_type::none: break; - case value_format_type::value: _colour_value.format(comp, ctx); break; + case value_format_type::none: break; + case value_format_type::value: _colour_value.format(comp, ctx); break; case value_format_type::integer: _integer.format(comp, ctx); break; case value_format_type::floating: _floating.format(double(comp) / T::max_value, ctx); break; } @@ -900,7 +911,7 @@ struct fmt::formatter { out = detail::copy(_separator, out); break; case alpha_handle_type::no_alpha: --size; break; - default: break; + default: break; } } else if (_alpha_handle_type == alpha_handle_type::argb) { write_value(T::max_value); @@ -929,8 +940,18 @@ struct fmt::formatter { fmt::formatter _integer; fmt::formatter _floating; - enum value_format_type { none, value, integer, floating } _value_format_type = value_format_type::none; - enum alpha_handle_type { follow_type, no_alpha, argb, rgba } _alpha_handle_type = alpha_handle_type::follow_type; + enum value_format_type { + none, + value, + integer, + floating + } _value_format_type = value_format_type::none; + enum alpha_handle_type { + follow_type, + no_alpha, + argb, + rgba + } _alpha_handle_type = alpha_handle_type::follow_type; basic_string_view _separator = detail::string_literal {}; basic_string_view _opening_bracket = detail::string_literal {}; @@ -940,7 +961,7 @@ struct fmt::formatter { namespace std { template struct tuple_size<::OpenVic::basic_colour_t> - : integral_constant::size()> {}; + : integral_constant::size()> {}; template struct tuple_element> { diff --git a/src/openvic-simulation/core/object/Date.cpp b/src/openvic-simulation/core/object/Date.cpp index 26a67da59..d08819d08 100644 --- a/src/openvic-simulation/core/object/Date.cpp +++ b/src/openvic-simulation/core/object/Date.cpp @@ -12,8 +12,8 @@ #include -#include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/memory/String.hpp" using namespace OpenVic; @@ -176,11 +176,11 @@ struct date_writer { void on_loc_date(numeric_system ns) { char buf[8]; write_digit2_separated( - buf, // - detail::to_unsigned(_date.get_day()), // - detail::to_unsigned(_date.get_month()), // - detail::to_unsigned(split_year_lower(_date.get_year())), // - '/' + buf, + detail::to_unsigned(_date.get_day()), + detail::to_unsigned(_date.get_month()), + detail::to_unsigned(split_year_lower(_date.get_year())), + '/' ); _out = detail::copy(std::begin(buf), std::end(buf), _out); } @@ -188,11 +188,11 @@ struct date_writer { void on_us_date() { char buf[8]; write_digit2_separated( - buf, // - detail::to_unsigned(_date.get_month()), // - detail::to_unsigned(_date.get_day()), // - detail::to_unsigned(split_year_lower(_date.get_year())), // - '/' + buf, + detail::to_unsigned(_date.get_month()), + detail::to_unsigned(_date.get_day()), + detail::to_unsigned(split_year_lower(_date.get_year())), + '/' ); _out = detail::copy(std::begin(buf), std::end(buf), _out); } @@ -209,11 +209,11 @@ struct date_writer { year = 0; } write_digit2_separated( - buf + 2, // - static_cast(year % 100), // - detail::to_unsigned(_date.get_month()), // - detail::to_unsigned(_date.get_day()), // - '-' + buf + 2, + static_cast(year % 100), + detail::to_unsigned(_date.get_month()), + detail::to_unsigned(_date.get_day()), + '-' ); _out = detail::copy(std::begin(buf) + offset, std::end(buf), _out); } diff --git a/src/openvic-simulation/core/object/Date.hpp b/src/openvic-simulation/core/object/Date.hpp index a96bdc62f..9cf09381c 100644 --- a/src/openvic-simulation/core/object/Date.hpp +++ b/src/openvic-simulation/core/object/Date.hpp @@ -14,14 +14,14 @@ #include -#include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/Hash.hpp" +#include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/memory/Formatting.hpp" #include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/object/Timespan.hpp" #include "openvic-simulation/core/stl/containers/StackString.hpp" #include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -58,18 +58,24 @@ namespace OpenVic { static constexpr char SEPARATOR_CHARACTER = '.'; static constexpr std::array MONTH_NAMES { - "January", "February", "March", "April", "May", "June", // - "July", "August", "September", "October", "November", "December" // + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" }; static constexpr std::string_view INVALID_MONTH_NAME = "Invalid Month"; static constexpr std::array WEEKDAY_NAMES = std::to_array({ - "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" // + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", }); static constexpr day_t INITIAL_WEEKDAY_NAME = 2; // Jan 1st, 0 Tuesday, makes Jan 1st, 1836 Friday static_assert( - INITIAL_WEEKDAY_NAME < WEEKDAY_NAMES.size(), "INITIAL_WEEKDAY_NAME must be less than WEEKDAY_NAMES.size()" + INITIAL_WEEKDAY_NAME < WEEKDAY_NAMES.size(), "INITIAL_WEEKDAY_NAME must be less than WEEKDAY_NAMES.size()" ); public: @@ -77,8 +83,8 @@ namespace OpenVic { // Negative Timespans indicate dates before Jan 1st, Year 0. OV_ALWAYS_INLINE constexpr Date(Timespan new_timespan) : timespan { new_timespan } {} // Year month day specification - OV_ALWAYS_INLINE constexpr Date(year_t year = 0, month_t month = 1, day_t day = 1) - : timespan { _date_to_timespan(year, month, day) } {} + OV_ALWAYS_INLINE constexpr Date(year_t year = 0, month_t month = 1, day_t day = 1) : + timespan { _date_to_timespan(year, month, day) } {} OV_SPEED_INLINE constexpr Timespan::value_t get_day_of_year() const { Timespan::value_t day_in_year = static_cast(timespan) % DAYS_IN_YEAR; @@ -90,8 +96,8 @@ namespace OpenVic { OV_SPEED_INLINE constexpr year_t get_year() const { return (timespan >= 0 ? static_cast(timespan) - : static_cast(timespan) - DAYS_IN_YEAR + 1) / - DAYS_IN_YEAR; + : static_cast(timespan) - DAYS_IN_YEAR + 1) / + DAYS_IN_YEAR; } OV_SPEED_INLINE constexpr month_t get_month() const { return MONTH_FROM_DAY_IN_YEAR[get_day_of_year()]; @@ -245,13 +251,14 @@ namespace OpenVic { struct stack_string; OV_SPEED_INLINE constexpr stack_string to_array( - bool pad_year = false, bool pad_month = true, bool pad_day = true // + bool pad_year = false, bool pad_month = true, bool pad_day = true ) const; - struct stack_string final : StackString< - fmt::detail::count_digits(uint64_t(std::numeric_limits::max())) + - fmt::detail::count_digits(uint64_t(MONTHS_IN_YEAR)) + - fmt::detail::count_digits(uint64_t(MAX_DAYS_IN_MONTH)) + 4> { + struct stack_string final + : StackString< + fmt::detail::count_digits(uint64_t(std::numeric_limits::max())) + + fmt::detail::count_digits(uint64_t(MONTHS_IN_YEAR)) + fmt::detail::count_digits(uint64_t(MAX_DAYS_IN_MONTH)) + + 4> { protected: using StackString::StackString; friend OV_SPEED_INLINE constexpr stack_string Date::to_array(bool pad_year, bool pad_month, bool pad_day) const; @@ -260,7 +267,11 @@ namespace OpenVic { memory::string to_string(bool pad_year = false, bool pad_month = true, bool pad_day = true) const; explicit operator memory::string() const; - enum class errc_type : uint8_t { day, month, year }; + enum class errc_type : uint8_t { + day, + month, + year + }; struct from_chars_result : std::from_chars_result { const char* type_first = nullptr; errc_type type; @@ -268,34 +279,34 @@ namespace OpenVic { private: /* - type is set to errc_type::year - type_first is set to first - May return std::from_chars errors for year, year remains unchanged - If year < 0, ec == not_supported and ptr == first, year remains unchanged - If year > 32767 or year < -32768, ec == value_too_large and ptr == first, year remains unchanged - If string only includes a valid year value, - ec == result_out_of_range and ptr == first, only year is changed - If string doesn't contain a separator, - ec == invalid_argument and ptr == expected year/month separator position, only year is changed - - type is set to errc_type::month - type_first is set to month's first - May return std::from_chars errors for month, month remains unchanged - If month == 0, ec == not_supported and ptr == month's first, only year is changed - If month > 12, ec == value_too_large and ptr == month's first, only year is changed - If string only includes a valid year and month value, - ec == result_out_of_range and ptr == month's first, only year and month are changed - If string doesn't contain a separator, - ec == invalid_argument and ptr == expected month/day separator position, only year and month are changed - - type is set to errc_type::day - type_first is set to day's first - May return std::from_chars errors for day, day remains unchanged - If day == 0, ec == not_supported and ptr == day's first, only year and month are changed - If day > days in month, ec == value_too_large and ptr == month's first, only year month are changed + type is set to errc_type::year + type_first is set to first + May return std::from_chars errors for year, year remains unchanged + If year < 0, ec == not_supported and ptr == first, year remains unchanged + If year > 32767 or year < -32768, ec == value_too_large and ptr == first, year remains unchanged + If string only includes a valid year value, + ec == result_out_of_range and ptr == first, only year is changed + If string doesn't contain a separator, + ec == invalid_argument and ptr == expected year/month separator position, only year is changed + + type is set to errc_type::month + type_first is set to month's first + May return std::from_chars errors for month, month remains unchanged + If month == 0, ec == not_supported and ptr == month's first, only year is changed + If month > 12, ec == value_too_large and ptr == month's first, only year is changed + If string only includes a valid year and month value, + ec == result_out_of_range and ptr == month's first, only year and month are changed + If string doesn't contain a separator, + ec == invalid_argument and ptr == expected month/day separator position, only year and month are changed + + type is set to errc_type::day + type_first is set to day's first + May return std::from_chars errors for day, day remains unchanged + If day == 0, ec == not_supported and ptr == day's first, only year and month are changed + If day > days in month, ec == value_too_large and ptr == month's first, only year month are changed */ - OV_SPEED_INLINE static constexpr from_chars_result parse_from_chars( // - const char* first, const char* last, year_t& year, month_t& month, day_t& day + OV_SPEED_INLINE static constexpr from_chars_result parse_from_chars( + const char* first, const char* last, year_t& year, month_t& month, day_t& day ) { int32_t year_check = year; from_chars_result result = { OpenVic::from_chars(first, last, year_check) }; @@ -306,8 +317,8 @@ namespace OpenVic { } if (OV_unlikely( - year_check > std::numeric_limits::max() || year_check < std::numeric_limits::min() - )) { + year_check > std::numeric_limits::max() || year_check < std::numeric_limits::min() + )) { result.ec = std::errc::value_too_large; result.ptr = first; return result; @@ -413,61 +424,71 @@ namespace OpenVic { Date date = from_string(str, from_chars); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && - from_chars->ptr == from_chars->type_first, - date, "Could not parse year value." + from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && + from_chars->ptr == from_chars->type_first, + date, + "Could not parse year value." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::year, date, - "Year value was too large or too small." + from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::year, + date, + "Year value was too large or too small." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::result_out_of_range && from_chars->type == errc_type::year, date, - "Only year value could be found." + from_chars->ec == std::errc::result_out_of_range && from_chars->type == errc_type::year, + date, + "Only year value could be found." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && - from_chars->ptr != from_chars->type_first, - date, memory::fmt::format("Year value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) + from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::year && + from_chars->ptr != from_chars->type_first, + date, + memory::fmt::format("Year value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && - from_chars->ptr == from_chars->type_first, - date, "Could not parse month value." + from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && + from_chars->ptr == from_chars->type_first, + date, + "Could not parse month value." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::not_supported && from_chars->type == errc_type::month, date, - "Month value cannot be 0." + from_chars->ec == std::errc::not_supported && from_chars->type == errc_type::month, + date, + "Month value cannot be 0." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::month && - from_chars->ptr == from_chars->type_first, - date, memory::fmt::format("Month value cannot be larger than {}.", MONTHS_IN_YEAR) + from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::month && + from_chars->ptr == from_chars->type_first, + date, + memory::fmt::format("Month value cannot be larger than {}.", MONTHS_IN_YEAR) ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::result_out_of_range && from_chars->type == errc_type::month, date, - "Only year and month value could be found." + from_chars->ec == std::errc::result_out_of_range && from_chars->type == errc_type::month, + date, + "Only year and month value could be found." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && - from_chars->ptr != from_chars->type_first, - date, memory::fmt::format("Month value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) + from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::month && + from_chars->ptr != from_chars->type_first, + date, + memory::fmt::format("Month value was missing a separator (\"{}\").", SEPARATOR_CHARACTER) ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::day && - from_chars->ptr == from_chars->type_first, - date, "Could not parse day value." + from_chars->ec == std::errc::invalid_argument && from_chars->type == errc_type::day && + from_chars->ptr == from_chars->type_first, + date, + "Could not parse day value." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::not_supported && from_chars->type == errc_type::day, date, "Day value cannot be 0." + from_chars->ec == std::errc::not_supported && from_chars->type == errc_type::day, date, "Day value cannot be 0." ); OV_ERR_FAIL_COND_V_MSG( - from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::day && - from_chars->ptr == from_chars->type_first, - date, - memory::fmt::format( - "Day value cannot be larger than {} for {}.", DAYS_IN_MONTH[date.get_month() - 1], date.get_month() - ) + from_chars->ec == std::errc::value_too_large && from_chars->type == errc_type::day && + from_chars->ptr == from_chars->type_first, + date, + memory::fmt::format( + "Day value cannot be larger than {} for {}.", DAYS_IN_MONTH[date.get_month() - 1], date.get_month() + ) ); return date; @@ -505,8 +526,9 @@ namespace OpenVic { OV_SPEED_INLINE constexpr Date::stack_string Date::to_array(bool pad_year, bool pad_month, bool pad_day) const { stack_string str {}; - std::to_chars_result result = - to_chars(str._array.data(), str._array.data() + str._array.size(), pad_year, pad_month, pad_day); + std::to_chars_result result = to_chars( + str._array.data(), str._array.data() + str._array.size(), pad_year, pad_month, pad_day + ); str._string_size = result.ptr - str.data(); return str; } @@ -524,7 +546,10 @@ namespace ovfmt::detail { space, }; - enum class numeric_system { standard, alternative }; + enum class numeric_system { + standard, + alternative + }; template struct null_date_spec_handler { diff --git a/src/openvic-simulation/core/object/FixedPoint.cpp b/src/openvic-simulation/core/object/FixedPoint.cpp index 1020fac97..e126d5de3 100644 --- a/src/openvic-simulation/core/object/FixedPoint.cpp +++ b/src/openvic-simulation/core/object/FixedPoint.cpp @@ -6,8 +6,8 @@ #include #include -#include "openvic-simulation/core/object/FixedPoint/String.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/object/FixedPoint/String.hpp" #include "openvic-simulation/utility/Logger.hpp" /* Base e exponential lookup table */ @@ -21,14 +21,11 @@ static_assert(_detail::LUT::_2_16_EXP_e_DIVISOR == 1 << fixed_point_t::PRECISION static_assert(_detail::LUT::_2_16_EXP_2001_DIVISOR == 1 << fixed_point_t::PRECISION); OV_SPEED_INLINE void fixed_point_t::warn_if_truncated() const { - if (OV_unlikely( - value != 0 - && abs() < fixed_point_t::_1 - )) { + if (OV_unlikely(value != 0 && abs() < fixed_point_t::_1)) { spdlog::warn_s( - "0 < abs(Fixed point) < 1, truncation will result in zero, this may be a bug. raw_value: {} as float: {}", - get_raw_value(), - static_cast(*this) + "0 < abs(Fixed point) < 1, truncation will result in zero, this may be a bug. raw_value: {} as float: {}", + get_raw_value(), + static_cast(*this) ); } } @@ -91,7 +88,7 @@ namespace OpenVic { } template -requires (sizeof(T) >= 4) +requires(sizeof(T) >= 4) static fixed_point_t parse_capped_generic(const T value) { fixed_point_t result; if (value > std::numeric_limits::max()) { @@ -109,8 +106,12 @@ static fixed_point_t parse_capped_generic(const T value) { return result; } -fixed_point_t fixed_point_t::parse_capped(const int64_t value) { return parse_capped_generic(value); } -fixed_point_t fixed_point_t::parse_capped(const uint64_t value) { return parse_capped_generic(value); } +fixed_point_t fixed_point_t::parse_capped(const int64_t value) { + return parse_capped_generic(value); +} +fixed_point_t fixed_point_t::parse_capped(const uint64_t value) { + return parse_capped_generic(value); +} template EXP_LUT> OV_SPEED_INLINE static constexpr fixed_point_t _exp_internal(fixed_point_t const& x) { diff --git a/src/openvic-simulation/core/object/FixedPoint.hpp b/src/openvic-simulation/core/object/FixedPoint.hpp index ccb6461d4..1c550319a 100644 --- a/src/openvic-simulation/core/object/FixedPoint.hpp +++ b/src/openvic-simulation/core/object/FixedPoint.hpp @@ -13,7 +13,10 @@ #include "openvic-simulation/core/Typedefs.hpp" namespace OpenVic { - enum class midpoint_rounding { AWAY_ZERO, TO_ZERO }; + enum class midpoint_rounding { + AWAY_ZERO, + TO_ZERO + }; template concept integral_max_size_4 = std::integral && sizeof(T) <= 4; @@ -144,7 +147,7 @@ namespace OpenVic { template OV_SPEED_INLINE constexpr T unsafe_truncate() const { - if constexpr(std::unsigned_integral) { + if constexpr (std::unsigned_integral) { assert(OV_likely(!is_negative())); } return value >> PRECISION; @@ -154,11 +157,11 @@ namespace OpenVic { template OV_SPEED_INLINE explicit constexpr operator T() const { - #ifdef DEV_ENABLED +#ifdef DEV_ENABLED if (!std::is_constant_evaluated()) { warn_if_truncated(); } - #endif +#endif return unsafe_truncate(); } @@ -263,21 +266,23 @@ namespace OpenVic { return fixed_point_t { raw_value, value }; } - OV_SPEED_INLINE static constexpr fixed_point_t parse_capped(const int32_t value) { return fixed_point_t(value); } + OV_SPEED_INLINE static constexpr fixed_point_t parse_capped(const int32_t value) { + return fixed_point_t(value); + } template - requires (sizeof(T) < 4) - OV_SPEED_INLINE static constexpr fixed_point_t parse_capped(const T value) { return fixed_point_t(static_cast(value)); } + requires(sizeof(T) < 4) + OV_SPEED_INLINE static constexpr fixed_point_t parse_capped(const T value) { + return fixed_point_t(static_cast(value)); + } static fixed_point_t parse_capped(const int64_t value); static fixed_point_t parse_capped(const uint64_t value); template - requires (sizeof(T) >= 4) + requires(sizeof(T) >= 4) static fixed_point_t parse_capped(const T value) { - return std::is_signed_v - ? parse_capped(static_cast(value)) - : parse_capped(static_cast(value)); + return std::is_signed_v ? parse_capped(static_cast(value)) : parse_capped(static_cast(value)); } // Not Deterministic diff --git a/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp b/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp index cbd98d35f..0187c6d73 100644 --- a/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp +++ b/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/object/FixedPoint.hpp" namespace std { template<> @@ -164,8 +164,9 @@ namespace std { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m1, m2); } - OV_ALWAYS_INLINE bool - compare_exchange_strong(value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst) noexcept { + OV_ALWAYS_INLINE bool compare_exchange_strong( + value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst + ) noexcept { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m); } OV_ALWAYS_INLINE bool compare_exchange_strong( // diff --git a/src/openvic-simulation/core/object/FixedPoint/Fraction.hpp b/src/openvic-simulation/core/object/FixedPoint/Fraction.hpp index a291d82e1..49e0c6c59 100644 --- a/src/openvic-simulation/core/object/FixedPoint/Fraction.hpp +++ b/src/openvic-simulation/core/object/FixedPoint/Fraction.hpp @@ -1,8 +1,8 @@ #pragma once +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Math.hpp" -#include "openvic-simulation/core/Typedefs.hpp" namespace OpenVic { struct Fraction { diff --git a/src/openvic-simulation/core/object/FixedPoint/Math.hpp b/src/openvic-simulation/core/object/FixedPoint/Math.hpp index 816fcd52d..c9507b24a 100644 --- a/src/openvic-simulation/core/object/FixedPoint/Math.hpp +++ b/src/openvic-simulation/core/object/FixedPoint/Math.hpp @@ -4,9 +4,9 @@ #include "openvic-simulation/core/Math.hpp" #include "openvic-simulation/core/MathSqrt.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/Typedefs.hpp" /* Sin lookup table */ #include "openvic-simulation/core/object/FixedPoint/LUT_sin.hpp" @@ -46,32 +46,35 @@ namespace OpenVic::fp { OV_SPEED_INLINE static constexpr fixed_point_t sqrt(fixed_point_t const& v) { return !v.is_negative() - ? fixed_point_t::parse_raw(OpenVic::sqrt(static_cast(v.get_raw_value()) << fixed_point_t::PRECISION)) - : fixed_point_t::_0; + ? fixed_point_t::parse_raw(OpenVic::sqrt(static_cast(v.get_raw_value()) << fixed_point_t::PRECISION)) + : fixed_point_t::_0; } // Preserves accuracy. Performing a normal multiplication of small values results in 0. template - OV_SPEED_INLINE static constexpr fixed_point_t - mul_div(fixed_point_t const& multiplier, T const& numerator, T const& denominator) { + OV_SPEED_INLINE static constexpr fixed_point_t mul_div( + fixed_point_t const& multiplier, T const& numerator, T const& denominator + ) { return fixed_point_t::parse_raw(multiplier.get_raw_value() * numerator / denominator); } - OV_SPEED_INLINE static constexpr fixed_point_t - mul_div(fixed_point_t const& multiplier, fixed_point_t const& numerator, fixed_point_t const& denominator) { + OV_SPEED_INLINE static constexpr fixed_point_t mul_div( + fixed_point_t const& multiplier, fixed_point_t const& numerator, fixed_point_t const& denominator + ) { return mul_div(multiplier, numerator.get_raw_value(), denominator.get_raw_value()); } template - OV_SPEED_INLINE static constexpr fixed_point_t - mul_div(fixed_point_t const& multiplier, StrongType const& numerator, StrongType const& denominator) { + OV_SPEED_INLINE static constexpr fixed_point_t mul_div( + fixed_point_t const& multiplier, StrongType const& numerator, StrongType const& denominator + ) { return mul_div(multiplier, type_safe::get(numerator), type_safe::get(denominator)); } template OV_SPEED_INLINE static constexpr T multiply_truncate(T const& integer, fixed_point_t const& v) { return static_cast( - (static_cast(integer) * v.get_raw_value()) >> fixed_point_t::PRECISION + (static_cast(integer) * v.get_raw_value()) >> fixed_point_t::PRECISION ); } @@ -83,8 +86,8 @@ namespace OpenVic::fp { template OV_SPEED_INLINE static constexpr fixed_point_t from_fraction(const TNumerator numerator, const TDenominator denominator) { return fixed_point_t::parse_raw( - (static_cast(numerator) << fixed_point_t::PRECISION) / - static_cast(denominator) + (static_cast(numerator) << fixed_point_t::PRECISION) / + static_cast(denominator) ); } diff --git a/src/openvic-simulation/core/object/FixedPoint/String.hpp b/src/openvic-simulation/core/object/FixedPoint/String.hpp index e2d1fba50..f0abd151d 100644 --- a/src/openvic-simulation/core/object/FixedPoint/String.hpp +++ b/src/openvic-simulation/core/object/FixedPoint/String.hpp @@ -3,16 +3,17 @@ #include #include "openvic-simulation/core/Math.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/stl/containers/StackString.hpp" #include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/utility/Logger.hpp" namespace OpenVic::fp { struct stack_string final : public StackString<25> { protected: using StackString::StackString; + public: constexpr char* front() OV_LIFETIME_BOUND { return _array.data(); @@ -28,10 +29,7 @@ namespace OpenVic::fp { }; OV_SPEED_INLINE static constexpr std::to_chars_result to_chars( - const fixed_point_t v, - char* first, - char* last, - size_t decimal_places = -1 + const fixed_point_t v, char* first, char* last, size_t decimal_places = -1 ) { if (first == nullptr || first >= last) { return { last, std::errc::value_too_large }; @@ -105,27 +103,15 @@ namespace OpenVic::fp { return result; } - OV_SPEED_INLINE static constexpr stack_string to_array( - const fixed_point_t v, - size_t decimal_places = -1 - ) { + OV_SPEED_INLINE static constexpr stack_string to_array(const fixed_point_t v, size_t decimal_places = -1) { stack_string str {}; - std::to_chars_result result = OpenVic::fp::to_chars( - v, - str.front(), - str.back(), - decimal_places - ); + std::to_chars_result result = OpenVic::fp::to_chars(v, str.front(), str.back(), decimal_places); str.string_size() = result.ptr - str.data(); return str; } // Deterministic - OV_SPEED_INLINE static constexpr std::from_chars_result from_chars( - fixed_point_t& v, - char const* begin, - char const* end - ) { + OV_SPEED_INLINE static constexpr std::from_chars_result from_chars(fixed_point_t& v, char const* begin, char const* end) { if (begin == nullptr || begin >= end) { return { begin, std::errc::invalid_argument }; } @@ -150,7 +136,7 @@ namespace OpenVic::fp { // Non-empty integer part, may be negative int64_t parsed_value = 0; from_chars = string_to_int64(begin, dot_pointer, parsed_value); - if (from_chars.ec == std::errc{}) { + if (from_chars.ec == std::errc {}) { if (parsed_value > std::numeric_limits::max()) { from_chars.ec = std::errc::value_too_large; } else { @@ -159,7 +145,7 @@ namespace OpenVic::fp { } } - if (from_chars.ec != std::errc{}) { + if (from_chars.ec != std::errc {}) { return from_chars; } @@ -173,8 +159,9 @@ namespace OpenVic::fp { end = end - fraction_begin > fixed_point_t::PRECISION ? fraction_begin + fixed_point_t::PRECISION : end; uint64_t parsed_value; from_chars = string_to_uint64(fraction_begin, end, parsed_value); - if (from_chars.ec == std::errc{}) { - for (ptrdiff_t remaining_shift = fixed_point_t::PRECISION - (end - fraction_begin); remaining_shift > 0; remaining_shift--) { + if (from_chars.ec == std::errc {}) { + for (ptrdiff_t remaining_shift = fixed_point_t::PRECISION - (end - fraction_begin); remaining_shift > 0; + remaining_shift--) { parsed_value *= 10; } uint64_t decimal = OpenVic::pow(static_cast(10), fixed_point_t::PRECISION); @@ -193,7 +180,7 @@ namespace OpenVic::fp { result += result.is_negative() || (*begin == '-' && result == fixed_point_t::_0) ? -adder : adder; } - if (from_chars.ec != std::errc{}) { + if (from_chars.ec != std::errc {}) { return { begin, from_chars.ec }; } @@ -203,9 +190,7 @@ namespace OpenVic::fp { // Deterministic OV_SPEED_INLINE static constexpr std::from_chars_result from_chars_with_plus( - fixed_point_t& v, - char const* begin, - char const* end + fixed_point_t& v, char const* begin, char const* end ) { if (begin && *begin == '+') { begin++; @@ -226,7 +211,9 @@ namespace OpenVic::fp { spdlog::error_s("Unsafe fixed point parse failed to parse the end of a string: \"{}\"", endpointer); } - fixed_point_t::value_type integer_value = static_cast(double_value * fixed_point_t::ONE + 0.5 * (double_value < 0 ? -1 : 1)); + fixed_point_t::value_type integer_value = static_cast( + double_value * fixed_point_t::ONE + 0.5 * (double_value < 0 ? -1 : 1) + ); return fixed_point_t::parse_raw(integer_value); } diff --git a/src/openvic-simulation/core/object/Timespan.hpp b/src/openvic-simulation/core/object/Timespan.hpp index dadb6fd9b..58c68bc73 100644 --- a/src/openvic-simulation/core/object/Timespan.hpp +++ b/src/openvic-simulation/core/object/Timespan.hpp @@ -5,8 +5,8 @@ #include #include -#include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/memory/String.hpp" namespace OpenVic { // A relative period between points in time, measured in days @@ -24,8 +24,7 @@ namespace OpenVic { static constexpr month_t MONTHS_IN_YEAR = DAYS_IN_MONTH.size(); static_assert(MONTHS_IN_YEAR == 12); - static constexpr value_t DAYS_IN_YEAR = - std::accumulate(DAYS_IN_MONTH.begin(), DAYS_IN_MONTH.end(), value_t { 0 }); + static constexpr value_t DAYS_IN_YEAR = std::accumulate(DAYS_IN_MONTH.begin(), DAYS_IN_MONTH.end(), value_t { 0 }); static_assert(DAYS_IN_YEAR == 365); static constexpr std::array DAYS_UP_TO_MONTH = [] { diff --git a/src/openvic-simulation/core/object/Vector.hpp b/src/openvic-simulation/core/object/Vector.hpp index 0f88c4253..eba4afd02 100644 --- a/src/openvic-simulation/core/object/Vector.hpp +++ b/src/openvic-simulation/core/object/Vector.hpp @@ -6,11 +6,11 @@ #include #include "openvic-simulation/core/Math.hpp" // IWYU pragma: keep +#include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Math.hpp" // IWYU pragma: keep #include "openvic-simulation/core/stl/BasicIterator.hpp" // IWYU pragma: keep #include "openvic-simulation/core/template/Concepts.hpp" // IWYU pragma: keep -#include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep #define VEC_TYPE vec2_t #define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) @@ -22,7 +22,9 @@ #undef VEC_TYPE #define VEC_TYPE vec3_t -#define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) #define FOR_VEC_COMPONENTS_END(F, END_F) F(x) F(y) F(z) END_F(z) #include "VectorN.inc" @@ -31,7 +33,10 @@ #undef VEC_TYPE #define VEC_TYPE vec4_t -#define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) \ + SEP F(w) #define FOR_VEC_COMPONENTS_END(F, END_F) F(x) F(y) F(z) F(w) END_F(w) #include "VectorN.inc" @@ -44,8 +49,8 @@ namespace OpenVic { #define MAKE_VEC_ALIAS(prefix, type, size) \ using prefix##vec##size##_t = vec##size##_t; \ static_assert( \ - sizeof(prefix##vec##size##_t) == size * sizeof(type), \ - #prefix "vec" #size "_t size does not equal the sum of its parts' sizes" \ + sizeof(prefix##vec##size##_t) == size * sizeof(type), \ + #prefix "vec" #size "_t size does not equal the sum of its parts' sizes" \ ); \ extern template struct vec##size##_t; diff --git a/src/openvic-simulation/core/object/VectorN.inc b/src/openvic-simulation/core/object/VectorN.inc index daadcbc82..145dbbb54 100644 --- a/src/openvic-simulation/core/object/VectorN.inc +++ b/src/openvic-simulation/core/object/VectorN.inc @@ -14,13 +14,18 @@ // They are safe to ignore so long as they don't appear in the compiler log. #ifndef VEC_TYPE - #warning "VEC_TYPE not defined, defaulting to example: vec5_t" - #define VEC_TYPE vec5_t +#warning "VEC_TYPE not defined, defaulting to example: vec5_t" +#define VEC_TYPE vec5_t #endif #ifndef FOR_VEC_COMPONENTS - #warning "FOR_VEC_COMPONENTS not defined, defaulting to example: FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v)" - #define FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v) +#warning \ + "FOR_VEC_COMPONENTS not defined, defaulting to example: FOR_VEC_COMPONENTS(F, SEP) F(x) SEP F(y) SEP F(z) SEP F(w) SEP F(v)" +#define FOR_VEC_COMPONENTS(F, SEP) \ + F(x) SEP F(y) \ + SEP F(z) \ + SEP F(w) \ + SEP F(v) #endif #define COMMA , @@ -99,15 +104,18 @@ namespace OpenVic { } #define VEC_CONSTRUCTOR_ARG(v) T new_##v -#define VEC_CONSTRUCTOR_INITIALISE(v) v { new_##v } - OV_SPEED_INLINE constexpr VEC_TYPE(FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_ARG, COMMA)) - : FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_INITIALISE, COMMA) {} +#define VEC_CONSTRUCTOR_INITIALISE(v) \ + v { \ + new_##v \ + } + OV_SPEED_INLINE constexpr VEC_TYPE(FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_ARG, COMMA)) : + FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_INITIALISE, COMMA) {} #undef VEC_CONSTRUCTOR_ARG #undef VEC_CONSTRUCTOR_INITIALISE #define VEC_CONSTRUCTOR_SINGLE_ARG(v) new_val - OV_SPEED_INLINE explicit constexpr VEC_TYPE(T VEC_CONSTRUCTOR_SINGLE_ARG()) - : VEC_TYPE { FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_SINGLE_ARG, COMMA) } {} + OV_SPEED_INLINE explicit constexpr VEC_TYPE(T VEC_CONSTRUCTOR_SINGLE_ARG()) : + VEC_TYPE { FOR_VEC_COMPONENTS(VEC_CONSTRUCTOR_SINGLE_ARG, COMMA) } {} #undef VEC_CONSTRUCTOR_ARG_REPEAT OV_ALWAYS_INLINE constexpr VEC_TYPE() : VEC_TYPE { {} } {} @@ -130,7 +138,7 @@ namespace OpenVic { } #undef VEC_COMPONENT_ABS -#define VEC_COMPONENT_SQUARE(v) v * v +#define VEC_COMPONENT_SQUARE(v) (v) * (v) OV_SPEED_INLINE constexpr T length_squared() const { return FOR_VEC_COMPONENTS(VEC_COMPONENT_SQUARE, +); } @@ -143,7 +151,7 @@ namespace OpenVic { } #undef VEC_COMPONENT_DIST_SQUARE -#define VEC_COMPONENT_DOT(v) v * vec.v +#define VEC_COMPONENT_DOT(v) (v) * (vec.v) template OV_SPEED_INLINE constexpr T dot(VEC_TYPE const& vec) const { return FOR_VEC_COMPONENTS(VEC_COMPONENT_DOT, +); @@ -156,7 +164,9 @@ namespace OpenVic { } #undef VEC_COMPONENT_NONNEGATIVE -#define VEC_COMPONENT_COMPARE(v) if (left.v != right.v) return left.v <=> right.v; +#define VEC_COMPONENT_COMPARE(v) \ + if (left.v != right.v) \ + return left.v <=> right.v; #define VEC_COMPONENT_COMPARE_END(v) return left.v <=> right.v OV_SPEED_INLINE constexpr friend auto operator<=>(VEC_TYPE const& left, VEC_TYPE const& right) { FOR_VEC_COMPONENTS_END(VEC_COMPONENT_COMPARE, VEC_COMPONENT_COMPARE_END); @@ -164,7 +174,9 @@ namespace OpenVic { #undef VEC_COMPONENT_COMPARE #undef VEC_COMPONENT_COMPARE_END -#define VEC_COMPONENT_COMPARE(v) if (v != right.v) return v <=> right.v; +#define VEC_COMPONENT_COMPARE(v) \ + if (v != right.v) \ + return v <=> right.v; #define VEC_COMPONENT_COMPARE_END(v) return v <=> right.v template OV_SPEED_INLINE constexpr auto operator<=>(VEC_TYPE const& right) const { @@ -208,7 +220,7 @@ namespace OpenVic { #define VEC_COMPONENT_ADDEQ(v) v += right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator+=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ, ); return *this; } #undef VEC_COMPONENT_ADDEQ @@ -230,7 +242,7 @@ namespace OpenVic { #define VEC_COMPONENT_ADDEQ_RIGHT(v) v += right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator+=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_ADDEQ_RIGHT, ); return *this; } #undef VEC_COMPONENT_ADDEQ_RIGHT @@ -251,7 +263,7 @@ namespace OpenVic { #define VEC_COMPONENT_SUBEQ(v) v -= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator-=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ, ); return *this; } #undef VEC_COMPONENT_SUBEQ @@ -273,12 +285,12 @@ namespace OpenVic { #define VEC_COMPONENT_SUBEQ_RIGHT(v) v -= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator-=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_SUBEQ_RIGHT, ); return *this; } #undef VEC_COMPONENT_SUBEQ_RIGHT -#define VEC_COMPONENT_MUL(v) left.v * right.v +#define VEC_COMPONENT_MUL(v) (left.v) * (right.v) template OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(VEC_TYPE const& left, VEC_TYPE const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL, COMMA) }; @@ -288,19 +300,19 @@ namespace OpenVic { #define VEC_COMPONENT_MULEQ(v) v *= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator*=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ, ); return *this; } #undef VEC_COMPONENT_MULEQ -#define VEC_COMPONENT_MUL_RIGHT(v) left.v * right +#define VEC_COMPONENT_MUL_RIGHT(v) (left.v) * (right) template> S> OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(VEC_TYPE const& left, S const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL_RIGHT, COMMA) }; } #undef VEC_COMPONENT_MUL_RIGHT -#define VEC_COMPONENT_MUL_LEFT(v) left * right.v +#define VEC_COMPONENT_MUL_LEFT(v) (left) * (right.v) template> S> OV_SPEED_INLINE constexpr friend VEC_TYPE operator*(S const& left, VEC_TYPE const& right) { return { FOR_VEC_COMPONENTS(VEC_COMPONENT_MUL_LEFT, COMMA) }; @@ -310,7 +322,7 @@ namespace OpenVic { #define VEC_COMPONENT_MULEQ_RIGHT(v) v *= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator*=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_MULEQ_RIGHT, ); return *this; } #undef VEC_COMPONENT_MULEQ_RIGHT @@ -325,7 +337,7 @@ namespace OpenVic { #define VEC_COMPONENT_DIVEQ(v) v /= right.v; template OV_SPEED_INLINE constexpr VEC_TYPE& operator/=(VEC_TYPE const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ, ); return *this; } #undef VEC_COMPONENT_DIVEQ @@ -347,7 +359,7 @@ namespace OpenVic { #define VEC_COMPONENT_DIVEQ_RIGHT(v) v /= right; template> S> OV_SPEED_INLINE constexpr VEC_TYPE& operator/=(S const& right) { - FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ_RIGHT,) + FOR_VEC_COMPONENTS(VEC_COMPONENT_DIVEQ_RIGHT, ); return *this; } #undef VEC_COMPONENT_DIVEQ_RIGHT diff --git a/src/openvic-simulation/core/portable/Deque.hpp b/src/openvic-simulation/core/portable/Deque.hpp index 95f80dcd1..b42e6227c 100644 --- a/src/openvic-simulation/core/portable/Deque.hpp +++ b/src/openvic-simulation/core/portable/Deque.hpp @@ -41,8 +41,8 @@ namespace OpenVic::utility::_detail::deque { _Deque_unchecked_const_iterator() noexcept : _Mycont(), _Myoff(0) {} - _Deque_unchecked_const_iterator(_Size_type _Off, const _Container_base12* _Pdeque) noexcept - : _Mycont(static_cast(_Pdeque)), _Myoff(_Off) {} + _Deque_unchecked_const_iterator(_Size_type _Off, const _Container_base12* _Pdeque) noexcept : + _Mycont(static_cast(_Pdeque)), _Myoff(_Off) {} _NODISCARD reference operator*() const noexcept { return _Mycont->_Subscript(_Myoff); @@ -85,8 +85,9 @@ namespace OpenVic::utility::_detail::deque { return _Tmp; } - _NODISCARD friend _Deque_unchecked_const_iterator - operator+(const difference_type _Off, _Deque_unchecked_const_iterator _Next) noexcept { + _NODISCARD friend _Deque_unchecked_const_iterator operator+( + const difference_type _Off, _Deque_unchecked_const_iterator _Next + ) noexcept { _Next += _Off; return _Next; } @@ -205,8 +206,9 @@ namespace OpenVic::utility::_detail::deque { return _Tmp; } - _NODISCARD friend _Deque_unchecked_iterator - operator+(const difference_type _Off, _Deque_unchecked_iterator _Next) noexcept { + _NODISCARD friend _Deque_unchecked_iterator operator+( + const difference_type _Off, _Deque_unchecked_iterator _Next + ) noexcept { _Next += _Off; return _Next; } @@ -247,7 +249,9 @@ namespace OpenVic::utility::_detail::deque { using reference = const value_type&; using _Mydeque_t = _Mydeque; // helper for expression evaluator - enum { _EEN_DS = _Block_size }; // helper for expression evaluator + enum { + _EEN_DS = _Block_size + }; // helper for expression evaluator _Deque_const_iterator() noexcept : _Myoff(0) { _Setcont(nullptr); } @@ -261,8 +265,8 @@ namespace OpenVic::utility::_detail::deque { #if _ITERATOR_DEBUG_LEVEL != 0 _STL_VERIFY(_Mycont, "cannot dereference value-initialized deque iterator"); _STL_VERIFY( - _Mycont->_Myoff <= this->_Myoff && this->_Myoff < _Mycont->_Myoff + _Mycont->_Mysize, - "cannot deference out of range deque iterator" + _Mycont->_Myoff <= this->_Myoff && this->_Myoff < _Mycont->_Myoff + _Mycont->_Mysize, + "cannot deference out of range deque iterator" ); #endif // _ITERATOR_DEBUG_LEVEL != 0 @@ -313,8 +317,8 @@ namespace OpenVic::utility::_detail::deque { const auto _Mycont = static_cast(this->_Getcont()); _STL_VERIFY(_Mycont, "cannot seek value-initialized deque iterator"); _STL_VERIFY( - _Mycont->_Myoff <= this->_Myoff + _Off && this->_Myoff + _Off <= _Mycont->_Myoff + _Mycont->_Mysize, - "cannot seek deque iterator out of range" + _Mycont->_Myoff <= this->_Myoff + _Off && this->_Myoff + _Off <= _Mycont->_Myoff + _Mycont->_Mysize, + "cannot seek deque iterator out of range" ); } #endif // _ITERATOR_DEBUG_LEVEL != 0 @@ -412,8 +416,8 @@ namespace OpenVic::utility::_detail::deque { const auto _Mycont = static_cast(this->_Getcont()); _STL_VERIFY(_Mycont, "cannot use value-initialized deque iterator"); _STL_VERIFY( - _Mycont->_Myoff <= this->_Myoff + _Off && this->_Myoff + _Off <= _Mycont->_Myoff + _Mycont->_Mysize, - "cannot seek deque iterator out of range" + _Mycont->_Myoff <= this->_Myoff + _Off && this->_Myoff + _Off <= _Mycont->_Myoff + _Mycont->_Mysize, + "cannot seek deque iterator out of range" ); } #endif // ^^^ _ITERATOR_DEBUG_LEVEL != 0 ^^^ @@ -520,7 +524,12 @@ namespace OpenVic::utility::_detail::deque { }; template< - class _Value_type, class _Size_type, class _Difference_type, class _Pointer, class _Const_pointer, class _Mapptr_type> + class _Value_type, + class _Size_type, + class _Difference_type, + class _Pointer, + class _Const_pointer, + class _Mapptr_type> struct _Deque_iter_types { using value_type = _Value_type; using size_type = _Size_type; @@ -554,11 +563,11 @@ namespace OpenVic::utility::_detail::deque { public: static constexpr int _Block_size = 512 /*_Bytes <= 1 ? 16 - : _Bytes <= 2 ? 8 - : _Bytes <= 4 ? 4 - : _Bytes <= 8 ? 2 - : 1*/ - ; // elements per block (a power of 2) + : _Bytes <= 2 ? 8 + : _Bytes <= 4 ? 4 + : _Bytes <= 8 ? 2 + : 1*/ + ; // elements per block (a power of 2) _Deque_val() noexcept : _Map(), _Mapsize(0), _Myoff(0), _Mysize(0) {} @@ -596,13 +605,13 @@ namespace OpenVic::utility::_detail::deque { private: friend _Tidy_guard; static_assert( - !_ENFORCE_MATCHING_ALLOCATORS || is_same_v<_Ty, typename _Alloc::value_type>, - _MISMATCHED_ALLOCATOR_MESSAGE("deque", "T") + !_ENFORCE_MATCHING_ALLOCATORS || is_same_v<_Ty, typename _Alloc::value_type>, + _MISMATCHED_ALLOCATOR_MESSAGE("deque", "T") ); static_assert( - is_object_v<_Ty>, - "The C++ Standard forbids containers of non-object types " - "because of [container.requirements]." + is_object_v<_Ty>, + "The C++ Standard forbids containers of non-object types " + "because of [container.requirements]." ); using _Alty = _Rebind_alloc_t<_Alloc, _Ty>; @@ -615,10 +624,15 @@ namespace OpenVic::utility::_detail::deque { using _Map_difference_type = typename iterator_traits<_Mapptr>::difference_type; using _Scary_val = _Deque_val, _Deque_simple_types<_Ty>, - _Deque_iter_types< - _Ty, typename _Alty_traits::size_type, typename _Alty_traits::difference_type, typename _Alty_traits::pointer, - typename _Alty_traits::const_pointer, _Mapptr>>>; + _Is_simple_alloc_v<_Alty>, + _Deque_simple_types<_Ty>, + _Deque_iter_types< + _Ty, + typename _Alty_traits::size_type, + typename _Alty_traits::difference_type, + typename _Alty_traits::pointer, + typename _Alty_traits::const_pointer, + _Mapptr>>>; static constexpr int _Minimum_map_size = 8; static constexpr int _Block_size = _Scary_val::_Block_size; @@ -640,7 +654,9 @@ namespace OpenVic::utility::_detail::deque { using reverse_iterator = _STD reverse_iterator; using const_reverse_iterator = _STD reverse_iterator; - enum { _EEN_DS = _Block_size }; // helper for expression evaluator + enum { + _EEN_DS = _Block_size + }; // helper for expression evaluator deque() : _Mypair(_Zero_then_variadic_args_t {}) { _Get_data()._Alloc_proxy(static_cast<_Alproxy_ty>(_Getal())); @@ -650,8 +666,8 @@ namespace OpenVic::utility::_detail::deque { _Get_data()._Alloc_proxy(static_cast<_Alproxy_ty>(_Getal())); } - explicit deque(_CRT_GUARDOVERFLOW size_type _Count, const _Alloc& _Al = _Alloc()) - : _Mypair(_One_then_variadic_args_t {}, _Al) { + explicit deque(_CRT_GUARDOVERFLOW size_type _Count, const _Alloc& _Al = _Alloc()) : + _Mypair(_One_then_variadic_args_t {}, _Al) { _Alproxy_ty _Alproxy(_Getal()); _Container_proxy_ptr12<_Alproxy_ty> _Proxy(_Alproxy, _Get_data()); _Tidy_guard _Guard { this }; @@ -667,8 +683,8 @@ namespace OpenVic::utility::_detail::deque { #if _HAS_CXX17 template::value, int> = 0> #endif // _HAS_CXX17 - deque(_CRT_GUARDOVERFLOW size_type _Count, const _Ty& _Val, const _Alloc& _Al) - : _Mypair(_One_then_variadic_args_t {}, _Al) { + deque(_CRT_GUARDOVERFLOW size_type _Count, const _Ty& _Val, const _Alloc& _Al) : + _Mypair(_One_then_variadic_args_t {}, _Al) { _Construct_n(_Count, _Val); } @@ -694,8 +710,8 @@ namespace OpenVic::utility::_detail::deque { } #endif // _HAS_CXX23 - deque(const deque& _Right) - : _Mypair(_One_then_variadic_args_t {}, _Alty_traits::select_on_container_copy_construction(_Right._Getal())) { + deque(const deque& _Right) : + _Mypair(_One_then_variadic_args_t {}, _Alty_traits::select_on_container_copy_construction(_Right._Getal())) { _Construct(_Right._Unchecked_begin(), _Right._Unchecked_end()); } @@ -712,7 +728,7 @@ namespace OpenVic::utility::_detail::deque { if constexpr (!_Alty_traits::is_always_equal::value) { if (_Getal() != _Right._Getal()) { _Construct( - _STD make_move_iterator(_Right._Unchecked_begin()), _STD make_move_iterator(_Right._Unchecked_end()) + _STD make_move_iterator(_Right._Unchecked_begin()), _STD make_move_iterator(_Right._Unchecked_end()) ); return; } @@ -820,7 +836,7 @@ namespace OpenVic::utility::_detail::deque { } else if constexpr (_Pocma_val == _Pocma_values::_No_propagate_allocators) { if (_Al != _Right_al) { assign( - _STD make_move_iterator(_Right._Unchecked_begin()), _STD make_move_iterator(_Right._Unchecked_end()) + _STD make_move_iterator(_Right._Unchecked_begin()), _STD make_move_iterator(_Right._Unchecked_end()) ); return *this; } @@ -848,8 +864,8 @@ namespace OpenVic::utility::_detail::deque { template<_Container_compatible_range<_Ty> _Rng> void assign_range(_Rng&& _Range) { static_assert( - assignable_from<_Ty&, _RANGES range_reference_t<_Rng>>, - "Elements must be assignable from the range's reference type (N4993 [sequence.reqmts]/60)." + assignable_from<_Ty&, _RANGES range_reference_t<_Rng>>, + "Elements must be assignable from the range's reference type (N4993 [sequence.reqmts]/60)." ); _Assign_range(_RANGES _Ubegin(_Range), _RANGES _Uend(_Range)); } @@ -1022,14 +1038,15 @@ namespace OpenVic::utility::_detail::deque { // (_Myoff() + _Mysize() - 1) is for the last element, i.e. the back() of the deque. // Divide by _Block_size to get the unmasked index of the last used block. // Add 1 to get the unmasked index of the first unused block. - const auto _Unmasked_first_unused_block_idx = - static_cast(((_Myoff() + _Mysize() - 1) / _Block_size) + 1); + const auto _Unmasked_first_unused_block_idx = static_cast( + ((_Myoff() + _Mysize() - 1) / _Block_size) + 1 + ); const auto _First_unused_block_idx = static_cast(_Unmasked_first_unused_block_idx & _Mask); // deallocate unused blocks, traversing over the circular buffer until the first used block index for (auto _Block_idx = _First_unused_block_idx; _Block_idx != _First_used_block_idx; - _Block_idx = static_cast((_Block_idx + 1) & _Mask)) { + _Block_idx = static_cast((_Block_idx + 1) & _Mask)) { auto& _Block_ptr = _Map()[static_cast<_Map_difference_type>(_Block_idx)]; if (_Block_ptr != nullptr) { _Getal().deallocate(_Block_ptr, _Block_size); @@ -1037,8 +1054,9 @@ namespace OpenVic::utility::_detail::deque { } } - const auto _Used_block_count = - static_cast(_Unmasked_first_unused_block_idx - _Unmasked_first_used_block_idx); + const auto _Used_block_count = static_cast( + _Unmasked_first_unused_block_idx - _Unmasked_first_used_block_idx + ); size_type _New_block_count = _Minimum_map_size; // should be power of 2 @@ -1066,7 +1084,7 @@ namespace OpenVic::utility::_detail::deque { // null out the rest of the new map _STD _Uninitialized_value_construct_n_unchecked1( - _New_map + static_cast<_Map_difference_type>(_Used_block_count), _New_block_count - _Used_block_count + _New_map + static_cast<_Map_difference_type>(_Used_block_count), _New_block_count - _Used_block_count ); for (auto _Block = _Map_distance(); _Block > 0;) { @@ -1319,7 +1337,7 @@ namespace OpenVic::utility::_detail::deque { _STD _Adl_verify_range(_First, _Last); const size_type _Off = static_cast(_Where - begin()); return _Insert_range(_Is_cpp17_bidi_iter_v<_Iter>)>( - _Off, _STD _Get_unwrapped(_First), _STD _Get_unwrapped(_Last) + _Off, _STD _Get_unwrapped(_First), _STD _Get_unwrapped(_Last) ); } @@ -1330,7 +1348,7 @@ namespace OpenVic::utility::_detail::deque { if constexpr (_RANGES bidirectional_range<_Rng>) { return _Insert_range<_Is_bidi::_Yes>( - _Off, _RANGES _Ubegin(_Range), _RANGES _Get_final_iterator_unwrapped(_Range) + _Off, _RANGES _Ubegin(_Range), _RANGES _Get_final_iterator_unwrapped(_Range) ); } else { return _Insert_range<_Is_bidi::_Nope>(_Off, _RANGES _Ubegin(_Range), _RANGES _Uend(_Range)); @@ -1366,7 +1384,10 @@ namespace OpenVic::utility::_detail::deque { } }; - enum class _Is_bidi : bool { _Nope, _Yes }; + enum class _Is_bidi : bool { + _Nope, + _Yes + }; template<_Is_bidi _Bidi, class _Iter, class _Sent> iterator _Insert_range(const size_type _Off, _Iter _First, _Sent _Last) { @@ -1418,8 +1439,9 @@ namespace OpenVic::utility::_detail::deque { const auto _Myfirst = _Unchecked_begin(); _STD rotate( - _Myfirst + static_cast(_Off), _Myfirst + static_cast(_Oldsize), - _Unchecked_end() + _Myfirst + static_cast(_Off), + _Myfirst + static_cast(_Oldsize), + _Unchecked_end() ); return begin() + static_cast(_Off); @@ -1456,12 +1478,14 @@ namespace OpenVic::utility::_detail::deque { _Mid = _Unchecked_begin() + static_cast(_Count); _Alloc_temporary2<_Alty> _Tmp(_Getal(), _Val); // in case _Val is in sequence _STD move( - _Mid + static_cast(_Count), _Mid + static_cast(_Off), - _Mid + _Mid + static_cast(_Count), + _Mid + static_cast(_Off), + _Mid ); // copy rest of prefix _STD fill( - _Unchecked_begin() + static_cast(_Off), _Mid + static_cast(_Off), - _Tmp._Get_value() + _Unchecked_begin() + static_cast(_Off), + _Mid + static_cast(_Off), + _Tmp._Get_value() ); // fill in values } _Guard._Container = nullptr; @@ -1486,8 +1510,9 @@ namespace OpenVic::utility::_detail::deque { _Mid = _Unchecked_begin() + static_cast(_Off); _Alloc_temporary2<_Alty> _Tmp(_Getal(), _Val); // in case _Val is in sequence _STD move_backward( - _Mid, _Mid + static_cast(_Rem - _Count), - _Mid + static_cast(_Rem) + _Mid, + _Mid + static_cast(_Rem - _Count), + _Mid + static_cast(_Rem) ); // copy rest of prefix _STD fill_n(_Mid, _Count, _Tmp._Get_value()); // fill in values } @@ -1545,7 +1570,7 @@ namespace OpenVic::utility::_detail::deque { } iterator erase( - const_iterator _First_arg, const_iterator _Last_arg + const_iterator _First_arg, const_iterator _Last_arg ) noexcept(is_nothrow_move_assignable_v) /* strengthened */ { iterator _First = _Make_iter(_First_arg); iterator _Last = _Make_iter(_Last_arg); @@ -1801,8 +1826,9 @@ namespace OpenVic::utility::_detail::deque { #if _HAS_CXX17 template< - class _Iter, class _Alloc = allocator<_Iter_value_t<_Iter>>, - enable_if_t, _Is_allocator<_Alloc>>, int> = 0> + class _Iter, + class _Alloc = allocator<_Iter_value_t<_Iter>>, + enable_if_t, _Is_allocator<_Alloc>>, int> = 0> deque(_Iter, _Iter, _Alloc = _Alloc()) -> deque<_Iter_value_t<_Iter>, _Alloc>; #endif // _HAS_CXX17 @@ -1819,15 +1845,18 @@ namespace OpenVic::utility::_detail::deque { _EXPORT_STD template _NODISCARD bool operator==(const deque<_Ty, _Alloc>& _Left, const deque<_Ty, _Alloc>& _Right) { return _Left.size() == _Right.size() && - _STD equal(_Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin()); + _STD equal(_Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin()); } #if _HAS_CXX20 _EXPORT_STD template _NODISCARD _Synth_three_way_result<_Ty> operator<=>(const deque<_Ty, _Alloc>& _Left, const deque<_Ty, _Alloc>& _Right) { return _STD lexicographical_compare_three_way( - _Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin(), _Right._Unchecked_end(), - _Synth_three_way {} + _Left._Unchecked_begin(), + _Left._Unchecked_end(), + _Right._Unchecked_begin(), + _Right._Unchecked_end(), + _Synth_three_way {} ); } #else // ^^^ _HAS_CXX20 / !_HAS_CXX20 vvv @@ -1839,7 +1868,7 @@ namespace OpenVic::utility::_detail::deque { template _NODISCARD bool operator<(const deque<_Ty, _Alloc>& _Left, const deque<_Ty, _Alloc>& _Right) { return _STD lexicographical_compare( - _Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin(), _Right._Unchecked_end() + _Left._Unchecked_begin(), _Left._Unchecked_end(), _Right._Unchecked_begin(), _Right._Unchecked_end() ); } diff --git a/src/openvic-simulation/core/portable/ForwardableSpan.hpp b/src/openvic-simulation/core/portable/ForwardableSpan.hpp index 16815ceaa..d84483482 100644 --- a/src/openvic-simulation/core/portable/ForwardableSpan.hpp +++ b/src/openvic-simulation/core/portable/ForwardableSpan.hpp @@ -34,24 +34,25 @@ namespace OpenVic::_detail::forwardable_span { struct is_std_array> : std::true_type {}; template - concept span_compatible_range = !is_std_span>::value && // - std::ranges::contiguous_range && // - std::ranges::sized_range && // - (std::ranges::borrowed_range || std::is_const_v) && // - !is_std_array>::value && // - !std::is_array_v> && // - std::is_convertible_v> (*)[], ElementType (*)[]>; + concept span_compatible_range = + !is_std_span>::value && // + std::ranges::contiguous_range && // + std::ranges::sized_range && // + (std::ranges::borrowed_range || std::is_const_v) && // + !is_std_array>::value && // + !std::is_array_v> && // + std::is_convertible_v> (*)[], ElementType (*)[]>; template concept span_array_convertible = std::is_convertible_v; template concept span_compatible_iterator = - std::contiguous_iterator && span_array_convertible>, T>; + std::contiguous_iterator && span_array_convertible>, T>; template concept span_compatible_sentinel_for = - std::sized_sentinel_for && !std::is_convertible_v; + std::sized_sentinel_for && !std::is_convertible_v; template struct extent_storage { @@ -123,17 +124,17 @@ namespace OpenVic::_detail::forwardable_span { constexpr span() requires(Extent == dynamic_extent || Extent == 0) - : _ptr(nullptr), _extent(_v<0>) {} + : _ptr(nullptr), _extent(_v<0>) {} constexpr span(const span&) = default; template It> - constexpr explicit(extent != dynamic_extent) span(It first, size_type count) - : _ptr(std::to_address(first)), _extent(count) {} + constexpr explicit(extent != dynamic_extent) span(It first, size_type count) : + _ptr(std::to_address(first)), _extent(count) {} template It, span_compatible_sentinel_for End> - constexpr explicit(extent != dynamic_extent) span(It first, End last) - : _ptr(std::to_address(first)), _extent(static_cast(last - first)) {} + constexpr explicit(extent != dynamic_extent) span(It first, End last) : + _ptr(std::to_address(first)), _extent(static_cast(last - first)) {} template requires(Extent == dynamic_extent || ArrayExtent == Extent) @@ -147,20 +148,20 @@ namespace OpenVic::_detail::forwardable_span { constexpr span(std::array const& arr) : _ptr(arr.data()), _extent(_v) {} template Range> - constexpr explicit(extent != dynamic_extent) span(Range&& r) - : _ptr { std::ranges::data(r) }, _extent(std::ranges::size(r)) {} + constexpr explicit(extent != dynamic_extent) span(Range&& r) : + _ptr { std::ranges::data(r) }, _extent(std::ranges::size(r)) {} template OtherElementType, std::size_t OtherExtent> requires(Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) - constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) - span(span const& s) - : _ptr(s.data()), _extent(s.size()) {} + constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) span( + span const& s + ) : _ptr(s.data()), _extent(s.size()) {} template OtherElementType, std::size_t OtherExtent> requires(Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) - constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) - span(std::span const& s) - : _ptr(s.data()), _extent(s.size()) {} + constexpr explicit(extent != dynamic_extent && OtherExtent == dynamic_extent) span( + std::span const& s + ) : _ptr(s.data()), _extent(s.size()) {} constexpr span& operator=(span const&) = default; @@ -325,7 +326,7 @@ namespace OpenVic::_detail::forwardable_span { OV_ALWAYS_INLINE constexpr explicit span(_SizedPtr __ptr) requires(extent != dynamic_extent) - : _ptr(__ptr._ptr), _extent(_v) {} + : _ptr(__ptr._ptr), _extent(_v) {} pointer _ptr; OV_NO_UNIQUE_ADDRESS extent_storage _extent; @@ -364,9 +365,9 @@ namespace std { } template - [[nodiscard]] inline OpenVic::forwardable_span< - const std::byte, Extent == dynamic_extent ? dynamic_extent : Extent * sizeof(T)> - as_bytes(OpenVic::forwardable_span sp) { + [[nodiscard]] inline OpenVic:: + forwardable_span + as_bytes(OpenVic::forwardable_span sp) { auto data = reinterpret_cast(sp.data()); auto size = sp.size_bytes(); constexpr std::size_t extent = Extent == dynamic_extent ? dynamic_extent : Extent * sizeof(T); diff --git a/src/openvic-simulation/core/random/RandomGenerator.hpp b/src/openvic-simulation/core/random/RandomGenerator.hpp index 554d15c60..3606dae99 100644 --- a/src/openvic-simulation/core/random/RandomGenerator.hpp +++ b/src/openvic-simulation/core/random/RandomGenerator.hpp @@ -16,27 +16,27 @@ namespace OpenVic { using generator_type = T; using state_type = - std::conditional_t; + std::conditional_t; using result_type = - std::conditional_t; + std::conditional_t; [[nodiscard]] OV_ALWAYS_INLINE explicit constexpr RandomGenerator() requires requires { { T {} }; } - : _generator {} {} + : _generator {} {} [[nodiscard]] OV_ALWAYS_INLINE explicit constexpr RandomGenerator(std::uint64_t seed) requires requires { { T { seed } }; } - : _generator { seed } {} + : _generator { seed } {} [[nodiscard]] OV_ALWAYS_INLINE explicit constexpr RandomGenerator(state_type state) requires requires { { T { state } }; } - : _generator { state } {} + : _generator { state } {} OV_ALWAYS_INLINE constexpr result_type operator()() { return _generator(); @@ -78,6 +78,10 @@ namespace OpenVic { T _generator; }; - struct RandomU32 : RandomGenerator { using RandomGenerator::RandomGenerator; }; - struct RandomU64 : RandomGenerator { using RandomGenerator::RandomGenerator; }; + struct RandomU32 : RandomGenerator { + using RandomGenerator::RandomGenerator; + }; + struct RandomU64 : RandomGenerator { + using RandomGenerator::RandomGenerator; + }; } diff --git a/src/openvic-simulation/core/random/WeightedSampling.hpp b/src/openvic-simulation/core/random/WeightedSampling.hpp index 3a3bd7ba1..60ac84ca9 100644 --- a/src/openvic-simulation/core/random/WeightedSampling.hpp +++ b/src/openvic-simulation/core/random/WeightedSampling.hpp @@ -4,14 +4,12 @@ #include #include -#include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/object/FixedPoint.hpp" namespace OpenVic { OV_SPEED_INLINE static size_t sample_weighted_index( - const uint32_t random_value, - const std::span positive_weights, - const fixed_point_t weights_sum + const uint32_t random_value, const std::span positive_weights, const fixed_point_t weights_sum ) { if (positive_weights.empty() || weights_sum <= 0) { return -1; @@ -31,4 +29,4 @@ namespace OpenVic { return static_cast(positive_weights.size() - 1); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/stl/BasicIterator.hpp b/src/openvic-simulation/core/stl/BasicIterator.hpp index b81c656f7..ddaec66f8 100644 --- a/src/openvic-simulation/core/stl/BasicIterator.hpp +++ b/src/openvic-simulation/core/stl/BasicIterator.hpp @@ -148,13 +148,13 @@ namespace OpenVic { template constexpr inline auto iterator_base(std::reverse_iterator it) - -> decltype(std::make_reverse_iterator(iterator_base(it.base()))) { + -> decltype(std::make_reverse_iterator(iterator_base(it.base()))) { return std::make_reverse_iterator(iterator_base(it.base())); } template constexpr inline auto iterator_base(std::move_iterator it) - -> decltype(std::make_move_iterator(iterator_base(it.base()))) { + -> decltype(std::make_move_iterator(iterator_base(it.base()))) { return std::make_move_iterator(iterator_base(it.base())); } diff --git a/src/openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp b/src/openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp index 8968b7344..e97ca5faa 100644 --- a/src/openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp +++ b/src/openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp @@ -13,7 +13,7 @@ namespace OpenVic { // not thread safe - template + template struct bulk_insert_wrapper { public: // Member types based on std::vector @@ -39,11 +39,11 @@ namespace OpenVic { std::atomic pending_extra_size {}; constexpr void flush_pending_room() { - if (pending_extra_size > size_type{}) { + if (pending_extra_size > size_type {}) { size_type valid_size { size() }; container.resize(valid_size + pending_extra_size); container.resize(valid_size); - pending_extra_size = size_type{}; + pending_extra_size = size_type {}; } } @@ -55,9 +55,8 @@ namespace OpenVic { constexpr bulk_insert_wrapper() noexcept {}; // Forwarding constructor for custom allocators or initial capacities - template - constexpr explicit bulk_insert_wrapper(Args&&... args) - : container(std::forward(args)...) {} + template + constexpr explicit bulk_insert_wrapper(Args&&... args) : container(std::forward(args)...) {} // thread safe constexpr void make_room_for(const size_type count) noexcept { @@ -85,15 +84,19 @@ namespace OpenVic { constexpr reference back() OV_LIFETIME_BOUND { OV_HARDEN_ASSERT_NONEMPTY("back"); - return container[size()-1]; + return container[size() - 1]; } constexpr const_reference back() const OV_LIFETIME_BOUND { OV_HARDEN_ASSERT_NONEMPTY("back"); - return container[size()-1]; + return container[size() - 1]; } - constexpr value_type* data() noexcept OV_LIFETIME_BOUND { return container.data(); } - constexpr value_type const* data() const noexcept OV_LIFETIME_BOUND { return container.data(); } + constexpr value_type* data() noexcept OV_LIFETIME_BOUND { + return container.data(); + } + constexpr value_type const* data() const noexcept OV_LIFETIME_BOUND { + return container.data(); + } // Iterators based on std::vector constexpr iterator begin() noexcept OV_LIFETIME_BOUND { @@ -137,19 +140,27 @@ namespace OpenVic { } // Capacity based on std::vector - constexpr bool empty() const noexcept { return size() <= size_type{}; } - constexpr size_type size() const noexcept { return container.size(); } - constexpr size_type max_size() const noexcept { return container.max_size(); } + constexpr bool empty() const noexcept { + return size() <= size_type {}; + } + constexpr size_type size() const noexcept { + return container.size(); + } + constexpr size_type max_size() const noexcept { + return container.max_size(); + } // reserve() is omitted as we manage that via make_room_for - constexpr size_type capacity() const noexcept { return container.capacity(); } + constexpr size_type capacity() const noexcept { + return container.capacity(); + } constexpr void shrink_to_fit() { - pending_extra_size = size_type{}; + pending_extra_size = size_type {}; container.shrink_to_fit(); } // Modifiers based on std::vector constexpr void clear() noexcept { - pending_extra_size = size_type{}; + pending_extra_size = size_type {}; container.clear(); } @@ -165,7 +176,6 @@ namespace OpenVic { constexpr void push_back(value_type const& value) { flush_pending_room(); container.push_back(value); - } constexpr void push_back(value_type&& value) { flush_pending_room(); @@ -178,12 +188,12 @@ namespace OpenVic { return container.emplace_back(std::forward(args)...); } - template + template constexpr void append_range(OtherContainerT const& other) { append_range(other.begin(), other.end()); } - template + template constexpr void append_range(const InputIt first, const InputIt last) { flush_pending_room(); diff --git a/src/openvic-simulation/core/stl/containers/CowPtr.hpp b/src/openvic-simulation/core/stl/containers/CowPtr.hpp index 0439a12aa..efc3f4f7a 100644 --- a/src/openvic-simulation/core/stl/containers/CowPtr.hpp +++ b/src/openvic-simulation/core/stl/containers/CowPtr.hpp @@ -7,8 +7,8 @@ #include #include -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" namespace OpenVic::stl { /** @@ -78,13 +78,13 @@ namespace OpenVic::stl { template requires std::constructible_from&, Args...> - OV_ALWAYS_INLINE cow_ptr(Allocator const& alloc, std::in_place_t, std::initializer_list ilist, Args&&... args) - : cow_ptr(allocate_tag, alloc) { + OV_ALWAYS_INLINE cow_ptr(Allocator const& alloc, std::in_place_t, std::initializer_list ilist, Args&&... args) : + cow_ptr(allocate_tag, alloc) { std::construct_at(data, ilist, std::forward(args)...); } - OV_ALWAYS_INLINE cow_ptr(cow_ptr const& x) - : alloc(payload_allocator_traits::select_on_container_copy_construction(x.alloc)), data(x.data) { + OV_ALWAYS_INLINE cow_ptr(cow_ptr const& x) : + alloc(payload_allocator_traits::select_on_container_copy_construction(x.alloc)), data(x.data) { ++data->count; } diff --git a/src/openvic-simulation/core/stl/containers/CowVector.hpp b/src/openvic-simulation/core/stl/containers/CowVector.hpp index 890e1a4e2..0f7226db3 100644 --- a/src/openvic-simulation/core/stl/containers/CowVector.hpp +++ b/src/openvic-simulation/core/stl/containers/CowVector.hpp @@ -13,9 +13,9 @@ #include "openvic-simulation/core/Assert.hpp" #include "openvic-simulation/core/Compare.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/stl/BasicIterator.hpp" #include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/utility/Allocator.hpp" namespace OpenVic::stl { @@ -37,8 +37,8 @@ namespace OpenVic::stl { static constexpr allocate_tag_t allocate_tag {}; OV_ALWAYS_INLINE cow_vector(allocate_tag_t, size_t reserve) : _data(_allocate_payload(reserve)) {} - OV_ALWAYS_INLINE cow_vector(allocate_tag_t, Allocator const& alloc, size_t reserve) - : alloc(alloc), _data(_allocate_payload(reserve)) {} + OV_ALWAYS_INLINE cow_vector(allocate_tag_t, Allocator const& alloc, size_t reserve) : + alloc(alloc), _data(_allocate_payload(reserve)) {} [[noreturn]] void _abort_on_out_of_range(const char* func_name, const char* var_name, size_t var, size_t size) const { OV_THROW_OUT_OF_RANGE("cow_vector", func_name, var_name, var, size); @@ -65,19 +65,19 @@ namespace OpenVic::stl { _data->array_end = uninitialized_default_n(_data->array, count, this->alloc); } - OV_ALWAYS_INLINE cow_vector(size_type count, const T& value, Allocator const& alloc = Allocator()) - : cow_vector(count, alloc) { + OV_ALWAYS_INLINE cow_vector(size_type count, const T& value, Allocator const& alloc = Allocator()) : + cow_vector(count, alloc) { _data->array_end = uninitialized_fill_n(_data->array, count, value, this->alloc); } template - OV_ALWAYS_INLINE cow_vector(InputIt first, InputIt last, const Allocator& alloc = Allocator()) - : cow_vector(allocate_tag, alloc, _validate_iterator_difference(last - first)) { + OV_ALWAYS_INLINE cow_vector(InputIt first, InputIt last, const Allocator& alloc = Allocator()) : + cow_vector(allocate_tag, alloc, _validate_iterator_difference(last - first)) { _data->array_end = uninitialized_copy(first, last, _data->array, this->alloc); } - OV_ALWAYS_INLINE cow_vector(cow_vector const& other) - : alloc(allocator_traits::select_on_container_copy_construction(other.alloc)), _data(other._data) { + OV_ALWAYS_INLINE cow_vector(cow_vector const& other) : + alloc(allocator_traits::select_on_container_copy_construction(other.alloc)), _data(other._data) { if (_data) { ++_data->count; } @@ -87,8 +87,8 @@ namespace OpenVic::stl { other._data = nullptr; } - OV_ALWAYS_INLINE cow_vector(cow_vector const& other, std::type_identity_t const& alloc) - : cow_vector(other.begin(), other.end(), alloc) {} + OV_ALWAYS_INLINE cow_vector(cow_vector const& other, std::type_identity_t const& alloc) : + cow_vector(other.begin(), other.end(), alloc) {} OV_ALWAYS_INLINE cow_vector(cow_vector&& other, std::type_identity_t const& alloc) : alloc(alloc) { if constexpr (allocator_traits::is_always_equal::value) { @@ -105,8 +105,8 @@ namespace OpenVic::stl { } } - OV_ALWAYS_INLINE cow_vector(std::initializer_list init, Allocator const& alloc = Allocator()) - : cow_vector(init.begin(), init.end(), alloc) {} + OV_ALWAYS_INLINE cow_vector(std::initializer_list init, Allocator const& alloc = Allocator()) : + cow_vector(init.begin(), init.end(), alloc) {} OV_ALWAYS_INLINE ~cow_vector() { if (_data && --_data->count == 0) { @@ -128,8 +128,9 @@ namespace OpenVic::stl { cow_vector tmp = std::move(x); writer& tmp_writer = *reinterpret_cast(&tmp); - if constexpr (allocator_traits::propagate_on_container_move_assignment::value || - allocator_traits::is_always_equal::value) { + if constexpr ( + allocator_traits::propagate_on_container_move_assignment::value || allocator_traits::is_always_equal::value + ) { self_writer.swap(tmp_writer); } else if (alloc == x.alloc) { self_writer.swap(tmp_writer); @@ -139,8 +140,9 @@ namespace OpenVic::stl { tmp_writer = tmp.write(); self_writer._assign_aux( - std::make_move_iterator(tmp_writer.begin()), std::make_move_iterator(tmp_writer.end()), - std::random_access_iterator_tag() + std::make_move_iterator(tmp_writer.begin()), + std::make_move_iterator(tmp_writer.end()), + std::random_access_iterator_tag() ); tmp_writer.clear(); } @@ -1101,8 +1103,9 @@ namespace OpenVic::stl { }; template - inline constexpr cow_vector::size_type cow_vector::payload::content_size = - std::max(1ul, (sizeof(payload) - sizeof(array)) / sizeof(T)); + inline constexpr cow_vector::size_type cow_vector::payload::content_size = std::max( + 1ul, (sizeof(payload) - sizeof(array)) / sizeof(T) + ); template [[nodiscard]] inline bool operator==(cow_vector const& x, cow_vector const& y) { @@ -1115,7 +1118,7 @@ namespace OpenVic::stl { } static_assert( - sizeof(cow_vector) == sizeof(cow_vector::writer), "cow_vector must always be the same size as it's writer" + sizeof(cow_vector) == sizeof(cow_vector::writer), "cow_vector must always be the same size as it's writer" ); } diff --git a/src/openvic-simulation/core/stl/containers/FixedVector.hpp b/src/openvic-simulation/core/stl/containers/FixedVector.hpp index f3ca5784a..d2a81b300 100644 --- a/src/openvic-simulation/core/stl/containers/FixedVector.hpp +++ b/src/openvic-simulation/core/stl/containers/FixedVector.hpp @@ -8,14 +8,14 @@ #include #include "openvic-simulation/core/Assert.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" namespace OpenVic::stl { // fixed capacity vector // supports immovable + uncopyable value types - template > + template> class FixedVector { public: using const_reference = T const&; @@ -24,6 +24,7 @@ namespace OpenVic::stl { using size_type = SizeT; using value_type = T; using allocator_type = Allocator; + private: using allocator_traits = std::allocator_traits; size_type _max_size; @@ -32,144 +33,132 @@ namespace OpenVic::stl { T* _data_start_ptr; static constexpr T* allocate(Allocator allocator, const size_type capacity) { - return capacity > size_type{} - ? allocator_traits::allocate(allocator, get_index_as_size_t(capacity)) - : nullptr; + return capacity > size_type {} ? allocator_traits::allocate(allocator, get_index_as_size_t(capacity)) : nullptr; } public: - constexpr size_type size() const { return _size; } - constexpr size_type capacity() const { return _max_size; } - constexpr size_type max_size() const { return _max_size; } - constexpr T* data() { return _data_start_ptr; } - constexpr T const* data() const { return _data_start_ptr; } - constexpr bool empty() const { return _size == size_type{}; } + constexpr size_type size() const { + return _size; + } + constexpr size_type capacity() const { + return _max_size; + } + constexpr size_type max_size() const { + return _max_size; + } + constexpr T* data() { + return _data_start_ptr; + } + constexpr T const* data() const { + return _data_start_ptr; + } + constexpr bool empty() const { + return _size == size_type {}; + } - constexpr explicit FixedVector(const create_empty_t t) noexcept : FixedVector(t, size_type{}) {} - constexpr explicit FixedVector(const create_empty_t, const size_type capacity, std::type_identity_t const& alloc) - : _max_size(capacity), - _size(size_type{}), - _allocator(alloc), - _data_start_ptr(allocate(_allocator, capacity)) {} + constexpr explicit FixedVector(const create_empty_t t) noexcept : FixedVector(t, size_type {}) {} + constexpr explicit FixedVector( + const create_empty_t, const size_type capacity, std::type_identity_t const& alloc + ) : _max_size(capacity), _size(size_type {}), _allocator(alloc), _data_start_ptr(allocate(_allocator, capacity)) {} /** - * @brief Creates an uninitialised vector with fixed capacity - */ - constexpr explicit FixedVector(const create_empty_t, const size_type capacity) - : FixedVector(create_empty, capacity, Allocator()) {} + * @brief Creates an uninitialised vector with fixed capacity + */ + constexpr explicit FixedVector(const create_empty_t, const size_type capacity) : + FixedVector(create_empty, capacity, Allocator()) {} - constexpr FixedVector(const size_type size, T const& value_for_all_indices) - : FixedVector(size, value_for_all_indices, Allocator()) {} + constexpr FixedVector(const size_type size, T const& value_for_all_indices) : + FixedVector(size, value_for_all_indices, Allocator()) {} - constexpr FixedVector(const size_type size, T const& value_for_all_indices, std::type_identity_t const& alloc) - : _max_size(size), - _size(size), - _allocator(alloc), - _data_start_ptr(allocate(_allocator, size)) { + constexpr FixedVector( + const size_type size, T const& value_for_all_indices, std::type_identity_t const& alloc + ) : _max_size(size), _size(size), _allocator(alloc), _data_start_ptr(allocate(_allocator, size)) { std::fill(_data_start_ptr, _data_start_ptr + get_index_as_size_t(size), value_for_all_indices); } constexpr FixedVector(const generate_values_t, const size_type size, std::type_identity_t const& alloc) - requires ( - std::constructible_from - || std::is_default_constructible_v - ) : FixedVector( - size, - [](const size_type i)->value_type { - if constexpr (std::constructible_from) { - return value_type{i}; - } else { - return value_type{}; - } - } - ) {} + requires(std::constructible_from || std::is_default_constructible_v) + : + FixedVector(size, [](const size_type i) -> value_type { + if constexpr (std::constructible_from) { + return value_type { i }; + } else { + return value_type {}; + } + }) {} constexpr FixedVector(const generate_values_t, const size_type size) - requires ( - std::constructible_from - || std::is_default_constructible_v - ) : FixedVector(generate_values, size, Allocator()) {} + requires(std::constructible_from || std::is_default_constructible_v) + : FixedVector(generate_values, size, Allocator()) {} - //Generator (size_type i) -> U (where T is constructable from U) + // Generator (size_type i) -> U (where T is constructable from U) template // The generator must NOT return a tuple - requires (!specialization_of>, std::tuple>) - // The type must be constructible from the generator's single return value - && std::constructible_from()(std::declval()))> - constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator) - : FixedVector(size, std::forward(generator), Allocator()) { - } + requires(!specialization_of>, std::tuple>) + // The type must be constructible from the generator's single return value + && std::constructible_from()(std::declval()))> + constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator) : + FixedVector(size, std::forward(generator), Allocator()) {} - //Generator (size_type i) -> U (where T is constructable from U) + // Generator (size_type i) -> U (where T is constructable from U) template // The generator must NOT return a tuple - requires (!specialization_of>, std::tuple>) - // The type must be constructible from the generator's single return value - && std::constructible_from()(std::declval()))> - constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator, std::type_identity_t const& alloc) - : _max_size(size), - _size(size_type{}), - _allocator(alloc), - _data_start_ptr(allocate(_allocator, size)) { + requires(!specialization_of>, std::tuple>) + // The type must be constructible from the generator's single return value + && std::constructible_from()(std::declval()))> + constexpr FixedVector( + const size_type size, GeneratorTemplateType&& generator, std::type_identity_t const& alloc + ) : _max_size(size), _size(size_type {}), _allocator(alloc), _data_start_ptr(allocate(_allocator, size)) { for (size_type i {}; i < size; ++i) { - allocator_traits::construct( - _allocator, - begin()+get_index_as_size_t(i), - generator(i) - ); + allocator_traits::construct(_allocator, begin() + get_index_as_size_t(i), generator(i)); ++_size; } } - //Generator (size_type i) -> std::tuple (where T is constructable from Args) + // Generator (size_type i) -> std::tuple (where T is constructable from Args) template // The generator must return a tuple requires specialization_of>, std::tuple> - // The tuple must be constructible into a T - && requires(GeneratorTemplateType&& generator) { - { - std::apply( - [](auto&&... args) { - T obj{std::forward(args)...}; - }, - generator(std::declval()) - ) - }; - } - constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator) - : FixedVector(size, std::forward(generator), Allocator()) { - } + // The tuple must be constructible into a T + && requires(GeneratorTemplateType&& generator) { + { + std::apply( + [](auto&&... args) { + T obj { std::forward(args)... }; + }, + generator(std::declval()) + ) + }; + } + constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator) : + FixedVector(size, std::forward(generator), Allocator()) {} - //Generator (size_type i) -> std::tuple (where T is constructable from Args) + // Generator (size_type i) -> std::tuple (where T is constructable from Args) template // The generator must return a tuple requires specialization_of>, std::tuple> - // The tuple must be constructible into a T - && requires(GeneratorTemplateType&& generator) { - { - std::apply( - [](auto&&... args) { - T obj{std::forward(args)...}; - }, - generator(std::declval()) - ) - }; - } - constexpr FixedVector(const size_type size, GeneratorTemplateType&& generator, std::type_identity_t const& alloc) - : _max_size(size), - _size(size_type{}), - _allocator(alloc), - _data_start_ptr(allocate(_allocator, size)) { + // The tuple must be constructible into a T + && requires(GeneratorTemplateType&& generator) { + { + std::apply( + [](auto&&... args) { + T obj { std::forward(args)... }; + }, + generator(std::declval()) + ) + }; + } + constexpr FixedVector( + const size_type size, GeneratorTemplateType&& generator, std::type_identity_t const& alloc + ) : _max_size(size), _size(size_type {}), _allocator(alloc), _data_start_ptr(allocate(_allocator, size)) { for (size_type i {}; i < size; ++i) { std::apply( - [this, i](auto&&... args) { - allocator_traits::construct( - _allocator, - begin()+get_index_as_size_t(i), - std::forward(args)... - ); - }, - generator(i) + [this, i](auto&&... args) { + allocator_traits::construct( + _allocator, begin() + get_index_as_size_t(i), std::forward(args)... + ); + }, + generator(i) ); ++_size; } @@ -202,24 +191,48 @@ namespace OpenVic::stl { using iterator = T*; using const_iterator = T const*; - constexpr iterator begin() OV_LIFETIME_BOUND { return _data_start_ptr; } - constexpr const_iterator begin() const OV_LIFETIME_BOUND { return _data_start_ptr; } - constexpr const_iterator cbegin() const OV_LIFETIME_BOUND { return _data_start_ptr; } + constexpr iterator begin() OV_LIFETIME_BOUND { + return _data_start_ptr; + } + constexpr const_iterator begin() const OV_LIFETIME_BOUND { + return _data_start_ptr; + } + constexpr const_iterator cbegin() const OV_LIFETIME_BOUND { + return _data_start_ptr; + } - constexpr iterator end() OV_LIFETIME_BOUND { return begin() + get_index_as_size_t(_size); } - constexpr const_iterator end() const OV_LIFETIME_BOUND { return begin() + get_index_as_size_t(_size); } - constexpr const_iterator cend() const OV_LIFETIME_BOUND { return cbegin() + get_index_as_size_t(_size); } + constexpr iterator end() OV_LIFETIME_BOUND { + return begin() + get_index_as_size_t(_size); + } + constexpr const_iterator end() const OV_LIFETIME_BOUND { + return begin() + get_index_as_size_t(_size); + } + constexpr const_iterator cend() const OV_LIFETIME_BOUND { + return cbegin() + get_index_as_size_t(_size); + } using reverse_iterator = std::reverse_iterator; using const_reverse_iterator = std::reverse_iterator; - constexpr reverse_iterator rbegin() OV_LIFETIME_BOUND { return reverse_iterator(end()); } - constexpr const_reverse_iterator rbegin() const OV_LIFETIME_BOUND { return const_reverse_iterator(end()); } - constexpr const_reverse_iterator crbegin() const OV_LIFETIME_BOUND { return const_reverse_iterator(end()); } + constexpr reverse_iterator rbegin() OV_LIFETIME_BOUND { + return reverse_iterator(end()); + } + constexpr const_reverse_iterator rbegin() const OV_LIFETIME_BOUND { + return const_reverse_iterator(end()); + } + constexpr const_reverse_iterator crbegin() const OV_LIFETIME_BOUND { + return const_reverse_iterator(end()); + } - constexpr reverse_iterator rend() OV_LIFETIME_BOUND { return reverse_iterator(begin()); } - constexpr const_reverse_iterator rend() const OV_LIFETIME_BOUND { return const_reverse_iterator(begin()); } - constexpr const_reverse_iterator crend() const OV_LIFETIME_BOUND { return const_reverse_iterator(begin()); } + constexpr reverse_iterator rend() OV_LIFETIME_BOUND { + return reverse_iterator(begin()); + } + constexpr const_reverse_iterator rend() const OV_LIFETIME_BOUND { + return const_reverse_iterator(begin()); + } + constexpr const_reverse_iterator crend() const OV_LIFETIME_BOUND { + return const_reverse_iterator(begin()); + } constexpr T& operator[](const size_type typed_index) OV_LIFETIME_BOUND { OV_HARDEN_ASSERT_ACCESS(typed_index, "operator[]"); @@ -240,44 +253,34 @@ namespace OpenVic::stl { } constexpr T& back() OV_LIFETIME_BOUND { OV_HARDEN_ASSERT_NONEMPTY("back"); - return *(end()-1); + return *(end() - 1); } constexpr T const& back() const OV_LIFETIME_BOUND { OV_HARDEN_ASSERT_NONEMPTY("back"); - return *(cend()-1); + return *(cend() - 1); } - template + template constexpr iterator emplace_back(Args&&... args) OV_LIFETIME_BOUND { if (_size >= _max_size) { return end(); } - allocator_traits::construct( - _allocator, - begin() + get_index_as_size_t(_size), - std::forward(args)... - ); + allocator_traits::construct(_allocator, begin() + get_index_as_size_t(_size), std::forward(args)...); ++_size; - return end()-1; + return end() - 1; } constexpr void pop_back() { - if (_size > size_type{}) { - allocator_traits::destroy( - _allocator, - end() - 1 - ); + if (_size > size_type {}) { + allocator_traits::destroy(_allocator, end() - 1); --_size; } } constexpr void clear() { - for (iterator it = end(); it != begin(); ) { + for (iterator it = end(); it != begin();) { --it; - allocator_traits::destroy( - _allocator, - it - ); + allocator_traits::destroy(_allocator, it); } _size = {}; } diff --git a/src/openvic-simulation/core/stl/containers/RingBuffer.hpp b/src/openvic-simulation/core/stl/containers/RingBuffer.hpp index c886df666..e8a126086 100644 --- a/src/openvic-simulation/core/stl/containers/RingBuffer.hpp +++ b/src/openvic-simulation/core/stl/containers/RingBuffer.hpp @@ -45,8 +45,8 @@ namespace OpenVic::stl { using iterator_category = std::random_access_iterator_tag; constexpr _iterator() noexcept = default; - _iterator(pointer data, const size_type ring_offset, const size_type ring_index, const size_type ring_capacity) - : _data(data), _offset(ring_offset), _index(ring_index), _capacity(ring_capacity) {} + _iterator(pointer data, const size_type ring_offset, const size_type ring_index, const size_type ring_capacity) : + _data(data), _offset(ring_offset), _index(ring_index), _capacity(ring_capacity) {} constexpr operator _iterator() const { return _iterator(_data, _offset, _index, _capacity); @@ -151,8 +151,8 @@ namespace OpenVic::stl { _deallocate(); } - RingBuffer(RingBuffer const& other) - : RingBuffer(other, allocator_traits::select_on_container_copy_construction(other._allocator)) {} + RingBuffer(RingBuffer const& other) : + RingBuffer(other, allocator_traits::select_on_container_copy_construction(other._allocator)) {} RingBuffer(RingBuffer const& other, allocator_type const& allocator) : RingBuffer(other._capacity, allocator) { clear(); @@ -190,8 +190,8 @@ namespace OpenVic::stl { } RingBuffer& operator=(RingBuffer&& other) noexcept( - allocator_traits::propagate_on_container_move_assignment::value || - std::is_nothrow_move_constructible::value + allocator_traits::propagate_on_container_move_assignment::value || + std::is_nothrow_move_constructible::value ) { if (allocator_traits::propagate_on_container_move_assignment::value || _allocator == other._allocator) { // We're either getting the other's allocator or they're already the same, diff --git a/src/openvic-simulation/core/stl/containers/StackString.hpp b/src/openvic-simulation/core/stl/containers/StackString.hpp index 263913e45..5869b705b 100644 --- a/src/openvic-simulation/core/stl/containers/StackString.hpp +++ b/src/openvic-simulation/core/stl/containers/StackString.hpp @@ -6,8 +6,8 @@ #include #include "openvic-simulation/core/Assert.hpp" -#include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/memory/String.hpp" namespace OpenVic { template diff --git a/src/openvic-simulation/core/stl/containers/TypedSpan.hpp b/src/openvic-simulation/core/stl/containers/TypedSpan.hpp index ec76bc582..1804ccbb2 100644 --- a/src/openvic-simulation/core/stl/containers/TypedSpan.hpp +++ b/src/openvic-simulation/core/stl/containers/TypedSpan.hpp @@ -9,21 +9,14 @@ #include "openvic-simulation/core/template/Concepts.hpp" namespace OpenVic { - template< - is_strongly_typed IndexType, - typename ValueType, - size_t _Extent = std::dynamic_extent - > + template struct TypedSpan : public forwardable_span { public: using forwardable_span::forwardable_span; template - constexpr TypedSpan(OtherT& other) - : forwardable_span( - other.data(), - get_index_as_size_t(other.size()) - ) { } + constexpr TypedSpan(OtherT& other) : + forwardable_span(other.data(), get_index_as_size_t(other.size())) {} [[nodiscard]] constexpr IndexType size() const { return IndexType(forwardable_span::size()); @@ -35,7 +28,7 @@ namespace OpenVic { } [[nodiscard]] constexpr operator TypedSpan() const { - return TypedSpan{*this}; + return TypedSpan { *this }; } }; } diff --git a/src/openvic-simulation/core/string/CharConv.hpp b/src/openvic-simulation/core/string/CharConv.hpp index a952f1a6c..3d6dd8425 100644 --- a/src/openvic-simulation/core/string/CharConv.hpp +++ b/src/openvic-simulation/core/string/CharConv.hpp @@ -20,10 +20,10 @@ namespace OpenVic { constexpr unsigned char digit_from_byte[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, - 33, 34, 35, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, @@ -81,7 +81,7 @@ namespace OpenVic { } if (value < risky_val // never overflows - || (value == risky_val && digit <= max_digit)) { // overflows for certain digits + || (value == risky_val && digit <= max_digit)) { // overflows for certain digits value = static_cast(value * base + digit); } else { // value > risky_val always overflows overflowed = true; // keep going, next still needs to be updated, value is now irrelevant @@ -116,10 +116,10 @@ namespace OpenVic { } constexpr char digits[] = // - { // + { // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' - }; + }; static_assert(std::size(digits) == 36); using unsigned_type = std::make_unsigned_t; @@ -149,7 +149,7 @@ namespace OpenVic { constexpr bool use_chunks = sizeof(unsigned_type) > sizeof(size_t); if constexpr (use_chunks) { // For 64-bit numbers on 32-bit platforms, work in chunks to avoid 64-bit - // divisions. + // divisions. while (value > 0xFFFF'FFFFU) { // Performance note: Ryu's division workaround would be faster here. unsigned long chunk = static_cast(value % 1'000'000'000); @@ -250,8 +250,9 @@ namespace OpenVic { * still starts with "0", otherwise 10. The std::from_chars_result return value is used to report whether * or not conversion was successful. */ - [[nodiscard]] inline constexpr std::from_chars_result - string_to_uint64(char const* str, char const* const end, uint64_t& value, int base = 10) { + [[nodiscard]] inline constexpr std::from_chars_result string_to_uint64( + char const* str, char const* const end, uint64_t& value, int base = 10 + ) { // If base is zero, base is determined by the string prefix. if (base == 0) { if (str && *str == '0') { diff --git a/src/openvic-simulation/core/string/StringLiteral.hpp b/src/openvic-simulation/core/string/StringLiteral.hpp index 8b5c1687e..7075163cc 100644 --- a/src/openvic-simulation/core/string/StringLiteral.hpp +++ b/src/openvic-simulation/core/string/StringLiteral.hpp @@ -6,8 +6,8 @@ #include #include -#include "openvic-simulation/core/stl/BasicIterator.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/stl/BasicIterator.hpp" namespace OpenVic { template @@ -188,7 +188,7 @@ namespace OpenVic { template [[nodiscard]] constexpr decltype(auto) substr() // - const noexcept { + const noexcept { static_assert(pos <= size(), "pos must be less than or equal to size"); constexpr size_type result_size = std::min(count, size() - pos) + 1; @@ -259,7 +259,7 @@ namespace OpenVic { template [[nodiscard]] constexpr string_literal operator+( // - string_literal const& other + string_literal const& other ) const noexcept { string_literal result; for (size_type i = 0u; i != size(); i++) { @@ -274,7 +274,7 @@ namespace OpenVic { template [[nodiscard]] constexpr string_literal operator+( // - const value_type (&rhs)[N2] + const value_type (&rhs)[N2] ) const noexcept { return *this + _to_string(rhs); } diff --git a/src/openvic-simulation/core/string/Utility.hpp b/src/openvic-simulation/core/string/Utility.hpp index cb7cb274e..892dba1b5 100644 --- a/src/openvic-simulation/core/string/Utility.hpp +++ b/src/openvic-simulation/core/string/Utility.hpp @@ -174,7 +174,7 @@ namespace OpenVic { if constexpr (next_value != 0) { return append_sequence( - integer_to_string_sequence(), std::integer_sequence {} + integer_to_string_sequence(), std::integer_sequence {} ); } else { return std::integer_sequence {}; diff --git a/src/openvic-simulation/core/template/Concepts.hpp b/src/openvic-simulation/core/template/Concepts.hpp index d21d92c12..bad77b8fd 100644 --- a/src/openvic-simulation/core/template/Concepts.hpp +++ b/src/openvic-simulation/core/template/Concepts.hpp @@ -41,15 +41,17 @@ namespace OpenVic { concept not_same_as = !std::same_as; template> - concept move_insertable_allocator_for = - requires(Allocator& alloc, Value* value, T move) { std::allocator_traits::construct(alloc, value, move); }; + concept move_insertable_allocator_for = requires(Allocator& alloc, Value* value, T move) { + std::allocator_traits::construct(alloc, value, move); + }; template struct enable_copy_insertable : std::false_type {}; template - concept copy_insertable_allocator = enable_copy_insertable::value || - move_insertable_allocator_for; + concept copy_insertable_allocator = + enable_copy_insertable::value || + move_insertable_allocator_for; template struct enable_copy_insertable> : std::is_copy_constructible {}; @@ -59,7 +61,7 @@ namespace OpenVic { template concept move_insertable_allocator = - enable_move_insertable::value || move_insertable_allocator_for; + enable_move_insertable::value || move_insertable_allocator_for; template struct enable_move_insertable> : std::is_move_constructible {}; @@ -111,12 +113,11 @@ namespace OpenVic { concept is_strongly_typed = derived_from_specialization_of; template - concept has_index = requires { typename T::index_t; } && - is_strongly_typed && requires { - static_cast( - static_cast().index)>>(std::declval().index) - ); - }; + concept has_index = requires { typename T::index_t; } && is_strongly_typed && requires { + static_cast( + static_cast().index)>>(std::declval().index) + ); + }; // helper to avoid error 'index_t': is not a member of T template @@ -193,7 +194,7 @@ namespace OpenVic { template> concept multipliable = requires(Lhs const& lhs, Rhs const& rhs) { - { lhs* rhs } -> std::convertible_to; + { lhs * rhs } -> std::convertible_to; }; template> @@ -231,4 +232,4 @@ namespace OpenVic { concept strict_regular_invocable_r = std::regular_invocable && requires(F f, Args&&... args) { { f(static_cast(args)...) } -> std::same_as; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/template/EnumBitfield.hpp b/src/openvic-simulation/core/template/EnumBitfield.hpp index 87534490f..37cb177e7 100644 --- a/src/openvic-simulation/core/template/EnumBitfield.hpp +++ b/src/openvic-simulation/core/template/EnumBitfield.hpp @@ -4,10 +4,10 @@ namespace OpenVic { template - struct is_scoped_enum final : std::bool_constant < requires { + struct is_scoped_enum final : std::bool_constant < requires { requires std::is_enum_v; requires !std::is_convertible_v>; - } > {}; + }> {}; template inline constexpr bool is_scoped_enum_v = is_scoped_enum::value; @@ -16,8 +16,7 @@ namespace OpenVic { concept IsScopedEnum = is_scoped_enum_v; template - struct enable_bitfield final : std::false_type { - }; + struct enable_bitfield final : std::false_type {}; template inline constexpr bool enable_bitfield_v = enable_bitfield::value; diff --git a/src/openvic-simulation/core/template/Functional.hpp b/src/openvic-simulation/core/template/Functional.hpp index e24d926a4..7cfb73a84 100644 --- a/src/openvic-simulation/core/template/Functional.hpp +++ b/src/openvic-simulation/core/template/Functional.hpp @@ -6,12 +6,12 @@ // bug fix for std::hash & std::equal_to to work with std::reference_wrapper namespace std { - template + template struct hash> { using BaseType = std::remove_cv_t; [[nodiscard]] size_t operator()(T const& val) const noexcept { - return std::hash{}(val); + return std::hash {}(val); } }; } @@ -21,29 +21,27 @@ namespace concepts { namespace detail { template constexpr bool _is_ref_wrapper = false; - + template constexpr bool _is_ref_wrapper> = true; - + template - concept _ref_wrap_common_reference_with = _is_ref_wrapper - && requires { typename std::common_reference_t; } - && std::convertible_to>; + concept _ref_wrap_common_reference_with = _is_ref_wrapper && requires { + typename std::common_reference_t; + } && std::convertible_to>; } template class RQual, template class TQual> - requires detail::_ref_wrap_common_reference_with, TQual> - && (!detail::_ref_wrap_common_reference_with, RQual>) - struct basic_common_reference - { + requires detail::_ref_wrap_common_reference_with, TQual> && + (!detail::_ref_wrap_common_reference_with, RQual>) + struct basic_common_reference { using type = std::common_reference_t>; }; template class TQual, template class RQual> - requires detail::_ref_wrap_common_reference_with, TQual> - && (!detail::_ref_wrap_common_reference_with, RQual>) - struct basic_common_reference - { + requires detail::_ref_wrap_common_reference_with, TQual> && + (!detail::_ref_wrap_common_reference_with, RQual>) + struct basic_common_reference { using type = std::common_reference_t>; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/core/ui/TextFormat.hpp b/src/openvic-simulation/core/ui/TextFormat.hpp index 453c11e1d..f09b30b1a 100644 --- a/src/openvic-simulation/core/ui/TextFormat.hpp +++ b/src/openvic-simulation/core/ui/TextFormat.hpp @@ -3,6 +3,9 @@ namespace OpenVic { enum class text_format_t : uint8_t { - left, centre, right, justified + left, + centre, + right, + justified }; } diff --git a/src/openvic-simulation/country/CountryDefinition.cpp b/src/openvic-simulation/country/CountryDefinition.cpp index 207e0fd0f..1893421fa 100644 --- a/src/openvic-simulation/country/CountryDefinition.cpp +++ b/src/openvic-simulation/country/CountryDefinition.cpp @@ -4,11 +4,11 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/core/memory/FixedVector.hpp" #include "openvic-simulation/core/object/Colour.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/politics/Government.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/politics/PartyPolicy.hpp" @@ -21,32 +21,32 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; CountryDefinition::CountryDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - GraphicalCultureType const& new_graphical_culture, - IdentifierRegistry&& new_parties, - unit_names_map_t&& new_unit_names, - bool new_is_dynamic_tag, - government_colour_map_t&& new_alternative_colours, - colour_t new_primary_unit_colour, - colour_t new_secondary_unit_colour, - colour_t new_tertiary_unit_colour -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - graphical_culture { new_graphical_culture }, - parties { std::move(new_parties) }, - unit_names { std::move(new_unit_names) }, - is_dynamic_tag { new_is_dynamic_tag }, - alternative_colours { std::move(new_alternative_colours) }, - primary_unit_colour { new_primary_unit_colour }, - secondary_unit_colour { new_secondary_unit_colour }, - tertiary_unit_colour { new_tertiary_unit_colour } {} + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + GraphicalCultureType const& new_graphical_culture, + IdentifierRegistry&& new_parties, + unit_names_map_t&& new_unit_names, + bool new_is_dynamic_tag, + government_colour_map_t&& new_alternative_colours, + colour_t new_primary_unit_colour, + colour_t new_secondary_unit_colour, + colour_t new_tertiary_unit_colour +) : + HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, + graphical_culture { new_graphical_culture }, parties { std::move(new_parties) }, unit_names { std::move(new_unit_names) }, + is_dynamic_tag { new_is_dynamic_tag }, alternative_colours { std::move(new_alternative_colours) }, + primary_unit_colour { new_primary_unit_colour }, secondary_unit_colour { new_secondary_unit_colour }, + tertiary_unit_colour { new_tertiary_unit_colour } {} bool CountryDefinitionManager::add_country( - std::string_view identifier, colour_t colour, GraphicalCultureType const* graphical_culture, - IdentifierRegistry&& parties, CountryDefinition::unit_names_map_t&& unit_names, bool dynamic_tag, - CountryDefinition::government_colour_map_t&& alternative_colours + std::string_view identifier, + colour_t colour, + GraphicalCultureType const* graphical_culture, + IdentifierRegistry&& parties, + CountryDefinition::unit_names_map_t&& unit_names, + bool dynamic_tag, + CountryDefinition::government_colour_map_t&& alternative_colours ) { if (identifier.empty()) { spdlog::error_s("Invalid country identifier - empty!"); @@ -54,7 +54,7 @@ bool CountryDefinitionManager::add_country( } if (!valid_basic_identifier(identifier)) { spdlog::error_s( - "Invalid country identifier: {} (can only contain alphanumeric characters and underscores)", identifier + "Invalid country identifier: {} (can only contain alphanumeric characters and underscores)", identifier ); return false; } @@ -66,56 +66,61 @@ bool CountryDefinitionManager::add_country( static constexpr colour_t default_colour = colour_t::fill_as(colour_t::max_value); return country_definitions.emplace_item( - identifier, // - identifier, colour, index_from_count(get_country_definition_count()), *graphical_culture, - std::move(parties), std::move(unit_names), dynamic_tag, std::move(alternative_colours), - /* Default to country colour for the chest and grey for the others. Update later if necessary. */ - colour, default_colour, default_colour + identifier, // + identifier, + colour, + index_from_count(get_country_definition_count()), + *graphical_culture, + std::move(parties), + std::move(unit_names), + dynamic_tag, + std::move(alternative_colours), + /* Default to country colour for the chest and grey for the others. Update later if necessary. */ + colour, + default_colour, + default_colour ); } bool CountryDefinitionManager::load_countries( - DefinitionManager const& definition_manager, Dataloader const& dataloader, ast::NodeCPtr root + DefinitionManager const& definition_manager, Dataloader const& dataloader, ast::NodeCPtr root ) { static constexpr std::string_view common_dir = "common/"; bool is_dynamic = false; - const bool ret = expect_dictionary_reserve_length( - country_definitions, - [this, &definition_manager, &is_dynamic, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { - if (key == "dynamic_tags") { - return expect_bool([&is_dynamic](bool val) -> bool { - if (val == is_dynamic) { - spdlog::warn_s("Redundant \"is_dynamic\", already {}", val ? "true" : "false"); - } else { - if (is_dynamic) { - spdlog::warn_s("Changing \"is_dynamic\" back to false"); - } - is_dynamic = val; - } - return true; - })(value); - } - if (expect_string( - [this, &definition_manager, is_dynamic, &dataloader, &key](std::string_view filepath) -> bool { - if (load_country_data_file( - definition_manager, key, is_dynamic, - Dataloader::parse_defines( - dataloader.lookup_file(append_string_views(common_dir, filepath)) - ).get_file_node() - )) { - return true; - } - spdlog::critical_s("Failed to load country data file: {}", filepath); - return false; - } - )(value)) { - return true; - } - spdlog::critical_s("Failed to load country: {}", key); - return false; - } - )(root); + const bool ret = + expect_dictionary_reserve_length(country_definitions, [this, &definition_manager, &is_dynamic, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { + if (key == "dynamic_tags") { + return expect_bool([&is_dynamic](bool val) -> bool { + if (val == is_dynamic) { + spdlog::warn_s("Redundant \"is_dynamic\", already {}", val ? "true" : "false"); + } else { + if (is_dynamic) { + spdlog::warn_s("Changing \"is_dynamic\" back to false"); + } + is_dynamic = val; + } + return true; + })(value); + } + if (expect_string([this, &definition_manager, is_dynamic, &dataloader, &key](std::string_view filepath) -> bool { + if (load_country_data_file( + definition_manager, + key, + is_dynamic, + Dataloader::parse_defines(dataloader.lookup_file(append_string_views(common_dir, filepath))) + .get_file_node() + )) { + return true; + } + spdlog::critical_s("Failed to load country data file: {}", filepath); + return false; + })(value)) { + return true; + } + spdlog::critical_s("Failed to load country: {}", key); + return false; + })(root); lock_country_definitions(); return ret; } @@ -137,15 +142,14 @@ bool CountryDefinitionManager::load_country_colours(ast::NodeCPtr root) { } node_callback_t CountryDefinitionManager::load_country_party( - PoliticsManager const& politics_manager, IdentifierRegistry& country_parties + PoliticsManager const& politics_manager, IdentifierRegistry& country_parties ) const { return [&politics_manager, &country_parties](ast::NodeCPtr value) -> bool { std::string_view party_name; Date start_date, end_date; Ideology const* ideology = nullptr; memory::FixedVector policies { - party_policy_group_index_t(politics_manager.get_issue_manager().get_party_policy_group_count()), - nullptr + party_policy_group_index_t(politics_manager.get_issue_manager().get_party_policy_group_count()), nullptr }; bool ret = expect_dictionary_keys_and_default( @@ -194,9 +198,7 @@ node_callback_t CountryDefinitionManager::load_country_party( } ret &= country_parties.emplace_item( - party_name, - duplicate_warning_callback, - party_name, start_date, end_date, ideology, std::move(policies) + party_name, duplicate_warning_callback, party_name, start_date, end_date, ideology, std::move(policies) ); return ret; @@ -204,7 +206,7 @@ node_callback_t CountryDefinitionManager::load_country_party( } bool CountryDefinitionManager::load_country_data_file( - DefinitionManager const& definition_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root + DefinitionManager const& definition_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root ) { colour_t colour; GraphicalCultureType const* graphical_culture; @@ -235,7 +237,7 @@ bool CountryDefinitionManager::load_country_data_file( )(root); ret &= add_country( - name, colour, graphical_culture, std::move(parties), std::move(unit_names), is_dynamic, std::move(alternative_colours) + name, colour, graphical_culture, std::move(parties), std::move(unit_names), is_dynamic, std::move(alternative_colours) ); return ret; } diff --git a/src/openvic-simulation/country/CountryDefinition.hpp b/src/openvic-simulation/country/CountryDefinition.hpp index d61a62625..e5508cb7d 100644 --- a/src/openvic-simulation/country/CountryDefinition.hpp +++ b/src/openvic-simulation/country/CountryDefinition.hpp @@ -24,7 +24,7 @@ namespace OpenVic { /* Generic information about a TAG */ struct CountryDefinition : HasIdentifierAndColour, HasIndex { friend struct CountryDefinitionManager; - + using unit_names_map_t = ordered_map; using government_colour_map_t = ordered_map; @@ -49,10 +49,17 @@ namespace OpenVic { } CountryDefinition( - std::string_view new_identifier, colour_t new_colour, index_t new_index, - GraphicalCultureType const& new_graphical_culture, IdentifierRegistry&& new_parties, - unit_names_map_t&& new_unit_names, bool new_is_dynamic_tag, government_colour_map_t&& new_alternative_colours, - colour_t new_primary_unit_colour, colour_t new_secondary_unit_colour, colour_t new_tertiary_unit_colour + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + GraphicalCultureType const& new_graphical_culture, + IdentifierRegistry&& new_parties, + unit_names_map_t&& new_unit_names, + bool new_is_dynamic_tag, + government_colour_map_t&& new_alternative_colours, + colour_t new_primary_unit_colour, + colour_t new_secondary_unit_colour, + colour_t new_tertiary_unit_colour ); CountryDefinition(CountryDefinition&&) = default; @@ -64,21 +71,25 @@ namespace OpenVic { IdentifierRegistry IDENTIFIER_REGISTRY(country_definition); NodeTools::node_callback_t load_country_party( - PoliticsManager const& politics_manager, IdentifierRegistry& country_parties + PoliticsManager const& politics_manager, IdentifierRegistry& country_parties ) const; public: bool add_country( - std::string_view identifier, colour_t colour, GraphicalCultureType const* graphical_culture, - IdentifierRegistry&& parties, CountryDefinition::unit_names_map_t&& unit_names, bool dynamic_tag, - CountryDefinition::government_colour_map_t&& alternative_colours + std::string_view identifier, + colour_t colour, + GraphicalCultureType const* graphical_culture, + IdentifierRegistry&& parties, + CountryDefinition::unit_names_map_t&& unit_names, + bool dynamic_tag, + CountryDefinition::government_colour_map_t&& alternative_colours ); bool load_country_colours(ast::NodeCPtr root); bool load_countries(DefinitionManager const& definition_manager, Dataloader const& dataloader, ast::NodeCPtr root); bool load_country_data_file( - DefinitionManager const& definition_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root + DefinitionManager const& definition_manager, std::string_view name, bool is_dynamic, ast::NodeCPtr root ); }; } diff --git a/src/openvic-simulation/country/CountryInstance.cpp b/src/openvic-simulation/country/CountryInstance.cpp index 8c1960605..1c862f454 100644 --- a/src/openvic-simulation/country/CountryInstance.cpp +++ b/src/openvic-simulation/country/CountryInstance.cpp @@ -9,12 +9,12 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/object/Timespan.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/SharedCountryValues.hpp" #include "openvic-simulation/defines/CountryDefines.hpp" @@ -43,10 +43,10 @@ #include "openvic-simulation/politics/RuleSet.hpp" #include "openvic-simulation/population/Culture.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/research/Invention.hpp" #include "openvic-simulation/research/Technology.hpp" #include "openvic-simulation/types/ClampedValue.hpp" @@ -66,182 +66,168 @@ static constexpr size_t DAYS_OF_BALANCE_HISTORY = 30; static constexpr colour_t ERROR_COLOUR = colour_t::from_integer(0xFF0000); CountryInstance::CountryInstance( - CountryDefinition const& new_country_definition, - SharedCountryValues& new_shared_country_values, - CountryInstanceDeps const& country_instance_deps -) : FlagStrings { "country" }, - HasIndex { new_country_definition.index }, - PopsAggregate { country_instance_deps.pops_aggregate_deps }, - /* Main attributes */ - country_definition { new_country_definition }, - shared_country_values { new_shared_country_values }, - - country_relations_manager { country_instance_deps.country_relations_manager }, - game_rules_manager { country_instance_deps.game_rules_manager }, - good_instance_manager { country_instance_deps.good_instance_manager }, - market_instance { country_instance_deps.market_instance }, - modifier_effect_cache { country_instance_deps.modifier_effect_cache }, - unit_type_manager { country_instance_deps.unit_type_manager }, - - fallback_date_for_never_completing_research { country_instance_deps.fallback_date_for_never_completing_research }, - country_defines { country_instance_deps.country_defines }, - diplomacy_defines { country_instance_deps.diplomacy_defines }, - economy_defines { country_instance_deps.economy_defines }, - military_defines { country_instance_deps.military_defines }, - - colour { ERROR_COLOUR }, - - /* Production */ - building_type_unlock_levels { country_instance_deps.building_types }, - - /* Budget */ - balance_history{DAYS_OF_BALANCE_HISTORY}, - taxable_income_by_pop_type { country_instance_deps.pop_types }, - effective_tax_rate_by_strata { - country_instance_deps.stratas, - [this](Strata const& strata)->auto { - return [this,&strata](DependencyTracker& tracker)->fixed_point_t { - return tax_efficiency.get(tracker) * tax_rate_slider_value_by_strata.at(strata).get_value(tracker); - }; - } - }, - administration_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_administration_salary_base(tracker); - }; - } - }, - education_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_education_salary_base(tracker); - }; - } - }, - military_salary_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_military_salary_base(tracker); - }; - } - }, - social_income_variant_base_by_pop_type{ - country_instance_deps.pop_types, - [this](PopType const& pop_type)->auto { - return [this,&pop_type](DependencyTracker& tracker)->fixed_point_t { - return corruption_cost_multiplier.get(tracker) - * shared_country_values.get_shared_pop_type_values(pop_type) - .get_social_income_variant_base(tracker); - }; - } - }, - tax_rate_slider_value_by_strata { country_instance_deps.stratas }, - - /* Technology */ - technology_unlock_levels { country_instance_deps.technologies }, - invention_unlock_levels { country_instance_deps.inventions }, - - /* Politics */ - upper_house_proportion_by_ideology { country_instance_deps.ideologies }, - reforms { country_instance_deps.reform_groups }, - flag_overrides_by_government_type { country_instance_deps.government_types }, - crime_unlock_levels { country_instance_deps.crimes }, - - /* Trade */ - goods_data { country_instance_deps.good_instances }, - - /* Diplomacy */ - - /* Military */ - regiment_type_unlock_levels { - regiment_type_index_t(country_instance_deps.regiment_types.size()), - technology_unlock_level_t(0) - }, - ship_type_unlock_levels { - ship_type_index_t(country_instance_deps.ship_types.size()), - technology_unlock_level_t(0) - }, - - /* DerivedState */ - flag_government_type { [this](DependencyTracker& tracker)->GovernmentType const* { - GovernmentType const* current_government_type = government_type.get(tracker); - if (current_government_type == nullptr) { - return nullptr; - } - GovernmentType const* flag_override = flag_overrides_by_government_type.at(*current_government_type); - return flag_override == nullptr - ? current_government_type - : flag_override; - }}, - total_score{[this](DependencyTracker& tracker)->fixed_point_t { - return prestige.get(tracker) + industrial_power.get(tracker) + military_power.get(tracker); - }}, - military_power{[this](DependencyTracker& tracker)->fixed_point_t { - return military_power_from_land.get(tracker) + military_power_from_sea.get(tracker) + military_power_from_leaders.get(tracker); - }}, - research_progress{[this](DependencyTracker& tracker)->fixed_point_t { - const fixed_point_t current_research_cost_copy = current_research_cost.get(tracker); - return current_research_cost_copy > 0 - ? invested_research_points.get(tracker) / current_research_cost_copy - : fixed_point_t::_0; - }}, - desired_administrator_percentage{[this](DependencyTracker& tracker)->fixed_point_t { - return country_defines.get_max_bureaucracy_percentage() - + total_administrative_multiplier.get(tracker) * country_defines.get_bureaucracy_percentage_increment(); - }}, - corruption_cost_multiplier{[this](DependencyTracker& tracker)->fixed_point_t { - return 2 - administrative_efficiency_from_administrators.get(tracker); - }}, - tariff_efficiency{[this](DependencyTracker& tracker)->fixed_point_t { - return std::min( - fixed_point_t::_1, - administrative_efficiency_from_administrators.get(tracker) + country_defines.get_base_country_tax_efficiency() - ); - }}, - effective_tariff_rate{[this](DependencyTracker& tracker)->fixed_point_t { - return administrative_efficiency_from_administrators.get(tracker) * tariff_rate_slider_value.get_value(tracker); - }}, - projected_administration_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return administration_spending_slider_value.get_value(tracker) * projected_administration_spending_unscaled_by_slider.get(tracker); - }}, - projected_education_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return education_spending_slider_value.get_value(tracker) * projected_education_spending_unscaled_by_slider.get(tracker); - }}, - projected_military_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return military_spending_slider_value.get_value(tracker) * projected_military_spending_unscaled_by_slider.get(tracker); - }}, - projected_social_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return social_spending_slider_value.get_value(tracker) * projected_social_spending_unscaled_by_slider.get(tracker); - }}, - projected_social_spending_unscaled_by_slider{[this](DependencyTracker& tracker)->fixed_point_t { - return projected_pensions_spending_unscaled_by_slider.get(tracker) - + projected_unemployment_subsidies_spending_unscaled_by_slider.get(tracker); - }}, - projected_import_subsidies{[this](DependencyTracker& tracker)->fixed_point_t { - return has_import_subsidies.get(tracker) - ? -effective_tariff_rate.get(tracker) * get_yesterdays_import_value(tracker) - : fixed_point_t::_0; - }}, - projected_spending{[this](DependencyTracker& tracker)->fixed_point_t { - return projected_administration_spending.get(tracker) - + projected_education_spending.get(tracker) - + projected_military_spending.get(tracker) - + projected_social_spending.get(tracker) - + projected_import_subsidies.get(tracker); - }}, - has_import_subsidies{[this](DependencyTracker& tracker)->bool { - return effective_tariff_rate.get(tracker) < 0; - }} { + CountryDefinition const& new_country_definition, + SharedCountryValues& new_shared_country_values, + CountryInstanceDeps const& country_instance_deps +) : + FlagStrings { "country" }, HasIndex { new_country_definition.index }, + PopsAggregate { country_instance_deps.pops_aggregate_deps }, + /* Main attributes */ + country_definition { new_country_definition }, shared_country_values { new_shared_country_values }, + + country_relations_manager { country_instance_deps.country_relations_manager }, + game_rules_manager { country_instance_deps.game_rules_manager }, + good_instance_manager { country_instance_deps.good_instance_manager }, + market_instance { country_instance_deps.market_instance }, + modifier_effect_cache { country_instance_deps.modifier_effect_cache }, + unit_type_manager { country_instance_deps.unit_type_manager }, + + fallback_date_for_never_completing_research { country_instance_deps.fallback_date_for_never_completing_research }, + country_defines { country_instance_deps.country_defines }, diplomacy_defines { country_instance_deps.diplomacy_defines }, + economy_defines { country_instance_deps.economy_defines }, military_defines { country_instance_deps.military_defines }, + + colour { ERROR_COLOUR }, + + /* Production */ + building_type_unlock_levels { country_instance_deps.building_types }, + + /* Budget */ + balance_history { DAYS_OF_BALANCE_HISTORY }, taxable_income_by_pop_type { country_instance_deps.pop_types }, + effective_tax_rate_by_strata { + country_instance_deps.stratas, + [this](Strata const& strata) -> auto { + return [this, &strata](DependencyTracker& tracker) -> fixed_point_t { + return tax_efficiency.get(tracker) * tax_rate_slider_value_by_strata.at(strata).get_value(tracker); + }; + } + }, + administration_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_administration_salary_base(tracker); + }; + } + }, + education_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_education_salary_base(tracker); + }; + } + }, + military_salary_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_military_salary_base(tracker); + }; + } + }, + social_income_variant_base_by_pop_type { + country_instance_deps.pop_types, + [this](PopType const& pop_type) -> auto { + return [this, &pop_type](DependencyTracker& tracker) -> fixed_point_t { + return corruption_cost_multiplier.get(tracker) * + shared_country_values.get_shared_pop_type_values(pop_type).get_social_income_variant_base(tracker); + }; + } + }, + tax_rate_slider_value_by_strata { country_instance_deps.stratas }, + + /* Technology */ + technology_unlock_levels { country_instance_deps.technologies }, + invention_unlock_levels { country_instance_deps.inventions }, + + /* Politics */ + upper_house_proportion_by_ideology { country_instance_deps.ideologies }, reforms { country_instance_deps.reform_groups }, + flag_overrides_by_government_type { country_instance_deps.government_types }, + crime_unlock_levels { country_instance_deps.crimes }, + + /* Trade */ + goods_data { country_instance_deps.good_instances }, + + /* Diplomacy */ + + /* Military */ + regiment_type_unlock_levels { + regiment_type_index_t(country_instance_deps.regiment_types.size()), technology_unlock_level_t(0) + }, + ship_type_unlock_levels { ship_type_index_t(country_instance_deps.ship_types.size()), technology_unlock_level_t(0) }, + + /* DerivedState */ + flag_government_type { [this](DependencyTracker& tracker) -> GovernmentType const* { + GovernmentType const* current_government_type = government_type.get(tracker); + if (current_government_type == nullptr) { + return nullptr; + } + GovernmentType const* flag_override = flag_overrides_by_government_type.at(*current_government_type); + return flag_override == nullptr ? current_government_type : flag_override; + } }, + total_score { [this](DependencyTracker& tracker) -> fixed_point_t { + return prestige.get(tracker) + industrial_power.get(tracker) + military_power.get(tracker); + } }, + military_power { [this](DependencyTracker& tracker) -> fixed_point_t { + return military_power_from_land.get(tracker) + military_power_from_sea.get(tracker) + + military_power_from_leaders.get(tracker); + } }, + research_progress { [this](DependencyTracker& tracker) -> fixed_point_t { + const fixed_point_t current_research_cost_copy = current_research_cost.get(tracker); + return current_research_cost_copy > 0 + ? invested_research_points.get(tracker) / current_research_cost_copy + : fixed_point_t::_0; + } }, + desired_administrator_percentage { [this](DependencyTracker& tracker) -> fixed_point_t { + return country_defines.get_max_bureaucracy_percentage() + + total_administrative_multiplier.get(tracker) * country_defines.get_bureaucracy_percentage_increment(); + } }, + corruption_cost_multiplier { [this](DependencyTracker& tracker) -> fixed_point_t { + return 2 - administrative_efficiency_from_administrators.get(tracker); + } }, + tariff_efficiency { [this](DependencyTracker& tracker) -> fixed_point_t { + return std::min( + fixed_point_t::_1, + administrative_efficiency_from_administrators.get(tracker) + country_defines.get_base_country_tax_efficiency() + ); + } }, + effective_tariff_rate { [this](DependencyTracker& tracker) -> fixed_point_t { + return administrative_efficiency_from_administrators.get(tracker) * tariff_rate_slider_value.get_value(tracker); + } }, + projected_administration_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return administration_spending_slider_value.get_value(tracker) * + projected_administration_spending_unscaled_by_slider.get(tracker); + } }, + projected_education_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return education_spending_slider_value.get_value(tracker) * + projected_education_spending_unscaled_by_slider.get(tracker); + } }, + projected_military_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return military_spending_slider_value.get_value(tracker) * projected_military_spending_unscaled_by_slider.get(tracker); + } }, + projected_social_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return social_spending_slider_value.get_value(tracker) * projected_social_spending_unscaled_by_slider.get(tracker); + } }, + projected_social_spending_unscaled_by_slider { [this](DependencyTracker& tracker) -> fixed_point_t { + return projected_pensions_spending_unscaled_by_slider.get(tracker) + + projected_unemployment_subsidies_spending_unscaled_by_slider.get(tracker); + } }, + projected_import_subsidies { [this](DependencyTracker& tracker) -> fixed_point_t { + return has_import_subsidies.get(tracker) + ? -effective_tariff_rate.get(tracker) * get_yesterdays_import_value(tracker) + : fixed_point_t::_0; + } }, + projected_spending { [this](DependencyTracker& tracker) -> fixed_point_t { + return projected_administration_spending.get(tracker) + projected_education_spending.get(tracker) + + projected_military_spending.get(tracker) + projected_social_spending.get(tracker) + + projected_import_subsidies.get(tracker); + } }, + has_import_subsidies { [this](DependencyTracker& tracker) -> bool { + return effective_tariff_rate.get(tracker) < 0; + } } { modifier_sum.set_this_source(this); // Exclude PROVINCE (local) modifier effects from the country's modifier sum modifier_sum.set_this_excluded_targets(ModifierEffect::target_t::PROVINCE); @@ -261,9 +247,7 @@ CountryInstance::CountryInstance( navy_spending_slider_value.set_bounds(economy_defines.get_minimum_navy_spending_slider_value(), 1); navy_spending_slider_value.set_value(1); - construction_spending_slider_value.set_bounds( - economy_defines.get_minimum_construction_spending_slider_value(), 1 - ); + construction_spending_slider_value.set_bounds(economy_defines.get_minimum_construction_spending_slider_value(), 1); construction_spending_slider_value.set_value(1); education_spending_slider_value.set_bounds(0, 1); @@ -344,28 +328,27 @@ bool CountryInstance::is_neighbour(CountryInstance const& country) const { return neighbouring_countries.contains(&country); } -bool CountryInstance::may_build_in(const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location) const { +bool CountryInstance::may_build_in( + const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location +) const { CountryInstance const* const owner_ptr = location.get_owner(); if (owner_ptr == nullptr) { - //Can't build in uncolonised provinces + // Can't build in uncolonised provinces return false; } CountryInstance const& owner = *owner_ptr; if (owner == *this) { - switch(restriction_category) { - case BuildingRestrictionCategory::UNRESTRICTED: - return true; - case BuildingRestrictionCategory::INFRASTRUCTURE: - return rule_set.may_expand_infrastructure_domestically(); - case BuildingRestrictionCategory::FACTORY: - return rule_set.may_build_factory_domestically(); + switch (restriction_category) { + case BuildingRestrictionCategory::UNRESTRICTED: return true; + case BuildingRestrictionCategory::INFRASTRUCTURE: return rule_set.may_expand_infrastructure_domestically(); + case BuildingRestrictionCategory::FACTORY: return rule_set.may_build_factory_domestically(); } } if (is_at_war_with(owner)) { - //Not allowed to build in hostile lands. + // Not allowed to build in hostile lands. return false; } @@ -373,13 +356,10 @@ bool CountryInstance::may_build_in(const BuildingRestrictionCategory restriction return false; } - switch(restriction_category) { - case BuildingRestrictionCategory::UNRESTRICTED: - return false; //For example you can't invest in foreign forts. - case BuildingRestrictionCategory::INFRASTRUCTURE: - return rule_set.may_invest_in_expanding_infrastructure_abroad(); - case BuildingRestrictionCategory::FACTORY: - return rule_set.may_invest_in_building_factory_abroad(); + switch (restriction_category) { + case BuildingRestrictionCategory::UNRESTRICTED: return false; // For example you can't invest in foreign forts. + case BuildingRestrictionCategory::INFRASTRUCTURE: return rule_set.may_invest_in_expanding_infrastructure_abroad(); + case BuildingRestrictionCategory::FACTORY: return rule_set.may_invest_in_building_factory_abroad(); } OpenVic::unreachable(); @@ -453,7 +433,9 @@ CountryRelationManager::OpinionType CountryInstance::get_opinion_of(CountryInsta } void CountryInstance::set_opinion_of(CountryInstance& country, CountryRelationManager::OpinionType opinion) { - if (OV_unlikely(country.sphere_owner.get_untracked() != nullptr && opinion == CountryRelationManager::OpinionType::Sphere)) { + if (OV_unlikely( + country.sphere_owner.get_untracked() != nullptr && opinion == CountryRelationManager::OpinionType::Sphere + )) { spdlog::warn_s("Attempting to add '{}' to a sphere when it is already included in a sphere.", country); } country_relations_manager.set_country_opinion(this, &country, opinion); @@ -484,11 +466,15 @@ void CountryInstance::set_influence_with(CountryInstance& country, CountryRelati country_relations_manager.set_influence_with(this, &country, influence); } -CountryRelationManager::influence_priority_value_type CountryInstance::get_influence_priority_with(CountryInstance const& country) const { +CountryRelationManager::influence_priority_value_type CountryInstance::get_influence_priority_with( + CountryInstance const& country +) const { return country_relations_manager.get_influence_priority_with(this, &country); } -void CountryInstance::set_influence_priority_with(CountryInstance& country, CountryRelationManager::influence_priority_value_type influence) { +void CountryInstance::set_influence_priority_with( + CountryInstance& country, CountryRelationManager::influence_priority_value_type influence +) { country_relations_manager.set_influence_priority_with(this, &country, influence); } @@ -559,80 +545,90 @@ ReadOnlyClampedValue const& CountryInstance::get_tax_rate_slider_value_by_strata bool CountryInstance::add_owned_province(ProvinceInstance& new_item) { OV_ERR_FAIL_COND_V_MSG( - !owned_provinces.emplace(&new_item).second, false, - memory::fmt::format("owned_province \"{}\" already present in country {}", new_item, *this) + !owned_provinces.emplace(&new_item).second, + false, + memory::fmt::format("owned_province \"{}\" already present in country {}", new_item, *this) ); return true; } bool CountryInstance::remove_owned_province(ProvinceInstance const& item_to_remove) { OV_ERR_FAIL_COND_V_MSG( - owned_provinces.erase(&item_to_remove) == 0, false, - memory::fmt::format("owned_province \"{}\" not present in country {}", item_to_remove, *this) + owned_provinces.erase(&item_to_remove) == 0, + false, + memory::fmt::format("owned_province \"{}\" not present in country {}", item_to_remove, *this) ); return true; } bool CountryInstance::add_controlled_province(ProvinceInstance& new_item) { OV_ERR_FAIL_COND_V_MSG( - !controlled_provinces.emplace(&new_item).second, false, - memory::fmt::format("controlled_province \"{}\" already present in country {}", new_item, *this) + !controlled_provinces.emplace(&new_item).second, + false, + memory::fmt::format("controlled_province \"{}\" already present in country {}", new_item, *this) ); return true; } bool CountryInstance::remove_controlled_province(ProvinceInstance const& item_to_remove) { OV_ERR_FAIL_COND_V_MSG( - controlled_provinces.erase(&item_to_remove) == 0, false, - memory::fmt::format("controlled_province \"{}\" not present in country {}", item_to_remove, *this) + controlled_provinces.erase(&item_to_remove) == 0, + false, + memory::fmt::format("controlled_province \"{}\" not present in country {}", item_to_remove, *this) ); return true; } bool CountryInstance::add_core_province(ProvinceInstance& new_item) { OV_ERR_FAIL_COND_V_MSG( - !core_provinces.emplace(&new_item).second, false, - memory::fmt::format("core_province \"{}\" already present in country {}", new_item, *this) + !core_provinces.emplace(&new_item).second, + false, + memory::fmt::format("core_province \"{}\" already present in country {}", new_item, *this) ); return true; } bool CountryInstance::remove_core_province(ProvinceInstance const& item_to_remove) { OV_ERR_FAIL_COND_V_MSG( - core_provinces.erase(&item_to_remove) == 0, false, - memory::fmt::format("core_province \"{}\" not present in country {}", item_to_remove, *this) + core_provinces.erase(&item_to_remove) == 0, + false, + memory::fmt::format("core_province \"{}\" not present in country {}", item_to_remove, *this) ); return true; } bool CountryInstance::add_state(State& new_item) { OV_ERR_FAIL_COND_V_MSG( - !states.emplace(&new_item).second, false, - memory::fmt::format("state \"{}\" already present in country {}", new_item, *this) + !states.emplace(&new_item).second, + false, + memory::fmt::format("state \"{}\" already present in country {}", new_item, *this) ); return true; } bool CountryInstance::remove_state(State const& item_to_remove) { OV_ERR_FAIL_COND_V_MSG( - states.erase(&item_to_remove) == 0, false, - memory::fmt::format("state \"{}\" not present in country {}", item_to_remove, *this) + states.erase(&item_to_remove) == 0, + false, + memory::fmt::format("state \"{}\" not present in country {}", item_to_remove, *this) ); return true; } bool CountryInstance::add_accepted_culture(Culture const& new_item) { OV_ERR_FAIL_COND_V_MSG( - !accepted_cultures.emplace(&new_item).second, false, - memory::fmt::format("accepted_culture \"{}\" already present in country {}", new_item, *this) + !accepted_cultures.emplace(&new_item).second, + false, + memory::fmt::format("accepted_culture \"{}\" already present in country {}", new_item, *this) ); return true; } bool CountryInstance::remove_accepted_culture(Culture const& item_to_remove) { OV_ERR_FAIL_COND_V_MSG( - accepted_cultures.erase(&item_to_remove) == 0, false, - memory::fmt::format("accepted_culture \"{}\" not present in country {}", item_to_remove, *this) + accepted_cultures.erase(&item_to_remove) == 0, + false, + memory::fmt::format("accepted_culture \"{}\" not present in country {}", item_to_remove, *this) ); return true; } @@ -714,38 +710,35 @@ bool CountryInstance::add_unit_instance_group(UnitInstanceGroup& group) { using enum unit_branch_t; switch (group.branch) { - case LAND: - armies.emplace_back(static_cast(group)); - return true; - case NAVAL: - navies.emplace_back(static_cast(group)); - return true; + case LAND: armies.emplace_back(static_cast(group)); return true; + case NAVAL: navies.emplace_back(static_cast(group)); return true; default: spdlog::error_s( - "Trying to add unit group \"{}\" with invalid branch {} to country {}", - group.get_name(), static_cast(group.branch), *this + "Trying to add unit group \"{}\" with invalid branch {} to country {}", + group.get_name(), + static_cast(group.branch), + *this ); return false; } } bool CountryInstance::remove_unit_instance_group(UnitInstanceGroup const& group) { - const auto remove_from_vector = [this, &group]( - memory::vector>>& unit_instance_groups - ) -> bool { - const auto it = std::find( - unit_instance_groups.begin(), - unit_instance_groups.end(), - group - ); + const auto remove_from_vector = + [this, &group]( + memory::vector>>& unit_instance_groups + ) -> bool { + const auto it = std::find(unit_instance_groups.begin(), unit_instance_groups.end(), group); if (it != unit_instance_groups.end()) { unit_instance_groups.erase(it); return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from country {}", - get_branched_unit_group_name(Branch), group.get_name(), *this + "Trying to remove non-existent {} \"{}\" from country {}", + get_branched_unit_group_name(Branch), + group.get_name(), + *this ); return false; } @@ -754,14 +747,14 @@ bool CountryInstance::remove_unit_instance_group(UnitInstanceGroup const& group) using enum unit_branch_t; switch (group.branch) { - case LAND: - return remove_from_vector(armies); - case NAVAL: - return remove_from_vector(navies); + case LAND: return remove_from_vector(armies); + case NAVAL: return remove_from_vector(navies); default: spdlog::error_s( - "Trying to remove unit group \"{}\" with invalid branch {} from country {}", - group.get_name(), static_cast(group.branch), *this + "Trying to remove unit group \"{}\" with invalid branch {} from country {}", + group.get_name(), + static_cast(group.branch), + *this ); return false; } @@ -771,16 +764,14 @@ bool CountryInstance::add_leader(LeaderInstance& leader) { using enum unit_branch_t; switch (leader.branch) { - case LAND: - generals.push_back(leader); - return true; - case NAVAL: - admirals.push_back(leader); - return true; + case LAND: generals.push_back(leader); return true; + case NAVAL: admirals.push_back(leader); return true; default: spdlog::error_s( - "Trying to add leader \"{}\" with invalid branch {} to country {}", - leader.get_name(), static_cast(leader.branch), *this + "Trying to add leader \"{}\" with invalid branch {} to country {}", + leader.get_name(), + static_cast(leader.branch), + *this ); return false; } @@ -792,16 +783,14 @@ bool CountryInstance::remove_leader(LeaderInstance const& leader) { memory::vector>* leaders; switch (leader.branch) { - case LAND: - leaders = &generals; - break; - case NAVAL: - leaders = &admirals; - break; + case LAND: leaders = &generals; break; + case NAVAL: leaders = &admirals; break; default: spdlog::error_s( - "Trying to remove leader \"{}\" with invalid branch {} from country {}", - leader.get_name(), static_cast(leader.branch), *this + "Trying to remove leader \"{}\" with invalid branch {} from country {}", + leader.get_name(), + static_cast(leader.branch), + *this ); return false; } @@ -813,17 +802,17 @@ bool CountryInstance::remove_leader(LeaderInstance const& leader) { return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from country {}", - get_branched_leader_name(leader.branch), leader.get_name(), *this + "Trying to remove non-existent {} \"{}\" from country {}", + get_branched_leader_name(leader.branch), + leader.get_name(), + *this ); return false; } } bool CountryInstance::has_leader_with_name(std::string_view name) const { - const auto check_leaders = [name]( - memory::vector> const& leaders - ) -> bool { + const auto check_leaders = [name](memory::vector> const& leaders) -> bool { for (LeaderInstance const& leader : leaders) { if (leader.get_name() == name) { return true; @@ -835,12 +824,14 @@ bool CountryInstance::has_leader_with_name(std::string_view name) const { return check_leaders(generals) || check_leaders(admirals); } -bool CountryInstance::modify_unit_type_unlock(const regiment_type_index_t regiment_type_index, technology_unlock_level_t unlock_level_change) { +bool CountryInstance::modify_unit_type_unlock( + const regiment_type_index_t regiment_type_index, technology_unlock_level_t unlock_level_change +) { technology_unlock_level_t& unlock_level = regiment_type_unlock_levels[regiment_type_index]; - if(!validate_unit_unlock_change(regiment_type_index, unlock_level, unlock_level_change)) { + if (!validate_unit_unlock_change(regiment_type_index, unlock_level, unlock_level_change)) { return false; } - + const bool was_unlocked_before = is_unlocked(unlock_level); unlock_level += unlock_level_change; const bool is_unlocked_after = is_unlocked(unlock_level); @@ -848,7 +839,7 @@ bool CountryInstance::modify_unit_type_unlock(const regiment_type_index_t regime if (was_unlocked_before != is_unlocked_after) { TypedSpan regiment_types = shared_country_values.regiment_types; if (was_unlocked_before) { - //recalculate entirely + // recalculate entirely allowed_regiment_cultures = regiment_allowed_cultures_t::NO_CULTURES; for (RegimentType const& regiment_type : regiment_types) { if (!is_unit_type_unlocked(regiment_type)) { @@ -856,22 +847,22 @@ bool CountryInstance::modify_unit_type_unlock(const regiment_type_index_t regime } allowed_regiment_cultures = RegimentType::allowed_cultures_get_most_permissive( - allowed_regiment_cultures, - regiment_type.allowed_cultures + allowed_regiment_cultures, regiment_type.allowed_cultures ); } } else { allowed_regiment_cultures = RegimentType::allowed_cultures_get_most_permissive( - allowed_regiment_cultures, - regiment_types[regiment_type_index].allowed_cultures + allowed_regiment_cultures, regiment_types[regiment_type_index].allowed_cultures ); } } return true; } -bool CountryInstance::modify_unit_type_unlock(const ship_type_index_t ship_type_index, technology_unlock_level_t unlock_level_change) { +bool CountryInstance::modify_unit_type_unlock( + const ship_type_index_t ship_type_index, technology_unlock_level_t unlock_level_change +) { technology_unlock_level_t& unlock_level = ship_type_unlock_levels[ship_type_index]; - if(!validate_unit_unlock_change(ship_type_index, unlock_level, unlock_level_change)) { + if (!validate_unit_unlock_change(ship_type_index, unlock_level, unlock_level_change)) { return false; } unlock_level += unlock_level_change; @@ -882,14 +873,15 @@ bool CountryInstance::modify_unit_type_unlock(UnitType const& unit_type, technol using enum unit_branch_t; switch (unit_type.branch) { - case LAND: - return modify_unit_type_unlock(static_cast const&>(unit_type).index, unlock_level_change); + case LAND: return modify_unit_type_unlock(static_cast const&>(unit_type).index, unlock_level_change); case NAVAL: return modify_unit_type_unlock(static_cast const&>(unit_type).index, unlock_level_change); default: spdlog::error_s( - "Attempted to change unlock level for unit type \"{}\" with invalid branch {} for country {}", - unit_type, static_cast(unit_type.branch), *this + "Attempted to change unlock level for unit type \"{}\" with invalid branch {} for country {}", + unit_type, + static_cast(unit_type.branch), + *this ); return false; } @@ -903,21 +895,21 @@ bool CountryInstance::is_unit_type_unlocked(UnitType const& unit_type) const { using enum unit_branch_t; switch (unit_type.branch) { - case LAND: - return is_unit_type_unlocked(static_cast const&>(unit_type).index); - case NAVAL: - return is_unit_type_unlocked(static_cast const&>(unit_type).index); + case LAND: return is_unit_type_unlocked(static_cast const&>(unit_type).index); + case NAVAL: return is_unit_type_unlocked(static_cast const&>(unit_type).index); default: spdlog::error_s( - "Attempted to check if unit type \"{}\" with invalid branch {} is unlocked for country {}", - unit_type, static_cast(unit_type.branch), *this + "Attempted to check if unit type \"{}\" with invalid branch {} is unlocked for country {}", + unit_type, + static_cast(unit_type.branch), + *this ); return false; } } bool CountryInstance::modify_building_type_unlock( - BuildingType const& building_type, technology_unlock_level_t tech_unlock_level_change + BuildingType const& building_type, technology_unlock_level_t tech_unlock_level_change ) { building_level_t& unlock_level = building_type_unlock_levels.at(building_type); building_level_t unlock_level_change = building_level_t(type_safe::get(tech_unlock_level_change)); @@ -925,9 +917,13 @@ bool CountryInstance::modify_building_type_unlock( // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < building_level_t(0)) { spdlog::error_s( - "Attempted to change unlock level for building type {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - building_type, *this, unlock_level, unlock_level_change, - unlock_level + unlock_level_change + "Attempted to change unlock level for building type {} in country {} to invalid value: current level = {}, change " + "= {}, invalid new value = {}", + building_type, + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); return false; } @@ -959,9 +955,13 @@ bool CountryInstance::modify_crime_unlock(Crime const& crime, technology_unlock_ // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for crime {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - crime, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for crime {} in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + crime, + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); return false; } @@ -983,9 +983,12 @@ bool CountryInstance::modify_gas_attack_unlock(technology_unlock_level_t unlock_ // This catches subtracting below 0 or adding above the int types maximum value if (gas_attack_unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for gas attack in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - *this, gas_attack_unlock_level, - unlock_level_change, gas_attack_unlock_level + unlock_level_change + "Attempted to change unlock level for gas attack in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + *this, + gas_attack_unlock_level, + unlock_level_change, + gas_attack_unlock_level + unlock_level_change ); return false; } @@ -1007,9 +1010,12 @@ bool CountryInstance::modify_gas_defence_unlock(technology_unlock_level_t unlock // This catches subtracting below 0 or adding above the int types maximum value if (gas_defence_unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for gas defence in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - *this, gas_defence_unlock_level, - unlock_level_change, gas_defence_unlock_level + unlock_level_change + "Attempted to change unlock level for gas defence in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + *this, + gas_defence_unlock_level, + unlock_level_change, + gas_defence_unlock_level + unlock_level_change ); return false; } @@ -1044,9 +1050,13 @@ bool CountryInstance::modify_unit_variant_unlock(unit_variant_t unit_variant, te // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for unit variant {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - static_cast(unit_variant), *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for unit variant {} in country {} to invalid value: current level = {}, change = " + "{}, invalid new value = {}", + static_cast(unit_variant), + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); ret = false; } else { @@ -1068,17 +1078,19 @@ unit_variant_t CountryInstance::get_max_unlocked_unit_variant() const { return unit_variant_unlock_levels.size(); } -bool CountryInstance::modify_technology_unlock( - Technology const& technology, technology_unlock_level_t unlock_level_change -) { +bool CountryInstance::modify_technology_unlock(Technology const& technology, technology_unlock_level_t unlock_level_change) { technology_unlock_level_t& unlock_level = technology_unlock_levels.at(technology); // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for technology {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - technology, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for technology {} in country {} to invalid value: current level = {}, change = " + "{}, invalid new value = {}", + technology, + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); return false; } @@ -1102,9 +1114,7 @@ bool CountryInstance::modify_technology_unlock( return ret; } -bool CountryInstance::set_technology_unlock_level( - Technology const& technology, technology_unlock_level_t unlock_level -) { +bool CountryInstance::set_technology_unlock_level(Technology const& technology, technology_unlock_level_t unlock_level) { const technology_unlock_level_t unlock_level_change = unlock_level - technology_unlock_levels.at(technology); return unlock_level_change != 0 ? modify_technology_unlock(technology, unlock_level_change) : true; } @@ -1117,17 +1127,19 @@ bool CountryInstance::is_technology_unlocked(Technology const& technology) const return is_unlocked(technology_unlock_levels.at(technology)); } -bool CountryInstance::modify_invention_unlock( - Invention const& invention, technology_unlock_level_t unlock_level_change -) { +bool CountryInstance::modify_invention_unlock(Invention const& invention, technology_unlock_level_t unlock_level_change) { technology_unlock_level_t& unlock_level = invention_unlock_levels.at(invention); // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for invention {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - invention, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for invention {} in country {} to invalid value: current level = {}, change = " + "{}, invalid new value = {}", + invention, + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); return false; } @@ -1136,9 +1148,9 @@ bool CountryInstance::modify_invention_unlock( unlock_level += unlock_level_change; if (invention_was_unlocked != is_unlocked(unlock_level)) { if (invention_was_unlocked) { - inventions_count-=1; + inventions_count -= 1; } else { - inventions_count+=1; + inventions_count += 1; } } @@ -1165,9 +1177,7 @@ bool CountryInstance::modify_invention_unlock( return ret; } -bool CountryInstance::set_invention_unlock_level( - Invention const& invention, technology_unlock_level_t unlock_level -) { +bool CountryInstance::set_invention_unlock_level(Invention const& invention, technology_unlock_level_t unlock_level) { const technology_unlock_level_t unlock_level_change = unlock_level - invention_unlock_levels.at(invention); return unlock_level_change != 0 ? modify_invention_unlock(invention, unlock_level_change) : true; } @@ -1194,19 +1204,15 @@ bool CountryInstance::is_primary_or_accepted_culture(Culture const& culture) con fixed_point_t CountryInstance::calculate_research_cost(Technology const& technology) const { // TODO - what if research bonus is -100%? Divide by 0 -> infinite cost? - return technology.cost / (fixed_point_t::_1 + get_modifier_effect_value( - *modifier_effect_cache.get_research_bonus_effects(technology.area.folder) - )); + return technology.cost / + (fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_research_bonus_effects(technology.area.folder))); } bool CountryInstance::can_research_tech(Technology const& technology, const Date today) const { Technology const* current_research_copy = current_research.get_untracked(); - if ( - technology.year > today.get_year() - || !is_civilised() - || is_technology_unlocked(technology) - || (current_research_copy && technology == *current_research_copy) - ) { + if (technology.year > today.get_year() || !is_civilised() || is_technology_unlocked(technology) || + (current_research_copy && technology == *current_research_copy)) { return false; } @@ -1218,8 +1224,9 @@ bool CountryInstance::can_research_tech(Technology const& technology, const Date void CountryInstance::start_research(Technology const& technology, const Date today) { if (OV_unlikely(!can_research_tech(technology, today))) { spdlog::warn_s( - "Attempting to start research for country \"{}\" on technology \"{}\" - cannot research this tech!", - *this, technology + "Attempting to start research for country \"{}\" on technology \"{}\" - cannot research this tech!", + *this, + technology ); return; } @@ -1231,7 +1238,7 @@ void CountryInstance::start_research(Technology const& technology, const Date to } void CountryInstance::apply_foreign_investments( - fixed_point_map_t const& investments, CountryInstanceManager const& country_instance_manager + fixed_point_map_t const& investments, CountryInstanceManager const& country_instance_manager ) { for (auto const& [country, money_invested] : investments) { foreign_investments[country_instance_manager.get_country_instance_by_definition(*country)] = money_invested; @@ -1239,10 +1246,10 @@ void CountryInstance::apply_foreign_investments( } bool CountryInstance::apply_history_to_country( - CountryHistoryEntry const& entry, - CountryInstanceManager const& country_instance_manager, - FlagStrings& global_flags, - MapInstance& map_instance + CountryHistoryEntry const& entry, + CountryInstanceManager const& country_instance_manager, + FlagStrings& global_flags, + MapInstance& map_instance ) { constexpr auto set_optional = [](T& target, std::optional const& source) { if (source) { @@ -1327,9 +1334,7 @@ void CountryInstance::_update_production() { for (auto const& [country, money_invested] : foreign_investments) { if (country.get().exists()) { const fixed_point_t investment_industrial_power = fp::mul_div( - money_invested, - country_defines.get_country_investment_industrial_score_factor(), - 100 + money_invested, country_defines.get_country_investment_industrial_score_factor(), 100 ); if (investment_industrial_power != 0) { @@ -1342,12 +1347,16 @@ void CountryInstance::_update_production() { industrial_power.set(industrial_power_running_total); std::stable_sort( - industrial_power_from_states.begin(), industrial_power_from_states.end(), - [](auto const& a, auto const& b) -> bool { return a.second > b.second; } + industrial_power_from_states.begin(), industrial_power_from_states.end(), [](auto const& a, auto const& b) -> bool { + return a.second > b.second; + } ); std::stable_sort( - industrial_power_from_investments.begin(), industrial_power_from_investments.end(), - [](auto const& a, auto const& b) -> bool { return a.second > b.second; } + industrial_power_from_investments.begin(), + industrial_power_from_investments.end(), + [](auto const& a, auto const& b) -> bool { + return a.second > b.second; + } ); } @@ -1366,30 +1375,28 @@ void CountryInstance::_update_budget() { // Education and administration spending sliders have no min/max modifiers social_spending_slider_value.set_bounds( - get_modifier_effect_value(*modifier_effect_cache.get_min_social_spending()), - nonzero_or_one(get_modifier_effect_value(*modifier_effect_cache.get_max_social_spending())) + get_modifier_effect_value(*modifier_effect_cache.get_min_social_spending()), + nonzero_or_one(get_modifier_effect_value(*modifier_effect_cache.get_max_social_spending())) ); military_spending_slider_value.set_bounds( - get_modifier_effect_value(*modifier_effect_cache.get_min_military_spending()), - nonzero_or_one(get_modifier_effect_value(*modifier_effect_cache.get_max_military_spending())) + get_modifier_effect_value(*modifier_effect_cache.get_min_military_spending()), + nonzero_or_one(get_modifier_effect_value(*modifier_effect_cache.get_max_military_spending())) ); tariff_rate_slider_value.set_bounds( - get_modifier_effect_value(*modifier_effect_cache.get_min_tariff()), - get_modifier_effect_value(*modifier_effect_cache.get_max_tariff()) + get_modifier_effect_value(*modifier_effect_cache.get_min_tariff()), + get_modifier_effect_value(*modifier_effect_cache.get_max_tariff()) ); // TODO - make sure we properly update everything dependent on these sliders' values, // as they might change if their sliders' bounds shrink past their previous values. tax_efficiency.set( - country_defines.get_base_country_tax_efficiency() - + get_modifier_effect_value(*modifier_effect_cache.get_tax_efficiency()) - + get_modifier_effect_value(*modifier_effect_cache.get_tax_eff()) / 100 + country_defines.get_base_country_tax_efficiency() + + get_modifier_effect_value(*modifier_effect_cache.get_tax_efficiency()) + + get_modifier_effect_value(*modifier_effect_cache.get_tax_eff()) / 100 ); - TypedSpan pop_types( - shared_country_values.get_shared_pop_type_values().get_keys() - ); + TypedSpan pop_types(shared_country_values.get_shared_pop_type_values().get_keys()); /* In Victoria 2, administration efficiency is updated in the UI immediately. @@ -1428,26 +1435,26 @@ void CountryInstance::_update_budget() { administrator_percentage.set(fp::from_fraction(administrators, total_non_colonial_population)); const pop_sum_t desired_administrators = fp::multiply_truncate( - total_non_colonial_population, - desired_administrator_percentage.get_untracked() + total_non_colonial_population, desired_administrator_percentage.get_untracked() ); const pop_sum_t effective_administrators = fp::multiply_truncate( - administrators, - fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency()) + administrators, + fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency()) ); const fixed_point_t administrative_efficiency_from_administrators_unclamped = - desired_administrators == 0 - ? fixed_point_t::_1 - : std::min( - fp::from_fraction(effective_administrators, desired_administrators) - * (fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency_modifier())), - fixed_point_t::_1 - ); + desired_administrators == 0 + ? fixed_point_t::_1 + : std::min( + fp::from_fraction(effective_administrators, desired_administrators) * + (fixed_point_t::_1 + + get_modifier_effect_value(*modifier_effect_cache.get_administrative_efficiency_modifier())), + fixed_point_t::_1 + ); administrative_efficiency_from_administrators.set( - game_rules_manager.get_prevent_negative_administration_efficiency() - ? std::max(fixed_point_t::_0, administrative_efficiency_from_administrators_unclamped) - : administrative_efficiency_from_administrators_unclamped + game_rules_manager.get_prevent_negative_administration_efficiency() + ? std::max(fixed_point_t::_0, administrative_efficiency_from_administrators_unclamped) + : administrative_efficiency_from_administrators_unclamped ); } @@ -1462,54 +1469,53 @@ void CountryInstance::_update_budget() { for (const pop_sum_t pop_size : get_population_by_type()) { PopType const& pop_type = pop_types[pop_type_index]; const int64_t size = type_safe::get(pop_size); - projected_administration_spending_unscaled_by_slider_running_total += size - * administration_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_education_spending_unscaled_by_slider_running_total += size - * education_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_military_spending_unscaled_by_slider_running_total += size - * military_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); - projected_pensions_spending_unscaled_by_slider_running_total += size - * calculate_pensions_base(pop_type).get_raw_value(); - projected_unemployment_subsidies_spending_unscaled_by_slider_running_total += type_safe::get( - get_unemployed_pops_by_type()[pop_type_index] - ) - * calculate_unemployment_subsidies_base(pop_type).get_raw_value(); + projected_administration_spending_unscaled_by_slider_running_total += + size * administration_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_education_spending_unscaled_by_slider_running_total += + size * education_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_military_spending_unscaled_by_slider_running_total += + size * military_salary_base_by_pop_type.at(pop_type).get_untracked().get_raw_value(); + projected_pensions_spending_unscaled_by_slider_running_total += + size * calculate_pensions_base(pop_type).get_raw_value(); + projected_unemployment_subsidies_spending_unscaled_by_slider_running_total += + type_safe::get(get_unemployed_pops_by_type()[pop_type_index]) * + calculate_unemployment_subsidies_base(pop_type).get_raw_value(); ++pop_type_index; } } const int64_t denominator = type_safe::get(Pop::size_denominator); - projected_administration_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_administration_spending_unscaled_by_slider_running_total / denominator - )); - projected_education_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_education_spending_unscaled_by_slider_running_total / denominator - )); - projected_military_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_military_spending_unscaled_by_slider_running_total / denominator - )); - projected_pensions_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_pensions_spending_unscaled_by_slider_running_total / denominator - )); - projected_unemployment_subsidies_spending_unscaled_by_slider.set(fixed_point_t::parse_raw( - projected_unemployment_subsidies_spending_unscaled_by_slider_running_total / denominator - )); + projected_administration_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_administration_spending_unscaled_by_slider_running_total / denominator) + ); + projected_education_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_education_spending_unscaled_by_slider_running_total / denominator) + ); + projected_military_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_military_spending_unscaled_by_slider_running_total / denominator) + ); + projected_pensions_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_pensions_spending_unscaled_by_slider_running_total / denominator) + ); + projected_unemployment_subsidies_spending_unscaled_by_slider.set( + fixed_point_t::parse_raw(projected_unemployment_subsidies_spending_unscaled_by_slider_running_total / denominator) + ); } fixed_point_t CountryInstance::calculate_pensions_base(PopType const& pop_type) { - return get_modifier_effect_value(*modifier_effect_cache.get_pension_level()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_pension_level()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } fixed_point_t CountryInstance::calculate_unemployment_subsidies_base(PopType const& pop_type) { - return get_modifier_effect_value(*modifier_effect_cache.get_unemployment_benefit()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_unemployment_benefit()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } fixed_point_t CountryInstance::calculate_minimum_wage_base(PopType const& pop_type) { if (pop_type.is_slave) { return 0; } - return get_modifier_effect_value(*modifier_effect_cache.get_minimum_wage()) - * social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); + return get_modifier_effect_value(*modifier_effect_cache.get_minimum_wage()) * + social_income_variant_base_by_pop_type.at(pop_type).get_untracked(); } void CountryInstance::_update_current_tech(const Date today) { @@ -1518,20 +1524,14 @@ void CountryInstance::_update_current_tech(const Date today) { return; } - current_research_cost.set( - calculate_research_cost(*current_research_copy) - ); + current_research_cost.set(calculate_research_cost(*current_research_copy)); const fixed_point_t daily_research_points_copy = daily_research_points.get_untracked(); if (daily_research_points_copy > 0) { expected_research_completion_date.set( - today - + static_cast( - ( - (current_research_cost.get_untracked() - invested_research_points.get_untracked()) - / daily_research_points_copy - ).ceil() - ) + today + static_cast(((current_research_cost.get_untracked() - invested_research_points.get_untracked()) / + daily_research_points_copy) + .ceil()) ); } else { expected_research_completion_date.set(fallback_date_for_never_completing_research); @@ -1544,9 +1544,9 @@ void CountryInstance::_update_technology(const Date today) { } daily_research_points += get_modifier_effect_value(*modifier_effect_cache.get_research_points()); - daily_research_points *= fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_research_points_modifier()) + - get_modifier_effect_value(*modifier_effect_cache.get_increase_research()); + daily_research_points *= + fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_research_points_modifier()) + + get_modifier_effect_value(*modifier_effect_cache.get_increase_research()); if (daily_research_points.get_untracked() < 0) { daily_research_points.set(0); @@ -1555,9 +1555,7 @@ void CountryInstance::_update_technology(const Date today) { _update_current_tech(today); } -void CountryInstance::_update_politics() { - -} +void CountryInstance::_update_politics() {} void CountryInstance::_update_population() { clear_pops_aggregate(); @@ -1573,26 +1571,19 @@ void CountryInstance::_update_population() { research_points_from_pop_types.clear(); leadership_points_from_pop_types.clear(); - TypedSpan pop_types( - shared_country_values.get_shared_pop_type_values().get_keys() - ); + TypedSpan pop_types(shared_country_values.get_shared_pop_type_values().get_keys()); { pop_type_index_t pop_type_index {}; for (const pop_sum_t pop_size : get_population_by_type()) { PopType const& pop_type = pop_types[pop_type_index]; if (pop_type.research_leadership_optimum > 0 && pop_size > 0) { const pop_sum_t optimum_size = fp::multiply_truncate( - get_total_population(), - pop_type.research_leadership_optimum + get_total_population(), pop_type.research_leadership_optimum ); - const fixed_point_t factor = optimum_size == 0 - ? fixed_point_t::_1 - : std::min( - fp::from_fraction( - pop_size, - optimum_size - ), fixed_point_t::_1 - ); + const fixed_point_t factor = + optimum_size == 0 + ? fixed_point_t::_1 + : std::min(fp::from_fraction(pop_size, optimum_size), fixed_point_t::_1); if (pop_type.research_points != 0) { const fixed_point_t research_points = pop_type.research_points * factor; @@ -1657,11 +1648,12 @@ void CountryInstance::_update_military() { } military_power_from_land.set( - supply_consumption * fp::mul_div( - sum_of_regiment_type_stats, - fixed_point_t::parse_raw(regular_army_size), - fixed_point_t::parse_raw(7 * (1 + unit_type_manager.get_regiment_type_count())) - ) + supply_consumption * + fp::mul_div( + sum_of_regiment_type_stats, + fixed_point_t::parse_raw(regular_army_size), + fixed_point_t::parse_raw(7 * (1 + unit_type_manager.get_regiment_type_count())) + ) ); if (disarmed) { @@ -1677,31 +1669,26 @@ void CountryInstance::_update_military() { // TODO - include gun power and hull modifiers + naval attack and defense modifiers - military_power_from_sea_running_total += (ship_type.gun_power /*+ naval_attack_modifier*/) - * (ship_type.hull /* + naval_defense_modifier*/); + military_power_from_sea_running_total += + (ship_type.gun_power /*+ naval_attack_modifier*/) * (ship_type.hull /* + naval_defense_modifier*/); } } } military_power_from_sea.set(military_power_from_sea_running_total / 250); military_power_from_leaders.set( - fixed_point_t::parse_capped( - std::min( - get_leader_count(), - deployed_non_mobilised_regiments - ) - ) + fixed_point_t::parse_capped(std::min(get_leader_count(), deployed_non_mobilised_regiments)) ); // Mobilisation calculations mobilisation_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilization_impact()); mobilisation_economy_impact = get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_tech()) + - get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_country()); + get_modifier_effect_value(*modifier_effect_cache.get_mobilisation_economy_impact_country()); - // TODO - use country_defines.get_min_mobilize_limit(); (wiki: "lowest maximum of brigades you can mobilize. (by default 3)") + // TODO - use country_defines.get_min_mobilize_limit(); (wiki: "lowest maximum of brigades you can mobilize. (by default + // 3)") - mobilisation_max_regiment_count = regiment_count - + fp::multiply_truncate(regiment_count, mobilisation_impact); + mobilisation_max_regiment_count = regiment_count + fp::multiply_truncate(regiment_count, mobilisation_impact); mobilisation_potential_regiment_count = 0; // TODO - calculate max regiments from poor citizens if (mobilisation_potential_regiment_count > mobilisation_max_regiment_count) { @@ -1712,12 +1699,11 @@ void CountryInstance::_update_military() { // max war exhaustion can be negative, but in such cases the war exhaustion clamping behaviour is // very buggy and regardless it doesn't seem to make any modifier effect contributions. war_exhaustion_max = std::max( - get_modifier_effect_value(*modifier_effect_cache.get_max_war_exhaustion()), fixed_point_t::_0 + get_modifier_effect_value(*modifier_effect_cache.get_max_war_exhaustion()), fixed_point_t::_0 ); - organisation_regain = fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + - get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); + organisation_regain = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_org_regain()) + + get_modifier_effect_value(*modifier_effect_cache.get_morale_global()); land_organisation = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_land_organisation()); naval_organisation = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_naval_organisation()); @@ -1729,12 +1715,11 @@ void CountryInstance::_update_military() { recruit_time = fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_unit_recruitment_time()); combat_width = fp::multiply_truncate( - military_defines.get_base_combat_width(), - get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()) + military_defines.get_base_combat_width(), get_modifier_effect_value(*modifier_effect_cache.get_combat_width_additive()) ); dig_in_cap = get_modifier_effect_value(*modifier_effect_cache.get_dig_in_cap()).floor(); military_tactics = military_defines.get_base_military_tactics() + - get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); + get_modifier_effect_value(*modifier_effect_cache.get_military_tactics()); if (leadership_point_stockpile < 0) { leadership_point_stockpile = 0; @@ -1742,8 +1727,8 @@ void CountryInstance::_update_military() { create_leader_count = (leadership_point_stockpile / military_defines.get_leader_recruit_cost()).floor(); monthly_leadership_points += get_modifier_effect_value(*modifier_effect_cache.get_leadership()); - monthly_leadership_points *= fixed_point_t::_1 + - get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); + monthly_leadership_points *= + fixed_point_t::_1 + get_modifier_effect_value(*modifier_effect_cache.get_leadership_modifier()); if (monthly_leadership_points < 0) { monthly_leadership_points = 0; @@ -1773,7 +1758,7 @@ bool CountryInstance::update_rule_set() { } static constexpr Modifier const& get_country_status_static_effect( - CountryInstance::country_status_t country_status, StaticModifierCache const& static_modifier_cache + CountryInstance::country_status_t country_status, StaticModifierCache const& static_modifier_cache ) { using enum CountryInstance::country_status_t; @@ -1887,7 +1872,7 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan } owns_colonial_province = std::any_of( - owned_provinces.begin(), owned_provinces.end(), std::bind_front(&ProvinceInstance::is_colonial_province) + owned_provinces.begin(), owned_provinces.end(), std::bind_front(&ProvinceInstance::is_colonial_province) ); { @@ -1984,8 +1969,9 @@ void CountryInstance::update_gamestate(const Date today, MapInstance& map_instan _update_politics(); _update_diplomacy(); - const CountryDefinition::government_colour_map_t::const_iterator it = - country_definition.get_alternative_colours().find(government_type.get_untracked()); + const CountryDefinition::government_colour_map_t::const_iterator it = country_definition.get_alternative_colours().find( + government_type.get_untracked() + ); if (it != country_definition.get_alternative_colours().end()) { colour = it.value(); @@ -2031,17 +2017,14 @@ void CountryInstance::after_sell(void* actor, SellResult const& sell_result, mem } void CountryInstance::country_tick_before_map( - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector ) { - //TODO AI sliders - // + reparations + war subsidies - // + industrial subsidies - // + loan interest + // TODO AI sliders + // + reparations + war subsidies + // + industrial subsidies + // + loan interest fixed_point_t available_funds = cash_stockpile_start_of_tick = cash_stockpile; const fixed_point_t projected_administration_spending_copy = projected_administration_spending.get_untracked(); @@ -2049,7 +2032,7 @@ void CountryInstance::country_tick_before_map( const fixed_point_t projected_military_spending_copy = projected_military_spending.get_untracked(); const fixed_point_t projected_social_spending_copy = projected_social_spending.get_untracked(); const fixed_point_t projected_import_subsidies_copy = projected_import_subsidies.get_untracked(); - //excluding national stockpile + // excluding national stockpile const fixed_point_t projected_total_spending = projected_spending.get_untracked(); if (projected_total_spending <= available_funds) { actual_administration_budget = projected_administration_spending_copy; @@ -2059,8 +2042,8 @@ void CountryInstance::country_tick_before_map( actual_import_subsidies_budget = projected_import_subsidies_copy; available_funds -= projected_total_spending; } else { - //TODO try take loan (callback?) - //update available_funds with loan + // TODO try take loan (callback?) + // update available_funds with loan if (available_funds < projected_education_spending_copy) { actual_education_budget = available_funds; @@ -2120,31 +2103,19 @@ void CountryInstance::country_tick_before_map( calculate_government_good_needs(); - manage_national_stockpile( - reusable_goods_mask, - reusable_vectors, - reusable_good_index_vector, - available_funds - ); + manage_national_stockpile(reusable_goods_mask, reusable_vectors, reusable_good_index_vector, available_funds); - //TODO market maker orders + // TODO market maker orders taxable_income_by_pop_type.fill(0); - actual_administration_spending - = actual_education_spending - = actual_military_spending - = actual_pensions_spending - = actual_unemployment_subsidies_spending - = actual_import_subsidies_spending - = actual_tariff_income - = actual_national_stockpile_spending - = actual_national_stockpile_income - = 0; + actual_administration_spending = actual_education_spending = actual_military_spending = actual_pensions_spending = + actual_unemployment_subsidies_spending = actual_import_subsidies_spending = actual_tariff_income = + actual_national_stockpile_spending = actual_national_stockpile_income = 0; } void CountryInstance::calculate_government_good_needs() { - //TODO calculate government_needs, max_government_consumption, army_needs & navy_needs - //for each construction/recruitment + // TODO calculate government_needs, max_government_consumption, army_needs & navy_needs + // for each construction/recruitment // for each good // remainder = resources_total - already_consumed // daily_needs = exact_vic_2_game_rule @@ -2155,13 +2126,10 @@ void CountryInstance::calculate_government_good_needs() { } void CountryInstance::manage_national_stockpile( - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector, - fixed_point_t& available_funds + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector, + fixed_point_t& available_funds ) { TypedSpan wants_more_mask = reusable_goods_mask; const size_t mask_size = type_safe::get(wants_more_mask.size()); @@ -2181,12 +2149,14 @@ void CountryInstance::manage_national_stockpile( for (auto [good_instance, good_data] : goods_data) { const good_index_t good_index = good_instance.index; if (good_data.is_automated || !good_data.is_selling) { - const fixed_point_t quantity_to_allocate_for = good_data.is_automated - ? good_data.government_needs - good_data.stockpile_amount - : good_data.stockpile_cutoff - good_data.stockpile_amount; - const fixed_point_t max_quantity_to_buy = good_data.is_automated - ? good_data.max_government_consumption - good_data.stockpile_amount - : quantity_to_allocate_for; + const fixed_point_t quantity_to_allocate_for = + good_data.is_automated + ? good_data.government_needs - good_data.stockpile_amount + : good_data.stockpile_cutoff - good_data.stockpile_amount; + const fixed_point_t max_quantity_to_buy = + good_data.is_automated + ? good_data.max_government_consumption - good_data.stockpile_amount + : quantity_to_allocate_for; if (max_quantity_to_buy <= 0 || available_funds <= 0) { continue; } @@ -2194,10 +2164,8 @@ void CountryInstance::manage_national_stockpile( good_indices_to_buy.push_back(good_index); max_quantity_to_buy_per_good[good_index] = max_quantity_to_buy; - const fixed_point_t max_money_to_spend = max_costs_per_good[good_index] = market_instance.get_max_money_to_allocate_to_buy_quantity( - good_index, - quantity_to_allocate_for - ); + const fixed_point_t max_money_to_spend = max_costs_per_good[good_index] = + market_instance.get_max_money_to_allocate_to_buy_quantity(good_index, quantity_to_allocate_for); wants_more_mask[good_index] = true; const fixed_point_t weight = weights[good_index] = fixed_point_t::usable_max / max_money_to_spend; weights_sum += weight; @@ -2207,14 +2175,14 @@ void CountryInstance::manage_national_stockpile( continue; } market_instance.place_market_sell_order( - { - good_index, - index, - quantity_to_sell, - this, - after_sell, - }, - reusable_vectors[3] //temporarily used here and later used as money_to_spend_per_good + { + good_index, + index, + quantity_to_sell, + this, + after_sell, + }, + reusable_vectors[3] // temporarily used here and later used as money_to_spend_per_good ); } } @@ -2236,11 +2204,7 @@ void CountryInstance::manage_national_stockpile( const fixed_point_t weight = weights[good_index]; const fixed_point_t max_costs = max_costs_per_good[good_index]; - fixed_point_t cash_available_for_good = fp::mul_div( - cash_left_to_spend_draft, - weight, - weights_sum - ); + fixed_point_t cash_available_for_good = fp::mul_div(cash_left_to_spend_draft, weight, weights_sum); if (cash_available_for_good >= max_costs) { cash_left_to_spend_draft -= max_costs; @@ -2251,7 +2215,8 @@ void CountryInstance::manage_national_stockpile( break; } - const fixed_point_t max_possible_quantity_bought = cash_available_for_good / market_instance.get_min_next_price(good_index); + const fixed_point_t max_possible_quantity_bought = + cash_available_for_good / market_instance.get_min_next_price(good_index); if (max_possible_quantity_bought < fixed_point_t::epsilon) { money_to_spend_per_good[good_index] = 0; } else { @@ -2268,16 +2233,7 @@ void CountryInstance::manage_national_stockpile( } available_funds -= money_to_spend; - market_instance.place_buy_up_to_order( - { - good_index, - index, - max_quantity_to_buy, - money_to_spend, - this, - after_buy - } - ); + market_instance.place_buy_up_to_order({ good_index, index, max_quantity_to_buy, money_to_spend, this, after_buy }); } } @@ -2295,11 +2251,11 @@ void CountryInstance::country_tick_after_map(const Date today) { Technology const* current_research_copy = current_research.get_untracked(); if (current_research_copy != nullptr) { const fixed_point_t research_points_spent = std::min( - std::min( - research_point_stockpile.get_untracked(), - current_research_cost.get_untracked() - invested_research_points.get_untracked() - ), - economy_defines.get_max_daily_research() + std::min( + research_point_stockpile.get_untracked(), + current_research_cost.get_untracked() - invested_research_points.get_untracked() + ), + economy_defines.get_max_daily_research() ); research_point_stockpile -= research_points_spent; @@ -2314,9 +2270,9 @@ void CountryInstance::country_tick_after_map(const Date today) { } // Apply maximum research point stockpile limit - const fixed_point_t max_research_point_stockpile = is_civilised() - ? daily_research_points.get_untracked() * static_cast(Date::DAYS_IN_YEAR) - : country_defines.get_max_research_points(); + const fixed_point_t max_research_point_stockpile = + is_civilised() ? daily_research_points.get_untracked() * static_cast(Date::DAYS_IN_YEAR) + : country_defines.get_max_research_points(); if (research_point_stockpile.get_untracked() > max_research_point_stockpile) { research_point_stockpile.set(max_research_point_stockpile); } @@ -2352,8 +2308,11 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_administration_spending_copy = actual_administration_spending.load(); if (OV_unlikely(actual_administration_spending_copy > actual_administration_budget)) { spdlog::error_s( - "Country {} has overspend on administration. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", - *this, actual_administration_spending_copy, actual_administration_budget + "Country {} has overspend on administration. Spending {} instead of the allocated {}. This indicates a severe bug " + "in the economy code.", + *this, + actual_administration_spending_copy, + actual_administration_budget ); } cash_stockpile -= actual_administration_spending; @@ -2361,8 +2320,11 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_education_spending_copy = actual_education_spending.load(); if (OV_unlikely(actual_education_spending_copy > actual_education_budget)) { spdlog::error_s( - "Country {} has overspend on education. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", - *this, actual_education_spending_copy, actual_education_budget + "Country {} has overspend on education. Spending {} instead of the allocated {}. This indicates a severe bug in " + "the economy code.", + *this, + actual_education_spending_copy, + actual_education_budget ); } cash_stockpile -= actual_education_spending; @@ -2370,19 +2332,26 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_military_spending_copy = actual_military_spending.load(); if (OV_unlikely(actual_military_spending_copy > actual_military_budget)) { spdlog::error_s( - "Country {} has overspend on military. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", - *this, actual_military_spending_copy, actual_military_budget + "Country {} has overspend on military. Spending {} instead of the allocated {}. This indicates a severe bug in the " + "economy code.", + *this, + actual_military_spending_copy, + actual_military_budget ); } cash_stockpile -= actual_military_spending; - const fixed_point_t actual_social_spending_copy = actual_pensions_spending.load() + actual_unemployment_subsidies_spending.load(); + const fixed_point_t actual_social_spending_copy = + actual_pensions_spending.load() + actual_unemployment_subsidies_spending.load(); if (OV_unlikely(actual_social_spending_copy > actual_social_budget)) { spdlog::error_s( - "Country {} has overspend on pensions and/or unemployment subsidies. " - "Spending {} on pensions and {} on unemployment subsidies instead of the total allocated {}. " - "This indicates a severe bug in the economy code.", - *this, actual_pensions_spending.load(), actual_unemployment_subsidies_spending.load(), actual_social_budget + "Country {} has overspend on pensions and/or unemployment subsidies. " + "Spending {} on pensions and {} on unemployment subsidies instead of the total allocated {}. " + "This indicates a severe bug in the economy code.", + *this, + actual_pensions_spending.load(), + actual_unemployment_subsidies_spending.load(), + actual_social_budget ); } cash_stockpile -= actual_pensions_spending; @@ -2391,8 +2360,11 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t actual_import_subsidies_spending_copy = actual_import_subsidies_spending.load(); if (OV_unlikely(actual_import_subsidies_spending_copy > actual_import_subsidies_budget)) { spdlog::error_s( - "Country {} has overspend on import subsidies. Spending {} instead of the allocated {}. This indicates a severe bug in the economy code.", - *this, actual_import_subsidies_spending_copy, actual_import_subsidies_budget + "Country {} has overspend on import subsidies. Spending {} instead of the allocated {}. This indicates a severe " + "bug in the economy code.", + *this, + actual_import_subsidies_spending_copy, + actual_import_subsidies_budget ); } cash_stockpile -= actual_import_subsidies_spending; @@ -2400,77 +2372,77 @@ void CountryInstance::country_tick_after_map(const Date today) { const fixed_point_t cash_stockpile_copy = cash_stockpile.load(); if (OV_unlikely(cash_stockpile_copy < 0)) { spdlog::error_s( - "Country {} has overspend resulting in a cash stockpile of {}. This indicates a severe bug in the economy code.", - *this, cash_stockpile_copy + "Country {} has overspend resulting in a cash stockpile of {}. This indicates a severe bug in the economy code.", + *this, + cash_stockpile_copy ); } cash_stockpile += actual_tariff_income; - const fixed_point_t gold_income_value = country_defines.get_gold_to_cash_rate() * total_gold_production;; + const fixed_point_t gold_income_value = country_defines.get_gold_to_cash_rate() * total_gold_production; + ; gold_income.set(gold_income_value); cash_stockpile += gold_income_value; const fixed_point_t yesterdays_balance = cash_stockpile - cash_stockpile_start_of_tick; balance_history.push_back(yesterdays_balance); } -CountryInstance::good_data_t::good_data_t() - : mutex { memory::make_unique() } - { } +CountryInstance::good_data_t::good_data_t() : mutex { memory::make_unique() } {} void CountryInstance::good_data_t::clear_daily_recorded_data() { const std::lock_guard lock_guard { *mutex }; - stockpile_change_yesterday - = quantity_traded_yesterday - = money_traded_yesterday - = exported_amount - = max_government_consumption - = government_needs - = army_needs - = navy_needs - = overseas_maintenance - = factory_demand - = pop_demand - = available_amount - = 0; + stockpile_change_yesterday = quantity_traded_yesterday = money_traded_yesterday = exported_amount = + max_government_consumption = government_needs = army_needs = navy_needs = overseas_maintenance = factory_demand = + pop_demand = available_amount = 0; need_consumption_per_pop_type.clear(); input_consumption_per_production_type.clear(); production_per_production_type.clear(); } -void CountryInstance::report_pop_income_tax(PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax) { +void CountryInstance::report_pop_income_tax( + PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax +) { const std::lock_guard lock_guard { taxable_income_mutex }; taxable_income_by_pop_type.at(pop_type) += gross_income; cash_stockpile += paid_as_tax; } -void CountryInstance::report_pop_need_consumption(PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity) { +void CountryInstance::report_pop_need_consumption( + PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity +) { good_data_t& good_data = goods_data.at_index(good_index); const std::lock_guard lock_guard { *good_data.mutex }; good_data.need_consumption_per_pop_type[&pop_type] += quantity; } -void CountryInstance::report_pop_need_demand(PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity) { +void CountryInstance::report_pop_need_demand( + PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity +) { good_data_t& good_data = goods_data.at_index(good_index); const std::lock_guard lock_guard { *good_data.mutex }; good_data.pop_demand += quantity; } -void CountryInstance::report_input_consumption(ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity) { +void CountryInstance::report_input_consumption( + ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity +) { good_data_t& good_data = goods_data.at_index(good_index); const std::lock_guard lock_guard { *good_data.mutex }; good_data.input_consumption_per_production_type[&production_type] += quantity; } -void CountryInstance::report_input_demand(ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity) { +void CountryInstance::report_input_demand( + ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity +) { good_data_t& good_data = goods_data.at_index(good_index); if (production_type.template_type == ProductionType::template_type_t::ARTISAN) { switch (game_rules_manager.get_artisanal_input_demand_category()) { - case demand_category::FactoryNeeds: break; - case demand_category::PopNeeds: { - const std::lock_guard lock_guard { *good_data.mutex }; - good_data.pop_demand += quantity; - return; - } - default: return; //demand_category::None + case demand_category::FactoryNeeds: break; + case demand_category::PopNeeds: { + const std::lock_guard lock_guard { *good_data.mutex }; + good_data.pop_demand += quantity; + return; + } + default: return; // demand_category::None } } @@ -2489,11 +2461,13 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop SharedPopTypeValues const& pop_type_values = shared_country_values.get_shared_pop_type_values(pop_type); if (actual_administration_budget > 0) { - const fixed_point_t administration_salary = fp::mul_div( - pop_size * administration_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_administration_budget, - projected_administration_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t administration_salary = + fp::mul_div( + pop_size * administration_salary_base_by_pop_type.at(pop_type).get_untracked(), + actual_administration_budget, + projected_administration_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (administration_salary > 0) { pop.add_government_salary_administration(administration_salary); actual_administration_spending += administration_salary; @@ -2501,11 +2475,13 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop } if (actual_education_budget > 0) { - const fixed_point_t education_salary = fp::mul_div( - pop_size * education_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_education_budget, - projected_education_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t education_salary = + fp::mul_div( + pop_size * education_salary_base_by_pop_type.at(pop_type).get_untracked(), + actual_education_budget, + projected_education_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (education_salary > 0) { pop.add_government_salary_education(education_salary); actual_education_spending += education_salary; @@ -2513,11 +2489,13 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop } if (actual_military_budget > 0) { - const fixed_point_t military_salary = fp::mul_div( - pop_size * military_salary_base_by_pop_type.at(pop_type).get_untracked(), - actual_military_budget, - projected_military_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t military_salary = + fp::mul_div( + pop_size * military_salary_base_by_pop_type.at(pop_type).get_untracked(), + actual_military_budget, + projected_military_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (military_salary > 0) { pop.add_government_salary_military(military_salary); actual_military_spending += military_salary; @@ -2525,21 +2503,25 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop } if (actual_social_budget > 0) { - const fixed_point_t pension_income = fp::mul_div( - pop_size * calculate_pensions_base(pop_type), - actual_social_budget, - projected_social_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t pension_income = + fp::mul_div( + pop_size * calculate_pensions_base(pop_type), + actual_social_budget, + projected_social_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (pension_income > 0) { pop.add_pensions(pension_income); actual_pensions_spending += pension_income; } - const fixed_point_t unemployment_subsidies = fp::mul_div( - pop.get_unemployed() * calculate_unemployment_subsidies_base(pop_type), - actual_social_budget, - projected_social_spending_unscaled_by_slider.get_untracked() - ) / Pop::size_denominator; + const fixed_point_t unemployment_subsidies = + fp::mul_div( + pop.get_unemployed() * calculate_unemployment_subsidies_base(pop_type), + actual_social_budget, + projected_social_spending_unscaled_by_slider.get_untracked() + ) / + Pop::size_denominator; if (unemployment_subsidies > 0) { pop.add_unemployment_subsidies(unemployment_subsidies); actual_unemployment_subsidies_spending += unemployment_subsidies; @@ -2548,11 +2530,11 @@ void CountryInstance::request_salaries_and_welfare_and_import_subsidies(Pop& pop if (actual_import_subsidies_budget > 0) { const fixed_point_t import_subsidies = fp::mul_div( - effective_tariff_rate.get_untracked() // < 0 - * pop.get_yesterdays_import_value().get_copy_of_value(), - actual_import_subsidies_budget, // < 0 - projected_import_subsidies.get_untracked() // > 0 - ); //effective_tariff_rate * actual_net_tariffs cancel out the negative + effective_tariff_rate.get_untracked() // < 0 + * pop.get_yesterdays_import_value().get_copy_of_value(), + actual_import_subsidies_budget, // < 0 + projected_import_subsidies.get_untracked() // > 0 + ); // effective_tariff_rate * actual_net_tariffs cancel out the negative pop.add_import_subsidies(import_subsidies); actual_import_subsidies_spending += import_subsidies; } diff --git a/src/openvic-simulation/country/CountryInstance.hpp b/src/openvic-simulation/country/CountryInstance.hpp index 7a1ff65ed..59c4fc353 100644 --- a/src/openvic-simulation/country/CountryInstance.hpp +++ b/src/openvic-simulation/country/CountryInstance.hpp @@ -90,11 +90,11 @@ namespace OpenVic { friend struct CountryInstanceManager; /* - Westernisation Progress vs Status for Uncivilised Countries: - 15 - primitive - 16 - uncivilised - 50 - uncivilised - 51 - partially westernised + Westernisation Progress vs Status for Uncivilised Countries: + 15 - primitive + 16 - uncivilised + 50 - uncivilised + 51 - partially westernised */ enum struct country_status_t : uint8_t { @@ -157,8 +157,12 @@ namespace OpenVic { /* Production */ OV_STATE_PROPERTY(fixed_point_t, industrial_power); - memory::vector, fixed_point_t>> SPAN_PROPERTY(industrial_power_from_states); - memory::vector, fixed_point_t>> SPAN_PROPERTY(industrial_power_from_investments); + memory::vector, fixed_point_t>> SPAN_PROPERTY( + industrial_power_from_states + ); + memory::vector, fixed_point_t>> SPAN_PROPERTY( + industrial_power_from_investments + ); size_t PROPERTY(industrial_rank, 0); fixed_point_map_t> PROPERTY(foreign_investments); OV_IFLATMAP_PROPERTY(BuildingType, building_level_t, building_type_unlock_levels); @@ -173,23 +177,26 @@ namespace OpenVic { OV_IFLATMAP_PROPERTY(PopType, fixed_point_t, taxable_income_by_pop_type); OV_STATE_PROPERTY(fixed_point_t, tax_efficiency); IndexedFlatMap> PROPERTY(effective_tax_rate_by_strata); + public: DerivedState& get_effective_tax_rate_by_strata(Strata const& strata); + private: IndexedFlatMap tax_rate_slider_value_by_strata; + public: [[nodiscard]] constexpr IndexedFlatMap const& get_tax_rate_slider_value_by_strata() const { return tax_rate_slider_value_by_strata; } [[nodiscard]] ReadOnlyClampedValue& get_tax_rate_slider_value_by_strata(Strata const& strata); [[nodiscard]] ReadOnlyClampedValue const& get_tax_rate_slider_value_by_strata(Strata const& strata) const; - private: + private: OV_STATE_PROPERTY(fixed_point_t, administrative_efficiency_from_administrators); OV_STATE_PROPERTY(fixed_point_t, administrator_percentage); - //store per slider per good: desired, bought & cost - //store purchase record from last tick and prediction next tick + // store per slider per good: desired, bought & cost + // store purchase record from last tick and prediction next tick OV_CLAMPED_PROPERTY(army_spending_slider_value); OV_CLAMPED_PROPERTY(navy_spending_slider_value); OV_CLAMPED_PROPERTY(construction_spending_slider_value); @@ -222,7 +229,7 @@ namespace OpenVic { atomic_fixed_point_t PROPERTY(actual_pensions_spending); atomic_fixed_point_t PROPERTY(actual_unemployment_subsidies_spending); - //base here means not scaled by slider or pop size + // base here means not scaled by slider or pop size IndexedFlatMap> administration_salary_base_by_pop_type; IndexedFlatMap> education_salary_base_by_pop_type; IndexedFlatMap> military_salary_base_by_pop_type; @@ -237,8 +244,8 @@ namespace OpenVic { return actual_tariff_income.load() - actual_import_subsidies_spending.load(); } - //TODO actual factory subsidies - //projected cost is UI only and lists the different factories + // TODO actual factory subsidies + // projected cost is UI only and lists the different factories /* Technology */ OV_IFLATMAP_PROPERTY(Technology, technology_unlock_level_t, technology_unlock_levels); @@ -317,8 +324,8 @@ namespace OpenVic { fixed_point_t exported_amount; // negative if net importing - fixed_point_t max_government_consumption; //for automated BuyUpToOrder - fixed_point_t government_needs; //quantity to allocate for while automated + fixed_point_t max_government_consumption; // for automated BuyUpToOrder + fixed_point_t government_needs; // quantity to allocate for while automated fixed_point_t army_needs; fixed_point_t navy_needs; fixed_point_t overseas_maintenance; @@ -334,7 +341,7 @@ namespace OpenVic { good_data_t(good_data_t&&) = default; good_data_t& operator=(good_data_t&&) = default; - //thread safe + // thread safe void clear_daily_recorded_data(); }; @@ -401,9 +408,9 @@ namespace OpenVic { public: CountryInstance( - CountryDefinition const& new_country_definition, - SharedCountryValues& new_shared_country_values, - CountryInstanceDeps const& country_instance_deps + CountryDefinition const& new_country_definition, + SharedCountryValues& new_shared_country_values, + CountryInstanceDeps const& country_instance_deps ); CountryInstance(CountryInstance const&) = delete; CountryInstance& operator=(CountryInstance const&) = delete; @@ -456,7 +463,9 @@ namespace OpenVic { [[nodiscard]] bool is_secondary_power() const; [[nodiscard]] bool is_at_war() const; [[nodiscard]] bool is_neighbour(CountryInstance const& country) const; - [[nodiscard]] bool may_build_in(const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location) const; + [[nodiscard]] bool may_build_in( + const BuildingRestrictionCategory restriction_category, ProvinceInstance const& location + ) const; // Double-sided diplomacy functions @@ -496,7 +505,9 @@ namespace OpenVic { void set_influence_with(CountryInstance& country, CountryRelationManager::influence_value_type influence); CountryRelationManager::influence_priority_value_type get_influence_priority_with(CountryInstance const& country) const; - void set_influence_priority_with(CountryInstance& country, CountryRelationManager::influence_priority_value_type influence); + void set_influence_priority_with( + CountryInstance& country, CountryRelationManager::influence_priority_value_type influence + ); std::optional get_decredited_from_date(CountryInstance const& country) const; void set_discredited_from(CountryInstance& country, Date until); @@ -562,13 +573,13 @@ namespace OpenVic { [[nodiscard]] bool is_unit_type_unlocked(UnitType const& unit_type) const; bool modify_unit_type_unlock(UnitType const&, technology_unlock_level_t unlock_level_change); - bool modify_unit_type_unlock(const regiment_type_index_t regiment_type_index, technology_unlock_level_t unlock_level_change); + bool modify_unit_type_unlock( + const regiment_type_index_t regiment_type_index, technology_unlock_level_t unlock_level_change + ); bool modify_unit_type_unlock(const ship_type_index_t ship_type_index, technology_unlock_level_t unlock_level_change); bool unlock_unit_type(UnitType const& unit_type); - bool modify_building_type_unlock( - BuildingType const& building_type, technology_unlock_level_t unlock_level_change - ); + bool modify_building_type_unlock(BuildingType const& building_type, technology_unlock_level_t unlock_level_change); bool unlock_building_type(BuildingType const& building_type); [[nodiscard]] bool is_building_type_unlocked(BuildingType const& building_type) const; @@ -588,21 +599,13 @@ namespace OpenVic { bool unlock_unit_variant(unit_variant_t unit_variant); [[nodiscard]] unit_variant_t get_max_unlocked_unit_variant() const; - bool modify_technology_unlock( - Technology const& technology, technology_unlock_level_t unlock_level_change - ); - bool set_technology_unlock_level( - Technology const& technology, technology_unlock_level_t unlock_level - ); + bool modify_technology_unlock(Technology const& technology, technology_unlock_level_t unlock_level_change); + bool set_technology_unlock_level(Technology const& technology, technology_unlock_level_t unlock_level); bool unlock_technology(Technology const& technology); [[nodiscard]] bool is_technology_unlocked(Technology const& technology) const; - bool modify_invention_unlock( - Invention const& invention, technology_unlock_level_t unlock_level_change - ); - bool set_invention_unlock_level( - Invention const& invention, technology_unlock_level_t unlock_level - ); + bool modify_invention_unlock(Invention const& invention, technology_unlock_level_t unlock_level_change); + bool set_invention_unlock_level(Invention const& invention, technology_unlock_level_t unlock_level); bool unlock_invention(Invention const& invention); [[nodiscard]] bool is_invention_unlocked(Invention const& invention) const; @@ -617,15 +620,15 @@ namespace OpenVic { // Sets the investment of each country in the map (rather than adding to them), leaving the rest unchanged. void apply_foreign_investments( - fixed_point_map_t const& investments, - CountryInstanceManager const& country_instance_manager + fixed_point_map_t const& investments, + CountryInstanceManager const& country_instance_manager ); bool apply_history_to_country( - CountryHistoryEntry const& entry, - CountryInstanceManager const& country_instance_manager, - FlagStrings& global_flags, - MapInstance& map_instance + CountryHistoryEntry const& entry, + CountryInstanceManager const& country_instance_manager, + FlagStrings& global_flags, + MapInstance& map_instance ); private: @@ -635,16 +638,20 @@ namespace OpenVic { template constexpr bool validate_unit_unlock_change( - const IndexT index, - const technology_unlock_level_t unlock_level, - const technology_unlock_level_t unlock_level_change + const IndexT index, + const technology_unlock_level_t unlock_level, + const technology_unlock_level_t unlock_level_change ) const { // This catches subtracting below 0 or adding above the int types maximum value if (unlock_level + unlock_level_change < 0) { spdlog::error_s( - "Attempted to change unlock level for {} in country {} to invalid value: current level = {}, change = {}, invalid new value = {}", - index, *this, unlock_level, - unlock_level_change, unlock_level + unlock_level_change + "Attempted to change unlock level for {} in country {} to invalid value: current level = {}, change = {}, " + "invalid new value = {}", + index, + *this, + unlock_level, + unlock_level_change, + unlock_level + unlock_level_change ); return false; } @@ -653,25 +660,22 @@ namespace OpenVic { } static void after_buy(void* actor, BuyResult const& buy_result); - //matching GoodMarketSellOrder::callback_t + // matching GoodMarketSellOrder::callback_t static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector); void calculate_government_good_needs(); void manage_national_stockpile( - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector, - fixed_point_t& available_funds + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector, + fixed_point_t& available_funds ); void _update_production(); void _update_budget(); - //base here means not scaled by slider or pop size + // base here means not scaled by slider or pop size fixed_point_t calculate_pensions_base(PopType const& pop_type); fixed_point_t calculate_unemployment_subsidies_base(PopType const& pop_type); @@ -691,19 +695,16 @@ namespace OpenVic { void contribute_province_modifier_sum(ModifierSum const& province_modifier_sum); fixed_point_t get_modifier_effect_value(ModifierEffect const& effect) const; constexpr void for_each_contributing_modifier( - ModifierEffect const& effect, ContributingModifierCallback auto callback + ModifierEffect const& effect, ContributingModifierCallback auto callback ) const { return modifier_sum.for_each_contributing_modifier(effect, std::move(callback)); } void update_gamestate(const Date today, MapInstance& map_instance); void country_tick_before_map( - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_COUNTRY_TICK - > reusable_vectors, - memory::vector& reusable_good_index_vector + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_COUNTRY_TICK> reusable_vectors, + memory::vector& reusable_good_index_vector ); void country_tick_after_map(const Date today); @@ -712,12 +713,16 @@ namespace OpenVic { good_data_t& get_good_data(GoodDefinition const& good_definition); good_data_t const& get_good_data(GoodDefinition const& good_definition) const; - //thread safe + // thread safe void report_pop_income_tax(PopType const& pop_type, const fixed_point_t gross_income, const fixed_point_t paid_as_tax); void report_pop_need_consumption(PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity); void report_pop_need_demand(PopType const& pop_type, const good_index_t good_index, const fixed_point_t quantity); - void report_input_consumption(ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity); - void report_input_demand(ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity); + void report_input_consumption( + ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity + ); + void report_input_demand( + ProductionType const& production_type, const good_index_t good_index, const fixed_point_t quantity + ); void report_output(ProductionType const& production_type, const fixed_point_t quantity); void request_salaries_and_welfare_and_import_subsidies(Pop& pop); fixed_point_t calculate_minimum_wage_base(PopType const& pop_type); diff --git a/src/openvic-simulation/country/CountryInstanceDeps.hpp b/src/openvic-simulation/country/CountryInstanceDeps.hpp index 05af05b2e..b8ef4edae 100644 --- a/src/openvic-simulation/country/CountryInstanceDeps.hpp +++ b/src/openvic-simulation/country/CountryInstanceDeps.hpp @@ -48,10 +48,10 @@ namespace OpenVic { PopsAggregateDeps pops_aggregate_deps; forwardable_span pop_types; forwardable_span reform_groups; - memory::vector const& regiment_types; //can't use forwardable_span due to macos + memory::vector const& regiment_types; // can't use forwardable_span due to macos memory::vector const& ship_types; forwardable_span stratas; forwardable_span technologies; UnitTypeManager const& unit_type_manager; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/country/CountryInstanceManager.cpp b/src/openvic-simulation/country/CountryInstanceManager.cpp index 8652cdd99..bd341aca0 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.cpp +++ b/src/openvic-simulation/country/CountryInstanceManager.cpp @@ -3,11 +3,11 @@ #include #include +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/core/object/Timespan.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/defines/CountryDefines.hpp" -#include "openvic-simulation/DefinitionManager.hpp" -#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/history/CountryHistory.hpp" #include "openvic-simulation/military/UnitInstanceGroup.hpp" #include "openvic-simulation/population/Pop.hpp" @@ -16,38 +16,27 @@ using namespace OpenVic; CountryInstanceManager::CountryInstanceManager( - CountryDefines const& new_country_defines, - CountryDefinitionManager const& new_country_definition_manager, - CountryInstanceDeps const& country_instance_deps, - GoodInstanceManager const& new_good_instance_manager, - PopsDefines const& new_pop_defines, - forwardable_span pop_type_keys, - memory::vector const& regiment_types, - ThreadPool& new_thread_pool -) : thread_pool { new_thread_pool }, - country_definition_manager { new_country_definition_manager }, - country_defines { new_country_defines }, - shared_country_values { - new_pop_defines, - new_good_instance_manager, - pop_type_keys, - regiment_types - }, - country_instances { - country_index_t(new_country_definition_manager.get_country_definition_count()), - [ - this, - &new_country_definition_manager, - &country_instance_deps - ](const country_index_t country_index)->auto{ - return std::make_tuple( - std::ref(*new_country_definition_manager.get_country_definition_by_index(country_index)), - std::ref(shared_country_values), - std::ref(country_instance_deps) - ); - } - } -{ + CountryDefines const& new_country_defines, + CountryDefinitionManager const& new_country_definition_manager, + CountryInstanceDeps const& country_instance_deps, + GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, + forwardable_span pop_type_keys, + memory::vector const& regiment_types, + ThreadPool& new_thread_pool +) : + thread_pool { new_thread_pool }, country_definition_manager { new_country_definition_manager }, + country_defines { new_country_defines }, + shared_country_values { new_pop_defines, new_good_instance_manager, pop_type_keys, regiment_types }, country_instances { + country_index_t(new_country_definition_manager.get_country_definition_count()), + [this, &new_country_definition_manager, &country_instance_deps](const country_index_t country_index) -> auto { + return std::make_tuple( + std::ref(*new_country_definition_manager.get_country_definition_by_index(country_index)), + std::ref(shared_country_values), + std::ref(country_instance_deps) + ); + } + } { assert(new_country_definition_manager.country_definitions_are_locked()); great_powers.reserve(new_country_defines.get_great_power_rank()); secondary_powers.reserve(new_country_defines.get_max_secondary_power_count()); @@ -66,31 +55,27 @@ void CountryInstanceManager::update_rankings(const Date today) { industrial_power_ranking = total_ranking; military_power_ranking = total_ranking; + std::stable_sort(total_ranking.begin(), total_ranking.end(), [](CountryInstance& a, CountryInstance& b) -> bool { + const bool a_civilised = a.is_civilised(); + const bool b_civilised = b.is_civilised(); + return a_civilised != b_civilised ? a_civilised : a.total_score.get_untracked() > b.total_score.get_untracked(); + }); std::stable_sort( - total_ranking.begin(), total_ranking.end(), - [](CountryInstance& a, CountryInstance& b) -> bool { - const bool a_civilised = a.is_civilised(); - const bool b_civilised = b.is_civilised(); - return a_civilised != b_civilised ? a_civilised : a.total_score.get_untracked() > b.total_score.get_untracked(); - } - ); - std::stable_sort( - prestige_ranking.begin(), prestige_ranking.end(), - [](CountryInstance const& a, CountryInstance const& b) -> bool { - return a.get_prestige_untracked() > b.get_prestige_untracked(); - } + prestige_ranking.begin(), prestige_ranking.end(), [](CountryInstance const& a, CountryInstance const& b) -> bool { + return a.get_prestige_untracked() > b.get_prestige_untracked(); + } ); std::stable_sort( - industrial_power_ranking.begin(), industrial_power_ranking.end(), - [](CountryInstance const& a, CountryInstance const& b) -> bool { - return a.get_industrial_power_untracked() > b.get_industrial_power_untracked(); - } + industrial_power_ranking.begin(), + industrial_power_ranking.end(), + [](CountryInstance const& a, CountryInstance const& b) -> bool { + return a.get_industrial_power_untracked() > b.get_industrial_power_untracked(); + } ); std::stable_sort( - military_power_ranking.begin(), military_power_ranking.end(), - [](CountryInstance& a, CountryInstance& b) -> bool { - return a.military_power.get_untracked() > b.military_power.get_untracked(); - } + military_power_ranking.begin(), military_power_ranking.end(), [](CountryInstance& a, CountryInstance& b) -> bool { + return a.military_power.get_untracked() > b.military_power.get_untracked(); + } ); for (size_t index = 0; index < total_ranking.size(); ++index) { @@ -112,8 +97,8 @@ void CountryInstanceManager::update_rankings(const Date today) { std::erase_if(great_powers, [max_great_power_rank, today](CountryInstance& great_power) -> bool { if (OV_likely(great_power.get_country_status() == COUNTRY_STATUS_GREAT_POWER)) { if (OV_unlikely( - great_power.get_total_rank() > max_great_power_rank && great_power.get_lose_great_power_date() < today - )) { + great_power.get_total_rank() > max_great_power_rank && great_power.get_lose_great_power_date() < today + )) { great_power.country_status = COUNTRY_STATUS_CIVILISED; return true; } else { @@ -180,26 +165,24 @@ void CountryInstanceManager::update_rankings(const Date today) { CountryInstance* CountryInstanceManager::get_country_instance_by_identifier(std::string_view identifier) { CountryDefinition const* country_definition = country_definition_manager.get_country_definition_by_identifier(identifier); - return country_definition == nullptr - ? nullptr - : &get_country_instance_by_definition(*country_definition); + return country_definition == nullptr ? nullptr : &get_country_instance_by_definition(*country_definition); } CountryInstance const* CountryInstanceManager::get_country_instance_by_identifier(std::string_view identifier) const { CountryDefinition const* country_definition = country_definition_manager.get_country_definition_by_identifier(identifier); - return country_definition == nullptr - ? nullptr - : &(country_instances[country_definition->index]); + return country_definition == nullptr ? nullptr : &(country_instances[country_definition->index]); } CountryInstance& CountryInstanceManager::get_country_instance_by_definition(CountryDefinition const& country_definition) { return get_country_instance_by_index(country_definition.index); } -CountryInstance const& CountryInstanceManager::get_country_instance_by_definition(CountryDefinition const& country_definition) const { +CountryInstance const& CountryInstanceManager::get_country_instance_by_definition( + CountryDefinition const& country_definition +) const { return get_country_instance_by_index(country_definition.index); } bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instance_manager) { CountryHistoryManager const& history_manager = - instance_manager.definition_manager.get_history_manager().get_country_manager(); + instance_manager.definition_manager.get_history_manager().get_country_manager(); bool ret = true; @@ -214,9 +197,7 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc country_instance.last_war_loss_date = starting_last_war_loss_date; if (!country_instance.country_definition.is_dynamic_tag) { - CountryHistoryMap const* history_map = history_manager.get_country_history( - country_instance.country_definition - ); + CountryHistoryMap const* history_map = history_manager.get_country_history(country_instance.country_definition); if (history_map != nullptr) { static constexpr fixed_point_t DEFAULT_STATE_CULTURE_LITERACY = fixed_point_t::_0_50; @@ -228,12 +209,7 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc for (auto const& [entry_date, entry] : history_map->get_entries()) { if (entry_date <= today) { - ret &= country_instance.apply_history_to_country( - *entry, - *this, - global_flags, - map_instance - ); + ret &= country_instance.apply_history_to_country(*entry, *this, global_flags, map_instance); if (entry->get_initial_oob() != nullptr) { oob_history_entry = entry.get(); @@ -257,9 +233,10 @@ bool CountryInstanceManager::apply_history_to_countries(InstanceManager& instanc } if (oob_history_entry != nullptr) { - ret &= oob_history_entry->get_initial_oob() != nullptr && unit_instance_manager.generate_deployment( - map_instance, country_instance, *oob_history_entry->get_initial_oob() - ); + ret &= oob_history_entry->get_initial_oob() != nullptr && + unit_instance_manager.generate_deployment( + map_instance, country_instance, *oob_history_entry->get_initial_oob() + ); } // TODO - check if better to do "if"s then "for"s, so looping multiple times rather than having lots of diff --git a/src/openvic-simulation/country/CountryInstanceManager.hpp b/src/openvic-simulation/country/CountryInstanceManager.hpp index b0cffdf2d..5d3be89bd 100644 --- a/src/openvic-simulation/country/CountryInstanceManager.hpp +++ b/src/openvic-simulation/country/CountryInstanceManager.hpp @@ -45,14 +45,14 @@ namespace OpenVic { public: CountryInstanceManager( - CountryDefines const& new_country_defines, - CountryDefinitionManager const& new_country_definition_manager, - CountryInstanceDeps const& country_instance_deps, - GoodInstanceManager const& new_good_instance_manager, - PopsDefines const& new_pop_defines, - forwardable_span pop_type_keys, - memory::vector const& regiment_types, - ThreadPool& new_thread_pool + CountryDefines const& new_country_defines, + CountryDefinitionManager const& new_country_definition_manager, + CountryInstanceDeps const& country_instance_deps, + GoodInstanceManager const& new_good_instance_manager, + PopsDefines const& new_pop_defines, + forwardable_span pop_type_keys, + memory::vector const& regiment_types, + ThreadPool& new_thread_pool ); constexpr std::span get_country_instances() { diff --git a/src/openvic-simulation/country/CountryParty.cpp b/src/openvic-simulation/country/CountryParty.cpp index fb69e5a3f..bb24a81a9 100644 --- a/src/openvic-simulation/country/CountryParty.cpp +++ b/src/openvic-simulation/country/CountryParty.cpp @@ -5,14 +5,13 @@ using namespace OpenVic; CountryParty::CountryParty( - std::string_view new_identifier, Date new_start_date, Date new_end_date, Ideology const* new_ideology, - decltype(policies)&& new_policies -) : HasIdentifierAndColour { - new_identifier, - new_ideology != nullptr ? new_ideology->get_colour() : Ideology::NO_IDEOLOGY_COLOUR, - false - }, - start_date { new_start_date }, - end_date { new_end_date }, - ideology { new_ideology }, - policies { std::move(new_policies) } {} \ No newline at end of file + std::string_view new_identifier, + Date new_start_date, + Date new_end_date, + Ideology const* new_ideology, + decltype(policies)&& new_policies +) : + HasIdentifierAndColour { + new_identifier, new_ideology != nullptr ? new_ideology->get_colour() : Ideology::NO_IDEOLOGY_COLOUR, false + }, + start_date { new_start_date }, end_date { new_end_date }, ideology { new_ideology }, policies { std::move(new_policies) } {} diff --git a/src/openvic-simulation/country/CountryParty.hpp b/src/openvic-simulation/country/CountryParty.hpp index 2c2ca1cdb..d54107fd6 100644 --- a/src/openvic-simulation/country/CountryParty.hpp +++ b/src/openvic-simulation/country/CountryParty.hpp @@ -20,11 +20,11 @@ namespace OpenVic { Ideology const* const ideology; // Can be nullptr, shows up as "No Ideology" in game CountryParty( - std::string_view new_identifier, - Date new_start_date, - Date new_end_date, - Ideology const* new_ideology, - decltype(policies)&& new_policies + std::string_view new_identifier, + Date new_start_date, + Date new_end_date, + Ideology const* new_ideology, + decltype(policies)&& new_policies ); CountryParty(CountryParty&&) = default; }; diff --git a/src/openvic-simulation/country/SharedCountryValues.cpp b/src/openvic-simulation/country/SharedCountryValues.cpp index 39dc6e129..07b4ba402 100644 --- a/src/openvic-simulation/country/SharedCountryValues.cpp +++ b/src/openvic-simulation/country/SharedCountryValues.cpp @@ -10,15 +10,13 @@ using namespace OpenVic; SharedCountryValues::SharedCountryValues( - PopsDefines const& new_pop_defines, - GoodInstanceManager const& new_good_instance_manager, - decltype(shared_pop_type_values)::keys_span_type pop_type_keys, - memory::vector const& new_regiment_types -) : pop_defines { new_pop_defines }, - good_instance_manager { new_good_instance_manager }, - shared_pop_type_values { pop_type_keys }, - regiment_types { new_regiment_types } - {} + PopsDefines const& new_pop_defines, + GoodInstanceManager const& new_good_instance_manager, + decltype(shared_pop_type_values)::keys_span_type pop_type_keys, + memory::vector const& new_regiment_types +) : + pop_defines { new_pop_defines }, good_instance_manager { new_good_instance_manager }, + shared_pop_type_values { pop_type_keys }, regiment_types { new_regiment_types } {} SharedPopTypeValues& SharedCountryValues::get_shared_pop_type_values(PopType const& pop_type) { return shared_pop_type_values.at(pop_type); @@ -36,26 +34,26 @@ void SharedPopTypeValues::update_costs(PopsDefines const& pop_defines, GoodInsta fixed_point_t military_salary_base_running_total = 0; using enum PopType::income_type_t; - #define UPDATE_NEED_COSTS(need_category) \ - base_##need_category##_need_costs = 0; \ - for (auto const& [good_index, quantity] : pop_type.get_##need_category##_needs()) { \ - GoodInstance const& good_instance = *good_instance_manager.get_good_instance_by_index(good_index); \ - base_##need_category##_need_costs += good_instance.get_price() * quantity; \ - } \ - base_##need_category##_need_costs *= pop_defines.get_base_goods_demand(); \ - if ((pop_type.get_##need_category##_needs_income_types() & ADMINISTRATION) == ADMINISTRATION) { \ - administration_salary_base_running_total += base_##need_category##_need_costs; \ - } \ - if ((pop_type.get_##need_category##_needs_income_types() & EDUCATION) == EDUCATION) { \ - education_salary_base_running_total += base_##need_category##_need_costs; \ - } \ - if ((pop_type.get_##need_category##_needs_income_types() & MILITARY) == MILITARY) { \ - military_salary_base_running_total += base_##need_category##_need_costs; \ - } +#define UPDATE_NEED_COSTS(need_category) \ + base_##need_category##_need_costs = 0; \ + for (auto const& [good_index, quantity] : pop_type.get_##need_category##_needs()) { \ + GoodInstance const& good_instance = *good_instance_manager.get_good_instance_by_index(good_index); \ + base_##need_category##_need_costs += good_instance.get_price() * quantity; \ + } \ + base_##need_category##_need_costs *= pop_defines.get_base_goods_demand(); \ + if ((pop_type.get_##need_category##_needs_income_types() & ADMINISTRATION) == ADMINISTRATION) { \ + administration_salary_base_running_total += base_##need_category##_need_costs; \ + } \ + if ((pop_type.get_##need_category##_needs_income_types() & EDUCATION) == EDUCATION) { \ + education_salary_base_running_total += base_##need_category##_need_costs; \ + } \ + if ((pop_type.get_##need_category##_needs_income_types() & MILITARY) == MILITARY) { \ + military_salary_base_running_total += base_##need_category##_need_costs; \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(UPDATE_NEED_COSTS) - #undef UPDATE_NEED_COSTS +#undef UPDATE_NEED_COSTS administration_salary_base.set(administration_salary_base_running_total); education_salary_base.set(education_salary_base_running_total); diff --git a/src/openvic-simulation/country/SharedCountryValues.hpp b/src/openvic-simulation/country/SharedCountryValues.hpp index 8220c9c95..f39aae2a7 100644 --- a/src/openvic-simulation/country/SharedCountryValues.hpp +++ b/src/openvic-simulation/country/SharedCountryValues.hpp @@ -15,15 +15,15 @@ namespace OpenVic { struct SharedPopTypeValues { friend SharedCountryValues; + private: PopType const& pop_type; - #define NEED_COST_FIELD(need_category) \ - fixed_point_t base_##need_category##_need_costs; +#define NEED_COST_FIELD(need_category) fixed_point_t base_##need_category##_need_costs; OV_DO_FOR_ALL_NEED_CATEGORIES(NEED_COST_FIELD) - #undef NEED_COST_FIELD +#undef NEED_COST_FIELD OV_STATE_PROPERTY(fixed_point_t, administration_salary_base); OV_STATE_PROPERTY(fixed_point_t, education_salary_base); @@ -31,12 +31,14 @@ namespace OpenVic { OV_STATE_PROPERTY(fixed_point_t, social_income_variant_base); void update_costs(PopsDefines const& pop_defines, GoodInstanceManager const& good_instance_manager); + public: constexpr SharedPopTypeValues(PopType const& new_pop_type) : pop_type { new_pop_type } {}; }; struct SharedCountryValues { friend CountryInstanceManager; + private: PopsDefines const& pop_defines; GoodInstanceManager const& good_instance_manager; @@ -50,10 +52,10 @@ namespace OpenVic { SharedPopTypeValues& get_shared_pop_type_values(PopType const& pop_type); SharedCountryValues( - PopsDefines const& new_pop_defines, - GoodInstanceManager const& new_good_instance_manager, - decltype(shared_pop_type_values)::keys_span_type pop_type_keys, - memory::vector const& new_regiment_types + PopsDefines const& new_pop_defines, + GoodInstanceManager const& new_good_instance_manager, + decltype(shared_pop_type_values)::keys_span_type pop_type_keys, + memory::vector const& new_regiment_types ); SharedCountryValues(SharedCountryValues&&) = delete; SharedCountryValues(SharedCountryValues const&) = delete; diff --git a/src/openvic-simulation/dataloader/Dataloader.cpp b/src/openvic-simulation/dataloader/Dataloader.cpp index 8fe7603e8..f1be816ca 100644 --- a/src/openvic-simulation/dataloader/Dataloader.cpp +++ b/src/openvic-simulation/dataloader/Dataloader.cpp @@ -12,9 +12,9 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/core/string/Utility.hpp" #include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/interface/UI.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/misc/SoundEffect.hpp" @@ -147,7 +147,7 @@ bool Dataloader::should_ignore_path(fs::path const& path, path_span_t replace_pa template Dataloader::path_vector_t Dataloader::_lookup_files_in_dir( - std::string_view path, fs::path const& extension, _UniqueKey const& unique_key + std::string_view path, fs::path const& extension, _UniqueKey const& unique_key ) const { const fs::path dirpath { ensure_forward_slash_path(path) }; path_vector_t ret; @@ -166,7 +166,7 @@ Dataloader::path_vector_t Dataloader::_lookup_files_in_dir( if (entry.is_regular_file()) { fs::path file = entry; if (extension.empty() || file.extension() == extension) { - const memory::string full_path = file.string(memory::string::allocator_type{}); + const memory::string full_path = file.string(memory::string::allocator_type {}); std::string_view relative_path = full_path; relative_path.remove_prefix(root_len); relative_path = remove_leading_slashes(relative_path); @@ -178,8 +178,11 @@ Dataloader::path_vector_t Dataloader::_lookup_files_in_dir( ret.emplace_back(std::move(file)); } else if (it->second.root == &root) { spdlog::warn_s( - "Files under the same root with conflicting keys: {} - {} (accepted) and {} - {} (rejected)", - it->first, it->second.file, key, file + "Files under the same root with conflicting keys: {} - {} (accepted) and {} - {} (rejected)", + it->first, + it->second.file, + key, + file ); } } @@ -203,13 +206,13 @@ static std::string_view _extract_basic_identifier_prefix_from_path(std::string_v }; Dataloader::path_vector_t Dataloader::lookup_basic_identifier_prefixed_files_in_dir( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension ) const { return _lookup_files_in_dir(path, extension, _extract_basic_identifier_prefix_from_path); } Dataloader::path_vector_t Dataloader::lookup_basic_identifier_prefixed_files_in_dir_recursive( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension ) const { return _lookup_files_in_dir(path, extension, _extract_basic_identifier_prefix_from_path); } @@ -244,16 +247,16 @@ static Parser _run_ovdl_parser(fs::path const& path) { Parser parser; memory::string buffer; auto error_log_stream = ovdl::detail::make_callback_stream( - [](void const* s, std::streamsize n, void* user_data) -> std::streamsize { - if (s != nullptr && n > 0 && user_data != nullptr) { - static_cast(user_data)->append(static_cast(s), n); - return n; - } else { - spdlog::error_s("Invalid input to parser error log callback: {} / {} / {}", s, n, user_data); - return 0; - } - }, - &buffer + [](void const* s, std::streamsize n, void* user_data) -> std::streamsize { + if (s != nullptr && n > 0 && user_data != nullptr) { + static_cast(user_data)->append(static_cast(s), n); + return n; + } else { + spdlog::error_s("Invalid input to parser error log callback: {} / {} / {}", s, n, user_data); + return 0; + } + }, + &buffer ); parser.set_error_log_to(error_log_stream); parser.load_from_file(path); @@ -314,15 +317,12 @@ bool Dataloader::load_mod_descriptors(ModManager& mod_manager) const { static constexpr std::string_view mod_directory = "mod"; static constexpr std::string_view mod_descriptor_extension = ".mod"; - apply_to_files( - lookup_files_in_dir(mod_directory, mod_descriptor_extension), - [&mod_manager](fs::path const& file) -> bool { - if (!mod_manager.load_mod_file(parse_defines(file).get_file_node())) { - spdlog::warn_s("Invalid mod descriptor at path: {} could not be loaded!", file); - } - return true; + apply_to_files(lookup_files_in_dir(mod_directory, mod_descriptor_extension), [&mod_manager](fs::path const& file) -> bool { + if (!mod_manager.load_mod_file(parse_defines(file).get_file_node())) { + spdlog::warn_s("Invalid mod descriptor at path: {} could not be loaded!", file); } - ); + return true; + }); mod_manager.lock_mods(); @@ -332,12 +332,9 @@ bool Dataloader::load_mod_descriptors(ModManager& mod_manager) const { bool Dataloader::_load_interface_files(UIManager& ui_manager) const { static constexpr std::string_view interface_directory = "interface/"; - bool ret = apply_to_files( - lookup_files_in_dir(interface_directory, ".gfx"), - [&ui_manager](fs::path const& file) -> bool { - return ui_manager.load_gfx_file(parse_defines(file).get_file_node()); - } - ); + bool ret = apply_to_files(lookup_files_in_dir(interface_directory, ".gfx"), [&ui_manager](fs::path const& file) -> bool { + return ui_manager.load_gfx_file(parse_defines(file).get_file_node()); + }); ui_manager.lock_gfx_registries(); /* Hard-coded GUI file names, might be replaced with a dynamic system but everything should still be loaded on startup. */ @@ -346,11 +343,22 @@ bool Dataloader::_load_interface_files(UIManager& ui_manager) const { "core", /* Over-map menus */ - "province_interface", "topbar", "menubar", "outliner", "goto", "v2ledger", + "province_interface", + "topbar", + "menubar", + "outliner", + "goto", + "v2ledger", /* Nation management screens */ - "country_production", "country_budget", "country_technology", "country_politics", "country_pops", "country_trade", - "country_diplomacy", "country_military" + "country_production", + "country_budget", + "country_technology", + "country_politics", + "country_pops", + "country_trade", + "country_diplomacy", + "country_military" }; static constexpr std::string_view gui_file_extension = ".gui"; @@ -359,10 +367,10 @@ bool Dataloader::_load_interface_files(UIManager& ui_manager) const { for (std::string_view const& gui_file : gui_files) { if (!ui_manager.load_gui_file( - gui_file, parse_defines(lookup_file( - append_string_views(interface_directory, gui_file, gui_file_extension) - )).get_file_node() - )) { + gui_file, + parse_defines(lookup_file(append_string_views(interface_directory, gui_file, gui_file_extension))) + .get_file_node() + )) { spdlog::critical_s("Failed to load interface gui file: {}", gui_file); ret = false; } @@ -379,7 +387,7 @@ bool Dataloader::_load_pop_types(DefinitionManager& definition_manager) { bool ret = pop_manager.setup_stratas(); GoodDefinitionManager const& good_definition_manager = - definition_manager.get_economy_manager().get_good_definition_manager(); + definition_manager.get_economy_manager().get_good_definition_manager(); IdeologyManager const& ideology_manager = definition_manager.get_politics_manager().get_ideology_manager(); static constexpr std::string_view pop_type_directory = "poptypes"; @@ -389,12 +397,11 @@ bool Dataloader::_load_pop_types(DefinitionManager& definition_manager) { pop_manager.reserve_pop_types_and_delayed_nodes(pop_type_files.size()); ret &= apply_to_files( - pop_type_files, - [this, &pop_manager, &good_definition_manager, &ideology_manager](fs::path const& file) -> bool { - return pop_manager.load_pop_type_file( - file.stem().string(), good_definition_manager, ideology_manager, parse_defines_cached(file).get_file_node() - ); - } + pop_type_files, [this, &pop_manager, &good_definition_manager, &ideology_manager](fs::path const& file) -> bool { + return pop_manager.load_pop_type_file( + file.stem().string(), good_definition_manager, ideology_manager, parse_defines_cached(file).get_file_node() + ); + } ); pop_manager.lock_pop_types(); @@ -425,17 +432,14 @@ bool Dataloader::_load_units(DefinitionManager& definition_manager) const { unit_type_manager.reserve_all_unit_types(unit_files.size()); - bool ret = apply_to_files( - unit_files, - [&definition_manager, &unit_type_manager](fs::path const& file) -> bool { - return unit_type_manager.load_unit_type_file( - definition_manager.get_economy_manager().get_good_definition_manager(), - definition_manager.get_map_definition().get_terrain_type_manager(), - definition_manager.get_modifier_manager(), - parse_defines(file) - ); - } - ); + bool ret = apply_to_files(unit_files, [&definition_manager, &unit_type_manager](fs::path const& file) -> bool { + return unit_type_manager.load_unit_type_file( + definition_manager.get_economy_manager().get_good_definition_manager(), + definition_manager.get_map_definition().get_terrain_type_manager(), + definition_manager.get_modifier_manager(), + parse_defines(file) + ); + }); unit_type_manager.lock_all_unit_types(); @@ -506,16 +510,16 @@ bool Dataloader::_load_technologies(DefinitionManager& definition_manager) { static constexpr std::string_view technologies_directory = "technologies"; if (!apply_to_files( - lookup_files_in_dir(technologies_directory, ".txt"), - [this, &definition_manager, &technology_manager, &modifier_manager](fs::path const& file) -> bool { - return technology_manager.load_technologies_file( - modifier_manager, - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_economy_manager().get_building_type_manager(), - parse_defines_cached(file).get_file_node() - ); - } - )) { + lookup_files_in_dir(technologies_directory, ".txt"), + [this, &definition_manager, &technology_manager, &modifier_manager](fs::path const& file) -> bool { + return technology_manager.load_technologies_file( + modifier_manager, + definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_economy_manager().get_building_type_manager(), + parse_defines_cached(file).get_file_node() + ); + } + )) { spdlog::critical_s("Failed to load technologies!"); ret = false; } @@ -535,17 +539,17 @@ bool Dataloader::_load_inventions(DefinitionManager& definition_manager) { TechnologyManager& technology_manager = research_manager.get_technology_manager(); bool ret = apply_to_files( - lookup_files_in_dir(inventions_directory, ".txt"), - [this, &definition_manager, &invention_manager, &technology_manager](fs::path const& file) -> bool { - return invention_manager.load_inventions_file( - technology_manager, - definition_manager.get_modifier_manager(), - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_economy_manager().get_building_type_manager(), - definition_manager.get_crime_manager(), - parse_defines_cached(file).get_file_node() - ); - } + lookup_files_in_dir(inventions_directory, ".txt"), + [this, &definition_manager, &invention_manager, &technology_manager](fs::path const& file) -> bool { + return invention_manager.load_inventions_file( + technology_manager, + definition_manager.get_modifier_manager(), + definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_economy_manager().get_building_type_manager(), + definition_manager.get_crime_manager(), + parse_defines_cached(file).get_file_node() + ); + } ); invention_manager.lock_inventions(); @@ -564,10 +568,9 @@ bool Dataloader::_load_decisions(DefinitionManager& definition_manager) { DecisionManager& decision_manager = definition_manager.get_decision_manager(); bool ret = apply_to_files( - lookup_files_in_dir(decisions_directory, ".txt"), - [this, &decision_manager](fs::path const& file) -> bool { - return decision_manager.load_decision_file(parse_defines_cached(file).get_file_node()); - } + lookup_files_in_dir(decisions_directory, ".txt"), [this, &decision_manager](fs::path const& file) -> bool { + return decision_manager.load_decision_file(parse_defines_cached(file).get_file_node()); + } ); decision_manager.lock_decisions(); @@ -585,34 +588,37 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse DeploymentManager& deployment_manager = definition_manager.get_military_manager().get_deployment_manager(); static constexpr std::string_view country_history_directory = "history/countries"; - const path_vector_t country_history_files = - lookup_basic_identifier_prefixed_files_in_dir(country_history_directory, ".txt"); + const path_vector_t country_history_files = lookup_basic_identifier_prefixed_files_in_dir( + country_history_directory, ".txt" + ); country_history_manager.reserve_more_country_histories(country_history_files.size()); deployment_manager.reserve_more_deployments(country_history_files.size()); ret &= apply_to_files( - country_history_files, - [this, &definition_manager, &country_history_manager, unused_history_file_warnings](fs::path const& file) -> bool { - const memory::string filename = file.stem().string(memory::string::allocator_type{}); - const std::string_view country_id = extract_basic_identifier_prefix(filename); - - CountryDefinition const* country = - definition_manager.get_country_definition_manager().get_country_definition_by_identifier(country_id); - if (country == nullptr) { - if (unused_history_file_warnings) { - spdlog::warn_s("Found history file for non-existent country: {}", country_id); - } - return true; - } - - return country_history_manager.load_country_history_file( - definition_manager, *this, *country, - definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), - definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), - parse_defines(file).get_file_node() - ); - } + country_history_files, + [this, &definition_manager, &country_history_manager, unused_history_file_warnings](fs::path const& file) -> bool { + const memory::string filename = file.stem().string(memory::string::allocator_type {}); + const std::string_view country_id = extract_basic_identifier_prefix(filename); + + CountryDefinition const* country = + definition_manager.get_country_definition_manager().get_country_definition_by_identifier(country_id); + if (country == nullptr) { + if (unused_history_file_warnings) { + spdlog::warn_s("Found history file for non-existent country: {}", country_id); + } + return true; + } + + return country_history_manager.load_country_history_file( + definition_manager, + *this, + *country, + definition_manager.get_politics_manager().get_ideology_manager().get_ideologies(), + definition_manager.get_politics_manager().get_government_type_manager().get_government_types(), + parse_defines(file).get_file_node() + ); + } ); country_history_manager.lock_country_histories(); @@ -629,31 +635,32 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse MapDefinition const& map_definition = definition_manager.get_map_definition(); static constexpr std::string_view province_history_directory = "history/provinces"; - const path_vector_t province_history_files = - lookup_basic_identifier_prefixed_files_in_dir_recursive(province_history_directory, ".txt"); + const path_vector_t province_history_files = lookup_basic_identifier_prefixed_files_in_dir_recursive( + province_history_directory, ".txt" + ); province_history_manager.reserve_more_province_histories(province_history_files.size()); ret &= apply_to_files( - province_history_files, - [this, &definition_manager, &province_history_manager, &map_definition, unused_history_file_warnings]( - fs::path const& file - ) -> bool { - const memory::string filename = file.stem().string(memory::string::allocator_type{}); - const std::string_view province_id = extract_basic_identifier_prefix(filename); - - ProvinceDefinition const* province = map_definition.get_province_definition_by_identifier(province_id); - if (province == nullptr) { - if (unused_history_file_warnings) { - spdlog::warn_s("Found history file for non-existent province: {}", province_id); - } - return true; - } - - return province_history_manager.load_province_history_file( - definition_manager, *province, parse_defines(file).get_file_node() - ); - } + province_history_files, + [this, &definition_manager, &province_history_manager, &map_definition, unused_history_file_warnings]( + fs::path const& file + ) -> bool { + const memory::string filename = file.stem().string(memory::string::allocator_type {}); + const std::string_view province_id = extract_basic_identifier_prefix(filename); + + ProvinceDefinition const* province = map_definition.get_province_definition_by_identifier(province_id); + if (province == nullptr) { + if (unused_history_file_warnings) { + spdlog::warn_s("Found history file for non-existent province: {}", province_id); + } + return true; + } + + return province_history_manager.load_province_history_file( + definition_manager, *province, parse_defines(file).get_file_node() + ); + } ); /* Pop History */ @@ -661,24 +668,23 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse const string_set_t pop_history_dirs = lookup_dirs_in_dir(pop_history_directory); const Date last_bookmark_date = - definition_manager.get_history_manager().get_bookmark_manager().get_last_bookmark_date(); + definition_manager.get_history_manager().get_bookmark_manager().get_last_bookmark_date(); for (memory::string const& dir : pop_history_dirs) { Date::from_chars_result result; const Date date = Date::from_string_log(dir, &result); - if (result.ec == std::errc{} && date <= last_bookmark_date) { + if (result.ec == std::errc {} && date <= last_bookmark_date) { bool non_integer_size = false; ret &= apply_to_files( - lookup_files_in_dir(append_string_views(pop_history_directory, dir), ".txt"), - [this, &definition_manager, &province_history_manager, date, &non_integer_size]( - fs::path const& file - ) -> bool { - return province_history_manager.load_pop_history_file( - definition_manager, date, parse_defines(file).get_file_node(), &non_integer_size - ); - } + lookup_files_in_dir(append_string_views(pop_history_directory, dir), ".txt"), + [this, &definition_manager, &province_history_manager, date, &non_integer_size](fs::path const& file) + -> bool { + return province_history_manager.load_pop_history_file( + definition_manager, date, parse_defines(file).get_file_node(), &non_integer_size + ); + } ); if (non_integer_size) { @@ -692,18 +698,17 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse { /* Diplomacy History */ - DiplomaticHistoryManager& diplomatic_history_manager = - definition_manager.get_history_manager().get_diplomacy_manager(); + DiplomaticHistoryManager& diplomatic_history_manager = definition_manager.get_history_manager().get_diplomacy_manager(); static constexpr std::string_view diplomacy_history_directory = "history/diplomacy"; ret &= apply_to_files( - lookup_files_in_dir(diplomacy_history_directory, ".txt"), - [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { - return diplomatic_history_manager.load_diplomacy_history_file( - definition_manager.get_country_definition_manager(), parse_defines(file).get_file_node() - ); - } + lookup_files_in_dir(diplomacy_history_directory, ".txt"), + [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { + return diplomatic_history_manager.load_diplomacy_history_file( + definition_manager.get_country_definition_manager(), parse_defines(file).get_file_node() + ); + } ); /* War History */ @@ -713,12 +718,11 @@ bool Dataloader::_load_history(DefinitionManager& definition_manager, bool unuse diplomatic_history_manager.reserve_more_wars(war_history_files.size()); ret &= apply_to_files( - war_history_files, - [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { - return diplomatic_history_manager.load_war_history_file( - definition_manager, parse_defines(file).get_file_node() - ); - } + war_history_files, [this, &definition_manager, &diplomatic_history_manager](fs::path const& file) -> bool { + return diplomatic_history_manager.load_war_history_file( + definition_manager, parse_defines(file).get_file_node() + ); + } ); diplomatic_history_manager.lock_diplomatic_history(); @@ -731,12 +735,11 @@ bool Dataloader::_load_events(DefinitionManager& definition_manager) { static constexpr std::string_view events_directory = "events"; const bool ret = apply_to_files( - lookup_files_in_dir(events_directory, ".txt"), - [this, &definition_manager](fs::path const& file) -> bool { - return definition_manager.get_event_manager().load_event_file( - definition_manager.get_politics_manager().get_issue_manager(), parse_defines_cached(file).get_file_node() - ); - } + lookup_files_in_dir(events_directory, ".txt"), [this, &definition_manager](fs::path const& file) -> bool { + return definition_manager.get_event_manager().load_event_file( + definition_manager.get_politics_manager().get_issue_manager(), parse_defines_cached(file).get_file_node() + ); + } ); definition_manager.get_event_manager().lock_events(); @@ -812,8 +815,8 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { } if (!map_definition.load_province_definitions( - parse_csv(lookup_file(append_string_views(map_directory, definitions))).get_lines() - )) { + parse_csv(lookup_file(append_string_views(map_directory, definitions))).get_lines() + )) { spdlog::critical_s("Failed to load province definitions file!"); ret = false; } @@ -834,16 +837,17 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { colours.push_back(0xFFFFFF_rgb); /* This ensures there is always at least one region colour. */ if (!map_definition.load_region_file( - parse_defines(lookup_file(append_string_views(map_directory, region))).get_file_node(), colours)) { + parse_defines(lookup_file(append_string_views(map_directory, region))).get_file_node(), colours + )) { spdlog::critical_s("Failed to load region file!"); ret = false; } } if (!map_definition.get_terrain_type_manager().load_terrain_types( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, terrain_definition))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, terrain_definition))).get_file_node() + )) { spdlog::critical_s("Failed to load terrain types!"); ret = false; } @@ -853,17 +857,18 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { } if (!map_definition.load_map_images( - lookup_file(append_string_views(map_directory, provinces)), - lookup_file(append_string_views(map_directory, terrain)), - lookup_file(append_string_views(map_directory, rivers)), false - )) { + lookup_file(append_string_views(map_directory, provinces)), + lookup_file(append_string_views(map_directory, terrain)), + lookup_file(append_string_views(map_directory, rivers)), + false + )) { spdlog::critical_s("Failed to load map images!"); ret = false; } if (map_definition.generate_and_load_province_adjacencies( - parse_csv(lookup_file(append_string_views(map_directory, adjacencies))).get_lines() - )) { + parse_csv(lookup_file(append_string_views(map_directory, adjacencies))).get_lines() + )) { SPDLOG_INFO("Successfully generated and loaded province adjacencies!"); } else { spdlog::critical_s("Failed to generate and load province adjacencies!"); @@ -872,25 +877,25 @@ bool Dataloader::_load_map_dir(DefinitionManager& definition_manager) const { /* Must be loaded after adjacencies so we know what provinces are coastal, and so can have a port */ if (!map_definition.load_province_positions( - definition_manager.get_economy_manager().get_building_type_manager(), - parse_defines(lookup_file(append_string_views(map_directory, positions))).get_file_node() - )) { + definition_manager.get_economy_manager().get_building_type_manager(), + parse_defines(lookup_file(append_string_views(map_directory, positions))).get_file_node() + )) { spdlog::critical_s("Failed to load province positions file!"); ret = false; } if (!map_definition.load_climate_file( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, climate_file))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, climate_file))).get_file_node() + )) { spdlog::critical_s("Failed to load climates!"); ret = false; } if (!map_definition.load_continent_file( - definition_manager.get_modifier_manager(), - parse_defines(lookup_file(append_string_views(map_directory, continent))).get_file_node() - )) { + definition_manager.get_modifier_manager(), + parse_defines(lookup_file(append_string_views(map_directory, continent))).get_file_node() + )) { spdlog::critical_s("Failed to load continents!"); ret = false; } @@ -928,13 +933,9 @@ bool Dataloader::_load_sound_effect_defines(DefinitionManager& definition_manage sound_effect_manager.lock_sound_effects(); return ret; - } -bool Dataloader::load_defines( - GameRulesManager const& game_rules_manager, - DefinitionManager& definition_manager -) { +bool Dataloader::load_defines(GameRulesManager const& game_rules_manager, DefinitionManager& definition_manager) { if (roots.empty()) { spdlog::critical_s("Cannot load defines - Dataloader has no roots!"); return false; @@ -977,8 +978,8 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_define_manager().load_defines_file( - parse_lua_defines(lookup_file(defines_file)).get_file_node() - )) { + parse_lua_defines(lookup_file(defines_file)).get_file_node() + )) { spdlog::critical_s("Failed to load defines!"); ret = false; } @@ -987,26 +988,26 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_pop_manager().get_culture_manager().load_graphical_culture_type_file( - parse_defines(lookup_file(graphical_culture_type_file)).get_file_node() - )) { + parse_defines(lookup_file(graphical_culture_type_file)).get_file_node() + )) { spdlog::critical_s("Failed to load graphical culture types!"); ret = false; } if (!definition_manager.get_pop_manager().get_religion_manager().load_religion_file( - parse_defines(lookup_file(religion_file)).get_file_node() - )) { + parse_defines(lookup_file(religion_file)).get_file_node() + )) { spdlog::critical_s("Failed to load religions!"); ret = false; } if (!definition_manager.get_politics_manager().get_ideology_manager().load_ideology_file( - parse_defines_cached(lookup_file(ideology_file)).get_file_node() - )) { + parse_defines_cached(lookup_file(ideology_file)).get_file_node() + )) { spdlog::critical_s("Failed to load ideologies!"); ret = false; } if (!definition_manager.get_politics_manager().load_government_types_file( - parse_defines(lookup_file(governments_file)).get_file_node() - )) { + parse_defines(lookup_file(governments_file)).get_file_node() + )) { spdlog::critical_s("Failed to load government types!"); ret = false; } @@ -1015,23 +1016,20 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_economy_manager().load_production_types_file( - game_rules_manager, - definition_manager.get_pop_manager(), - parse_defines_cached(lookup_file(production_types_file)) - )) { + game_rules_manager, definition_manager.get_pop_manager(), parse_defines_cached(lookup_file(production_types_file)) + )) { spdlog::critical_s("Failed to load production types!"); ret = false; } - if (!definition_manager.get_economy_manager().load_buildings_file(definition_manager.get_modifier_manager(), - parse_defines(lookup_file(buildings_file)).get_file_node() - )) { + if (!definition_manager.get_economy_manager().load_buildings_file( + definition_manager.get_modifier_manager(), parse_defines(lookup_file(buildings_file)).get_file_node() + )) { spdlog::critical_s("Failed to load buildings!"); ret = false; } if (!definition_manager.get_mapmode_manager().setup_mapmodes( - definition_manager.get_map_definition(), - definition_manager.get_economy_manager().get_building_type_manager() - )) { + definition_manager.get_map_definition(), definition_manager.get_economy_manager().get_building_type_manager() + )) { spdlog::critical_s("Failed to set up mapmodes!"); ret = false; } @@ -1054,56 +1052,57 @@ bool Dataloader::load_defines( } definition_manager.get_modifier_manager().lock_base_country_modifier_effects(); if (!definition_manager.get_politics_manager().load_issues_file( - definition_manager.get_modifier_manager(), - parse_defines_cached(lookup_file(issues_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(issues_file)).get_file_node() + )) { spdlog::critical_s("Failed to load issues and reforms!"); ret = false; } if (!definition_manager.get_pop_manager().load_delayed_parse_pop_type_data( - definition_manager.get_military_manager().get_unit_type_manager(), - definition_manager.get_politics_manager().get_issue_manager() - )) { + definition_manager.get_military_manager().get_unit_type_manager(), + definition_manager.get_politics_manager().get_issue_manager() + )) { spdlog::critical_s("Failed to load delayed parse pop type data (promotion and issue weights)!"); ret = false; } if (!definition_manager.get_politics_manager().load_national_foci_file( - definition_manager.get_pop_manager(), definition_manager.get_economy_manager().get_good_definition_manager(), - definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(national_foci_file)).get_file_node() - )) { + definition_manager.get_pop_manager(), + definition_manager.get_economy_manager().get_good_definition_manager(), + definition_manager.get_modifier_manager(), + parse_defines_cached(lookup_file(national_foci_file)).get_file_node() + )) { spdlog::critical_s("Failed to load national foci!"); ret = false; } if (!definition_manager.get_politics_manager().get_national_value_manager().load_national_values_file( - definition_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines(lookup_file(national_values_file)).get_file_node() + )) { spdlog::critical_s("Failed to load national values!"); ret = false; } if (!definition_manager.get_crime_manager().load_crime_modifiers( - definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(crime_modifiers_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines_cached(lookup_file(crime_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load crime modifiers!"); ret = false; } if (!definition_manager.get_modifier_manager().load_event_modifiers( - parse_defines(lookup_file(event_modifiers_file)).get_file_node() - )) { + parse_defines(lookup_file(event_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load event modifiers!"); ret = false; } if (!definition_manager.get_modifier_manager().load_static_modifiers( - parse_defines(lookup_file(static_modifiers_file)).get_file_node() - )) { + parse_defines(lookup_file(static_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load static modifiers!"); ret = false; } definition_manager.get_modifier_manager().lock_event_modifiers(); if (!definition_manager.get_modifier_manager().load_triggered_modifiers( - parse_defines_cached(lookup_file(triggered_modifiers_file)).get_file_node() - )) { + parse_defines_cached(lookup_file(triggered_modifiers_file)).get_file_node() + )) { spdlog::critical_s("Failed to load triggered modifiers!"); ret = false; } @@ -1112,46 +1111,45 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_military_manager().get_leader_trait_manager().load_leader_traits_file( - definition_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() - )) { + definition_manager.get_modifier_manager(), parse_defines(lookup_file(leader_traits_file)).get_file_node() + )) { spdlog::critical_s("Failed to load leader traits!"); ret = false; } if (!definition_manager.get_military_manager().get_leader_trait_manager().setup_leader_prestige_modifier( - definition_manager.get_modifier_manager().get_modifier_effect_cache(), - definition_manager.get_define_manager().get_military_defines() - )) { + definition_manager.get_modifier_manager().get_modifier_effect_cache(), + definition_manager.get_define_manager().get_military_defines() + )) { spdlog::critical_s("Failed to set up leader prestige modifier!"); ret = false; } if (!definition_manager.get_military_manager().get_wargoal_type_manager().load_wargoal_file( - parse_defines_cached(lookup_file(cb_types_file)) - )) { + parse_defines_cached(lookup_file(cb_types_file)) + )) { spdlog::critical_s("Failed to load wargoals!"); ret = false; } if (!definition_manager.get_history_manager().get_bookmark_manager().load_bookmark_file( - definition_manager.get_map_definition().get_height(), - parse_defines(lookup_file(bookmark_file)).get_file_node() - )) { + definition_manager.get_map_definition().get_height(), parse_defines(lookup_file(bookmark_file)).get_file_node() + )) { spdlog::critical_s("Failed to load bookmarks!"); ret = false; } if (!definition_manager.get_country_definition_manager().load_countries( - definition_manager, *this, parse_defines(lookup_file(countries_file)).get_file_node() - )) { + definition_manager, *this, parse_defines(lookup_file(countries_file)).get_file_node() + )) { spdlog::critical_s("Failed to load countries!"); ret = false; } if (!definition_manager.get_country_definition_manager().load_country_colours( - parse_defines(lookup_file(country_colours_file)).get_file_node() - )) { + parse_defines(lookup_file(country_colours_file)).get_file_node() + )) { spdlog::critical_s("Failed to load country colours!"); ret = false; } if (!definition_manager.get_pop_manager().get_culture_manager().load_culture_file( - definition_manager.get_country_definition_manager(), parse_defines(lookup_file(culture_file)).get_file_node() - )) { + definition_manager.get_country_definition_manager(), parse_defines(lookup_file(culture_file)).get_file_node() + )) { spdlog::critical_s("Failed to load cultures!"); ret = false; } @@ -1176,8 +1174,8 @@ bool Dataloader::load_defines( ret = false; } if (!definition_manager.get_event_manager().load_on_action_file( - parse_defines(lookup_file(on_actions_file)).get_file_node() - )) { + parse_defines(lookup_file(on_actions_file)).get_file_node() + )) { spdlog::critical_s("Failed to load on actions!"); ret = false; } @@ -1244,10 +1242,7 @@ static bool _load_localisation_file(Dataloader::localisation_callback_t callback } bool Dataloader::load_localisation_files(localisation_callback_t callback, std::string_view localisation_dir) const { - return apply_to_files( - lookup_files_in_dir(localisation_dir, ".csv"), - [callback](fs::path path) -> bool { - return _load_localisation_file(callback, parse_csv(path).get_lines()); - } - ); + return apply_to_files(lookup_files_in_dir(localisation_dir, ".csv"), [callback](fs::path path) -> bool { + return _load_localisation_file(callback, parse_csv(path).get_lines()); + }); } diff --git a/src/openvic-simulation/dataloader/Dataloader.hpp b/src/openvic-simulation/dataloader/Dataloader.hpp index 9e433a9cb..933949cfa 100644 --- a/src/openvic-simulation/dataloader/Dataloader.hpp +++ b/src/openvic-simulation/dataloader/Dataloader.hpp @@ -51,7 +51,7 @@ namespace OpenVic { * or matches an earlier found path's key is discarded, ensuring each looked up path's key is non-empty and unique. */ template path_vector_t _lookup_files_in_dir( - std::string_view path, fs::path const& extension, _UniqueKey const& unique_key + std::string_view path, fs::path const& extension, _UniqueKey const& unique_key ) const; public: @@ -114,16 +114,18 @@ namespace OpenVic { path_vector_t lookup_files_in_dir_recursive(std::string_view path, fs::path const& extension) const; path_vector_t lookup_basic_identifier_prefixed_files_in_dir(std::string_view path, fs::path const& extension) const; path_vector_t lookup_basic_identifier_prefixed_files_in_dir_recursive( - std::string_view path, fs::path const& extension + std::string_view path, fs::path const& extension ) const; static constexpr size_t apply_callback_stack_size = sizeof(std::intptr_t) * 4; - using apply_files_callback_t = fu2::function_base, false, false, bool(fs::path const&)>; + using apply_files_callback_t = fu2:: + function_base, false, false, bool(fs::path const&)>; bool apply_to_files(path_span_t files, apply_files_callback_t callback) const; string_set_t lookup_dirs_in_dir(std::string_view path) const; - /* Load all mod descriptors present in the mod/ directory. Importantly, loads dependencies and replace_paths for us to check. */ + /* Load all mod descriptors present in the mod/ directory. Importantly, loads dependencies and replace_paths for us to + * check. */ bool load_mod_descriptors(ModManager& mod_manager) const; /* Load and parse all of the text defines data, including parsing cached condition and effect scripts after all the @@ -137,18 +139,29 @@ namespace OpenVic { public: enum locale_t : size_t { - English, French, German, Polish, Spanish, Italian, Swedish, - Czech, Hungarian, Dutch, Portuguese, Russian, Finnish, _LocaleCount + English, + French, + German, + Polish, + Spanish, + Italian, + Swedish, + Czech, + Hungarian, + Dutch, + Portuguese, + Russian, + Finnish, + _LocaleCount }; static constexpr char const* locale_names[_LocaleCount] = { - "en_GB", "fr_FR", "de_DE", "pl_PL", "es_ES", "it_IT", "sv_SE", - "cs_CZ", "hu_HU", "nl_NL", "pt_PT", "ru_RU", "fi_FI" + "en_GB", "fr_FR", "de_DE", "pl_PL", "es_ES", "it_IT", "sv_SE", "cs_CZ", "hu_HU", "nl_NL", "pt_PT", "ru_RU", "fi_FI" }; /* Args: key, locale, localisation */ using localisation_callback_t = NodeTools::callback_t; bool load_localisation_files( - localisation_callback_t callback, std::string_view localisation_dir = "localisation" + localisation_callback_t callback, std::string_view localisation_dir = "localisation" ) const; }; } diff --git a/src/openvic-simulation/dataloader/ModManager.cpp b/src/openvic-simulation/dataloader/ModManager.cpp index 8a970883b..328728d7b 100644 --- a/src/openvic-simulation/dataloader/ModManager.cpp +++ b/src/openvic-simulation/dataloader/ModManager.cpp @@ -13,19 +13,15 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Mod::Mod( - ModManager const& manager, - std::string_view new_identifier, - std::string_view new_path, - std::optional new_user_dir, - memory::vector new_replace_paths, - memory::vector new_dependencies -) - : HasIdentifier { new_identifier }, - mod_manager { manager }, - dataloader_root_path { new_path }, - user_dir { new_user_dir }, - replace_paths { new_replace_paths }, - dependencies { new_dependencies } {} + ModManager const& manager, + std::string_view new_identifier, + std::string_view new_path, + std::optional new_user_dir, + memory::vector new_replace_paths, + memory::vector new_dependencies +) : + HasIdentifier { new_identifier }, mod_manager { manager }, dataloader_root_path { new_path }, user_dir { new_user_dir }, + replace_paths { new_replace_paths }, dependencies { new_dependencies } {} vector_ordered_set> Mod::generate_dependency_list(bool* success) const { static constexpr size_t MAX_RECURSE = 16; @@ -33,28 +29,21 @@ vector_ordered_set> Mod::generate_dependency_l vector_ordered_set> result; - auto dep_cycle = [this, ¤t_recurse]( - auto self, - Mod const& mod, - vector_ordered_set>& dep_list - ) -> bool { + auto dep_cycle = + [this, + ¤t_recurse](auto self, Mod const& mod, vector_ordered_set>& dep_list) -> bool { bool ret = true; for (std::string_view dep_identifier : mod.get_dependencies()) { Mod const* dep_ptr = mod_manager.get_mod_by_identifier(dep_identifier); if (dep_ptr == nullptr) { - spdlog::error_s( - "Mod \"{}\" has unmet dependency \"{}\" and cannot be loaded!", - mod, dep_identifier - ); + spdlog::error_s("Mod \"{}\" has unmet dependency \"{}\" and cannot be loaded!", mod, dep_identifier); return false; } Mod const& dep = *dep_ptr; - /* The poor man's cycle checking (cycles should be very rare and hard to accomplish with vic2 modding, this is a failsafe) */ + /* The poor man's cycle checking (cycles should be very rare and hard to accomplish with vic2 modding, this is a + * failsafe) */ if (current_recurse == MAX_RECURSE) { - spdlog::error_s( - "Mod \"{}\" has cyclical or broken dependency chain and cannot be loaded!", - mod - ); + spdlog::error_s("Mod \"{}\" has cyclical or broken dependency chain and cannot be loaded!", mod); return false; } else { current_recurse++; @@ -84,25 +73,20 @@ bool ModManager::load_mod_file(ast::NodeCPtr root) { memory::vector replace_paths; memory::vector dependencies; - bool ret = NodeTools::expect_dictionary_keys_and_default_map( - map_key_value_ignore_invalid_callback>, - "name", ONE_EXACTLY, expect_string(assign_variable_callback(identifier)), - "path", ONE_EXACTLY, expect_string(assign_variable_callback(path)), - "user_dir", ZERO_OR_ONE, expect_string(assign_variable_callback_opt(user_dir)), - "replace_path", ZERO_OR_MORE, expect_string(vector_callback_string(replace_paths)), - "dependencies", ZERO_OR_ONE, expect_list_reserve_length(dependencies, expect_string(vector_callback_string(dependencies))) - )(root); + bool + ret = + NodeTools:: + expect_dictionary_keys_and_default_map(map_key_value_ignore_invalid_callback>, "name", ONE_EXACTLY, expect_string(assign_variable_callback(identifier)), "path", ONE_EXACTLY, expect_string(assign_variable_callback(path)), "user_dir", ZERO_OR_ONE, expect_string(assign_variable_callback_opt(user_dir)), "replace_path", ZERO_OR_MORE, expect_string(vector_callback_string(replace_paths)), "dependencies", ZERO_OR_ONE, expect_list_reserve_length(dependencies, expect_string(vector_callback_string(dependencies))))( + root + ); if (!ret) { - //NodeTools already logs and an invalid (unloaded) mod won't stop the game. + // NodeTools already logs and an invalid (unloaded) mod won't stop the game. return true; } SPDLOG_INFO("Loaded mod descriptor for \"{}\"", identifier); - mods.emplace_item( - identifier, - *this, identifier, path, user_dir, std::move(replace_paths), std::move(dependencies) - ); + mods.emplace_item(identifier, *this, identifier, path, user_dir, std::move(replace_paths), std::move(dependencies)); return true; } diff --git a/src/openvic-simulation/dataloader/ModManager.hpp b/src/openvic-simulation/dataloader/ModManager.hpp index 20a6837bc..0a387e7f6 100644 --- a/src/openvic-simulation/dataloader/ModManager.hpp +++ b/src/openvic-simulation/dataloader/ModManager.hpp @@ -4,9 +4,9 @@ #include #include +#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -24,14 +24,12 @@ namespace OpenVic { const memory::vector SPAN_PROPERTY(dependencies); public: - Mod( - ModManager const& manager, - std::string_view new_identifier, - std::string_view new_path, - std::optional new_user_dir, - memory::vector new_replace_paths, - memory::vector new_dependencies - ); + Mod(ModManager const& manager, + std::string_view new_identifier, + std::string_view new_path, + std::optional new_user_dir, + memory::vector new_replace_paths, + memory::vector new_dependencies); Mod(Mod&&) = default; vector_ordered_set> generate_dependency_list(bool* success = nullptr) const; @@ -51,4 +49,4 @@ namespace OpenVic { void set_loaded_mods(memory::vector>&& new_loaded_mods); size_t get_loaded_mod_count() const; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/dataloader/NodeTools.cpp b/src/openvic-simulation/dataloader/NodeTools.cpp index e9793b711..b525ea208 100644 --- a/src/openvic-simulation/dataloader/NodeTools.cpp +++ b/src/openvic-simulation/dataloader/NodeTools.cpp @@ -36,10 +36,7 @@ static NodeCallback auto _expect_type(Callback auto&& callback) { if (cast_node != nullptr) { return callback(cast_node); } - spdlog::error_s( - "Invalid node type {} when expecting {}", - ast::get_type_name(node->kind()), type_name() - ); + spdlog::error_s("Invalid node type {} when expecting {}", ast::get_type_name(node->kind()), type_name()); } else { spdlog::error_s("Null node when expecting {}", type_name()); } @@ -60,14 +57,13 @@ static NodeCallback auto _abstract_statement_node_callback(Callback<_NodeStateme return callback(list_value->statements()); } spdlog::error_s( - "Invalid node type {} when expecting {} or {}", - ast::get_type_name(node->kind()), type_name(), type_name() + "Invalid node type {} when expecting {} or {}", + ast::get_type_name(node->kind()), + type_name(), + type_name() ); } else { - spdlog::error_s( - "Null node when expecting {} or {}", - type_name(), type_name() - ); + spdlog::error_s("Null node when expecting {} or {}", type_name(), type_name()); } return false; }; @@ -92,10 +88,10 @@ static Callback auto _abstract_symbol_node_callback(Callback T> static Callback auto _abstract_string_node_callback(Callback auto&& callback, bool allow_empty) { return _abstract_symbol_node_callback( - [callback = FWD(callback)](ovdl::symbol symbol) mutable -> bool { - return callback(symbol.view()); - }, - allow_empty + [callback = FWD(callback)](ovdl::symbol symbol) mutable -> bool { + return callback(symbol.view()); + }, + allow_empty ); } @@ -123,13 +119,14 @@ node_callback_t NodeTools::expect_identifier_or_string(callback_t(FWD(callback), allow_empty)(cast_node); } spdlog::error_s( - "Invalid node type {} when expecting {} or {}", - ast::get_type_name(node->kind()), type_name(), type_name() + "Invalid node type {} when expecting {} or {}", + ast::get_type_name(node->kind()), + type_name(), + type_name() ); } else { spdlog::error_s( - "Null node when expecting {} or {}", - type_name(), type_name() + "Null node when expecting {} or {}", type_name(), type_name() ); } return false; @@ -154,7 +151,7 @@ node_callback_t NodeTools::expect_int64(callback_t callback, int base) return expect_identifier([callback, base](std::string_view identifier) mutable -> bool { int64_t val; std::from_chars_result result = string_to_int64(identifier, val, base); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(val); } spdlog::error_s("Invalid int identifier text: {}", identifier); @@ -166,7 +163,7 @@ node_callback_t NodeTools::expect_uint64(callback_t callback, int base return expect_identifier([callback, base](std::string_view identifier) mutable -> bool { uint64_t val; std::from_chars_result result = string_to_uint64(identifier, val, base); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(val); } spdlog::error_s("Invalid uint identifier text: {}", identifier); @@ -178,8 +175,10 @@ callback_t NodeTools::expect_fixed_point_str(callback_t bool { bool successful = false; fixed_point_t val; - const std::from_chars_result result = fp::from_chars_with_plus(val, identifier.data(), identifier.data()+identifier.length()); - if (result.ec == std::errc{}) { + const std::from_chars_result result = fp::from_chars_with_plus( + val, identifier.data(), identifier.data() + identifier.length() + ); + if (result.ec == std::errc {}) { return callback(val); } spdlog::error_s("Invalid fixed point identifier text: {}", identifier); @@ -195,25 +194,24 @@ node_callback_t NodeTools::expect_colour(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { colour_t col = colour_t::null(); int32_t components = 0; - bool ret = expect_list_of_length(3, expect_fixed_point( - [&col, &components](fixed_point_t val) -> bool { - if (val < 0 || val > 255) { - spdlog::error_s( - "Invalid colour component #{}: {}", - components++, val - ); - return false; - } else { - if (val <= 1) { - val *= 255; - } else if (!val.is_integer()) { - spdlog::warn_s("Fractional part of colour component #{} will be truncated: {}", components, val); - } - col[components++] = val.truncate(); - return true; - } - } - ))(node); + bool ret = expect_list_of_length(3, expect_fixed_point([&col, &components](fixed_point_t val) -> bool { + if (val < 0 || val > 255) { + spdlog::error_s("Invalid colour component #{}: {}", components++, val); + return false; + } else { + if (val <= 1) { + val *= 255; + } else if (!val.is_integer()) { + spdlog::warn_s( + "Fractional part of colour component #{} will be truncated: {}", + components, + val + ); + } + col[components++] = val.truncate(); + return true; + } + }))(node); if (ret) { ret &= callback(col); } @@ -222,16 +220,19 @@ node_callback_t NodeTools::expect_colour(callback_t callback) { } node_callback_t NodeTools::expect_colour_hex(callback_t callback) { - return expect_uint([callback](colour_argb_t::integer_type val) mutable -> bool { - return callback(colour_argb_t::from_argb(val)); - }, 16); + return expect_uint( + [callback](colour_argb_t::integer_type val) mutable -> bool { + return callback(colour_argb_t::from_argb(val)); + }, + 16 + ); } callback_t NodeTools::expect_date_str(callback_t callback) { return [callback](std::string_view identifier) mutable -> bool { Date::from_chars_result result; const Date date = Date::from_string_log(identifier, &result); - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { return callback(date); } spdlog::error_s("Invalid date identifier text: {}", identifier); @@ -273,10 +274,10 @@ template)> NodeCallback auto _expect_vec2(Callback> auto&& callback) { return [callback = FWD(callback)](ast::NodeCPtr node) mutable -> bool { vec2_t vec; - bool ret = expect_dictionary_keys( - "x", ONE_EXACTLY, expect_func(assign_variable_callback(vec.x)), - "y", ONE_EXACTLY, expect_func(assign_variable_callback(vec.y)) - )(node); + bool ret = + expect_dictionary_keys("x", ONE_EXACTLY, expect_func(assign_variable_callback(vec.x)), "y", ONE_EXACTLY, expect_func(assign_variable_callback(vec.y)))( + node + ); if (ret) { ret &= callback(vec); } @@ -288,11 +289,7 @@ node_callback_t NodeTools::expect_text_format(callback_t callback using enum text_format_t; static const string_map_t format_map = { - { "left", left }, - { "right", right }, - { "centre", centre }, - { "center", centre }, - { "justified", justified } + { "left", left }, { "right", right }, { "centre", centre }, { "center", centre }, { "justified", justified } }; return expect_identifier(expect_mapped_string(format_map, callback)); @@ -316,12 +313,10 @@ node_callback_t NodeTools::expect_fvec3(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { fvec3_t vec; int32_t components = 0; - bool ret = expect_list_of_length(3, expect_fixed_point( - [&vec, &components](fixed_point_t val) -> bool { - vec[components++] = val; - return true; - } - ))(node); + bool ret = expect_list_of_length(3, expect_fixed_point([&vec, &components](fixed_point_t val) -> bool { + vec[components++] = val; + return true; + }))(node); if (ret) { ret &= callback(vec); } @@ -333,12 +328,10 @@ node_callback_t NodeTools::expect_fvec4(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { fvec4_t vec; int32_t components = 0; - bool ret = expect_list_of_length(4, expect_fixed_point( - [&vec, &components](fixed_point_t val) -> bool { - vec[components++] = val; - return true; - } - ))(node); + bool ret = expect_list_of_length(4, expect_fixed_point([&vec, &components](fixed_point_t val) -> bool { + vec[components++] = val; + return true; + }))(node); if (ret) { ret &= callback(vec); } @@ -369,10 +362,7 @@ node_callback_t NodeTools::expect_list_and_length(length_callback_t length_callb size_t size = length_callback(dist); if (size > dist) { - spdlog::error_s( - "Trying to read more values than the list contains: {} > {}", - size, dist - ); + spdlog::error_s("Trying to read more values than the list contains: {} > {}", size, dist); size = dist; ret = false; } @@ -453,63 +443,63 @@ static node_callback_t _expect_key(Key key, NodeCallback auto&& callback, bool* } }; - return _abstract_statement_node_callback([key, callback = FWD(callback), key_found, allow_duplicates](_NodeStatementRange list) mutable -> bool { - bool ret = true; - size_t keys_found = 0; - for (ast::Statement const* sub_node : list) { - auto const* assign_node = dryad::node_try_cast(sub_node); - if (assign_node == nullptr) { - continue; - } - Key left; - if (!assign_left(left)(assign_node->left())) { - continue; - } - if (left == key) { - if (keys_found++ == 0) { - ret &= callback(assign_node->right()); - if (allow_duplicates) { - break; - } - } - } - } - std::string_view key_str = [&] { - if constexpr (std::same_as) { - return key; - } else { - return key.view(); - } - }(); - if (keys_found == 0) { - if (key_found != nullptr) { - *key_found = false; - } else { - spdlog::error_s("Failed to find expected key: \"{}\"", key_str); - } - ret = false; - } else { - if (key_found != nullptr) { - *key_found = true; - } - if (!allow_duplicates && keys_found > 1) { - spdlog::error_s( - "Found {} instances of key: \"{}\" (expected 1)", - keys_found, key_str - ); - ret = false; - } - } - return ret; - }); + return _abstract_statement_node_callback( + [key, callback = FWD(callback), key_found, allow_duplicates](_NodeStatementRange list) mutable -> bool { + bool ret = true; + size_t keys_found = 0; + for (ast::Statement const* sub_node : list) { + auto const* assign_node = dryad::node_try_cast(sub_node); + if (assign_node == nullptr) { + continue; + } + Key left; + if (!assign_left(left)(assign_node->left())) { + continue; + } + if (left == key) { + if (keys_found++ == 0) { + ret &= callback(assign_node->right()); + if (allow_duplicates) { + break; + } + } + } + } + std::string_view key_str = [&] { + if constexpr (std::same_as) { + return key; + } else { + return key.view(); + } + }(); + if (keys_found == 0) { + if (key_found != nullptr) { + *key_found = false; + } else { + spdlog::error_s("Failed to find expected key: \"{}\"", key_str); + } + ret = false; + } else { + if (key_found != nullptr) { + *key_found = true; + } + if (!allow_duplicates && keys_found > 1) { + spdlog::error_s("Found {} instances of key: \"{}\" (expected 1)", keys_found, key_str); + ret = false; + } + } + return ret; + } + ); } node_callback_t NodeTools::expect_key(std::string_view key, node_callback_t callback, bool* key_found, bool allow_duplicates) { return _expect_key(key, callback, key_found, allow_duplicates); } -node_callback_t -NodeTools::expect_key(ovdl::symbol key, node_callback_t callback, bool* key_found, bool allow_duplicates) { +node_callback_t NodeTools::expect_key( + ovdl::symbol key, node_callback_t callback, bool* key_found, bool allow_duplicates +) { return _expect_key(key, callback, key_found, allow_duplicates); } @@ -524,9 +514,7 @@ node_callback_t NodeTools::expect_dictionary(key_value_callback_t callback) { node_callback_t NodeTools::name_list_callback(callback_t callback) { return [callback](ast::NodeCPtr node) mutable -> bool { name_list_t list; - bool ret = expect_list_reserve_length( - list, expect_identifier_or_string(vector_callback(list)) - )(node); + bool ret = expect_list_reserve_length(list, expect_identifier_or_string(vector_callback(list)))(node); ret &= callback(std::move(list)); return ret; }; diff --git a/src/openvic-simulation/dataloader/NodeTools.hpp b/src/openvic-simulation/dataloader/NodeTools.hpp index 0f94171d1..f6c0769ad 100644 --- a/src/openvic-simulation/dataloader/NodeTools.hpp +++ b/src/openvic-simulation/dataloader/NodeTools.hpp @@ -41,7 +41,7 @@ namespace OpenVic { static constexpr std::string_view get_type_name(NodeKind kind) { #ifdef _MSC_VER // type_name starts with "struct " -using namespace std::string_view_literals; + using namespace std::string_view_literals; #define NODE_CASE(Node) \ case Node: return OpenVic::type_name().substr("struct "sv.size()); #else @@ -99,11 +99,8 @@ using namespace std::string_view_literals; template constexpr static MapKeyValueCallback auto ignore_map(KeyValueCallback auto&& callback) { - return [default_callback = MOV(callback)]( - Map const& key_map, - std::string_view key, - ast::NodeCPtr value - ) mutable -> bool { + return [default_callback = MOV(callback)](Map const& key_map, std::string_view key, ast::NodeCPtr value) mutable + -> bool { return default_callback(key, value); }; } @@ -134,19 +131,13 @@ using namespace std::string_view_literals; template inline bool map_key_value_invalid_callback(Map const& key_map, std::string_view key, ast::NodeCPtr) { - spdlog::error_s( - "Invalid dictionary key \"{}\". Valid values are [{}]", - key, string_join(key_map) - ); + spdlog::error_s("Invalid dictionary key \"{}\". Valid values are [{}]", key, string_join(key_map)); return false; } template inline bool map_key_value_ignore_invalid_callback(Map const& key_map, std::string_view key, ast::NodeCPtr) { - spdlog::warn_s( - "Invalid dictionary key \"{}\" is ignored. Valid values are [{}]", - key, string_join(key_map) - ); + spdlog::warn_s("Invalid dictionary key \"{}\" is ignored. Valid values are [{}]", key, string_join(key_map)); return true; } @@ -162,19 +153,22 @@ using namespace std::string_view_literals; template NodeCallback auto expect_int(callback_t& callback, int base = 10) { - return expect_int64([callback](int64_t val) mutable -> bool { - if (static_cast(std::numeric_limits::lowest()) <= val && - val <= static_cast(std::numeric_limits::max())) { - return callback(val); - } - spdlog::error_s( - "Invalid int: {} (valid range: [{}, {}])", - val, - static_cast(std::numeric_limits::lowest()), - static_cast(std::numeric_limits::max()) - ); - return false; - }, base); + return expect_int64( + [callback](int64_t val) mutable -> bool { + if (static_cast(std::numeric_limits::lowest()) <= val && + val <= static_cast(std::numeric_limits::max())) { + return callback(val); + } + spdlog::error_s( + "Invalid int: {} (valid range: [{}, {}])", + val, + static_cast(std::numeric_limits::lowest()), + static_cast(std::numeric_limits::max()) + ); + return false; + }, + base + ); } template NodeCallback auto expect_int(callback_t&& callback, int base = 10) { @@ -183,16 +177,18 @@ using namespace std::string_view_literals; template NodeCallback auto expect_uint(callback_t& callback, int base = 10) { - return expect_uint64([callback](uint64_t val) mutable -> bool { - if (val <= static_cast(std::numeric_limits::max())) { - return callback(val); - } - spdlog::error_s( - "Invalid uint: {} (valid range: [0, {}])", - val, static_cast(std::numeric_limits::max()) - ); - return false; - }, base); + return expect_uint64( + [callback](uint64_t val) mutable -> bool { + if (val <= static_cast(std::numeric_limits::max())) { + return callback(val); + } + spdlog::error_s( + "Invalid uint: {} (valid range: [0, {}])", val, static_cast(std::numeric_limits::max()) + ); + return false; + }, + base + ); } template NodeCallback auto expect_uint(callback_t&& callback, int base = 10) { @@ -203,33 +199,35 @@ using namespace std::string_view_literals; NodeCallback auto expect_strong_typedef(callback_t& callback, int base = 10) { if constexpr (std::unsigned_integral) { return expect_uint64( - [callback](uint64_t val) mutable -> bool { - if (val <= static_cast(std::numeric_limits::max())) { - return callback(T(val)); - } - spdlog::error_s( - "Invalid uint: {} (valid range: [0, {}])", val, - static_cast(std::numeric_limits::max()) - ); - return false; - }, - base + [callback](uint64_t val) mutable -> bool { + if (val <= static_cast(std::numeric_limits::max())) { + return callback(T(val)); + } + spdlog::error_s( + "Invalid uint: {} (valid range: [0, {}])", + val, + static_cast(std::numeric_limits::max()) + ); + return false; + }, + base ); } else { return expect_int64( - [callback](int64_t val) mutable -> bool { - if (val >= static_cast(std::numeric_limits::min()) && - val <= static_cast(std::numeric_limits::max())) { - return callback(T(val)); - } - spdlog::error_s( - "Invalid int: {} (valid range: [{}, {}])", val, - static_cast(std::numeric_limits::min()), - static_cast(std::numeric_limits::max()) - ); - return false; - }, - base + [callback](int64_t val) mutable -> bool { + if (val >= static_cast(std::numeric_limits::min()) && + val <= static_cast(std::numeric_limits::max())) { + return callback(T(val)); + } + spdlog::error_s( + "Invalid int: {} (valid range: [{}, {}])", + val, + static_cast(std::numeric_limits::min()), + static_cast(std::numeric_limits::max()) + ); + return false; + }, + base ); } } @@ -283,11 +281,11 @@ using namespace std::string_view_literals; node_callback_t expect_length(callback_t callback); node_callback_t expect_key( - ovdl::symbol key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false + ovdl::symbol key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false ); node_callback_t expect_key( - std::string_view key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false + std::string_view key, node_callback_t callback, bool* key_found = nullptr, bool allow_duplicates = false ); node_callback_t expect_dictionary_and_length(length_callback_t length_callback, key_value_callback_t callback); @@ -306,8 +304,8 @@ using namespace std::string_view_literals; node_callback_t callback; size_t count = 0; - dictionary_entry_t(expected_count_t new_expected_count, node_callback_t&& new_callback) - : expected_count { new_expected_count }, callback { MOV(new_callback) } {} + dictionary_entry_t(expected_count_t new_expected_count, node_callback_t&& new_callback) : + expected_count { new_expected_count }, callback { MOV(new_callback) } {} constexpr bool must_appear() const { return static_cast(expected_count) & static_cast(expected_count_t::_MUST_APPEAR); @@ -326,8 +324,10 @@ using namespace std::string_view_literals; template bool add_key_map_entry( - Map&& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, - NodeCallback auto&& callback + Map&& key_map, + std::string_view key, + dictionary_entry_t::expected_count_t expected_count, + NodeCallback auto&& callback ) { if (!key_map.contains(key)) { key_map.emplace(key, dictionary_entry_t { expected_count, MOV(callback) }); @@ -347,10 +347,9 @@ using namespace std::string_view_literals; } template - KeyValueCallback auto dictionary_keys_callback( - Map&& key_map, MapKeyValueCallback auto&& default_callback - ) { - return [&key_map, default_callback = FWD(default_callback)](std::string_view key, ast::NodeCPtr value) mutable -> bool { + KeyValueCallback auto dictionary_keys_callback(Map&& key_map, MapKeyValueCallback auto&& default_callback) { + return [&key_map, + default_callback = FWD(default_callback)](std::string_view key, ast::NodeCPtr value) mutable -> bool { typename std::remove_reference_t::iterator it = key_map.find(key); if (it == key_map.end()) { return default_callback(key_map, key, value); @@ -390,8 +389,11 @@ using namespace std::string_view_literals; template bool add_key_map_entries( - Map&& key_map, std::string_view key, dictionary_entry_t::expected_count_t expected_count, - NodeCallback auto&& callback, Args&&... args + Map&& key_map, + std::string_view key, + dictionary_entry_t::expected_count_t expected_count, + NodeCallback auto&& callback, + Args&&... args ) { bool ret = add_key_map_entry(FWD(key_map), FWD(key), expected_count, FWD(callback)); ret &= add_key_map_entries(FWD(key_map), FWD(args)...); @@ -400,48 +402,53 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_key_map_and_length_and_default( - Map&& key_map, LengthCallback auto&& length_callback, MapKeyValueCallback auto&& default_callback + Map&& key_map, LengthCallback auto&& length_callback, MapKeyValueCallback auto&& default_callback ) { - return [length_callback = FWD(length_callback), default_callback = FWD(default_callback), key_map = MOV(key_map)]( - ast::NodeCPtr node - ) mutable -> bool { - bool ret = expect_dictionary_and_length( - FWD(length_callback), dictionary_keys_callback(key_map, FWD(default_callback)) - )(node); + return [length_callback = FWD(length_callback), + default_callback = FWD(default_callback), + key_map = MOV(key_map)](ast::NodeCPtr node) mutable -> bool { + bool ret = + expect_dictionary_and_length(FWD(length_callback), dictionary_keys_callback(key_map, FWD(default_callback)))( + node + ); ret &= check_key_map_counts(key_map); return ret; }; } template - NodeCallback auto expect_dictionary_key_map_and_length( - Map&& key_map, LengthCallback auto&& length_callback - ) { + NodeCallback auto expect_dictionary_key_map_and_length(Map&& key_map, LengthCallback auto&& length_callback) { return expect_dictionary_key_map_and_length_and_default( - FWD(key_map), FWD(length_callback), map_key_value_invalid_callback + FWD(key_map), FWD(length_callback), map_key_value_invalid_callback ); } template NodeCallback auto expect_dictionary_key_map_and_default( - Map&& key_map, MapKeyValueCallback auto&& default_callback + Map&& key_map, MapKeyValueCallback auto&& default_callback ) { return expect_dictionary_key_map_and_length_and_default( - FWD(key_map), default_length_callback, FWD(default_callback) + FWD(key_map), default_length_callback, FWD(default_callback) ); } template NodeCallback auto expect_dictionary_key_map(template_key_map_t&& key_map) { return expect_dictionary_key_map_and_length_and_default( - MOV(key_map), default_length_callback, map_key_value_ignore_invalid_callback> // we use map_key_value_ignore_invalid_callback here as some mods add extraneous keys (like maxWidth) which V2 ignores, so we must too + MOV(key_map), + default_length_callback, + map_key_value_ignore_invalid_callback> // we use map_key_value_ignore_invalid_callback + // here as some mods add extraneous keys (like + // maxWidth) which V2 ignores, so we must too ); } template NodeCallback auto expect_dictionary_key_map_and_length_and_default( - Map&& key_map, LengthCallback auto&& length_callback, MapKeyValueCallback auto&& default_callback, - Args&&... args + Map&& key_map, + LengthCallback auto&& length_callback, + MapKeyValueCallback auto&& default_callback, + Args&&... args ) { // TODO - pass return value back up (part of big key_map_t rewrite?) add_key_map_entries(FWD(key_map), FWD(args)...); @@ -450,7 +457,7 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_key_map_and_length( - Map&& key_map, LengthCallback auto&& length_callback, Args&&... args + Map&& key_map, LengthCallback auto&& length_callback, Args&&... args ) { add_key_map_entries(FWD(key_map), FWD(args)...); return expect_dictionary_key_map_and_length(FWD(key_map), FWD(length_callback)); @@ -458,20 +465,16 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_key_map_and_default_map( - Map&& key_map, MapKeyValueCallback auto&& default_callback, Args&&... args + Map&& key_map, MapKeyValueCallback auto&& default_callback, Args&&... args ) { add_key_map_entries(FWD(key_map), FWD(args)...); return expect_dictionary_key_map_and_default(FWD(key_map), FWD(default_callback)); } template NodeCallback auto expect_dictionary_key_map_and_default( - Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args + Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args ) { - return expect_dictionary_key_map_and_default_map( - key_map, - ignore_map(FWD(default_callback)), - FWD(args)... - ); + return expect_dictionary_key_map_and_default_map(key_map, ignore_map(FWD(default_callback)), FWD(args)...); } template @@ -482,38 +485,47 @@ using namespace std::string_view_literals; template NodeCallback auto expect_dictionary_keys_and_length_and_default( - LengthCallback auto&& length_callback, MapKeyValueCallback> auto&& default_callback, Args&&... args + LengthCallback auto&& length_callback, + MapKeyValueCallback> auto&& default_callback, + Args&&... args ) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, FWD(length_callback), FWD(default_callback), FWD(args)... + template_key_map_t {}, FWD(length_callback), FWD(default_callback), FWD(args)... ); } template NodeCallback auto expect_dictionary_keys_and_length(LengthCallback auto&& length_callback, Args&&... args) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, FWD(length_callback), map_key_value_invalid_callback>, FWD(args)... + template_key_map_t {}, + FWD(length_callback), + map_key_value_invalid_callback>, + FWD(args)... ); } template - NodeCallback auto expect_dictionary_keys_and_default_map(MapKeyValueCallback> auto&& default_callback, Args&&... args) { + NodeCallback auto expect_dictionary_keys_and_default_map( + MapKeyValueCallback> auto&& default_callback, Args&&... args + ) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, default_length_callback, FWD(default_callback), FWD(args)... + template_key_map_t {}, default_length_callback, FWD(default_callback), FWD(args)... ); } template NodeCallback auto expect_dictionary_keys_and_default(KeyValueCallback auto&& default_callback, Args&&... args) { return expect_dictionary_keys_and_default_map( - ignore_map>(FWD(default_callback)), - FWD(args)... + ignore_map>(FWD(default_callback)), FWD(args)... ); } template NodeCallback auto expect_dictionary_keys(Args&&... args) { return expect_dictionary_key_map_and_length_and_default( - template_key_map_t {}, default_length_callback, map_key_value_invalid_callback>, FWD(args)... + template_key_map_t {}, + default_length_callback, + map_key_value_invalid_callback>, + FWD(args)... ); } @@ -531,36 +543,31 @@ using namespace std::string_view_literals; } template NodeCallback auto expect_dictionary_key_map_reserve_length_and_default( - reservable auto& reservable, Map&& key_map, KeyValueCallback auto&& default_callback, - Args&&... args + reservable auto& reservable, Map&& key_map, KeyValueCallback auto&& default_callback, Args&&... args ) { return expect_dictionary_key_map_and_length_and_default( - FWD(key_map), reserve_length_callback(reservable), FWD(default_callback), FWD(args)... + FWD(key_map), reserve_length_callback(reservable), FWD(default_callback), FWD(args)... ); } template - NodeCallback auto expect_dictionary_key_map_reserve_length( - reservable auto& reservable, Map&& key_map, Args&&... args - ) { + NodeCallback auto expect_dictionary_key_map_reserve_length(reservable auto& reservable, Map&& key_map, Args&&... args) { return expect_dictionary_key_map_and_length(FWD(key_map), reserve_length_callback(reservable), FWD(args)...); } template NodeCallback auto expect_dictionary_keys_reserve_length_and_default_map( - reservable auto& reservable, MapKeyValueCallback> auto&& default_callback, Args&&... args + reservable auto& reservable, MapKeyValueCallback> auto&& default_callback, Args&&... args ) { return expect_dictionary_keys_and_length_and_default( - reserve_length_callback(reservable), FWD(default_callback), FWD(args)... + reserve_length_callback(reservable), FWD(default_callback), FWD(args)... ); } template NodeCallback auto expect_dictionary_keys_reserve_length_and_default( - reservable auto& reservable, KeyValueCallback auto&& default_callback, Args&&... args + reservable auto& reservable, KeyValueCallback auto&& default_callback, Args&&... args ) { return expect_dictionary_keys_reserve_length_and_default_map( - reservable, - ignore_map>(FWD(default_callback)), - FWD(args)... + reservable, ignore_map>(FWD(default_callback)), FWD(args)... ); } @@ -573,7 +580,7 @@ using namespace std::string_view_literals; template Callback auto expect_mapped_string( - template_string_map_t const& map, Callback auto&& callback, bool warn = false + template_string_map_t const& map, Callback auto&& callback, bool warn = false ) { return [&map, callback = FWD(callback), warn](std::string_view string) mutable -> bool { const typename template_string_map_t::const_iterator it = map.find(string); @@ -581,9 +588,10 @@ using namespace std::string_view_literals; return callback(it->second); } spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "\"{}\" is not a valid key. Valid keys: [{}]", - string, string_join(map) + warn ? spdlog::level::warn : spdlog::level::err, + "\"{}\" is not a valid key. Valid keys: [{}]", + string, + string_join(map) ); return warn; }; @@ -614,9 +622,7 @@ using namespace std::string_view_literals; /* By default this will only allow an optional to be set once. Set allow_overwrite * to true to allow multiple assignments, with the last taking precedence. */ template - Callback auto assign_variable_callback_opt( - std::optional& var, bool allow_overwrite = false - ) { + Callback auto assign_variable_callback_opt(std::optional& var, bool allow_overwrite = false) { return [&var, allow_overwrite](T const& val) -> bool { if (!allow_overwrite && var.has_value()) { spdlog::error_s("Cannot assign value to already-initialised optional!"); @@ -630,9 +636,7 @@ using namespace std::string_view_literals; /* By default this will only allow an optional to be set once. Set allow_overwrite * to true to allow multiple assignments, with the last taking precedence. */ template - auto emplace_opt_callback( - std::optional& var, bool allow_overwrite = false - ) { + auto emplace_opt_callback(std::optional& var, bool allow_overwrite = false) { return [&var, allow_overwrite](auto&&... args) -> bool { if (!allow_overwrite && var.has_value()) { spdlog::error_s("Cannot assign value to already-initialised optional!"); @@ -691,7 +695,7 @@ using namespace std::string_view_literals; * to true to allow multiple assignments, with the last taking precedence. */ template Callback auto assign_variable_callback_pointer_opt( - std::optional& var, bool allow_overwrite = false + std::optional& var, bool allow_overwrite = false ) { return [&var, allow_overwrite](T const& val) -> bool { if (!allow_overwrite && var.has_value()) { @@ -740,10 +744,7 @@ using namespace std::string_view_literals; if (set.emplace(std::move(val)).second) { return true; } - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate set entry: \"{}\"", val - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate set entry: \"{}\"", val); return warn; }; } @@ -754,42 +755,32 @@ using namespace std::string_view_literals; if (set.emplace(&val).second) { return true; } - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate set entry: \"{}\"", - val - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate set entry: \"{}\"", val); return warn; }; } template - Callback auto map_callback( - tsl::ordered_map& map, Key key, bool warn = false - ) { + Callback auto map_callback(tsl::ordered_map& map, Key key, bool warn = false) { return [&map, key, warn](Value value) -> bool { if (map.emplace(key, std::move(value)).second) { return true; } - if constexpr(std::is_pointer_v) { + if constexpr (std::is_pointer_v) { spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate map entry with key: \"{}\"", ovfmt::validate(key) + warn ? spdlog::level::warn : spdlog::level::err, + "Duplicate map entry with key: \"{}\"", + ovfmt::validate(key) ); } else { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Duplicate map entry with key: \"{}\"", key - ); + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", key); } return warn; }; } template - Callback auto map_callback( - IndexedFlatMap& map, Key const* key, bool warn = false - ) { + Callback auto map_callback(IndexedFlatMap& map, Key const* key, bool warn = false) { return [&map, key, warn](Value value) -> bool { if (key == nullptr) { spdlog::error_s("Null key in map_callback"); @@ -798,7 +789,9 @@ using namespace std::string_view_literals; Value& map_value = map.at(*key); bool ret = true; if (map_value != Value {}) { - spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", *key); + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Duplicate map entry with key: \"{}\"", *key + ); ret = warn; } map_value = std::move(value); diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp index 3b169d6ea..3f925be15 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch.cpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch.cpp @@ -73,8 +73,10 @@ struct search_log { bool _warn; search_log( - bool warn, spdlog::format_string_t fmt, Args&&... args, - std::source_location const& location = std::source_location::current() + bool warn, + spdlog::format_string_t fmt, + Args&&... args, + std::source_location const& location = std::source_location::current() ) { _warn = warn; #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO @@ -82,8 +84,9 @@ struct search_log { fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); spdlog::default_logger_raw()->log( - spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, - warn ? spdlog::level::warn : spdlog::level::info, spdlog::string_view_t(buf.data(), buf.size()) + spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + warn ? spdlog::level::warn : spdlog::level::info, + spdlog::string_view_t(buf.data(), buf.size()) ); #else if (warn) { @@ -91,8 +94,9 @@ struct search_log { fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); spdlog::default_logger_raw()->log( - spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, - spdlog::level::warn, spdlog::string_view_t(buf.data(), buf.size()) + spdlog::source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + spdlog::level::warn, + spdlog::string_view_t(buf.data(), buf.size()) ); } #endif @@ -130,8 +134,9 @@ static fs::path _search_for_game_path(fs::path hint_path) { if (hint_empty) { #if defined(_WIN32) - static const fs::path registry_path = - Windows::ReadRegValue(HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path"); + static const fs::path registry_path = Windows::ReadRegValue( + HKEY_LOCAL_MACHINE, "SOFTWARE\\WOW6432Node\\Paradox Interactive\\Victoria 2", "path" + ); if (!registry_path.empty()) { return registry_path; @@ -215,21 +220,21 @@ static fs::path _search_for_game_path(fs::path hint_path) { bool vic2_install_confirmed = false; // if current_path is not a regular file, this is a non-default Steam Library, skip this parser evaluation if (fs::is_regular_file(current_path, error_code) && - (is_libraryfolders_vdf || filename_equals(libraryfolders, current_path))) { + (is_libraryfolders_vdf || filename_equals(libraryfolders, current_path))) { lexy_vdf::Parser parser; memory::string buffer; auto error_log_stream = detail::make_callback_stream( - [](void const* s, std::streamsize n, void* user_data) -> std::streamsize { - if (s != nullptr && n > 0 && user_data != nullptr) { - static_cast(user_data)->append(static_cast(s), n); - return n; - } else { - spdlog::warn("Invalid input to parser error log callback: {} / {} / {}", s, n, user_data); - return 0; - } - }, - &buffer + [](void const* s, std::streamsize n, void* user_data) -> std::streamsize { + if (s != nullptr && n > 0 && user_data != nullptr) { + static_cast(user_data)->append(static_cast(s), n); + return n; + } else { + spdlog::warn("Invalid input to parser error log callback: {} / {} / {}", s, n, user_data); + return 0; + } + }, + &buffer ); parser.set_error_log_to(error_log_stream); @@ -261,7 +266,8 @@ static fs::path _search_for_game_path(fs::path hint_path) { current_node = std::visit(visit_node, it->second); if (!current_node.has_value()) { - return search_log(hint_empty, "Expected libraryfolders.vdf's libraryfolders key to be a KeyValue dictionary.").result(); + return search_log(hint_empty, "Expected libraryfolders.vdf's libraryfolders key to be a KeyValue dictionary.") + .result(); } // Array of strings contain "0" to std::to_string(max_amount_of_steam_libraries - 1) @@ -293,15 +299,15 @@ static fs::path _search_for_game_path(fs::path hint_path) { it = node.value().find("path"); if (it != node.value().end()) { vic2_steam_lib_directory = std::visit( - [](auto&& arg) -> std::string_view { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return arg; - } else { - return ""; - } - }, - it->second + [](auto&& arg) -> std::string_view { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return arg; + } else { + return ""; + } + }, + it->second ); vic2_install_confirmed = true; break; @@ -350,12 +356,12 @@ static fs::path _search_for_game_path(fs::path hint_path) { bool is_Victoria_2_folder = false; if ((is_common_folder || filename_equals(common_folder, vic2_steam_lib_directory)) && - fs::is_directory(vic2_steam_lib_directory, error_code)) { + fs::is_directory(vic2_steam_lib_directory, error_code)) { vic2_steam_lib_directory /= Victoria_2_folder; is_Victoria_2_folder = true; } if ((is_Victoria_2_folder || filename_equals(Victoria_2_folder, vic2_steam_lib_directory)) && - fs::is_regular_file(vic2_steam_lib_directory / v2_game_exe, error_code)) { + fs::is_regular_file(vic2_steam_lib_directory / v2_game_exe, error_code)) { return vic2_steam_lib_directory; } diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp index f84d8002a..657fced48 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp @@ -57,7 +57,7 @@ namespace OpenVic::Windows { template RegistryKey( - HKEY parent_key_handle, std::basic_string_view child_key_name, std::basic_string_view value_name + HKEY parent_key_handle, std::basic_string_view child_key_name, std::basic_string_view value_name ) { open_key(parent_key_handle, child_key_name); query_key(value_name); @@ -89,10 +89,10 @@ namespace OpenVic::Windows { bool is_predefined() const { return (_key_handle == HKEY_CURRENT_USER) || (_key_handle == HKEY_LOCAL_MACHINE) || - (_key_handle == HKEY_CLASSES_ROOT) || (_key_handle == HKEY_CURRENT_CONFIG) || - (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (_key_handle == HKEY_PERFORMANCE_DATA) || - (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || (_key_handle == HKEY_PERFORMANCE_TEXT) || - (_key_handle == HKEY_USERS); + (_key_handle == HKEY_CLASSES_ROOT) || (_key_handle == HKEY_CURRENT_CONFIG) || + (_key_handle == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (_key_handle == HKEY_PERFORMANCE_DATA) || + (_key_handle == HKEY_PERFORMANCE_NLSTEXT) || (_key_handle == HKEY_PERFORMANCE_TEXT) || + (_key_handle == HKEY_USERS); } LSTATUS close_key() { @@ -124,7 +124,7 @@ namespace OpenVic::Windows { } _value = memory::wstring(data_size / sizeof(wchar_t), L'\0'); result = RegQueryValueExW( - _key_handle, wide_value.data(), NULL, NULL, reinterpret_cast(_value.data()), &data_size + _key_handle, wide_value.data(), NULL, NULL, reinterpret_cast(_value.data()), &data_size ); close_key(); diff --git a/src/openvic-simulation/defines/AIDefines.cpp b/src/openvic-simulation/defines/AIDefines.cpp index c57e3d00d..8dcebf171 100644 --- a/src/openvic-simulation/defines/AIDefines.cpp +++ b/src/openvic-simulation/defines/AIDefines.cpp @@ -11,51 +11,122 @@ std::string_view AIDefines::get_name() const { node_callback_t AIDefines::expect_defines() { return expect_dictionary_keys( - "COLONY_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colony_weight)), - "ADMINISTRATOR_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(administrator_weight)), - "INDUSTRYWORKER_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(industryworker_weight)), - "EDUCATOR_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(educator_weight)), - "SOLDIER_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_weight)), - "SOLDIER_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_fraction)), - "CAPITALIST_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(capitalist_fraction)), - "PRODUCTION_WEIGHT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(production_weight)), - "SPAM_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spam_penalty)), - "ONE_SIDE_MAX_WARSCORE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(one_side_max_warscore)), - "POP_PROJECT_INVESTMENT_MAX_BUDGET_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_project_investment_max_budget_factor)), - "RELATION_LIMIT_NO_ALLIANCE_OFFER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(relation_limit_no_alliance_offer)), - "NAVAL_SUPPLY_PENALTY_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_supply_penalty_limit)), - "CHANCE_BUILD_RAILROAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_railroad)), - "CHANCE_BUILD_NAVAL_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_naval_base)), - "CHANCE_BUILD_FORT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_build_fort)), - "CHANCE_INVEST_POP_PROJ", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_invest_pop_proj)), - "CHANCE_FOREIGN_INVEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(chance_foreign_invest)), - "TWS_AWARENESS_SCORE_LOW_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_awareness_score_low_cap)), - "TWS_AWARENESS_SCORE_ASPECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_awareness_score_aspect)), - "PEACE_BASE_RELUCTANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_base_reluctance)), - "PEACE_TIME_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(peace_time_duration)), - "PEACE_TIME_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_time_factor)), - "PEACE_TIME_FACTOR_NO_GOALS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_time_factor_no_goals)), - "PEACE_WAR_EXHAUSTION_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_war_exhaustion_factor)), - "PEACE_WAR_DIRECTION_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_war_direction_factor)), - "PEACE_WAR_DIRECTION_WINNING_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_war_direction_winning_mult)), - "PEACE_FORCE_BALANCE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_force_balance_factor)), - "PEACE_ALLY_BASE_RELUCTANCE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_base_reluctance_mult)), - "PEACE_ALLY_TIME_MULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_ally_time_mult)), - "PEACE_ALLY_WAR_EXHAUSTION_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_war_exhaustion_mult)), - "PEACE_ALLY_WAR_DIRECTION_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_war_direction_mult)), - "PEACE_ALLY_FORCE_BALANCE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_ally_force_balance_mult)), - "AGGRESSION_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(aggression_base)), - "AGGRESSION_UNCIV_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(aggression_unciv_bonus)), - "FLEET_SIZE", ONE_EXACTLY, expect_uint(assign_variable_callback(fleet_size)), - "MIN_FLEETS", ONE_EXACTLY, expect_uint(assign_variable_callback(min_fleets)), - "MAX_FLEETS", ONE_EXACTLY, expect_uint(assign_variable_callback(max_fleets)), - "MONTHS_BEFORE_DISBAND", ONE_EXACTLY, expect_months(assign_variable_callback(time_before_disband)) + "COLONY_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colony_weight)), + "ADMINISTRATOR_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(administrator_weight)), + "INDUSTRYWORKER_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(industryworker_weight)), + "EDUCATOR_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(educator_weight)), + "SOLDIER_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(soldier_weight)), + "SOLDIER_FRACTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(soldier_fraction)), + "CAPITALIST_FRACTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(capitalist_fraction)), + "PRODUCTION_WEIGHT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(production_weight)), + "SPAM_PENALTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spam_penalty)), + "ONE_SIDE_MAX_WARSCORE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(one_side_max_warscore)), + "POP_PROJECT_INVESTMENT_MAX_BUDGET_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_project_investment_max_budget_factor)), + "RELATION_LIMIT_NO_ALLIANCE_OFFER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(relation_limit_no_alliance_offer)), + "NAVAL_SUPPLY_PENALTY_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_supply_penalty_limit)), + "CHANCE_BUILD_RAILROAD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_build_railroad)), + "CHANCE_BUILD_NAVAL_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_build_naval_base)), + "CHANCE_BUILD_FORT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_build_fort)), + "CHANCE_INVEST_POP_PROJ", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_invest_pop_proj)), + "CHANCE_FOREIGN_INVEST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(chance_foreign_invest)), + "TWS_AWARENESS_SCORE_LOW_CAP", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_awareness_score_low_cap)), + "TWS_AWARENESS_SCORE_ASPECT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_awareness_score_aspect)), + "PEACE_BASE_RELUCTANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_base_reluctance)), + "PEACE_TIME_MONTHS", + ONE_EXACTLY, + expect_months(assign_variable_callback(peace_time_duration)), + "PEACE_TIME_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_time_factor)), + "PEACE_TIME_FACTOR_NO_GOALS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_time_factor_no_goals)), + "PEACE_WAR_EXHAUSTION_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_war_exhaustion_factor)), + "PEACE_WAR_DIRECTION_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_war_direction_factor)), + "PEACE_WAR_DIRECTION_WINNING_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_war_direction_winning_mult)), + "PEACE_FORCE_BALANCE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_force_balance_factor)), + "PEACE_ALLY_BASE_RELUCTANCE_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_base_reluctance_mult)), + "PEACE_ALLY_TIME_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_time_mult)), + "PEACE_ALLY_WAR_EXHAUSTION_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_war_exhaustion_mult)), + "PEACE_ALLY_WAR_DIRECTION_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_war_direction_mult)), + "PEACE_ALLY_FORCE_BALANCE_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_ally_force_balance_mult)), + "AGGRESSION_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(aggression_base)), + "AGGRESSION_UNCIV_BONUS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(aggression_unciv_bonus)), + "FLEET_SIZE", + ONE_EXACTLY, + expect_uint(assign_variable_callback(fleet_size)), + "MIN_FLEETS", + ONE_EXACTLY, + expect_uint(assign_variable_callback(min_fleets)), + "MAX_FLEETS", + ONE_EXACTLY, + expect_uint(assign_variable_callback(max_fleets)), + "MONTHS_BEFORE_DISBAND", + ONE_EXACTLY, + expect_months(assign_variable_callback(time_before_disband)) ); } diff --git a/src/openvic-simulation/defines/CountryDefines.cpp b/src/openvic-simulation/defines/CountryDefines.cpp index fe28cf070..36cb8de9a 100644 --- a/src/openvic-simulation/defines/CountryDefines.cpp +++ b/src/openvic-simulation/defines/CountryDefines.cpp @@ -11,131 +11,266 @@ std::string_view CountryDefines::get_name() const { node_callback_t CountryDefines::expect_defines() { return expect_dictionary_keys( - "YEARS_OF_NATIONALISM", ONE_EXACTLY, expect_years(assign_variable_callback(nationalism_duration)), - "MONTHS_UNTIL_BROKEN", ZERO_OR_ONE, // NOT USED - expect_months(assign_variable_callback(rebels_hold_capital_success_duration)), - "REBEL_ACCEPTANCE_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(rebel_success_duration)), - "BASE_COUNTRY_TAX_EFFICIENCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_country_tax_efficiency)), - "BASE_COUNTRY_ADMIN_EFFICIENCY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(base_country_admin_efficiency)), - "GOLD_TO_CASH_RATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gold_to_cash_rate)), - "GOLD_TO_WORKER_PAY_RATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gold_to_worker_pay_rate)), - "GREAT_NATIONS_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(great_power_rank)), - "GREATNESS_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(lose_great_power_grace_days)), - "BADBOY_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_containment_limit)), - "MAX_BUREAUCRACY_PERCENTAGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_bureaucracy_percentage)), - "BUREAUCRACY_PERCENTAGE_INCREMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(bureaucracy_percentage_increment)), - "MIN_CRIMEFIGHT_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_crimefight_percent)), - "MAX_CRIMEFIGHT_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_crimefight_percent)), - "ADMIN_EFFICIENCY_CRIMEFIGHT_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(admin_efficiency_crimefight_percent)), - "CONSERVATIVE_INCREASE_AFTER_REFORM", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(conservative_increase_after_reform)), - "CAMPAIGN_EVENT_BASE_TIME", ONE_EXACTLY, expect_days(assign_variable_callback(campaign_event_base_duration)), - "CAMPAIGN_EVENT_MIN_TIME", ZERO_OR_ONE, expect_days(assign_variable_callback(campaign_event_min_duration)), // NOT USED - "CAMPAIGN_EVENT_STATE_SCALE", ZERO_OR_ONE, // NOT USED - expect_days(assign_variable_callback(campaign_event_state_duration_modifier)), - "CAMPAIGN_DURATION", ONE_EXACTLY, expect_months(assign_variable_callback(campaign_duration)), - "COLONIAL_RANK", ONE_EXACTLY, expect_uint(assign_variable_callback(secondary_power_rank)), - "COLONY_TO_STATE_PRESTIGE_GAIN", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colony_to_state_prestige_gain)), - "COLONIAL_LIFERATING", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(colonial_liferating)), - "BASE_GREATPOWER_DAILY_INFLUENCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(base_greatpower_daily_influence)), - "AI_SUPPORT_REFORM", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_support_reform)), - "BASE_MONTHLY_DIPLOPOINTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_monthly_diplopoints)), - "DIPLOMAT_TRAVEL_TIME", ONE_EXACTLY, expect_days(assign_variable_callback(diplomat_travel_duration)), - "PROVINCE_OVERSEAS_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(province_overseas_penalty)), - "NONCORE_TAX_PENALTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(noncore_tax_penalty)), - "BASE_TARIFF_EFFICIENCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_tariff_efficiency)), - "COLONY_FORMED_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colony_formed_prestige)), - "CREATED_CB_VALID_TIME", ONE_EXACTLY, expect_months(assign_variable_callback(created_cb_valid_time)), - "LOYALTY_BOOST_ON_PARTY_WIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(loyalty_boost_on_party_win)), - "MOVEMENT_RADICALISM_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_radicalism_base)), - "MOVEMENT_RADICALISM_PASSED_REFORM_EFFECT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(movement_radicalism_passed_reform_effect)), - "MOVEMENT_RADICALISM_NATIONALISM_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(movement_radicalism_nationalism_factor)), - "SUPPRESSION_POINTS_GAIN_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(suppression_points_gain_base)), - "SUPPRESS_BUREAUCRAT_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(suppress_bureaucrat_factor)), - "WRONG_REFORM_MILITANCY_IMPACT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(wrong_reform_militancy_impact)), - "SUPPRESSION_RADICALISATION_HIT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(suppression_radicalisation_hit)), - "INVESTMENT_SCORE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(country_investment_industrial_score_factor)), - "UNCIV_TECH_SPREAD_MAX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_tech_spread_max)), - "UNCIV_TECH_SPREAD_MIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_tech_spread_min)), - "MIN_DELAY_BETWEEN_REFORMS", ONE_EXACTLY, expect_months(assign_variable_callback(min_delay_duration_between_reforms)), - "ECONOMIC_REFORM_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(economic_reform_uh_factor)), - "MILITARY_REFORM_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(military_reform_uh_factor)), - "WRONG_REFORM_RADICAL_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(wrong_reform_radical_impact)), - "TECH_YEAR_SPAN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tech_year_span)), - "TECH_FACTOR_VASSAL", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tech_factor_vassal)), - "MAX_SUPPRESSION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_suppression)), - "PRESTIGE_HIT_ON_BREAK_COUNTRY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_hit_on_break_country)), - "MIN_MOBILIZE_LIMIT", ONE_EXACTLY, expect_uint(assign_variable_callback(min_mobilize_limit)), - "POP_GROWTH_COUNTRY_CACHE_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(pop_growth_country_cache_days)), - "NEWSPAPER_PRINTING_FREQUENCY", ONE_EXACTLY, expect_days(assign_variable_callback(newspaper_printing_frequency)), - "NEWSPAPER_TIMEOUT_PERIOD", ONE_EXACTLY, expect_days(assign_variable_callback(newspaper_timeout_period)), - "NEWSPAPER_MAX_TENSION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(newspaper_max_tension)), - "NAVAL_BASE_SUPPLY_SCORE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_supply_score_base)), - "NAVAL_BASE_SUPPLY_SCORE_EMPTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_supply_score_empty)), - "NAVAL_BASE_NON_CORE_SUPPLY_SCORE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_base_non_core_supply_score)), - "COLONIAL_POINTS_FROM_SUPPLY_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonial_points_from_supply_factor)), - "COLONIAL_POINTS_FOR_NON_CORE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonial_points_for_non_core_base)), - "MOBILIZATION_SPEED_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mobilization_speed_base)), - "MOBILIZATION_SPEED_RAILS_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(mobilization_speed_rails_mult)), - "COLONIZATION_INTEREST_LEAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_interest_lead)), - "COLONIZATION_INFLUENCE_LEAD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_influence_lead)), - "COLONIZATION_MONTHS_TO_COLONIZE", ONE_EXACTLY, expect_months(assign_variable_callback(colonization_duration)), - "COLONIZATION_DAYS_BETWEEN_INVESTMENT", ONE_EXACTLY, - expect_days(assign_variable_callback(colonization_days_between_investment)), - "COLONIZATION_DAYS_FOR_INITIAL_INVESTMENT", ONE_EXACTLY, - expect_days(assign_variable_callback(colonization_days_for_initial_investment)), - "COLONIZATION_PROTECTORATE_PROVINCE_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_protectorate_province_maintenance)), - "COLONIZATION_COLONY_PROVINCE_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_province_maintenance)), - "COLONIZATION_COLONY_INDUSTRY_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_industry_maintenance)), - "COLONIZATION_COLONY_RAILWAY_MAINTAINANCE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(colonization_colony_railway_maintenance)), - "COLONIZATION_INTEREST_COST_INITIAL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_interest_cost_initial)), - "COLONIZATION_INTEREST_COST_NEIGHBOR_MODIFIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_interest_cost_neighbor_modifier)), - "COLONIZATION_INTEREST_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_interest_cost)), - "COLONIZATION_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(colonization_influence_cost)), - "COLONIZATION_EXTRA_GUARD_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_extra_guard_cost)), - "COLONIZATION_RELEASE_DOMINION_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_release_dominion_cost)), - "COLONIZATION_CREATE_STATE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_state_cost)), - "COLONIZATION_CREATE_PROTECTORATE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_protectorate_cost)), - "COLONIZATION_CREATE_COLONY_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_create_colony_cost)), - "COLONIZATION_COLONY_STATE_DISTANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_colony_state_distance)), - "COLONIZATION_INFLUENCE_TEMPERATURE_PER_DAY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_day)), - "COLONIZATION_INFLUENCE_TEMPERATURE_PER_LEVEL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_level)), - "PARTY_LOYALTY_HIT_ON_WAR_LOSS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(party_loyalty_hit_on_war_loss)), - "RESEARCH_POINTS_ON_CONQUER_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(research_points_on_conquer_mult)), - "MAX_RESEARCH_POINTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_research_points)) + "YEARS_OF_NATIONALISM", + ONE_EXACTLY, + expect_years(assign_variable_callback(nationalism_duration)), + "MONTHS_UNTIL_BROKEN", + ZERO_OR_ONE, // NOT USED + expect_months(assign_variable_callback(rebels_hold_capital_success_duration)), + "REBEL_ACCEPTANCE_MONTHS", + ONE_EXACTLY, + expect_months(assign_variable_callback(rebel_success_duration)), + "BASE_COUNTRY_TAX_EFFICIENCY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_country_tax_efficiency)), + "BASE_COUNTRY_ADMIN_EFFICIENCY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_country_admin_efficiency)), + "GOLD_TO_CASH_RATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gold_to_cash_rate)), + "GOLD_TO_WORKER_PAY_RATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gold_to_worker_pay_rate)), + "GREAT_NATIONS_COUNT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(great_power_rank)), + "GREATNESS_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(lose_great_power_grace_days)), + "BADBOY_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_containment_limit)), + "MAX_BUREAUCRACY_PERCENTAGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_bureaucracy_percentage)), + "BUREAUCRACY_PERCENTAGE_INCREMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(bureaucracy_percentage_increment)), + "MIN_CRIMEFIGHT_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(min_crimefight_percent)), + "MAX_CRIMEFIGHT_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_crimefight_percent)), + "ADMIN_EFFICIENCY_CRIMEFIGHT_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(admin_efficiency_crimefight_percent)), + "CONSERVATIVE_INCREASE_AFTER_REFORM", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(conservative_increase_after_reform)), + "CAMPAIGN_EVENT_BASE_TIME", + ONE_EXACTLY, + expect_days(assign_variable_callback(campaign_event_base_duration)), + "CAMPAIGN_EVENT_MIN_TIME", + ZERO_OR_ONE, + expect_days(assign_variable_callback(campaign_event_min_duration)), // NOT USED + "CAMPAIGN_EVENT_STATE_SCALE", + ZERO_OR_ONE, // NOT USED + expect_days(assign_variable_callback(campaign_event_state_duration_modifier)), + "CAMPAIGN_DURATION", + ONE_EXACTLY, + expect_months(assign_variable_callback(campaign_duration)), + "COLONIAL_RANK", + ONE_EXACTLY, + expect_uint(assign_variable_callback(secondary_power_rank)), + "COLONY_TO_STATE_PRESTIGE_GAIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colony_to_state_prestige_gain)), + "COLONIAL_LIFERATING", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(colonial_liferating)), + "BASE_GREATPOWER_DAILY_INFLUENCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_greatpower_daily_influence)), + "AI_SUPPORT_REFORM", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_support_reform)), + "BASE_MONTHLY_DIPLOPOINTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_monthly_diplopoints)), + "DIPLOMAT_TRAVEL_TIME", + ONE_EXACTLY, + expect_days(assign_variable_callback(diplomat_travel_duration)), + "PROVINCE_OVERSEAS_PENALTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(province_overseas_penalty)), + "NONCORE_TAX_PENALTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(noncore_tax_penalty)), + "BASE_TARIFF_EFFICIENCY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_tariff_efficiency)), + "COLONY_FORMED_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colony_formed_prestige)), + "CREATED_CB_VALID_TIME", + ONE_EXACTLY, + expect_months(assign_variable_callback(created_cb_valid_time)), + "LOYALTY_BOOST_ON_PARTY_WIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(loyalty_boost_on_party_win)), + "MOVEMENT_RADICALISM_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_radicalism_base)), + "MOVEMENT_RADICALISM_PASSED_REFORM_EFFECT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_radicalism_passed_reform_effect)), + "MOVEMENT_RADICALISM_NATIONALISM_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_radicalism_nationalism_factor)), + "SUPPRESSION_POINTS_GAIN_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(suppression_points_gain_base)), + "SUPPRESS_BUREAUCRAT_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(suppress_bureaucrat_factor)), + "WRONG_REFORM_MILITANCY_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(wrong_reform_militancy_impact)), + "SUPPRESSION_RADICALISATION_HIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(suppression_radicalisation_hit)), + "INVESTMENT_SCORE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(country_investment_industrial_score_factor)), + "UNCIV_TECH_SPREAD_MAX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unciv_tech_spread_max)), + "UNCIV_TECH_SPREAD_MIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unciv_tech_spread_min)), + "MIN_DELAY_BETWEEN_REFORMS", + ONE_EXACTLY, + expect_months(assign_variable_callback(min_delay_duration_between_reforms)), + "ECONOMIC_REFORM_UH_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(economic_reform_uh_factor)), + "MILITARY_REFORM_UH_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(military_reform_uh_factor)), + "WRONG_REFORM_RADICAL_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(wrong_reform_radical_impact)), + "TECH_YEAR_SPAN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tech_year_span)), + "TECH_FACTOR_VASSAL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tech_factor_vassal)), + "MAX_SUPPRESSION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_suppression)), + "PRESTIGE_HIT_ON_BREAK_COUNTRY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_hit_on_break_country)), + "MIN_MOBILIZE_LIMIT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(min_mobilize_limit)), + "POP_GROWTH_COUNTRY_CACHE_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(pop_growth_country_cache_days)), + "NEWSPAPER_PRINTING_FREQUENCY", + ONE_EXACTLY, + expect_days(assign_variable_callback(newspaper_printing_frequency)), + "NEWSPAPER_TIMEOUT_PERIOD", + ONE_EXACTLY, + expect_days(assign_variable_callback(newspaper_timeout_period)), + "NEWSPAPER_MAX_TENSION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(newspaper_max_tension)), + "NAVAL_BASE_SUPPLY_SCORE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_base_supply_score_base)), + "NAVAL_BASE_SUPPLY_SCORE_EMPTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_base_supply_score_empty)), + "NAVAL_BASE_NON_CORE_SUPPLY_SCORE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_base_non_core_supply_score)), + "COLONIAL_POINTS_FROM_SUPPLY_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonial_points_from_supply_factor)), + "COLONIAL_POINTS_FOR_NON_CORE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonial_points_for_non_core_base)), + "MOBILIZATION_SPEED_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mobilization_speed_base)), + "MOBILIZATION_SPEED_RAILS_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mobilization_speed_rails_mult)), + "COLONIZATION_INTEREST_LEAD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_interest_lead)), + "COLONIZATION_INFLUENCE_LEAD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_influence_lead)), + "COLONIZATION_MONTHS_TO_COLONIZE", + ONE_EXACTLY, + expect_months(assign_variable_callback(colonization_duration)), + "COLONIZATION_DAYS_BETWEEN_INVESTMENT", + ONE_EXACTLY, + expect_days(assign_variable_callback(colonization_days_between_investment)), + "COLONIZATION_DAYS_FOR_INITIAL_INVESTMENT", + ONE_EXACTLY, + expect_days(assign_variable_callback(colonization_days_for_initial_investment)), + "COLONIZATION_PROTECTORATE_PROVINCE_MAINTENANCE", + ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(colonization_protectorate_province_maintenance)), + "COLONIZATION_COLONY_PROVINCE_MAINTENANCE", + ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(colonization_colony_province_maintenance)), + "COLONIZATION_COLONY_INDUSTRY_MAINTENANCE", + ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(colonization_colony_industry_maintenance)), + "COLONIZATION_COLONY_RAILWAY_MAINTENANCE", + ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(colonization_colony_railway_maintenance)), + "COLONIZATION_INTEREST_COST_INITIAL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_interest_cost_initial)), + "COLONIZATION_INTEREST_COST_NEIGHBOR_MODIFIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_interest_cost_neighbor_modifier)), + "COLONIZATION_INTEREST_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_interest_cost)), + "COLONIZATION_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_influence_cost)), + "COLONIZATION_EXTRA_GUARD_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_extra_guard_cost)), + "COLONIZATION_RELEASE_DOMINION_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_release_dominion_cost)), + "COLONIZATION_CREATE_STATE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_create_state_cost)), + "COLONIZATION_CREATE_PROTECTORATE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_create_protectorate_cost)), + "COLONIZATION_CREATE_COLONY_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_create_colony_cost)), + "COLONIZATION_COLONY_STATE_DISTANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_colony_state_distance)), + "COLONIZATION_INFLUENCE_TEMPERATURE_PER_DAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_day)), + "COLONIZATION_INFLUENCE_TEMPERATURE_PER_LEVEL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(colonization_influence_temperature_per_level)), + "PARTY_LOYALTY_HIT_ON_WAR_LOSS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(party_loyalty_hit_on_war_loss)), + "RESEARCH_POINTS_ON_CONQUER_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(research_points_on_conquer_mult)), + "MAX_RESEARCH_POINTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_research_points)) ); } diff --git a/src/openvic-simulation/defines/CountryDefines.hpp b/src/openvic-simulation/defines/CountryDefines.hpp index 74b439d5c..da07b5644 100644 --- a/src/openvic-simulation/defines/CountryDefines.hpp +++ b/src/openvic-simulation/defines/CountryDefines.hpp @@ -30,10 +30,12 @@ namespace OpenVic { fixed_point_t PROPERTY(min_crimefight_percent); fixed_point_t PROPERTY(max_crimefight_percent); fixed_point_t PROPERTY(admin_efficiency_crimefight_percent); + public: constexpr fixed_point_t get_admin_spending_crimefight_percent() const { return fixed_point_t::_1 - admin_efficiency_crimefight_percent; } + private: fixed_point_t PROPERTY(conservative_increase_after_reform); Timespan PROPERTY(campaign_event_base_duration); diff --git a/src/openvic-simulation/defines/Define.cpp b/src/openvic-simulation/defines/Define.cpp index 897b60e6d..7615a2b0f 100644 --- a/src/openvic-simulation/defines/Define.cpp +++ b/src/openvic-simulation/defines/Define.cpp @@ -27,8 +27,8 @@ bool DefineManager::load_defines_file(ast::NodeCPtr root) { if (military_defines.get_leader_recruit_cost() <= 0) { spdlog::error_s( - "Invalid leader recruit cost: {} - must be greater than 0, changing to 1", - military_defines.get_leader_recruit_cost() + "Invalid leader recruit cost: {} - must be greater than 0, changing to 1", + military_defines.get_leader_recruit_cost() ); ret = false; military_defines.leader_recruit_cost = 1; diff --git a/src/openvic-simulation/defines/DiplomacyDefines.cpp b/src/openvic-simulation/defines/DiplomacyDefines.cpp index 15c148b45..7cfb0b6c8 100644 --- a/src/openvic-simulation/defines/DiplomacyDefines.cpp +++ b/src/openvic-simulation/defines/DiplomacyDefines.cpp @@ -16,551 +16,1052 @@ node_callback_t DiplomacyDefines::expect_defines() { key_map_t key_map; add_key_map_entries( - key_map, - "PEACE_COST_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_add_to_sphere)), - "PEACE_COST_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_release_puppet)), - "PEACE_COST_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_make_puppet)), - "PEACE_COST_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_disarmament)), - "PEACE_COST_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_destroy_forts)), - "PEACE_COST_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_destroy_naval_bases)), - "PEACE_COST_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_reparations)), - "PEACE_COST_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_transfer_provinces)), - "PEACE_COST_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_remove_cores)), - "PEACE_COST_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_prestige)), - "PEACE_COST_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_concede)), - "PEACE_COST_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_status_quo)), - "PEACE_COST_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_annex)), - "PEACE_COST_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_demand_state)), - "PEACE_COST_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_install_communist_gov_type)), - "PEACE_COST_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_uninstall_communist_gov_type)), - "PEACE_COST_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_colony)), - "INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_add_to_sphere)), - "INFAMY_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_release_puppet)), - "INFAMY_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_make_puppet)), - "INFAMY_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_disarmament)), - "INFAMY_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_destroy_forts)), - "INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_destroy_naval_bases)), - "INFAMY_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_reparations)), - "INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_transfer_provinces)), - "INFAMY_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_remove_cores)), - "INFAMY_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_prestige)), - "INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_concede)), - "INFAMY_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_status_quo)), - "INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_annex)), - "INFAMY_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_demand_state)), - "INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(infamy_install_communist_gov_type)), - "INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(infamy_uninstall_communist_gov_type)), - "INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_colony)), - "PRESTIGE_ADD_TO_SPHERE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_add_to_sphere_base)), - "PRESTIGE_RELEASE_PUPPET_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_release_puppet_base)), - "PRESTIGE_MAKE_PUPPET_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_make_puppet_base)), - "PRESTIGE_DISARMAMENT_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_disarmament_base)), - "PRESTIGE_DESTROY_FORTS_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_destroy_forts_base)), - "PRESTIGE_DESTROY_NAVAL_BASES_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases_base)), - "PRESTIGE_REPARATIONS_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reparations_base)), - "PRESTIGE_TRANSFER_PROVINCES_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_transfer_provinces_base)), - "PRESTIGE_REMOVE_CORES_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_remove_cores_base)), - "PRESTIGE_PRESTIGE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_prestige_base)), - "PRESTIGE_CONCEDE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_concede_base)), - "PRESTIGE_STATUS_QUO_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_status_quo_base)), - "PRESTIGE_ANNEX_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_annex_base)), - "PRESTIGE_DEMAND_STATE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_demand_state_base)), - "PRESTIGE_CLEAR_UNION_SPHERE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere_base)), - "PRESTIGE_GUNBOAT_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_gunboat_base)), - "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type_base)), - "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type_base)), - "PRESTIGE_COLONY_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_colony_base)), - "PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_add_to_sphere)), - "PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_release_puppet)), - "PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_make_puppet)), - "PRESTIGE_DISARMAMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_disarmament)), - "PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_destroy_forts)), - "PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases)), - "PRESTIGE_REPARATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reparations)), - "PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_transfer_provinces)), - "PRESTIGE_REMOVE_CORES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_remove_cores)), - "PRESTIGE_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_prestige)), - "PRESTIGE_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_concede)), - "PRESTIGE_STATUS_QUO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_status_quo)), - "PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_annex)), - "PRESTIGE_DEMAND_STATE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_demand_state)), - "PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere)), - "PRESTIGE_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_gunboat)), - "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type)), - "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type)), - "PRESTIGE_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_colony)), - "BREAKTRUCE_INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_add_to_sphere)), - "BREAKTRUCE_INFAMY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_release_puppet)), - "BREAKTRUCE_INFAMY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_make_puppet)), - "BREAKTRUCE_INFAMY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_disarmament)), - "BREAKTRUCE_INFAMY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_forts)), - "BREAKTRUCE_INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_naval_bases)), - "BREAKTRUCE_INFAMY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_reparations)), - "BREAKTRUCE_INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_transfer_provinces)), - "BREAKTRUCE_INFAMY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_remove_cores)), - "BREAKTRUCE_INFAMY_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_prestige)), - "BREAKTRUCE_INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_concede)), - "BREAKTRUCE_INFAMY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_status_quo)), - "BREAKTRUCE_INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_annex)), - "BREAKTRUCE_INFAMY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_demand_state)), - "BREAKTRUCE_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_install_communist_gov_type)), - "BREAKTRUCE_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_uninstall_communist_gov_type)), - "BREAKTRUCE_INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_colony)), - "BREAKTRUCE_PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_add_to_sphere)), - "BREAKTRUCE_PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_release_puppet)), - "BREAKTRUCE_PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_make_puppet)), - "BREAKTRUCE_PRESTIGE_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_disarmament)), - "BREAKTRUCE_PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_forts)), - "BREAKTRUCE_PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_naval_bases)), - "BREAKTRUCE_PRESTIGE_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_reparations)), - "BREAKTRUCE_PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_transfer_provinces)), - "BREAKTRUCE_PRESTIGE_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_remove_cores)), - "BREAKTRUCE_PRESTIGE_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_prestige)), - "BREAKTRUCE_PRESTIGE_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_concede)), - "BREAKTRUCE_PRESTIGE_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_status_quo)), - "BREAKTRUCE_PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_annex)), - "BREAKTRUCE_PRESTIGE_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_demand_state)), - "BREAKTRUCE_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_install_communist_gov_type)), - "BREAKTRUCE_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_uninstall_communist_gov_type)), - "BREAKTRUCE_PRESTIGE_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_colony)), - "BREAKTRUCE_MILITANCY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_add_to_sphere)), - "BREAKTRUCE_MILITANCY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_release_puppet)), - "BREAKTRUCE_MILITANCY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_make_puppet)), - "BREAKTRUCE_MILITANCY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_disarmament)), - "BREAKTRUCE_MILITANCY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_forts)), - "BREAKTRUCE_MILITANCY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_naval_bases)), - "BREAKTRUCE_MILITANCY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_reparations)), - "BREAKTRUCE_MILITANCY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_transfer_provinces)), - "BREAKTRUCE_MILITANCY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_remove_cores)), - "BREAKTRUCE_MILITANCY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_prestige)), - "BREAKTRUCE_MILITANCY_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_concede)), - "BREAKTRUCE_MILITANCY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_status_quo)), - "BREAKTRUCE_MILITANCY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_annex)), - "BREAKTRUCE_MILITANCY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_demand_state)), - "BREAKTRUCE_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_install_communist_gov_type)), - "BREAKTRUCE_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_uninstall_communist_gov_type)), - "BREAKTRUCE_MILITANCY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_militancy_colony)), - "GOODRELATION_INFAMY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_add_to_sphere)), - "GOODRELATION_INFAMY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_release_puppet)), - "GOODRELATION_INFAMY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_make_puppet)), - "GOODRELATION_INFAMY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_disarmament)), - "GOODRELATION_INFAMY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_forts)), - "GOODRELATION_INFAMY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_naval_bases)), - "GOODRELATION_INFAMY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_reparations)), - "GOODRELATION_INFAMY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_transfer_provinces)), - "GOODRELATION_INFAMY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_remove_cores)), - "GOODRELATION_INFAMY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_prestige)), - "GOODRELATION_INFAMY_CONCEDE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_concede)), - "GOODRELATION_INFAMY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_status_quo)), - "GOODRELATION_INFAMY_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_annex)), - "GOODRELATION_INFAMY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_demand_state)), - "GOODRELATION_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_install_communist_gov_type)), - "GOODRELATION_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_uninstall_communist_gov_type)), - "GOODRELATION_INFAMY_COLONY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_colony)), - "GOODRELATION_PRESTIGE_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_add_to_sphere)), - "GOODRELATION_PRESTIGE_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_release_puppet)), - "GOODRELATION_PRESTIGE_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_make_puppet)), - "GOODRELATION_PRESTIGE_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_disarmament)), - "GOODRELATION_PRESTIGE_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_forts)), - "GOODRELATION_PRESTIGE_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_naval_bases)), - "GOODRELATION_PRESTIGE_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_reparations)), - "GOODRELATION_PRESTIGE_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_transfer_provinces)), - "GOODRELATION_PRESTIGE_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_remove_cores)), - "GOODRELATION_PRESTIGE_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_prestige)), - "GOODRELATION_PRESTIGE_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_concede)), - "GOODRELATION_PRESTIGE_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_status_quo)), - "GOODRELATION_PRESTIGE_ANNEX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_prestige_annex)), - "GOODRELATION_PRESTIGE_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_demand_state)), - "GOODRELATION_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_install_communist_gov_type)), - "GOODRELATION_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_uninstall_communist_gov_type)), - "GOODRELATION_PRESTIGE_COLONY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_colony)), - "GOODRELATION_MILITANCY_ADD_TO_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_add_to_sphere)), - "GOODRELATION_MILITANCY_RELEASE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_release_puppet)), - "GOODRELATION_MILITANCY_MAKE_PUPPET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_make_puppet)), - "GOODRELATION_MILITANCY_DISARMAMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_disarmament)), - "GOODRELATION_MILITANCY_DESTROY_FORTS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_forts)), - "GOODRELATION_MILITANCY_DESTROY_NAVAL_BASES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_naval_bases)), - "GOODRELATION_MILITANCY_REPARATIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_reparations)), - "GOODRELATION_MILITANCY_TRANSFER_PROVINCES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_transfer_provinces)), - "GOODRELATION_MILITANCY_REMOVE_CORES", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_remove_cores)), - "GOODRELATION_MILITANCY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_prestige)), - "GOODRELATION_MILITANCY_CONCEDE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_concede)), - "GOODRELATION_MILITANCY_STATUS_QUO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_status_quo)), - "GOODRELATION_MILITANCY_ANNEX", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_annex)), - "GOODRELATION_MILITANCY_DEMAND_STATE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_demand_state)), - "GOODRELATION_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_install_communist_gov_type)), - "GOODRELATION_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_uninstall_communist_gov_type)), - "GOODRELATION_MILITANCY_COLONY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_colony)) + key_map, + "PEACE_COST_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_add_to_sphere)), + "PEACE_COST_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_release_puppet)), + "PEACE_COST_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_make_puppet)), + "PEACE_COST_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_disarmament)), + "PEACE_COST_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_destroy_forts)), + "PEACE_COST_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_destroy_naval_bases)), + "PEACE_COST_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_reparations)), + "PEACE_COST_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_transfer_provinces)), + "PEACE_COST_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_remove_cores)), + "PEACE_COST_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_prestige)), + "PEACE_COST_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_concede)), + "PEACE_COST_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_status_quo)), + "PEACE_COST_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_annex)), + "PEACE_COST_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_demand_state)), + "PEACE_COST_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_install_communist_gov_type)), + "PEACE_COST_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_uninstall_communist_gov_type)), + "PEACE_COST_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_colony)), + "INFAMY_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_add_to_sphere)), + "INFAMY_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_release_puppet)), + "INFAMY_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_make_puppet)), + "INFAMY_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_disarmament)), + "INFAMY_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_destroy_forts)), + "INFAMY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_destroy_naval_bases)), + "INFAMY_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_reparations)), + "INFAMY_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_transfer_provinces)), + "INFAMY_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_remove_cores)), + "INFAMY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_prestige)), + "INFAMY_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_concede)), + "INFAMY_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_status_quo)), + "INFAMY_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_annex)), + "INFAMY_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_demand_state)), + "INFAMY_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_install_communist_gov_type)), + "INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_uninstall_communist_gov_type)), + "INFAMY_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_colony)), + "PRESTIGE_ADD_TO_SPHERE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_add_to_sphere_base)), + "PRESTIGE_RELEASE_PUPPET_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_release_puppet_base)), + "PRESTIGE_MAKE_PUPPET_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_make_puppet_base)), + "PRESTIGE_DISARMAMENT_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_disarmament_base)), + "PRESTIGE_DESTROY_FORTS_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_forts_base)), + "PRESTIGE_DESTROY_NAVAL_BASES_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases_base)), + "PRESTIGE_REPARATIONS_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reparations_base)), + "PRESTIGE_TRANSFER_PROVINCES_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_transfer_provinces_base)), + "PRESTIGE_REMOVE_CORES_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_remove_cores_base)), + "PRESTIGE_PRESTIGE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_prestige_base)), + "PRESTIGE_CONCEDE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_concede_base)), + "PRESTIGE_STATUS_QUO_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_status_quo_base)), + "PRESTIGE_ANNEX_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_annex_base)), + "PRESTIGE_DEMAND_STATE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_demand_state_base)), + "PRESTIGE_CLEAR_UNION_SPHERE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere_base)), + "PRESTIGE_GUNBOAT_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_gunboat_base)), + "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type_base)), + "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type_base)), + "PRESTIGE_COLONY_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_colony_base)), + "PRESTIGE_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_add_to_sphere)), + "PRESTIGE_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_release_puppet)), + "PRESTIGE_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_make_puppet)), + "PRESTIGE_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_disarmament)), + "PRESTIGE_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_forts)), + "PRESTIGE_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_destroy_naval_bases)), + "PRESTIGE_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reparations)), + "PRESTIGE_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_transfer_provinces)), + "PRESTIGE_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_remove_cores)), + "PRESTIGE_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_prestige)), + "PRESTIGE_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_concede)), + "PRESTIGE_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_status_quo)), + "PRESTIGE_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_annex)), + "PRESTIGE_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_demand_state)), + "PRESTIGE_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_clear_union_sphere)), + "PRESTIGE_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_gunboat)), + "PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_install_communist_gov_type)), + "PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_uninstall_communist_gov_type)), + "PRESTIGE_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_colony)), + "BREAKTRUCE_INFAMY_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_add_to_sphere)), + "BREAKTRUCE_INFAMY_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_release_puppet)), + "BREAKTRUCE_INFAMY_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_make_puppet)), + "BREAKTRUCE_INFAMY_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_disarmament)), + "BREAKTRUCE_INFAMY_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_forts)), + "BREAKTRUCE_INFAMY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_destroy_naval_bases)), + "BREAKTRUCE_INFAMY_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_reparations)), + "BREAKTRUCE_INFAMY_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_transfer_provinces)), + "BREAKTRUCE_INFAMY_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_remove_cores)), + "BREAKTRUCE_INFAMY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_prestige)), + "BREAKTRUCE_INFAMY_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_concede)), + "BREAKTRUCE_INFAMY_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_status_quo)), + "BREAKTRUCE_INFAMY_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_annex)), + "BREAKTRUCE_INFAMY_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_demand_state)), + "BREAKTRUCE_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_install_communist_gov_type)), + "BREAKTRUCE_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_uninstall_communist_gov_type)), + "BREAKTRUCE_INFAMY_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_colony)), + "BREAKTRUCE_PRESTIGE_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_add_to_sphere)), + "BREAKTRUCE_PRESTIGE_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_release_puppet)), + "BREAKTRUCE_PRESTIGE_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_make_puppet)), + "BREAKTRUCE_PRESTIGE_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_disarmament)), + "BREAKTRUCE_PRESTIGE_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_forts)), + "BREAKTRUCE_PRESTIGE_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_destroy_naval_bases)), + "BREAKTRUCE_PRESTIGE_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_reparations)), + "BREAKTRUCE_PRESTIGE_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_transfer_provinces)), + "BREAKTRUCE_PRESTIGE_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_remove_cores)), + "BREAKTRUCE_PRESTIGE_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_prestige)), + "BREAKTRUCE_PRESTIGE_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_concede)), + "BREAKTRUCE_PRESTIGE_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_status_quo)), + "BREAKTRUCE_PRESTIGE_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_annex)), + "BREAKTRUCE_PRESTIGE_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_demand_state)), + "BREAKTRUCE_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_install_communist_gov_type)), + "BREAKTRUCE_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_uninstall_communist_gov_type)), + "BREAKTRUCE_PRESTIGE_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_colony)), + "BREAKTRUCE_MILITANCY_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_add_to_sphere)), + "BREAKTRUCE_MILITANCY_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_release_puppet)), + "BREAKTRUCE_MILITANCY_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_make_puppet)), + "BREAKTRUCE_MILITANCY_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_disarmament)), + "BREAKTRUCE_MILITANCY_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_forts)), + "BREAKTRUCE_MILITANCY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_destroy_naval_bases)), + "BREAKTRUCE_MILITANCY_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_reparations)), + "BREAKTRUCE_MILITANCY_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_transfer_provinces)), + "BREAKTRUCE_MILITANCY_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_remove_cores)), + "BREAKTRUCE_MILITANCY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_prestige)), + "BREAKTRUCE_MILITANCY_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_concede)), + "BREAKTRUCE_MILITANCY_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_status_quo)), + "BREAKTRUCE_MILITANCY_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_annex)), + "BREAKTRUCE_MILITANCY_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_demand_state)), + "BREAKTRUCE_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_install_communist_gov_type)), + "BREAKTRUCE_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_uninstall_communist_gov_type)), + "BREAKTRUCE_MILITANCY_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_colony)), + "GOODRELATION_INFAMY_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_add_to_sphere)), + "GOODRELATION_INFAMY_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_release_puppet)), + "GOODRELATION_INFAMY_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_make_puppet)), + "GOODRELATION_INFAMY_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_disarmament)), + "GOODRELATION_INFAMY_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_forts)), + "GOODRELATION_INFAMY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_destroy_naval_bases)), + "GOODRELATION_INFAMY_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_reparations)), + "GOODRELATION_INFAMY_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_transfer_provinces)), + "GOODRELATION_INFAMY_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_remove_cores)), + "GOODRELATION_INFAMY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_prestige)), + "GOODRELATION_INFAMY_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_concede)), + "GOODRELATION_INFAMY_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_status_quo)), + "GOODRELATION_INFAMY_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_annex)), + "GOODRELATION_INFAMY_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_demand_state)), + "GOODRELATION_INFAMY_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_install_communist_gov_type)), + "GOODRELATION_INFAMY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_uninstall_communist_gov_type)), + "GOODRELATION_INFAMY_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_colony)), + "GOODRELATION_PRESTIGE_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_add_to_sphere)), + "GOODRELATION_PRESTIGE_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_release_puppet)), + "GOODRELATION_PRESTIGE_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_make_puppet)), + "GOODRELATION_PRESTIGE_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_disarmament)), + "GOODRELATION_PRESTIGE_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_forts)), + "GOODRELATION_PRESTIGE_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_destroy_naval_bases)), + "GOODRELATION_PRESTIGE_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_reparations)), + "GOODRELATION_PRESTIGE_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_transfer_provinces)), + "GOODRELATION_PRESTIGE_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_remove_cores)), + "GOODRELATION_PRESTIGE_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_prestige)), + "GOODRELATION_PRESTIGE_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_concede)), + "GOODRELATION_PRESTIGE_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_status_quo)), + "GOODRELATION_PRESTIGE_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_annex)), + "GOODRELATION_PRESTIGE_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_demand_state)), + "GOODRELATION_PRESTIGE_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_install_communist_gov_type)), + "GOODRELATION_PRESTIGE_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_uninstall_communist_gov_type)), + "GOODRELATION_PRESTIGE_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_colony)), + "GOODRELATION_MILITANCY_ADD_TO_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_add_to_sphere)), + "GOODRELATION_MILITANCY_RELEASE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_release_puppet)), + "GOODRELATION_MILITANCY_MAKE_PUPPET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_make_puppet)), + "GOODRELATION_MILITANCY_DISARMAMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_disarmament)), + "GOODRELATION_MILITANCY_DESTROY_FORTS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_forts)), + "GOODRELATION_MILITANCY_DESTROY_NAVAL_BASES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_destroy_naval_bases)), + "GOODRELATION_MILITANCY_REPARATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_reparations)), + "GOODRELATION_MILITANCY_TRANSFER_PROVINCES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_transfer_provinces)), + "GOODRELATION_MILITANCY_REMOVE_CORES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_remove_cores)), + "GOODRELATION_MILITANCY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_prestige)), + "GOODRELATION_MILITANCY_CONCEDE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_concede)), + "GOODRELATION_MILITANCY_STATUS_QUO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_status_quo)), + "GOODRELATION_MILITANCY_ANNEX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_annex)), + "GOODRELATION_MILITANCY_DEMAND_STATE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_demand_state)), + "GOODRELATION_MILITANCY_INSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_install_communist_gov_type)), + "GOODRELATION_MILITANCY_UNINSTALL_COMMUNIST_GOV_TYPE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_uninstall_communist_gov_type)), + "GOODRELATION_MILITANCY_COLONY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_colony)) ); add_key_map_entries( - key_map, - "WAR_PRESTIGE_COST_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_base)), - "WAR_PRESTIGE_COST_HIGH_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_high_prestige)), - "WAR_PRESTIGE_COST_NEG_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_neg_prestige)), - "WAR_PRESTIGE_COST_TRUCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_truce)), - "WAR_PRESTIGE_COST_HONOR_ALLIANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_alliance)), - "WAR_PRESTIGE_COST_HONOR_GUARNATEE", ONE_EXACTLY, // paradox typo - expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_guarantee)), - "WAR_PRESTIGE_COST_UNCIVILIZED", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_prestige_cost_uncivilized)), - "WAR_PRESTIGE_COST_CORE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_prestige_cost_core)), - "WAR_FAILED_GOAL_MILITANCY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_militancy)), - "WAR_FAILED_GOAL_PRESTIGE_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(war_failed_goal_prestige_base)), - "WAR_FAILED_GOAL_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(war_failed_goal_prestige)), - "DISCREDIT_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(discredit_days)), - "DISCREDIT_INFLUENCE_COST_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_influence_cost_factor)), - "DISCREDIT_INFLUENCE_GAIN_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_influence_gain_factor)), - "BANEMBASSY_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(banembassy_days)), - "DECLAREWAR_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(declarewar_relation_on_accept)), - "DECLAREWAR_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(declarewar_diplomatic_cost)), - "ADDWARGOAL_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(addwargoal_relation_on_accept)), - "ADDWARGOAL_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(addwargoal_diplomatic_cost)), - "ADD_UNJUSTIFIED_GOAL_BADBOY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(add_unjustified_goal_badboy)), - "PEACE_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_relation_on_accept)), - "PEACE_RELATION_ON_DECLINE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_relation_on_decline)), - "PEACE_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_diplomatic_cost)), - "ALLIANCE_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(alliance_relation_on_accept)), - "ALLIANCE_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(alliance_relation_on_decline)), - "ALLIANCE_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(alliance_diplomatic_cost)), - "CANCELALLIANCE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelalliance_relation_on_accept)), - "CANCELALLIANCE_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelalliance_diplomatic_cost)), - "CALLALLY_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_relation_on_accept)), - "CALLALLY_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(callally_relation_on_decline)), - "CALLALLY_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(callally_diplomatic_cost)), - "ASKMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_accept)), - "ASKMILACCESS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_decline)), - "ASKMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(askmilaccess_diplomatic_cost)), - "CANCELASKMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelaskmilaccess_relation_on_accept)), - "CANCELASKMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelaskmilaccess_diplomatic_cost)), - "GIVEMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_accept)), - "GIVEMILACCESS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_decline)), - "GIVEMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(givemilaccess_diplomatic_cost)), - "CANCELGIVEMILACCESS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelgivemilaccess_relation_on_accept)), - "CANCELGIVEMILACCESS_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelgivemilaccess_diplomatic_cost)), - "WARSUBSIDY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(warsubsidy_relation_on_accept)), - "WARSUBSIDY_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidy_diplomatic_cost)), - "CANCELWARSUBSIDY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelwarsubsidy_relation_on_accept)), - "CANCELWARSUBSIDY_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cancelwarsubsidy_diplomatic_cost)), - "DISCREDIT_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(discredit_relation_on_accept)), - "DISCREDIT_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(discredit_influence_cost)), - "EXPELADVISORS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(expeladvisors_relation_on_accept)), - "EXPELADVISORS_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(expeladvisors_influence_cost)), - "CEASECOLONIZATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_accept)), - "CEASECOLONIZATION_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_decline)), - "CEASECOLONIZATION_DIPLOMATIC_COST", ONE_OR_MORE, // Appears twice in vanilla! - expect_fixed_point(assign_variable_callback(ceasecolonization_diplomatic_cost)), - "BANEMBASSY_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(banembassy_relation_on_accept)), - "BANEMBASSY_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(banembassy_influence_cost)), - "INCREASERELATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_relation_on_accept)), - "INCREASERELATION_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_relation_on_decline)), - "INCREASERELATION_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaserelation_diplomatic_cost)), - "DECREASERELATION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaserelation_relation_on_accept)), - "DECREASERELATION_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaserelation_diplomatic_cost)), - "ADDTOSPHERE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(addtosphere_relation_on_accept)), - "ADDTOSPHERE_INFLUENCE_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(addtosphere_influence_cost)), - "REMOVEFROMSPHERE_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_relation_on_accept)), - "REMOVEFROMSPHERE_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_influence_cost)), - "REMOVEFROMSPHERE_PRESTIGE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_prestige_cost)), - "REMOVEFROMSPHERE_INFAMY_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(removefromsphere_infamy_cost)), - "INCREASEOPINION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaseopinion_relation_on_accept)), - "INCREASEOPINION_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(increaseopinion_influence_cost)), - "DECREASEOPINION_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaseopinion_relation_on_accept)), - "DECREASEOPINION_INFLUENCE_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(decreaseopinion_influence_cost)), - "MAKE_CB_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_diplomatic_cost)), - "MAKE_CB_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_relation_on_accept)), - "DISARMAMENT_ARMY_HIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(disarmed_penalty)), - "REPARATIONS_TAX_HIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reparations_tax_hit)), - "PRESTIGE_REDUCTION_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reduction_base)), - "PRESTIGE_REDUCTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(prestige_reduction)), - "REPARATIONS_YEARS", ONE_EXACTLY, expect_years(assign_variable_callback(reparations_duration)), - "MIN_WARSCORE_TO_INTERVENE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_warscore_to_intervene)), - "MIN_MONTHS_TO_INTERVENE", ONE_EXACTLY, expect_months(assign_variable_callback(min_time_to_intervene)), - "MAX_WARSCORE_FROM_BATTLES", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_warscore_from_battles)), - "GUNBOAT_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_diplomatic_cost)), - "GUNBOAT_RELATION_ON_ACCEPT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_relation_on_accept)), - "WARGOAL_JINGOISM_REQUIREMENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(wargoal_jingoism_requirement)), - "LIBERATE_STATE_RELATION_INCREASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(liberate_state_relation_increase)), - "DISHONORED_CALLALLY_PRESTIGE_PENALTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(dishonored_callally_prestige_penalty)), - "BASE_TRUCE_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(base_truce_duration)), - "MAX_INFLUENCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_influence)), - "WARSUBSIDIES_PERCENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(warsubsidies_percent)), - "NEIGHBOUR_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(neighbour_bonus_influence_percent)), - "SPHERE_NEIGHBOUR_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(sphere_neighbour_bonus_influence_percent)), - "OTHER_CONTINENT_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(other_continent_bonus_influence_percent)), - "PUPPET_BONUS_INFLUENCE_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(puppet_bonus_influence_percent)), - "RELEASE_NATION_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_prestige)), - "RELEASE_NATION_INFAMY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(release_nation_infamy)), - "INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_clear_union_sphere)), - "BREAKTRUCE_INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_infamy_clear_union_sphere)), - "BREAKTRUCE_PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_prestige_clear_union_sphere)), - "BREAKTRUCE_MILITANCY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_clear_union_sphere)), - "GOODRELATION_INFAMY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_infamy_clear_union_sphere)), - "GOODRELATION_PRESTIGE_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_clear_union_sphere)), - "GOODRELATION_MILITANCY_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_clear_union_sphere)), - "PEACE_COST_CLEAR_UNION_SPHERE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(peace_cost_clear_union_sphere)), - "GOOD_PEACE_REFUSAL_MILITANCY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(good_peace_refusal_militancy)), - "GOOD_PEACE_REFUSAL_WAREXH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(good_peace_refusal_warexh)), - "PEACE_COST_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(peace_cost_gunboat)), - "INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(infamy_gunboat)), - "BREAKTRUCE_INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_infamy_gunboat)), - "BREAKTRUCE_PRESTIGE_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(breaktruce_prestige_gunboat)), - "BREAKTRUCE_MILITANCY_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(breaktruce_militancy_gunboat)), - "GOODRELATION_INFAMY_GUNBOAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goodrelation_infamy_gunboat)), - "GOODRELATION_PRESTIGE_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_prestige_gunboat)), - "GOODRELATION_MILITANCY_GUNBOAT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(goodrelation_militancy_gunboat)), - "CB_GENERATION_BASE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cb_generation_base_speed)), - "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition)), - "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION_TROOPS_PRESENCE", ONE_EXACTLY, expect_fixed_point( - assign_variable_callback(cb_generation_speed_bonus_on_colony_competition_troops_presence) - ), - "MAKE_CB_RELATION_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(make_cb_relation_limit)), - "CB_DETECTION_CHANCE_BASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(cb_detection_chance_base)), - "INVESTMENT_INFLUENCE_DEFENSE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(investment_influence_defense)), - "RELATION_INFLUENCE_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(relation_influence_modifier)), - "ON_CB_DETECTED_RELATION_CHANGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(on_cb_detected_relation_change)), - "GW_INTERVENE_MIN_RELATIONS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_intervene_min_relations)), - "GW_INTERVENE_MAX_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_intervene_max_exhaustion)), - "GW_JUSTIFY_CB_BADBOY_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_justify_cb_badboy_impact)), - "GW_CB_CONSTRUCTION_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_cb_construction_speed)), - "GW_WARGOAL_JINGOISM_REQUIREMENT_MOD", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(gw_wargoal_jingoism_requirement_mod)), - "GW_WARSCORE_COST_MOD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod)), - "GW_WARSCORE_COST_MOD_2", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod_2)), - "GW_WARSCORE_2_THRESHOLD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gw_warscore_2_threshold)), - "TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_decay)), - "TENSION_FROM_CB", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_cb)), - "TENSION_FROM_MOVEMENT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_movement)), - "TENSION_FROM_MOVEMENT_MAX", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_from_movement_max)), - "AT_WAR_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(at_war_tension_decay)), - "TENSION_ON_CB_DISCOVERED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_on_cb_discovered)), - "TENSION_ON_REVOLT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_on_revolt)), - "TENSION_WHILE_CRISIS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tension_while_crisis)), - "CRISIS_COOLDOWN_MONTHS", ONE_EXACTLY, expect_months(assign_variable_callback(crisis_cooldown_duration)), - "CRISIS_BASE_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_base_chance)), - "CRISIS_TEMPERATURE_INCREASE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_temperature_increase)), - "CRISIS_OFFER_DIPLOMATIC_COST", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_diplomatic_cost)), - "CRISIS_OFFER_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_accept)), - "CRISIS_OFFER_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_decline)), - "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_base)), - "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_YEAR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_year)), - "CRISIS_WINNER_PRESTIGE_FACTOR_BASE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_base)), - "CRISIS_WINNER_PRESTIGE_FACTOR_YEAR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_year)), - "CRISIS_WINNER_RELATIONS_IMPACT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_winner_relations_impact)), - "BACK_CRISIS_DIPLOMATIC_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(back_crisis_diplomatic_cost)), - "BACK_CRISIS_RELATION_ON_ACCEPT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(back_crisis_relation_on_accept)), - "BACK_CRISIS_RELATION_ON_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(back_crisis_relation_on_decline)), - "CRISIS_TEMPERATURE_ON_OFFER_DECLINE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_on_offer_decline)), - "CRISIS_TEMPERATURE_PARTICIPANT_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_participant_factor)), - "CRISIS_TEMPERATURE_ON_MOBILIZE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_temperature_on_mobilize)), - "CRISIS_WARGOAL_INFAMY_MULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(crisis_wargoal_infamy_mult)), - "CRISIS_WARGOAL_PRESTIGE_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_wargoal_prestige_mult)), - "CRISIS_WARGOAL_MILITANCY_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_wargoal_militancy_mult)), - "CRISIS_INTEREST_WAR_EXHAUSTION_LIMIT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(crisis_interest_war_exhaustion_limit)), - "RANK_1_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_1_tension_decay)), - "RANK_2_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_2_tension_decay)), - "RANK_3_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_3_tension_decay)), - "RANK_4_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_4_tension_decay)), - "RANK_5_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_5_tension_decay)), - "RANK_6_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_6_tension_decay)), - "RANK_7_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_7_tension_decay)), - "RANK_8_TENSION_DECAY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(rank_8_tension_decay)), - "TWS_FULFILLED_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_fulfilled_speed)), - "TWS_NOT_FULFILLED_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_not_fulfilled_speed)), - "TWS_GRACE_PERIOD_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(tws_grace_period_days)), - "TWS_CB_LIMIT_DEFAULT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_cb_limit_default)), - "TWS_FULFILLED_IDLE_SPACE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_fulfilled_idle_space)), - "TWS_BATTLE_MIN_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(tws_battle_min_count)), - "TWS_BATTLE_MAX_ASPECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(tws_battle_max_aspect)), - "LARGE_POPULATION_INFLUENCE_PENALTY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(large_population_influence_penalty)), - "LONE_BACKER_PRESTIGE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(lone_backer_prestige_factor)) + key_map, + "WAR_PRESTIGE_COST_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_base)), + "WAR_PRESTIGE_COST_HIGH_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_high_prestige)), + "WAR_PRESTIGE_COST_NEG_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_neg_prestige)), + "WAR_PRESTIGE_COST_TRUCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_truce)), + "WAR_PRESTIGE_COST_HONOR_ALLIANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_alliance)), + "WAR_PRESTIGE_COST_HONOR_GUARANTEE", + ONE_EXACTLY, // paradox typo + expect_fixed_point(assign_variable_callback(war_prestige_cost_honor_guarantee)), + "WAR_PRESTIGE_COST_UNCIVILIZED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_uncivilized)), + "WAR_PRESTIGE_COST_CORE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_prestige_cost_core)), + "WAR_FAILED_GOAL_MILITANCY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_failed_goal_militancy)), + "WAR_FAILED_GOAL_PRESTIGE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_failed_goal_prestige_base)), + "WAR_FAILED_GOAL_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(war_failed_goal_prestige)), + "DISCREDIT_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(discredit_days)), + "DISCREDIT_INFLUENCE_COST_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(discredit_influence_cost_factor)), + "DISCREDIT_INFLUENCE_GAIN_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(discredit_influence_gain_factor)), + "BANEMBASSY_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(banembassy_days)), + "DECLAREWAR_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(declarewar_relation_on_accept)), + "DECLAREWAR_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(declarewar_diplomatic_cost)), + "ADDWARGOAL_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addwargoal_relation_on_accept)), + "ADDWARGOAL_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addwargoal_diplomatic_cost)), + "ADD_UNJUSTIFIED_GOAL_BADBOY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(add_unjustified_goal_badboy)), + "PEACE_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_relation_on_accept)), + "PEACE_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_relation_on_decline)), + "PEACE_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_diplomatic_cost)), + "ALLIANCE_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_relation_on_accept)), + "ALLIANCE_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_relation_on_decline)), + "ALLIANCE_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(alliance_diplomatic_cost)), + "CANCELALLIANCE_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelalliance_relation_on_accept)), + "CANCELALLIANCE_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelalliance_diplomatic_cost)), + "CALLALLY_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(callally_relation_on_accept)), + "CALLALLY_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(callally_relation_on_decline)), + "CALLALLY_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(callally_diplomatic_cost)), + "ASKMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_accept)), + "ASKMILACCESS_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(askmilaccess_relation_on_decline)), + "ASKMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(askmilaccess_diplomatic_cost)), + "CANCELASKMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelaskmilaccess_relation_on_accept)), + "CANCELASKMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelaskmilaccess_diplomatic_cost)), + "GIVEMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_accept)), + "GIVEMILACCESS_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(givemilaccess_relation_on_decline)), + "GIVEMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(givemilaccess_diplomatic_cost)), + "CANCELGIVEMILACCESS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelgivemilaccess_relation_on_accept)), + "CANCELGIVEMILACCESS_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelgivemilaccess_diplomatic_cost)), + "WARSUBSIDY_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(warsubsidy_relation_on_accept)), + "WARSUBSIDY_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(warsubsidy_diplomatic_cost)), + "CANCELWARSUBSIDY_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelwarsubsidy_relation_on_accept)), + "CANCELWARSUBSIDY_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cancelwarsubsidy_diplomatic_cost)), + "DISCREDIT_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(discredit_relation_on_accept)), + "DISCREDIT_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(discredit_influence_cost)), + "EXPELADVISORS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(expeladvisors_relation_on_accept)), + "EXPELADVISORS_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(expeladvisors_influence_cost)), + "CEASECOLONIZATION_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_accept)), + "CEASECOLONIZATION_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ceasecolonization_relation_on_decline)), + "CEASECOLONIZATION_DIPLOMATIC_COST", + ONE_OR_MORE, // Appears twice in vanilla! + expect_fixed_point(assign_variable_callback(ceasecolonization_diplomatic_cost)), + "BANEMBASSY_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(banembassy_relation_on_accept)), + "BANEMBASSY_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(banembassy_influence_cost)), + "INCREASERELATION_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(increaserelation_relation_on_accept)), + "INCREASERELATION_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(increaserelation_relation_on_decline)), + "INCREASERELATION_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(increaserelation_diplomatic_cost)), + "DECREASERELATION_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(decreaserelation_relation_on_accept)), + "DECREASERELATION_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(decreaserelation_diplomatic_cost)), + "ADDTOSPHERE_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addtosphere_relation_on_accept)), + "ADDTOSPHERE_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(addtosphere_influence_cost)), + "REMOVEFROMSPHERE_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(removefromsphere_relation_on_accept)), + "REMOVEFROMSPHERE_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(removefromsphere_influence_cost)), + "REMOVEFROMSPHERE_PRESTIGE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(removefromsphere_prestige_cost)), + "REMOVEFROMSPHERE_INFAMY_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(removefromsphere_infamy_cost)), + "INCREASEOPINION_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(increaseopinion_relation_on_accept)), + "INCREASEOPINION_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(increaseopinion_influence_cost)), + "DECREASEOPINION_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(decreaseopinion_relation_on_accept)), + "DECREASEOPINION_INFLUENCE_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(decreaseopinion_influence_cost)), + "MAKE_CB_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(make_cb_diplomatic_cost)), + "MAKE_CB_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(make_cb_relation_on_accept)), + "DISARMAMENT_ARMY_HIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(disarmed_penalty)), + "REPARATIONS_TAX_HIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reparations_tax_hit)), + "PRESTIGE_REDUCTION_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reduction_base)), + "PRESTIGE_REDUCTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(prestige_reduction)), + "REPARATIONS_YEARS", + ONE_EXACTLY, + expect_years(assign_variable_callback(reparations_duration)), + "MIN_WARSCORE_TO_INTERVENE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(min_warscore_to_intervene)), + "MIN_MONTHS_TO_INTERVENE", + ONE_EXACTLY, + expect_months(assign_variable_callback(min_time_to_intervene)), + "MAX_WARSCORE_FROM_BATTLES", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_warscore_from_battles)), + "GUNBOAT_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_diplomatic_cost)), + "GUNBOAT_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_relation_on_accept)), + "WARGOAL_JINGOISM_REQUIREMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(wargoal_jingoism_requirement)), + "LIBERATE_STATE_RELATION_INCREASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(liberate_state_relation_increase)), + "DISHONORED_CALLALLY_PRESTIGE_PENALTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(dishonored_callally_prestige_penalty)), + "BASE_TRUCE_MONTHS", + ONE_EXACTLY, + expect_months(assign_variable_callback(base_truce_duration)), + "MAX_INFLUENCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_influence)), + "WARSUBSIDIES_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(warsubsidies_percent)), + "NEIGHBOUR_BONUS_INFLUENCE_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(neighbour_bonus_influence_percent)), + "SPHERE_NEIGHBOUR_BONUS_INFLUENCE_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(sphere_neighbour_bonus_influence_percent)), + "OTHER_CONTINENT_BONUS_INFLUENCE_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(other_continent_bonus_influence_percent)), + "PUPPET_BONUS_INFLUENCE_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(puppet_bonus_influence_percent)), + "RELEASE_NATION_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(release_nation_prestige)), + "RELEASE_NATION_INFAMY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(release_nation_infamy)), + "INFAMY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_clear_union_sphere)), + "BREAKTRUCE_INFAMY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_clear_union_sphere)), + "BREAKTRUCE_PRESTIGE_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_clear_union_sphere)), + "BREAKTRUCE_MILITANCY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_clear_union_sphere)), + "GOODRELATION_INFAMY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_clear_union_sphere)), + "GOODRELATION_PRESTIGE_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_clear_union_sphere)), + "GOODRELATION_MILITANCY_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_clear_union_sphere)), + "PEACE_COST_CLEAR_UNION_SPHERE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_clear_union_sphere)), + "GOOD_PEACE_REFUSAL_MILITANCY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(good_peace_refusal_militancy)), + "GOOD_PEACE_REFUSAL_WAREXH", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(good_peace_refusal_warexh)), + "PEACE_COST_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(peace_cost_gunboat)), + "INFAMY_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(infamy_gunboat)), + "BREAKTRUCE_INFAMY_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_infamy_gunboat)), + "BREAKTRUCE_PRESTIGE_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_prestige_gunboat)), + "BREAKTRUCE_MILITANCY_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(breaktruce_militancy_gunboat)), + "GOODRELATION_INFAMY_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_infamy_gunboat)), + "GOODRELATION_PRESTIGE_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_prestige_gunboat)), + "GOODRELATION_MILITANCY_GUNBOAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goodrelation_militancy_gunboat)), + "CB_GENERATION_BASE_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cb_generation_base_speed)), + "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition)), + "CB_GENERATION_SPEED_BONUS_ON_COLONY_COMPETITION_TROOPS_PRESENCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cb_generation_speed_bonus_on_colony_competition_troops_presence)), + "MAKE_CB_RELATION_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(make_cb_relation_limit)), + "CB_DETECTION_CHANCE_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(cb_detection_chance_base)), + "INVESTMENT_INFLUENCE_DEFENSE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(investment_influence_defense)), + "RELATION_INFLUENCE_MODIFIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(relation_influence_modifier)), + "ON_CB_DETECTED_RELATION_CHANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(on_cb_detected_relation_change)), + "GW_INTERVENE_MIN_RELATIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_intervene_min_relations)), + "GW_INTERVENE_MAX_EXHAUSTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_intervene_max_exhaustion)), + "GW_JUSTIFY_CB_BADBOY_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_justify_cb_badboy_impact)), + "GW_CB_CONSTRUCTION_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_cb_construction_speed)), + "GW_WARGOAL_JINGOISM_REQUIREMENT_MOD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_wargoal_jingoism_requirement_mod)), + "GW_WARSCORE_COST_MOD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod)), + "GW_WARSCORE_COST_MOD_2", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_warscore_cost_mod_2)), + "GW_WARSCORE_2_THRESHOLD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gw_warscore_2_threshold)), + "TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_decay)), + "TENSION_FROM_CB", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_cb)), + "TENSION_FROM_MOVEMENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_movement)), + "TENSION_FROM_MOVEMENT_MAX", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_from_movement_max)), + "AT_WAR_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(at_war_tension_decay)), + "TENSION_ON_CB_DISCOVERED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_on_cb_discovered)), + "TENSION_ON_REVOLT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_on_revolt)), + "TENSION_WHILE_CRISIS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tension_while_crisis)), + "CRISIS_COOLDOWN_MONTHS", + ONE_EXACTLY, + expect_months(assign_variable_callback(crisis_cooldown_duration)), + "CRISIS_BASE_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_base_chance)), + "CRISIS_TEMPERATURE_INCREASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_temperature_increase)), + "CRISIS_OFFER_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_offer_diplomatic_cost)), + "CRISIS_OFFER_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_accept)), + "CRISIS_OFFER_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_offer_relation_on_decline)), + "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_base)), + "CRISIS_DID_NOT_TAKE_SIDE_PRESTIGE_FACTOR_YEAR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_did_not_take_side_prestige_factor_year)), + "CRISIS_WINNER_PRESTIGE_FACTOR_BASE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_base)), + "CRISIS_WINNER_PRESTIGE_FACTOR_YEAR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_winner_prestige_factor_year)), + "CRISIS_WINNER_RELATIONS_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_winner_relations_impact)), + "BACK_CRISIS_DIPLOMATIC_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(back_crisis_diplomatic_cost)), + "BACK_CRISIS_RELATION_ON_ACCEPT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(back_crisis_relation_on_accept)), + "BACK_CRISIS_RELATION_ON_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(back_crisis_relation_on_decline)), + "CRISIS_TEMPERATURE_ON_OFFER_DECLINE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_temperature_on_offer_decline)), + "CRISIS_TEMPERATURE_PARTICIPANT_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_temperature_participant_factor)), + "CRISIS_TEMPERATURE_ON_MOBILIZE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_temperature_on_mobilize)), + "CRISIS_WARGOAL_INFAMY_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_wargoal_infamy_mult)), + "CRISIS_WARGOAL_PRESTIGE_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_wargoal_prestige_mult)), + "CRISIS_WARGOAL_MILITANCY_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_wargoal_militancy_mult)), + "CRISIS_INTEREST_WAR_EXHAUSTION_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(crisis_interest_war_exhaustion_limit)), + "RANK_1_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_1_tension_decay)), + "RANK_2_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_2_tension_decay)), + "RANK_3_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_3_tension_decay)), + "RANK_4_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_4_tension_decay)), + "RANK_5_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_5_tension_decay)), + "RANK_6_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_6_tension_decay)), + "RANK_7_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_7_tension_decay)), + "RANK_8_TENSION_DECAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rank_8_tension_decay)), + "TWS_FULFILLED_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_fulfilled_speed)), + "TWS_NOT_FULFILLED_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_not_fulfilled_speed)), + "TWS_GRACE_PERIOD_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(tws_grace_period_days)), + "TWS_CB_LIMIT_DEFAULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_cb_limit_default)), + "TWS_FULFILLED_IDLE_SPACE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_fulfilled_idle_space)), + "TWS_BATTLE_MIN_COUNT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(tws_battle_min_count)), + "TWS_BATTLE_MAX_ASPECT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(tws_battle_max_aspect)), + "LARGE_POPULATION_INFLUENCE_PENALTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(large_population_influence_penalty)), + "LONE_BACKER_PRESTIGE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(lone_backer_prestige_factor)) ); return expect_dictionary_key_map(std::move(key_map)); diff --git a/src/openvic-simulation/defines/EconomyDefines.cpp b/src/openvic-simulation/defines/EconomyDefines.cpp index 0ae597d97..bfaed3c3f 100644 --- a/src/openvic-simulation/defines/EconomyDefines.cpp +++ b/src/openvic-simulation/defines/EconomyDefines.cpp @@ -11,52 +11,101 @@ std::string_view EconomyDefines::get_name() const { node_callback_t EconomyDefines::expect_defines() { return expect_dictionary_keys( - "MAX_DAILY_RESEARCH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_daily_research)), - "LOAN_BASE_INTEREST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(loan_base_interest)), - "BANKRUPTCY_EXTERNAL_LOAN_YEARS", ONE_EXACTLY, - expect_years(assign_variable_callback(bankruptcy_external_loan_duration)), - "BANKRUPTCY_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bankruptcy_factor)), - "SHADOWY_FINANCIERS_MAX_LOAN_AMOUNT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(shadowy_financiers_max_loan_amount)), - "MAX_LOAN_CAP_FROM_BANKS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_loan_cap_from_banks)), - "GUNBOAT_LOW_TAX_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_low_tax_cap)), - "GUNBOAT_HIGH_TAX_CAP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_high_tax_cap)), - "GUNBOAT_FLEET_SIZE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(gunboat_fleet_size_factor)), - "PROVINCE_SIZE_DIVIDER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(province_size_divider)), - "CAPITALIST_BUILD_FACTORY_STATE_EMPLOYMENT_PERCENT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(capitalist_build_factory_state_employment_percent)), - "GOODS_FOCUS_SWAP_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(goods_focus_swap_chance)), - "NUM_CLOSED_FACTORIES_PER_STATE_LASSIEZ_FAIRE", ONE_EXACTLY, - expect_uint(assign_variable_callback(num_closed_factories_per_state_lassiez_faire)), - "MIN_NUM_FACTORIES_PER_STATE_BEFORE_DELETING_LASSIEZ_FAIRE", ONE_EXACTLY, - expect_uint(assign_variable_callback(min_num_factories_per_state_before_deleting_lassiez_faire)), - "BANKRUPCY_DURATION", ONE_EXACTLY, expect_years(assign_variable_callback(bankruptcy_duration)), // paradox typo - "SECOND_RANK_BASE_SHARE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(second_rank_base_share_factor)), - "CIV_BASE_SHARE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(civ_base_share_factor)), - "UNCIV_BASE_SHARE_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unciv_base_share_factor)), - "FACTORY_PAYCHECKS_LEFTOVER_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_paychecks_leftover_factor)), - "MAX_FACTORY_MONEY_SAVE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_factory_money_save)), - "SMALL_DEBT_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(small_debt_limit)), - "FACTORY_UPGRADE_EMPLOYEE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_upgrade_employee_factor)), - "RGO_SUPPLY_DEMAND_FACTOR_HIRE_HI", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_hi)), - "RGO_SUPPLY_DEMAND_FACTOR_HIRE_LO", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_lo)), - "RGO_SUPPLY_DEMAND_FACTOR_FIRE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_fire)), - "EMPLOYMENT_HIRE_LOWEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(employment_hire_lowest)), - "EMPLOYMENT_FIRE_LOWEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(employment_fire_lowest)), - "TRADE_CAP_LOW_LIMIT_LAND", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_army_spending_slider_value)), - "TRADE_CAP_LOW_LIMIT_NAVAL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_navy_spending_slider_value)), - "TRADE_CAP_LOW_LIMIT_CONSTRUCTIONS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(minimum_construction_spending_slider_value)), - "FACTORY_PURCHASE_MIN_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(factory_purchase_min_factor)), - "FACTORY_PURCHASE_DRAWDOWN_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(factory_purchase_drawdown_factor)) + "MAX_DAILY_RESEARCH", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_daily_research)), + "LOAN_BASE_INTEREST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(loan_base_interest)), + "BANKRUPTCY_EXTERNAL_LOAN_YEARS", + ONE_EXACTLY, + expect_years(assign_variable_callback(bankruptcy_external_loan_duration)), + "BANKRUPTCY_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(bankruptcy_factor)), + "SHADOWY_FINANCIERS_MAX_LOAN_AMOUNT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(shadowy_financiers_max_loan_amount)), + "MAX_LOAN_CAP_FROM_BANKS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_loan_cap_from_banks)), + "GUNBOAT_LOW_TAX_CAP", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_low_tax_cap)), + "GUNBOAT_HIGH_TAX_CAP", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_high_tax_cap)), + "GUNBOAT_FLEET_SIZE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(gunboat_fleet_size_factor)), + "PROVINCE_SIZE_DIVIDER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(province_size_divider)), + "CAPITALIST_BUILD_FACTORY_STATE_EMPLOYMENT_PERCENT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(capitalist_build_factory_state_employment_percent)), + "GOODS_FOCUS_SWAP_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(goods_focus_swap_chance)), + "NUM_CLOSED_FACTORIES_PER_STATE_LASSIEZ_FAIRE", + ONE_EXACTLY, + expect_uint(assign_variable_callback(num_closed_factories_per_state_lassiez_faire)), + "MIN_NUM_FACTORIES_PER_STATE_BEFORE_DELETING_LASSIEZ_FAIRE", + ONE_EXACTLY, + expect_uint(assign_variable_callback(min_num_factories_per_state_before_deleting_lassiez_faire)), + "BANKRUPTCY_DURATION", + ONE_EXACTLY, + expect_years(assign_variable_callback(bankruptcy_duration)), // paradox typo + "SECOND_RANK_BASE_SHARE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(second_rank_base_share_factor)), + "CIV_BASE_SHARE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(civ_base_share_factor)), + "UNCIV_BASE_SHARE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unciv_base_share_factor)), + "FACTORY_PAYCHECKS_LEFTOVER_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(factory_paychecks_leftover_factor)), + "MAX_FACTORY_MONEY_SAVE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_factory_money_save)), + "SMALL_DEBT_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(small_debt_limit)), + "FACTORY_UPGRADE_EMPLOYEE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(factory_upgrade_employee_factor)), + "RGO_SUPPLY_DEMAND_FACTOR_HIRE_HI", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_hi)), + "RGO_SUPPLY_DEMAND_FACTOR_HIRE_LO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_hire_lo)), + "RGO_SUPPLY_DEMAND_FACTOR_FIRE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rgo_supply_demand_factor_fire)), + "EMPLOYMENT_HIRE_LOWEST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(employment_hire_lowest)), + "EMPLOYMENT_FIRE_LOWEST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(employment_fire_lowest)), + "TRADE_CAP_LOW_LIMIT_LAND", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(minimum_army_spending_slider_value)), + "TRADE_CAP_LOW_LIMIT_NAVAL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(minimum_navy_spending_slider_value)), + "TRADE_CAP_LOW_LIMIT_CONSTRUCTIONS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(minimum_construction_spending_slider_value)), + "FACTORY_PURCHASE_MIN_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(factory_purchase_min_factor)), + "FACTORY_PURCHASE_DRAWDOWN_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(factory_purchase_drawdown_factor)) ); } diff --git a/src/openvic-simulation/defines/GraphicsDefines.cpp b/src/openvic-simulation/defines/GraphicsDefines.cpp index adaf8dce0..f749b3474 100644 --- a/src/openvic-simulation/defines/GraphicsDefines.cpp +++ b/src/openvic-simulation/defines/GraphicsDefines.cpp @@ -11,20 +11,38 @@ std::string_view GraphicsDefines::get_name() const { node_callback_t GraphicsDefines::expect_defines() { return expect_dictionary_keys( - "CITIES_SPRAWL_OFFSET", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_offset)), - "CITIES_SPRAWL_WIDTH", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_width)), - "CITIES_SPRAWL_HEIGHT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_height)), - "CITIES_SPRAWL_ITERATIONS", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_sprawl_iterations)), - "CITIES_MESH_POOL_SIZE_FOR_COUNTRY", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_country)), - "CITIES_MESH_POOL_SIZE_FOR_CULTURE", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_culture)), - "CITIES_MESH_POOL_SIZE_FOR_GENERIC", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_mesh_pool_size_for_generic)), - "CITIES_MESH_TYPES_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_mesh_types_count)), - "CITIES_MESH_SIZES_COUNT", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_mesh_sizes_count)), - "CITIES_SPECIAL_BUILDINGS_POOL_SIZE", ONE_EXACTLY, - expect_uint(assign_variable_callback(cities_special_buildings_pool_size)), - "CITIES_SIZE_MAX_POPULATION_K", ONE_EXACTLY, expect_uint(assign_variable_callback(cities_size_max_population_k)) + "CITIES_SPRAWL_OFFSET", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_offset)), + "CITIES_SPRAWL_WIDTH", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_width)), + "CITIES_SPRAWL_HEIGHT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_height)), + "CITIES_SPRAWL_ITERATIONS", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_sprawl_iterations)), + "CITIES_MESH_POOL_SIZE_FOR_COUNTRY", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_pool_size_for_country)), + "CITIES_MESH_POOL_SIZE_FOR_CULTURE", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_pool_size_for_culture)), + "CITIES_MESH_POOL_SIZE_FOR_GENERIC", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_pool_size_for_generic)), + "CITIES_MESH_TYPES_COUNT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_types_count)), + "CITIES_MESH_SIZES_COUNT", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_mesh_sizes_count)), + "CITIES_SPECIAL_BUILDINGS_POOL_SIZE", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_special_buildings_pool_size)), + "CITIES_SIZE_MAX_POPULATION_K", + ONE_EXACTLY, + expect_uint(assign_variable_callback(cities_size_max_population_k)) ); } diff --git a/src/openvic-simulation/defines/MilitaryDefines.cpp b/src/openvic-simulation/defines/MilitaryDefines.cpp index 38037be25..29c886249 100644 --- a/src/openvic-simulation/defines/MilitaryDefines.cpp +++ b/src/openvic-simulation/defines/MilitaryDefines.cpp @@ -15,94 +15,197 @@ std::string_view MilitaryDefines::get_name() const { node_callback_t MilitaryDefines::expect_defines() { return expect_dictionary_keys( - "DIG_IN_INCREASE_EACH_DAYS", ONE_EXACTLY, expect_days(assign_variable_callback(dig_in_increase_each_days)), - "REINFORCE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reinforce_speed)), - "COMBAT_DIFFICULTY_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(combat_difficulty_impact)), - "BASE_COMBAT_WIDTH", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(base_combat_width)), - "POP_MIN_SIZE_FOR_REGIMENT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(min_pop_size_for_regiment)), - "POP_SIZE_PER_REGIMENT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(pop_size_per_regiment)), - "SOLDIER_TO_POP_DAMAGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(soldier_to_pop_damage)), - "LAND_SPEED_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(land_speed_modifier)), - "NAVAL_SPEED_MODIFIER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_speed_modifier)), - "EXP_GAIN_DIV", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(exp_gain_div)), - "LEADER_RECRUIT_COST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_recruit_cost)), - "SUPPLY_RANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(supply_range)), - "POP_MIN_SIZE_FOR_REGIMENT_PROTECTORATE_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_protectorate_multiplier)), - "POP_MIN_SIZE_FOR_REGIMENT_COLONY_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_colony_multiplier)), - "POP_MIN_SIZE_FOR_REGIMENT_NONCORE_MULTIPLIER", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(pop_size_per_regiment_non_core_multiplier)), - "GAS_ATTACK_MODIFIER", ONE_EXACTLY, expect_uint(assign_variable_callback(gas_attack_modifier)), - "COMBATLOSS_WAR_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(combatloss_war_exhaustion)), - "LEADER_MAX_RANDOM_PRESTIGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_max_random_prestige)), - "LEADER_AGE_DEATH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_age_death_factor)), - "LEADER_PRESTIGE_TO_MORALE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_prestige_to_morale_factor)), - "LEADER_PRESTIGE_TO_MAX_ORG_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_prestige_to_max_org_factor)), - "LEADER_TRANSFER_PENALTY_ON_COUNTRY_PRESTIGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(leader_transfer_penalty_on_country_prestige)), - "LEADER_PRESTIGE_LAND_GAIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_land_gain)), - "LEADER_PRESTIGE_NAVAL_GAIN", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(leader_prestige_naval_gain)), - "NAVAL_COMBAT_SEEKING_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance)), - "NAVAL_COMBAT_SEEKING_CHANCE_MIN", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance_min)), - "NAVAL_COMBAT_SELF_DEFENCE_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_self_defence_chance)), - "NAVAL_COMBAT_SHIFT_BACK_ON_NEXT_TARGET", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_shift_back_on_next_target)), - "NAVAL_COMBAT_SHIFT_BACK_DURATION_SCALE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_shift_back_duration_scale)), - "NAVAL_COMBAT_SPEED_TO_DISTANCE_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_speed_to_distance_factor)), - "NAVAL_COMBAT_CHANGE_TARGET_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_change_target_chance)), - "NAVAL_COMBAT_DAMAGE_ORG_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_org_mult)), - "NAVAL_COMBAT_DAMAGE_STR_MULT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_str_mult)), - "NAVAL_COMBAT_DAMAGE_MULT_NO_ORG", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damage_mult_no_org)), - "NAVAL_COMBAT_RETREAT_CHANCE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(naval_combat_retreat_chance)), - "NAVAL_COMBAT_RETREAT_STR_ORG_LEVEL", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_str_org_level)), - "NAVAL_COMBAT_RETREAT_SPEED_MOD", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_speed_mod)), - "NAVAL_COMBAT_RETREAT_MIN_DISTANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_retreat_min_distance)), - "NAVAL_COMBAT_DAMAGED_TARGET_SELECTION", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_damaged_target_selection)), - "NAVAL_COMBAT_STACKING_TARGET_CHANGE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_change)), - "NAVAL_COMBAT_STACKING_TARGET_SELECT", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_select)), - "NAVAL_COMBAT_MAX_TARGETS", ONE_EXACTLY, expect_uint(assign_variable_callback(naval_combat_max_targets)), - "AI_BIGSHIP_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_bigship_proportion)), - "AI_LIGHTSHIP_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_lightship_proportion)), - "AI_TRANSPORT_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_transport_proportion)), - "AI_CAVALRY_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_cavalry_proportion)), - "AI_SUPPORT_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_support_proportion)), - "AI_SPECIAL_PROPORTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_special_proportion)), - "AI_ESCORT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_escort_ratio)), - "AI_ARMY_TAXBASE_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_army_taxbase_fraction)), - "AI_NAVY_TAXBASE_FRACTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_navy_taxbase_fraction)), - "AI_BLOCKADE_RANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ai_blockade_range)), - "RECON_UNIT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(recon_unit_ratio)), - "ENGINEER_UNIT_RATIO", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(engineer_unit_ratio)), - "SIEGE_BRIGADES_MIN", ONE_EXACTLY, expect_uint(assign_variable_callback(siege_brigades_min)), - "SIEGE_BRIGADES_MAX", ONE_EXACTLY, expect_uint(assign_variable_callback(siege_brigades_max)), - "SIEGE_BRIGADES_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(siege_brigades_bonus)), - "RECON_SIEGE_EFFECT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(recon_siege_effect)), - "SIEGE_ATTRITION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(siege_attrition)), - "BASE_MILITARY_TACTICS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_military_tactics)), - "NAVAL_LOW_SUPPLY_DAMAGE_SUPPLY_STATUS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_supply_status)), - "NAVAL_LOW_SUPPLY_DAMAGE_DAYS_DELAY", ONE_EXACTLY, - expect_days(assign_variable_callback(naval_low_supply_damage_days_delay)), - "NAVAL_LOW_SUPPLY_DAMAGE_MIN_STR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_min_str)), - "NAVAL_LOW_SUPPLY_DAMAGE_PER_DAY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(naval_low_supply_damage_per_day)) + "DIG_IN_INCREASE_EACH_DAYS", + ONE_EXACTLY, + expect_days(assign_variable_callback(dig_in_increase_each_days)), + "REINFORCE_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reinforce_speed)), + "COMBAT_DIFFICULTY_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(combat_difficulty_impact)), + "BASE_COMBAT_WIDTH", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(base_combat_width)), + "POP_MIN_SIZE_FOR_REGIMENT", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(min_pop_size_for_regiment)), + "POP_SIZE_PER_REGIMENT", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(pop_size_per_regiment)), + "SOLDIER_TO_POP_DAMAGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(soldier_to_pop_damage)), + "LAND_SPEED_MODIFIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(land_speed_modifier)), + "NAVAL_SPEED_MODIFIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_speed_modifier)), + "EXP_GAIN_DIV", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(exp_gain_div)), + "LEADER_RECRUIT_COST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_recruit_cost)), + "SUPPLY_RANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(supply_range)), + "POP_MIN_SIZE_FOR_REGIMENT_PROTECTORATE_MULTIPLIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_size_per_regiment_protectorate_multiplier)), + "POP_MIN_SIZE_FOR_REGIMENT_COLONY_MULTIPLIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_size_per_regiment_colony_multiplier)), + "POP_MIN_SIZE_FOR_REGIMENT_NONCORE_MULTIPLIER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_size_per_regiment_non_core_multiplier)), + "GAS_ATTACK_MODIFIER", + ONE_EXACTLY, + expect_uint(assign_variable_callback(gas_attack_modifier)), + "COMBATLOSS_WAR_EXHAUSTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(combatloss_war_exhaustion)), + "LEADER_MAX_RANDOM_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_max_random_prestige)), + "LEADER_AGE_DEATH_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_age_death_factor)), + "LEADER_PRESTIGE_TO_MORALE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_prestige_to_morale_factor)), + "LEADER_PRESTIGE_TO_MAX_ORG_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_prestige_to_max_org_factor)), + "LEADER_TRANSFER_PENALTY_ON_COUNTRY_PRESTIGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_transfer_penalty_on_country_prestige)), + "LEADER_PRESTIGE_LAND_GAIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_prestige_land_gain)), + "LEADER_PRESTIGE_NAVAL_GAIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(leader_prestige_naval_gain)), + "NAVAL_COMBAT_SEEKING_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance)), + "NAVAL_COMBAT_SEEKING_CHANCE_MIN", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_seeking_chance_min)), + "NAVAL_COMBAT_SELF_DEFENCE_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_self_defence_chance)), + "NAVAL_COMBAT_SHIFT_BACK_ON_NEXT_TARGET", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_shift_back_on_next_target)), + "NAVAL_COMBAT_SHIFT_BACK_DURATION_SCALE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_shift_back_duration_scale)), + "NAVAL_COMBAT_SPEED_TO_DISTANCE_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_speed_to_distance_factor)), + "NAVAL_COMBAT_CHANGE_TARGET_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_change_target_chance)), + "NAVAL_COMBAT_DAMAGE_ORG_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_damage_org_mult)), + "NAVAL_COMBAT_DAMAGE_STR_MULT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_damage_str_mult)), + "NAVAL_COMBAT_DAMAGE_MULT_NO_ORG", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_damage_mult_no_org)), + "NAVAL_COMBAT_RETREAT_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_retreat_chance)), + "NAVAL_COMBAT_RETREAT_STR_ORG_LEVEL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_retreat_str_org_level)), + "NAVAL_COMBAT_RETREAT_SPEED_MOD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_retreat_speed_mod)), + "NAVAL_COMBAT_RETREAT_MIN_DISTANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_retreat_min_distance)), + "NAVAL_COMBAT_DAMAGED_TARGET_SELECTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_damaged_target_selection)), + "NAVAL_COMBAT_STACKING_TARGET_CHANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_change)), + "NAVAL_COMBAT_STACKING_TARGET_SELECT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_combat_stacking_target_select)), + "NAVAL_COMBAT_MAX_TARGETS", + ONE_EXACTLY, + expect_uint(assign_variable_callback(naval_combat_max_targets)), + "AI_BIGSHIP_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_bigship_proportion)), + "AI_LIGHTSHIP_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_lightship_proportion)), + "AI_TRANSPORT_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_transport_proportion)), + "AI_CAVALRY_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_cavalry_proportion)), + "AI_SUPPORT_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_support_proportion)), + "AI_SPECIAL_PROPORTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_special_proportion)), + "AI_ESCORT_RATIO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_escort_ratio)), + "AI_ARMY_TAXBASE_FRACTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_army_taxbase_fraction)), + "AI_NAVY_TAXBASE_FRACTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_navy_taxbase_fraction)), + "AI_BLOCKADE_RANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ai_blockade_range)), + "RECON_UNIT_RATIO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(recon_unit_ratio)), + "ENGINEER_UNIT_RATIO", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(engineer_unit_ratio)), + "SIEGE_BRIGADES_MIN", + ONE_EXACTLY, + expect_uint(assign_variable_callback(siege_brigades_min)), + "SIEGE_BRIGADES_MAX", + ONE_EXACTLY, + expect_uint(assign_variable_callback(siege_brigades_max)), + "SIEGE_BRIGADES_BONUS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(siege_brigades_bonus)), + "RECON_SIEGE_EFFECT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(recon_siege_effect)), + "SIEGE_ATTRITION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(siege_attrition)), + "BASE_MILITARY_TACTICS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_military_tactics)), + "NAVAL_LOW_SUPPLY_DAMAGE_SUPPLY_STATUS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_low_supply_damage_supply_status)), + "NAVAL_LOW_SUPPLY_DAMAGE_DAYS_DELAY", + ONE_EXACTLY, + expect_days(assign_variable_callback(naval_low_supply_damage_days_delay)), + "NAVAL_LOW_SUPPLY_DAMAGE_MIN_STR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_low_supply_damage_min_str)), + "NAVAL_LOW_SUPPLY_DAMAGE_PER_DAY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(naval_low_supply_damage_per_day)) ); } diff --git a/src/openvic-simulation/defines/PopsDefines.cpp b/src/openvic-simulation/defines/PopsDefines.cpp index f28258985..4ce08a3e2 100644 --- a/src/openvic-simulation/defines/PopsDefines.cpp +++ b/src/openvic-simulation/defines/PopsDefines.cpp @@ -11,72 +11,185 @@ std::string_view PopsDefines::get_name() const { node_callback_t PopsDefines::expect_defines() { return expect_dictionary_keys( - "BASE_CLERGY_FOR_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_clergy_for_literacy)), - "MAX_CLERGY_FOR_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_clergy_for_literacy)), - "LITERACY_CHANGE_SPEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(literacy_change_speed)), - "ASSIMILATION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(assimilation_scale)), - "CONVERSION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(conversion_scale)), - "IMMIGRATION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(immigration_scale)), - "PROMOTION_SCALE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(promotion_scale)), - "PROMOTION_ASSIMILATION_CHANCE", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(promotion_assimilation_chance)), - "LUXURY_THRESHOLD", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(luxury_threshold)), - "BASE_GOODS_DEMAND", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_goods_demand)), - "BASE_POPGROWTH", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_popgrowth)), - "MIN_LIFE_RATING_FOR_GROWTH", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(min_life_rating_for_growth)), - "LIFE_RATING_GROWTH_BONUS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_rating_growth_bonus)), - "LIFE_NEED_STARVATION_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(life_need_starvation_limit)), - "MIL_LACK_EVERYDAY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_lack_everyday_need)), - "MIL_HAS_EVERYDAY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_has_everyday_need)), - "MIL_HAS_LUXURY_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_has_luxury_need)), - "MIL_NO_LIFE_NEED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_no_life_need)), - "MIL_REQUIRE_REFORM", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_require_reform)), - "MIL_IDEOLOGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_ideology)), - "MIL_RULING_PARTY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_ruling_party)), - "MIL_REFORM_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_reform_impact)), - "MIL_WAR_EXHAUSTION", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_war_exhaustion)), - "MIL_NON_ACCEPTED", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_non_accepted)), - "CON_LITERACY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_literacy)), - "CON_LUXURY_GOODS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_luxury_goods)), - "CON_POOR_CLERGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_poor_clergy)), - "CON_MIDRICH_CLERGY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_midrich_clergy)), - "CON_REFORM_IMPACT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_reform_impact)), - "CON_COLONIAL_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(con_colonial_factor)), - "RULING_PARTY_HAPPY_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ruling_party_happy_change)), - "RULING_PARTY_ANGRY_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ruling_party_angry_change)), - "PDEF_BASE_CON", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pdef_base_con)), - "NATIONAL_FOCUS_DIVIDER", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(national_focus_divider)), - "POP_SAVINGS", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_savings)), - "STATE_CREATION_ADMIN_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(state_creation_admin_limit)), - "MIL_TO_JOIN_REBEL", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_join_rebel)), - "MIL_TO_JOIN_RISING", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_join_rising)), - "MIL_TO_AUTORISE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_to_autorise)), - "REDUCTION_AFTER_RISEING", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reduction_after_riseing)), - "REDUCTION_AFTER_DEFEAT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(reduction_after_defeat)), - "POP_TO_LEADERSHIP", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pop_to_leadership)), - "ARTISAN_MIN_PRODUCTIVITY", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(artisan_min_productivity)), - "SLAVE_GROWTH_DIVISOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(slave_growth_divisor)), - "MIL_HIT_FROM_CONQUEST", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_hit_from_conquest)), - "LUXURY_CON_CHANGE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(luxury_con_change)), - "INVENTION_IMPACT_ON_DEMAND", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(invention_impact_on_demand)), - "ARTISAN_SUPPRESSED_COLONIAL_GOODS_CATEGORY", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(artisan_suppressed_colonial_goods_category)), - "ISSUE_MOVEMENT_JOIN_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(issue_movement_join_limit)), - "ISSUE_MOVEMENT_LEAVE_LIMIT", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(issue_movement_leave_limit)), - "MOVEMENT_CON_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_con_factor)), - "MOVEMENT_LIT_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_lit_factor)), - "MIL_ON_REB_MOVE", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(mil_on_reb_move)), - "POPULATION_SUPPRESSION_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(population_suppression_factor)), - "POPULATION_MOVEMENT_RADICAL_FACTOR", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(population_movement_radical_factor)), - "NATIONALIST_MOVEMENT_MIL_CAP", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(nationalist_movement_mil_cap)), - "MOVEMENT_SUPPORT_UH_FACTOR", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_support_uh_factor)), - "REBEL_OCCUPATION_STRENGTH_BONUS", ONE_EXACTLY, - expect_fixed_point(assign_variable_callback(rebel_occupation_strength_bonus)), - "LARGE_POPULATION_LIMIT", ONE_EXACTLY, expect_strong_typedef(assign_variable_callback(large_population_limit)), - "LARGE_POPULATION_INFLUENCE_PENALTY_CHUNK", ONE_EXACTLY, - expect_strong_typedef(assign_variable_callback(large_population_influence_penalty_chunk)) + "BASE_CLERGY_FOR_LITERACY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_clergy_for_literacy)), + "MAX_CLERGY_FOR_LITERACY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_clergy_for_literacy)), + "LITERACY_CHANGE_SPEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(literacy_change_speed)), + "ASSIMILATION_SCALE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(assimilation_scale)), + "CONVERSION_SCALE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(conversion_scale)), + "IMMIGRATION_SCALE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(immigration_scale)), + "PROMOTION_SCALE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(promotion_scale)), + "PROMOTION_ASSIMILATION_CHANCE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(promotion_assimilation_chance)), + "LUXURY_THRESHOLD", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(luxury_threshold)), + "BASE_GOODS_DEMAND", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_goods_demand)), + "BASE_POPGROWTH", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(base_popgrowth)), + "MIN_LIFE_RATING_FOR_GROWTH", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(min_life_rating_for_growth)), + "LIFE_RATING_GROWTH_BONUS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(life_rating_growth_bonus)), + "LIFE_NEED_STARVATION_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(life_need_starvation_limit)), + "MIL_LACK_EVERYDAY_NEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_lack_everyday_need)), + "MIL_HAS_EVERYDAY_NEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_has_everyday_need)), + "MIL_HAS_LUXURY_NEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_has_luxury_need)), + "MIL_NO_LIFE_NEED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_no_life_need)), + "MIL_REQUIRE_REFORM", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_require_reform)), + "MIL_IDEOLOGY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_ideology)), + "MIL_RULING_PARTY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_ruling_party)), + "MIL_REFORM_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_reform_impact)), + "MIL_WAR_EXHAUSTION", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_war_exhaustion)), + "MIL_NON_ACCEPTED", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_non_accepted)), + "CON_LITERACY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_literacy)), + "CON_LUXURY_GOODS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_luxury_goods)), + "CON_POOR_CLERGY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_poor_clergy)), + "CON_MIDRICH_CLERGY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_midrich_clergy)), + "CON_REFORM_IMPACT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_reform_impact)), + "CON_COLONIAL_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(con_colonial_factor)), + "RULING_PARTY_HAPPY_CHANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ruling_party_happy_change)), + "RULING_PARTY_ANGRY_CHANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ruling_party_angry_change)), + "PDEF_BASE_CON", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pdef_base_con)), + "NATIONAL_FOCUS_DIVIDER", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(national_focus_divider)), + "POP_SAVINGS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_savings)), + "STATE_CREATION_ADMIN_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(state_creation_admin_limit)), + "MIL_TO_JOIN_REBEL", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_join_rebel)), + "MIL_TO_JOIN_RISING", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_join_rising)), + "MIL_TO_AUTORISE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_to_autorise)), + "REDUCTION_AFTER_RISEING", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reduction_after_riseing)), + "REDUCTION_AFTER_DEFEAT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(reduction_after_defeat)), + "POP_TO_LEADERSHIP", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pop_to_leadership)), + "ARTISAN_MIN_PRODUCTIVITY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(artisan_min_productivity)), + "SLAVE_GROWTH_DIVISOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(slave_growth_divisor)), + "MIL_HIT_FROM_CONQUEST", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_hit_from_conquest)), + "LUXURY_CON_CHANGE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(luxury_con_change)), + "INVENTION_IMPACT_ON_DEMAND", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(invention_impact_on_demand)), + "ARTISAN_SUPPRESSED_COLONIAL_GOODS_CATEGORY", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(artisan_suppressed_colonial_goods_category)), + "ISSUE_MOVEMENT_JOIN_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(issue_movement_join_limit)), + "ISSUE_MOVEMENT_LEAVE_LIMIT", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(issue_movement_leave_limit)), + "MOVEMENT_CON_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_con_factor)), + "MOVEMENT_LIT_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_lit_factor)), + "MIL_ON_REB_MOVE", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(mil_on_reb_move)), + "POPULATION_SUPPRESSION_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(population_suppression_factor)), + "POPULATION_MOVEMENT_RADICAL_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(population_movement_radical_factor)), + "NATIONALIST_MOVEMENT_MIL_CAP", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(nationalist_movement_mil_cap)), + "MOVEMENT_SUPPORT_UH_FACTOR", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(movement_support_uh_factor)), + "REBEL_OCCUPATION_STRENGTH_BONUS", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(rebel_occupation_strength_bonus)), + "LARGE_POPULATION_LIMIT", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(large_population_limit)), + "LARGE_POPULATION_INFLUENCE_PENALTY_CHUNK", + ONE_EXACTLY, + expect_strong_typedef(assign_variable_callback(large_population_influence_penalty_chunk)) ); } diff --git a/src/openvic-simulation/defines/PopsDefines.hpp b/src/openvic-simulation/defines/PopsDefines.hpp index 0b3d3ea25..3e2856553 100644 --- a/src/openvic-simulation/defines/PopsDefines.hpp +++ b/src/openvic-simulation/defines/PopsDefines.hpp @@ -2,8 +2,8 @@ #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/map/LifeRating.hpp" +#include "openvic-simulation/population/PopSum.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/diplomacy/CountryRelation.cpp b/src/openvic-simulation/diplomacy/CountryRelation.cpp index dab393e14..9fb0c2fa1 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.cpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.cpp @@ -310,7 +310,7 @@ influence_value_type CRM::get_influence_with( // } influence_value_type& CRM::assign_or_get_influence_with( - CountryInstance* country, CountryInstance const* recipient, influence_value_type default_value + CountryInstance* country, CountryInstance const* recipient, influence_value_type default_value ) { decltype(influence)::iterator it = influence.find({ country, recipient }); if (it == influence.end()) { @@ -344,7 +344,7 @@ influence_priority_value_type CRM::get_influence_priority_with( // } influence_priority_value_type& CRM::assign_or_get_influence_priority_with( - CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type default_value + CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type default_value ) { decltype(influence_priority)::iterator it = influence_priority.find({ country, recipient }); if (it == influence_priority.end()) { @@ -353,7 +353,9 @@ influence_priority_value_type& CRM::assign_or_get_influence_priority_with( return it.value(); } -bool CRM::set_influence_priority_with(CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type value) { +bool CRM::set_influence_priority_with( + CountryInstance* country, CountryInstance const* recipient, influence_priority_value_type value +) { decltype(influence_priority)::iterator it = influence_priority.find({ country, recipient }); if (it == influence_priority.end()) { it = influence_priority.insert({ { country, recipient }, value }).first; diff --git a/src/openvic-simulation/diplomacy/CountryRelation.hpp b/src/openvic-simulation/diplomacy/CountryRelation.hpp index 119d0a0af..a60b56ef2 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.hpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.hpp @@ -25,9 +25,9 @@ namespace OpenVic { inline constexpr auto operator<=>(UnorderedCountryInstancePair const& rhs) const { const uintptr_t left1 = std::bit_cast(first), // - left2 = std::bit_cast(second), // - right1 = std::bit_cast(rhs.first), // - right2 = std::bit_cast(rhs.second); + left2 = std::bit_cast(second), // + right1 = std::bit_cast(rhs.first), // + right2 = std::bit_cast(rhs.second); using ordering = decltype(three_way_compare(std::tie(left1, left2), std::tie(right1, right2))); @@ -47,16 +47,14 @@ namespace OpenVic { auto& rhs_comp_first = rhs_left > rhs_right ? rhs_left : rhs_right; auto& rhs_comp_second = rhs_left < rhs_right ? rhs_left : rhs_right; - return three_way_compare( - std::tie(lhs_comp_first, lhs_comp_second), std::tie(rhs_comp_first, rhs_comp_second) - ); + return three_way_compare(std::tie(lhs_comp_first, lhs_comp_second), std::tie(rhs_comp_first, rhs_comp_second)); } inline constexpr bool operator==(UnorderedCountryInstancePair const& rhs) const { const uintptr_t left1 = std::bit_cast(first), // - left2 = std::bit_cast(second), // - right1 = std::bit_cast(rhs.first), // - right2 = std::bit_cast(rhs.second); + left2 = std::bit_cast(second), // + right1 = std::bit_cast(rhs.first), // + right2 = std::bit_cast(rhs.second); auto tied = std::tie(left1, left2); return tied == std::tie(right1, right2) || tied == std::tie(right2, right1); @@ -69,7 +67,7 @@ namespace std { struct hash { size_t operator()(OpenVic::CountryInstancePair const& pair) const { const uintptr_t first = std::bit_cast(pair.first), // - second = std::bit_cast(pair.second); + second = std::bit_cast(pair.second); std::size_t seed1 = 0; OpenVic::hash_combine(seed1, first); @@ -83,7 +81,7 @@ namespace std { struct hash { size_t operator()(OpenVic::UnorderedCountryInstancePair const& pair) const { const uintptr_t first = std::bit_cast(pair.first), // - second = std::bit_cast(pair.second); + second = std::bit_cast(pair.second); std::size_t seed1 = 0; OpenVic::hash_combine(seed1, first); @@ -222,8 +220,9 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& - operator%=(influence_value_type& lhs, influence_value_type const& rhs) { + friend inline constexpr influence_value_type& operator%=( + influence_value_type& lhs, influence_value_type const& rhs + ) { return lhs %= rhs.value; } @@ -250,7 +249,7 @@ namespace OpenVic { public: \ VALUE_TYPE get_##FUNC_NAME(CountryInstance const* country, CountryInstance const* recipient) const; \ VALUE_TYPE& assign_or_get_##FUNC_NAME( \ - CountryInstance* country, CountryInstance RECIPIENT_CONST* recipient, VALUE_TYPE default_value = {} \ + CountryInstance* country, CountryInstance RECIPIENT_CONST* recipient, VALUE_TYPE default_value = {} \ ); \ bool set_##FUNC_NAME(CountryInstance* country, CountryInstance RECIPIENT_CONST* recipient, VALUE_TYPE value); \ decltype(NAME)::values_container_type const& get_##FUNC_NAME##_values() const; \ @@ -267,7 +266,9 @@ public: \ RELATION_PAIR_MAP(CountryInstancePair, bool, vision, has_vision, const); RELATION_PAIR_MAP(CountryInstancePair, OpinionType, opinions, country_opinion, const); RELATION_PAIR_MAP(CountryInstancePair, influence_value_type, influence, influence_with, const); - RELATION_PAIR_MAP(CountryInstancePair, influence_priority_value_type, influence_priority, influence_priority_with, const); + RELATION_PAIR_MAP( + CountryInstancePair, influence_priority_value_type, influence_priority, influence_priority_with, const + ); vector_ordered_map discredits; vector_ordered_map embassy_bans; @@ -306,9 +307,9 @@ constexpr OpenVic::CountryRelationManager::OpinionType& operator++(OpenVic::Coun using underlying_type = std::underlying_type_t; type = static_cast(static_cast(type) + 1); type = static_cast(type) > - static_cast(OpenVic::CountryRelationManager::OpinionType::Sphere) // - ? OpenVic::CountryRelationManager::OpinionType::Sphere - : type; + static_cast(OpenVic::CountryRelationManager::OpinionType::Sphere) // + ? OpenVic::CountryRelationManager::OpinionType::Sphere + : type; return type; } @@ -322,9 +323,9 @@ constexpr OpenVic::CountryRelationManager::OpinionType& operator--(OpenVic::Coun using underlying_type = std::underlying_type_t; type = static_cast(static_cast(type) - 1); type = static_cast(type) < - static_cast(OpenVic::CountryRelationManager::OpinionType::Hostile) // - ? OpenVic::CountryRelationManager::OpinionType::Hostile - : type; + static_cast(OpenVic::CountryRelationManager::OpinionType::Hostile) // + ? OpenVic::CountryRelationManager::OpinionType::Hostile + : type; return type; } diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp index 6bd8d122c..58b5ac75a 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp @@ -13,36 +13,41 @@ using namespace OpenVic; -DiplomaticActionType::DiplomaticActionType(DiplomaticActionType::Initializer&& initializer) - : commit_action_caller { std::move(initializer.commit) }, allowed_to_commit { std::move(initializer.allowed) }, - get_acceptance { std::move(initializer.get_acceptance) } {} +DiplomaticActionType::DiplomaticActionType(DiplomaticActionType::Initializer&& initializer) : + commit_action_caller { std::move(initializer.commit) }, allowed_to_commit { std::move(initializer.allowed) }, + get_acceptance { std::move(initializer.get_acceptance) } {} -CancelableDiplomaticActionType::CancelableDiplomaticActionType(CancelableDiplomaticActionType::Initializer&& initializer) - : allowed_to_cancel { std::move(initializer.allowed_cancel) }, DiplomaticActionType { std::move(initializer) } {} +CancelableDiplomaticActionType::CancelableDiplomaticActionType(CancelableDiplomaticActionType::Initializer&& initializer) : + allowed_to_cancel { std::move(initializer.allowed_cancel) }, DiplomaticActionType { std::move(initializer) } {} bool DiplomaticActionManager::add_diplomatic_action( - std::string_view identifier, DiplomaticActionType::Initializer&& initializer + std::string_view identifier, DiplomaticActionType::Initializer&& initializer ) { if (identifier.empty()) { spdlog::error_s("Invalid diplomatic action identifier - empty!"); return false; } - return diplomatic_action_types.emplace_item( identifier, identifier, DiplomaticActionType { std::move(initializer) } ); + return diplomatic_action_types.emplace_item(identifier, identifier, DiplomaticActionType { std::move(initializer) }); } bool DiplomaticActionManager::add_cancelable_diplomatic_action( - std::string_view identifier, CancelableDiplomaticActionType::Initializer&& initializer + std::string_view identifier, CancelableDiplomaticActionType::Initializer&& initializer ) { if (identifier.empty()) { spdlog::error_s("Invalid cancelable diplomatic action identifier - empty!"); return false; } - return diplomatic_action_types.emplace_item( identifier, identifier, CancelableDiplomaticActionType { std::move(initializer) } ); + return diplomatic_action_types.emplace_item( + identifier, identifier, CancelableDiplomaticActionType { std::move(initializer) } + ); } DiplomaticActionTickCache DiplomaticActionManager::create_diplomatic_action_tick( - std::string_view identifier, CountryInstance* sender, CountryInstance* receiver, std::any context_data, - InstanceManager& instance_manager + std::string_view identifier, + CountryInstance* sender, + CountryInstance* receiver, + std::any context_data, + InstanceManager& instance_manager ) { auto type = diplomatic_action_types.get_item_by_identifier(identifier); @@ -77,51 +82,51 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { // TODO: implement _RELATION_ON_ACCEPT & _RELATION_ON_DECLINE result &= add_diplomatic_action( - "form_alliance", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // + "form_alliance", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_country_alliance( // arg.sender, arg.receiver, true ); - }, - } + }, + } ); result &= add_diplomatic_action( - "end_alliance", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // + "end_alliance", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_country_alliance( // arg.sender, arg.receiver, false ); - }, - } + }, + } ); result &= add_diplomatic_action( - "call_ally", - { - .commit = [](Argument& arg) {}, - .allowed = - [](Argument const& arg) { - return false; - }, - .get_acceptance = - [](Argument const& arg) { - return 1; - }, - } + "call_ally", + { + .commit = [](Argument& arg) {}, + .allowed = + [](Argument const& arg) { + return false; + }, + .get_acceptance = + [](Argument const& arg) { + return 1; + }, + } ); result &= add_diplomatic_action( - "request_military_access", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // + "request_military_access", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // arg.sender, arg.receiver, true ); - }, - } + }, + } ); result &= add_diplomatic_action( // "give_military_access", @@ -135,230 +140,230 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { } ); result &= add_diplomatic_action( - "increase_relations", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( - arg.sender, arg.receiver - ) += 25; // TODO: implement defines.diplomacy.INCREASERELATION_RELATION_ON_ACCEPT - }, - .allowed = - [](Argument const& arg) { - return false; - }, - } + "increase_relations", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) += 25; // TODO: implement defines.diplomacy.INCREASERELATION_RELATION_ON_ACCEPT + }, + .allowed = + [](Argument const& arg) { + return false; + }, + } ); result &= add_diplomatic_action( - "decrease_relations", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( - arg.sender, arg.receiver - ) -= 25; // TODO: implement defines.diplomacy.DECREASERELATION_RELATION_ON_ACCEPT - }, - .allowed = - [](Argument const& arg) { - return false; - }, - } + "decrease_relations", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) -= 25; // TODO: implement defines.diplomacy.DECREASERELATION_RELATION_ON_ACCEPT + }, + .allowed = + [](Argument const& arg) { + return false; + }, + } ); result &= add_diplomatic_action( - "war_subsidies", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // + "war_subsidies", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // arg.sender, arg.receiver, true ); - }, - } + }, + } ); result &= add_diplomatic_action( - "end_war_subsidies", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // + "end_war_subsidies", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // arg.sender, arg.receiver, false ); - }, - } + }, + } ); result &= add_diplomatic_action( - "declare_war", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_at_war_with( // + "declare_war", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_at_war_with( // arg.sender, arg.receiver, true ); - }, - } + }, + } ); result &= add_diplomatic_action( - "offer_peace", - { - .commit = [](Argument& arg) {}, - } + "offer_peace", + { + .commit = [](Argument& arg) {}, + } ); result &= add_diplomatic_action( - "command_units", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( // + "command_units", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( // arg.sender, arg.receiver ) = true; - }, - } + }, + } ); result &= add_diplomatic_action( - "discredit", - { - .influence_cost = 25, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_discredited_date( // + "discredit", + { + .influence_cost = 25, + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_discredited_date( // arg.sender, arg.receiver, arg.instance_manager.get_today() + 180 ); // TODO: implement defines.diplomacy.DISCREDIT_DAYS - }, - } + }, + } ); result &= add_diplomatic_action( - "expel_advisors", - { - .influence_cost = 50, // TODO: implement defines.diplomacy.EXPELADVISORS_INFLUENCE_COST - .commit = [](Argument& arg) {}, - } + "expel_advisors", + { + .influence_cost = 50, // TODO: implement defines.diplomacy.EXPELADVISORS_INFLUENCE_COST + .commit = [](Argument& arg) {}, + } ); result &= add_diplomatic_action( - "ban_embassy", - { - .influence_cost = 65, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( // + "ban_embassy", + { + .influence_cost = 65, + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( // arg.sender, arg.receiver, arg.instance_manager.get_today() + Timespan::from_years(1) ); // TODO: implement defines.diplomacy.BANEMBASSY_DAYS - }, - } + }, + } ); result &= add_diplomatic_action( - "increase_opinion", - { - .influence_cost = 50, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + "increase_opinion", + { + .influence_cost = 50, + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // arg.sender, arg.receiver )++; - }, - .allowed = - [](Argument const& arg) { - return true; - }, - } + }, + .allowed = + [](Argument const& arg) { + return true; + }, + } ); result &= add_diplomatic_action( - "decrease_opinion", - { - .influence_cost = 50, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + "decrease_opinion", + { + .influence_cost = 50, + .commit = + [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // std::any_cast(arg.context_data), arg.receiver ); - }, - .allowed = - [](Argument const& arg) { - return true; - }, - } + }, + .allowed = + [](Argument const& arg) { + return true; + }, + } ); result &= add_diplomatic_action( - "add_to_sphere", - { - .influence_cost = 100, - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + "add_to_sphere", + { + .influence_cost = 100, + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // arg.sender, arg.receiver ) = CountryRelationManager::OpinionType::Sphere; - }, - .allowed = - [](Argument const& arg) { - return true; - }, - } + }, + .allowed = + [](Argument const& arg) { + return true; + }, + } ); result &= add_diplomatic_action( - "remove_from_foreign_sphere", - { - .influence_cost = 100, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + "remove_from_foreign_sphere", + { + .influence_cost = 100, + .commit = + [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // std::any_cast(arg.context_data), arg.receiver ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // arg.sender, arg.receiver ) -= 10; - }, - .allowed = - [](Argument const& arg) { - return true; - }, - } + }, + .allowed = + [](Argument const& arg) { + return true; + }, + } ); result &= add_diplomatic_action( - "remove_from_own_sphere", - { - .influence_cost = 100, - .commit = - [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // + "remove_from_own_sphere", + { + .influence_cost = 100, + .commit = + [](Argument& arg) { + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // arg.sender, arg.receiver ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // arg.sender, arg.receiver ) -= 10; - // TODO: implement REMOVEFROMSPHERE_PRESTIGE_COST and REMOVEFROMSPHERE_INFAMY_COST - }, - .allowed = - [](Argument const& arg) { - return true; - }, - } + // TODO: implement REMOVEFROMSPHERE_PRESTIGE_COST and REMOVEFROMSPHERE_INFAMY_COST + }, + .allowed = + [](Argument const& arg) { + return true; + }, + } ); result &= add_diplomatic_action( - "justify_war", - { - .commit = [](Argument& arg) {}, - } + "justify_war", + { + .commit = [](Argument& arg) {}, + } ); result &= add_diplomatic_action( - "give_vision", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // + "give_vision", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_vision( // arg.sender, arg.receiver, true ); - }, - } + }, + } ); result &= add_diplomatic_action( - "remove_vision", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // + "remove_vision", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_vision( // arg.sender, arg.receiver, false ); - }, - } + }, + } ); diplomatic_action_types.lock(); diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.hpp b/src/openvic-simulation/diplomacy/DiplomaticAction.hpp index 53db2c458..1553635e3 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.hpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.hpp @@ -132,12 +132,15 @@ namespace OpenVic { bool add_diplomatic_action(std::string_view identifier, DiplomaticActionType::Initializer&& initializer); bool add_cancelable_diplomatic_action( - std::string_view identifier, CancelableDiplomaticActionType::Initializer&& initializer + std::string_view identifier, CancelableDiplomaticActionType::Initializer&& initializer ); DiplomaticActionTickCache create_diplomatic_action_tick( - std::string_view identifier, CountryInstance* sender, CountryInstance* receiver, std::any context_data, - InstanceManager& instance_manager + std::string_view identifier, + CountryInstance* sender, + CountryInstance* receiver, + std::any context_data, + InstanceManager& instance_manager ); bool setup_diplomatic_actions(); diff --git a/src/openvic-simulation/economy/BuildingInstance.cpp b/src/openvic-simulation/economy/BuildingInstance.cpp index 8cdbf432d..3c3a76898 100644 --- a/src/openvic-simulation/economy/BuildingInstance.cpp +++ b/src/openvic-simulation/economy/BuildingInstance.cpp @@ -4,34 +4,25 @@ using namespace OpenVic; -BuildingInstance::BuildingInstance(BuildingType const& new_building_type, building_level_t new_level) - : HasIdentifier { new_building_type }, - building_type { new_building_type }, - level { new_level } {} +BuildingInstance::BuildingInstance(BuildingType const& new_building_type, building_level_t new_level) : + HasIdentifier { new_building_type }, building_type { new_building_type }, level { new_level } {} bool BuildingInstance::_can_expand() const { return level < building_type.max_level; } bool BuildingInstance::expand( - ModifierEffectCache const& modifier_effect_cache, - CountryInstance& actor, - ProvinceInstance const& location + ModifierEffectCache const& modifier_effect_cache, CountryInstance& actor, ProvinceInstance const& location ) { if (expansion_state != ExpansionState::CanExpand) { return false; } - if (!building_type.can_be_built_in( - modifier_effect_cache, - level+1, - actor, - location - )) { + if (!building_type.can_be_built_in(modifier_effect_cache, level + 1, actor, location)) { return false; } - //TODO add construction costs to actor + // TODO add construction costs to actor expansion_state = ExpansionState::Preparing; expansion_progress = 0; return true; @@ -47,8 +38,9 @@ void BuildingInstance::update_gamestate(Date today) { end_date = start_date + building_type.build_time; break; case ExpansionState::Expanding: - expansion_progress = fixed_point_t { static_cast((today - start_date).to_int()) } - / static_cast((end_date - start_date).to_int()); + expansion_progress = fixed_point_t { + static_cast((today - start_date).to_int()) + } / static_cast((end_date - start_date).to_int()); break; default: expansion_state = _can_expand() ? ExpansionState::CanExpand : ExpansionState::CannotExpand; } @@ -84,4 +76,4 @@ void BuildingInstance::set_level(const building_level_t new_level) { } else { level = new_level; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/BuildingInstance.hpp b/src/openvic-simulation/economy/BuildingInstance.hpp index 862d08169..a6956b94c 100644 --- a/src/openvic-simulation/economy/BuildingInstance.hpp +++ b/src/openvic-simulation/economy/BuildingInstance.hpp @@ -12,7 +12,12 @@ namespace OpenVic { struct ProvinceInstance; struct BuildingInstance : HasIdentifier { // used in the actual game - enum class ExpansionState { CannotExpand, CanExpand, Preparing, Expanding }; + enum class ExpansionState { + CannotExpand, + CanExpand, + Preparing, + Expanding + }; private: building_level_t PROPERTY(level); @@ -29,11 +34,7 @@ namespace OpenVic { BuildingInstance(BuildingType const& new_building_type, building_level_t new_level = building_level_t { 0 }); BuildingInstance(BuildingInstance&&) = default; - bool expand( - ModifierEffectCache const& modifier_effect_cache, - CountryInstance& actor, - ProvinceInstance const& location - ); + bool expand(ModifierEffectCache const& modifier_effect_cache, CountryInstance& actor, ProvinceInstance const& location); void update_gamestate(Date today); void tick(Date today); void set_level(const building_level_t new_level); diff --git a/src/openvic-simulation/economy/BuildingLevel.hpp b/src/openvic-simulation/economy/BuildingLevel.hpp index ddbd2aa02..bd4eb9680 100644 --- a/src/openvic-simulation/economy/BuildingLevel.hpp +++ b/src/openvic-simulation/economy/BuildingLevel.hpp @@ -8,12 +8,13 @@ #include namespace OpenVic { - struct building_level_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + struct building_level_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } diff --git a/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp b/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp index b2bf0e976..bf8714d24 100644 --- a/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp +++ b/src/openvic-simulation/economy/BuildingRestrictionCategory.hpp @@ -6,4 +6,4 @@ namespace OpenVic { INFRASTRUCTURE, FACTORY }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/BuildingType.cpp b/src/openvic-simulation/economy/BuildingType.cpp index 4f75ba2ec..b7a214d4a 100644 --- a/src/openvic-simulation/economy/BuildingType.cpp +++ b/src/openvic-simulation/economy/BuildingType.cpp @@ -18,56 +18,45 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; BuildingType::BuildingType( - index_t new_index, - std::optional new_province_building_index, - std::string_view new_identifier, - building_type_args_t& building_type_args -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(building_type_args.modifier), modifier_type_t::BUILDING }, - province_building_index { new_province_building_index }, - type { building_type_args.type }, - on_completion { building_type_args.on_completion }, - completion_size { building_type_args.completion_size }, - max_level { building_type_args.max_level }, - goods_cost { std::move(building_type_args.goods_cost) }, - cost { building_type_args.cost }, - build_time { building_type_args.build_time }, - should_display_on_map { building_type_args.on_map }, - is_enabled_by_default { building_type_args.default_enabled }, - production_type { building_type_args.production_type }, - is_pop_build_factory { building_type_args.pop_build_factory }, - is_strategic_factory { building_type_args.strategic_factory }, - is_advanced_factory { building_type_args.advanced_factory }, - fort_level { building_type_args.fort_level }, - naval_capacity { building_type_args.naval_capacity }, - colonial_points { std::move(building_type_args.colonial_points) }, - is_in_province { building_type_args.in_province }, - restriction_category { - building_type_args.pop_build_factory - ? building_type_args.in_province - ? BuildingRestrictionCategory::INFRASTRUCTURE - : BuildingRestrictionCategory::FACTORY - : BuildingRestrictionCategory::UNRESTRICTED - }, - is_limited_to_one_per_state { building_type_args.one_per_state }, - colonial_range { building_type_args.colonial_range }, - infrastructure { building_type_args.infrastructure }, - should_spawn_railway_track { building_type_args.spawn_railway_track }, - is_sail { building_type_args.sail }, - is_steam { building_type_args.steam }, - capital { building_type_args.capital }, - is_port { building_type_args.port } {} + index_t new_index, + std::optional new_province_building_index, + std::string_view new_identifier, + building_type_args_t& building_type_args +) : + HasIndex { new_index }, Modifier { new_identifier, std::move(building_type_args.modifier), modifier_type_t::BUILDING }, + province_building_index { new_province_building_index }, type { building_type_args.type }, + on_completion { building_type_args.on_completion }, completion_size { building_type_args.completion_size }, + max_level { building_type_args.max_level }, goods_cost { std::move(building_type_args.goods_cost) }, + cost { building_type_args.cost }, build_time { building_type_args.build_time }, + should_display_on_map { building_type_args.on_map }, is_enabled_by_default { building_type_args.default_enabled }, + production_type { building_type_args.production_type }, is_pop_build_factory { building_type_args.pop_build_factory }, + is_strategic_factory { building_type_args.strategic_factory }, is_advanced_factory { building_type_args.advanced_factory }, + fort_level { building_type_args.fort_level }, naval_capacity { building_type_args.naval_capacity }, + colonial_points { std::move(building_type_args.colonial_points) }, is_in_province { building_type_args.in_province }, + restriction_category { + building_type_args.pop_build_factory + ? building_type_args.in_province + ? BuildingRestrictionCategory::INFRASTRUCTURE + : BuildingRestrictionCategory::FACTORY + : BuildingRestrictionCategory::UNRESTRICTED + }, + is_limited_to_one_per_state { building_type_args.one_per_state }, colonial_range { building_type_args.colonial_range }, + infrastructure { building_type_args.infrastructure }, should_spawn_railway_track { building_type_args.spawn_railway_track }, + is_sail { building_type_args.sail }, is_steam { building_type_args.steam }, capital { building_type_args.capital }, + is_port { building_type_args.port } {} bool BuildingType::can_be_built_in( - ModifierEffectCache const& modifier_effect_cache, - const building_level_t desired_level, - CountryInstance const& actor, - ProvinceInstance const& location + ModifierEffectCache const& modifier_effect_cache, + const building_level_t desired_level, + CountryInstance const& actor, + ProvinceInstance const& location ) const { OV_ERR_FAIL_COND_V_MSG( - !is_in_province, - false, - memory::fmt::format("BuildingType::can_be_built_in (province variant) was called on state level building {}", get_identifier()) + !is_in_province, + false, + memory::fmt::format( + "BuildingType::can_be_built_in (province variant) was called on state level building {}", get_identifier() + ) ); if (desired_level > max_level) { @@ -94,7 +83,8 @@ bool BuildingType::can_be_built_in( continue; } - const building_level_t other_building_level = province_in_state.get_buildings()[province_building_index.value()].get_level(); + const building_level_t other_building_level = + province_in_state.get_buildings()[province_building_index.value()].get_level(); if (other_building_level > building_level_t(0)) { return false; } @@ -105,8 +95,8 @@ bool BuildingType::can_be_built_in( building_level_t const& unlocked_max_level = actor.get_building_type_unlock_levels(*this); ModifierEffectCache::building_type_effects_t const& effects = modifier_effect_cache.get_building_type_effects(*this); const fixed_point_t min_level_modifier = location.get_modifier_effect_value(*effects.get_min_level()); - return fixed_point_t { type_safe::get(unlocked_max_level) } - >= fixed_point_t { type_safe::get(desired_level) } + min_level_modifier; + return fixed_point_t { type_safe::get(unlocked_max_level) } >= + fixed_point_t { type_safe::get(desired_level) } + min_level_modifier; } bool BuildingType::can_be_built_in(ProvinceDefinition const& location) const { @@ -116,21 +106,24 @@ bool BuildingType::can_be_built_in(ProvinceDefinition const& location) const { BuildingTypeManager::BuildingTypeManager() : infrastructure_building_type { nullptr }, port_building_type { nullptr } {} bool BuildingTypeManager::add_building_type( - std::string_view identifier, BuildingType::building_type_args_t& building_type_args + std::string_view identifier, BuildingType::building_type_args_t& building_type_args ) { if (identifier.empty()) { spdlog::error_s("Invalid building identifier - empty!"); return false; } - - std::optional province_building_index = building_type_args.in_province - ? std::make_optional(province_building_types.size()) - : std::nullopt; + + std::optional province_building_index = + building_type_args.in_province + ? std::make_optional(province_building_types.size()) + : std::nullopt; const bool ret = building_types.emplace_item( - identifier, - index_from_count(get_building_type_count()), province_building_index, identifier, - building_type_args + identifier, + index_from_count(get_building_type_count()), + province_building_index, + identifier, + building_type_args ); if (ret) { @@ -144,16 +137,16 @@ bool BuildingTypeManager::add_building_type( } bool BuildingTypeManager::load_buildings_file( - GoodDefinitionManager const& good_definition_manager, ProductionTypeManager const& production_type_manager, - ModifierManager& modifier_manager, ast::NodeCPtr root + GoodDefinitionManager const& good_definition_manager, + ProductionTypeManager const& production_type_manager, + ModifierManager& modifier_manager, + ast::NodeCPtr root ) { - bool ret = expect_dictionary_reserve_length( - building_types, [this, &good_definition_manager, &production_type_manager, &modifier_manager]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - BuildingType::building_type_args_t building_type_args {}; + bool ret = + expect_dictionary_reserve_length(building_types, [this, &good_definition_manager, &production_type_manager, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { + BuildingType::building_type_args_t building_type_args {}; - bool ret = NodeTools::expect_dictionary_keys_and_default( + bool ret = NodeTools::expect_dictionary_keys_and_default( modifier_manager.expect_base_province_modifier(building_type_args.modifier), "type", ONE_EXACTLY, expect_identifier(assign_variable_callback(building_type_args.type)), "on_completion", ZERO_OR_ONE, expect_identifier(assign_variable_callback(building_type_args.on_completion)), @@ -198,19 +191,16 @@ bool BuildingTypeManager::load_buildings_file( "port", ZERO_OR_ONE, expect_bool(assign_variable_callback(building_type_args.port)) )(value); - ret &= add_building_type(key, building_type_args); + ret &= add_building_type(key, building_type_args); - return ret; - } - )(root); + return ret; + })(root); lock_building_types(); auto& building_type_effects = modifier_manager.modifier_effect_cache.building_type_effects; building_type_effects = std::move( - decltype(ModifierEffectCache::building_type_effects) { - generate_values, - building_type_index_t(get_building_type_count()) - } + decltype(ModifierEffectCache::building_type_effects) { + generate_values, building_type_index_t(get_building_type_count()) } ); for (BuildingType const& building_type : get_building_types()) { @@ -222,13 +212,16 @@ bool BuildingTypeManager::load_buildings_file( static constexpr std::string_view max_prefix = "max_"; static constexpr std::string_view min_prefix = "min_build_"; ret &= modifier_manager.register_technology_modifier_effect( - this_building_type_effects.max_level, append_string_views(max_prefix, building_type.get_identifier()), - FORMAT_x1_0DP_POS, memory::fmt::format("${}$ $TECH_MAX_LEVEL$", building_type) + this_building_type_effects.max_level, + append_string_views(max_prefix, building_type.get_identifier()), + FORMAT_x1_0DP_POS, + memory::fmt::format("${}$ $TECH_MAX_LEVEL$", building_type) ); // TODO - add custom localisation for "min_build_$building_type$" modifiers ret &= modifier_manager.register_terrain_modifier_effect( - this_building_type_effects.min_level, append_string_views(min_prefix, building_type.get_identifier()), - FORMAT_x1_0DP_NEG + this_building_type_effects.min_level, + append_string_views(min_prefix, building_type.get_identifier()), + FORMAT_x1_0DP_NEG ); if (building_type.is_in_province) { if (building_type.is_port) { @@ -236,8 +229,9 @@ bool BuildingTypeManager::load_buildings_file( port_building_type = &building_type; } else { spdlog::error_s( - "Building type {} is marked as a port, but we are already using {} as the port building type!", - building_type, *port_building_type + "Building type {} is marked as a port, but we are already using {} as the port building type!", + building_type, + *port_building_type ); ret = false; } @@ -246,17 +240,17 @@ bool BuildingTypeManager::load_buildings_file( infrastructure_building_type = &building_type; } else { spdlog::error_s( - "Building type {} is marked as a infrastructure, but we are already using {} as the infrastructure building type!", - building_type, *infrastructure_building_type + "Building type {} is marked as a infrastructure, but we are already using {} as the infrastructure " + "building type!", + building_type, + *infrastructure_building_type ); ret = false; } } } else { if (building_type.is_port) { - spdlog::error_s( - "Building type {} is marked as a port, but is not a province building!", building_type - ); + spdlog::error_s("Building type {} is marked as a port, but is not a province building!", building_type); ret = false; } } @@ -277,8 +271,9 @@ bool BuildingTypeManager::load_buildings_file( ret = false; } else { SPDLOG_INFO( - "Found {} province building types out of {} total building types", - province_building_types.size(), get_building_type_count() + "Found {} province building types out of {} total building types", + province_building_types.size(), + get_building_type_count() ); } diff --git a/src/openvic-simulation/economy/BuildingType.hpp b/src/openvic-simulation/economy/BuildingType.hpp index 69bb4cfa6..beb9b8530 100644 --- a/src/openvic-simulation/economy/BuildingType.hpp +++ b/src/openvic-simulation/economy/BuildingType.hpp @@ -5,11 +5,11 @@ #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" -#include "openvic-simulation/modifier/Modifier.hpp" #include "openvic-simulation/core/object/Timespan.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" #include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/economy/BuildingRestrictionCategory.hpp" +#include "openvic-simulation/modifier/Modifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/TypedIndices.hpp" @@ -42,8 +42,8 @@ namespace OpenVic { fixed_point_map_t goods_cost; Timespan build_time; bool on_map = false, default_enabled = false, pop_build_factory = false, strategic_factory = false, - advanced_factory = false, in_province = false, one_per_state = false, spawn_railway_track = false, - sail = false, steam = false, capital = false, port = false; + advanced_factory = false, in_province = false, one_per_state = false, spawn_railway_track = false, + sail = false, steam = false, capital = false, port = false; ProductionType const* production_type = nullptr; naval_capacity_t naval_capacity = 0; memory::vector colonial_points; @@ -58,12 +58,12 @@ namespace OpenVic { const bool is_port; const bool capital; // only in naval base - const memory::string on_completion; //unknown + const memory::string on_completion; // unknown memory::vector SPAN_PROPERTY(colonial_points); public: - //general attributes + // general attributes const std::optional province_building_index; const bool is_pop_build_factory; @@ -81,12 +81,12 @@ namespace OpenVic { const building_level_t max_level; const fixed_point_t completion_size; - //costs + // costs const fixed_point_t cost; const Timespan build_time; const fixed_point_map_t goods_cost; - //effects + // effects ProductionType const* const production_type; const building_level_t fort_level; // fort bonus step-per-level const naval_capacity_t naval_capacity; @@ -94,18 +94,18 @@ namespace OpenVic { const fixed_point_t infrastructure; BuildingType( - index_t new_index, - std::optional new_province_building_index, - std::string_view new_identifier, - building_type_args_t& building_type_args + index_t new_index, + std::optional new_province_building_index, + std::string_view new_identifier, + building_type_args_t& building_type_args ); BuildingType(BuildingType&&) = default; [[nodiscard]] bool can_be_built_in( - ModifierEffectCache const& modifier_effect_cache, - const building_level_t desired_level, - CountryInstance const& actor, - ProvinceInstance const& location + ModifierEffectCache const& modifier_effect_cache, + const building_level_t desired_level, + CountryInstance const& actor, + ProvinceInstance const& location ) const; [[nodiscard]] bool can_be_built_in(ProvinceDefinition const& location) const; }; @@ -118,8 +118,10 @@ namespace OpenVic { BuildingType const* PROPERTY(port_building_type); memory::vector> province_building_types; + public: - constexpr TypedSpan> get_province_building_types() const { + constexpr TypedSpan> + get_province_building_types() const { return province_building_types; } @@ -128,8 +130,10 @@ namespace OpenVic { bool add_building_type(std::string_view identifier, BuildingType::building_type_args_t& building_type_args); bool load_buildings_file( - GoodDefinitionManager const& good_definition_manager, ProductionTypeManager const& production_type_manager, - ModifierManager& modifier_manager, ast::NodeCPtr root + GoodDefinitionManager const& good_definition_manager, + ProductionTypeManager const& production_type_manager, + ModifierManager& modifier_manager, + ast::NodeCPtr root ); }; } diff --git a/src/openvic-simulation/economy/EconomyManager.hpp b/src/openvic-simulation/economy/EconomyManager.hpp index 77226313c..30a784878 100644 --- a/src/openvic-simulation/economy/EconomyManager.hpp +++ b/src/openvic-simulation/economy/EconomyManager.hpp @@ -15,21 +15,16 @@ namespace OpenVic { public: inline bool load_production_types_file( - GameRulesManager const& game_rules_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, PopManager const& pop_manager, ovdl::v2script::Parser const& parser ) { return production_type_manager.load_production_types_file( - game_rules_manager, - good_definition_manager, - pop_manager, - parser + game_rules_manager, good_definition_manager, pop_manager, parser ); } inline bool load_buildings_file(ModifierManager& modifier_manager, ast::NodeCPtr root) { return building_type_manager.load_buildings_file( - good_definition_manager, production_type_manager, modifier_manager, root + good_definition_manager, production_type_manager, modifier_manager, root ); } }; diff --git a/src/openvic-simulation/economy/GoodDefinition.cpp b/src/openvic-simulation/economy/GoodDefinition.cpp index 14e7ab2d2..45d5e90a5 100644 --- a/src/openvic-simulation/economy/GoodDefinition.cpp +++ b/src/openvic-simulation/economy/GoodDefinition.cpp @@ -1,33 +1,29 @@ #include "GoodDefinition.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/core/memory/FixedVector.hpp" #include "openvic-simulation/core/string/Utility.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; -GoodCategory::GoodCategory(std::string_view new_identifier, index_t new_index) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} +GoodCategory::GoodCategory(std::string_view new_identifier, index_t new_index) : + HasIdentifier { new_identifier }, HasIndex { new_index } {} GoodDefinition::GoodDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - GoodCategory const& new_category, - fixed_point_t new_base_price, - bool new_is_available_from_start, - bool new_is_tradeable, - bool new_is_money, - bool new_counters_overseas_penalty -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - category { new_category }, - base_price { new_base_price }, - is_available_from_start { new_is_available_from_start }, - is_tradeable { new_is_tradeable }, - is_money { new_is_money }, - counters_overseas_penalty { new_counters_overseas_penalty } {} + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + GoodCategory const& new_category, + fixed_point_t new_base_price, + bool new_is_available_from_start, + bool new_is_tradeable, + bool new_is_money, + bool new_counters_overseas_penalty +) : + HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, category { new_category }, + base_price { new_base_price }, is_available_from_start { new_is_available_from_start }, is_tradeable { new_is_tradeable }, + is_money { new_is_money }, counters_overseas_penalty { new_counters_overseas_penalty } {} bool GoodDefinitionManager::add_good_category(std::string_view identifier, size_t expected_goods_in_category) { if (identifier.empty()) { @@ -36,9 +32,8 @@ bool GoodDefinitionManager::add_good_category(std::string_view identifier, size_ } if (good_categories.emplace_item( - identifier, - identifier, index_from_count(get_good_category_count()) - )) { + identifier, identifier, index_from_count(get_good_category_count()) + )) { good_categories.back().good_definitions.reserve(expected_goods_in_category); return true; } else { @@ -47,8 +42,14 @@ bool GoodDefinitionManager::add_good_category(std::string_view identifier, size_ } bool GoodDefinitionManager::add_good_definition( - std::string_view identifier, colour_t colour, GoodCategory& category, fixed_point_t base_price, - bool is_available_from_start, bool is_tradeable, bool is_money, bool has_overseas_penalty + std::string_view identifier, + colour_t colour, + GoodCategory& category, + fixed_point_t base_price, + bool is_available_from_start, + bool is_tradeable, + bool is_money, + bool has_overseas_penalty ) { if (identifier.empty()) { spdlog::error_s("Invalid good identifier - empty!"); @@ -61,16 +62,26 @@ bool GoodDefinitionManager::add_good_definition( if (is_tradeable == is_money) { spdlog::warn_s( - "Good {} has tradeable: {} and money: {}. Money goods are never tradeable. All other goods are tradeable. Setting tradeable has no effect.", - identifier, bool_to_yes_no(is_tradeable), bool_to_yes_no(is_money) + "Good {} has tradeable: {} and money: {}. Money goods are never tradeable. All other goods are tradeable. Setting " + "tradeable has no effect.", + identifier, + bool_to_yes_no(is_tradeable), + bool_to_yes_no(is_money) ); } if (good_definitions.emplace_item( - identifier, - identifier, colour, index_from_count(get_good_definition_count()), category, base_price, is_available_from_start, - is_tradeable, is_money, has_overseas_penalty - )) { + identifier, + identifier, + colour, + index_from_count(get_good_definition_count()), + category, + base_price, + is_available_from_start, + is_tradeable, + is_money, + has_overseas_penalty + )) { category.good_definitions.emplace_back(get_back_good_definition()); return true; } else { @@ -81,54 +92,43 @@ bool GoodDefinitionManager::add_good_definition( bool GoodDefinitionManager::load_goods_file(ast::NodeCPtr root) { size_t total_expected_goods = 0; - bool ret = expect_dictionary_reserve_length( - good_categories, - [this, &total_expected_goods](std::string_view key, ast::NodeCPtr value) -> bool { - size_t expected_goods_in_category = 0; + bool ret = + expect_dictionary_reserve_length(good_categories, [this, &total_expected_goods](std::string_view key, ast::NodeCPtr value) -> bool { + size_t expected_goods_in_category = 0; - bool ret = expect_length(assign_variable_callback(expected_goods_in_category))(value); + bool ret = expect_length(assign_variable_callback(expected_goods_in_category))(value); - if (add_good_category(key, expected_goods_in_category)) { - total_expected_goods += expected_goods_in_category; - } else { - ret = false; - } + if (add_good_category(key, expected_goods_in_category)) { + total_expected_goods += expected_goods_in_category; + } else { + ret = false; + } - return ret; - } - )(root); + return ret; + })(root); lock_good_categories(); reserve_more_good_definitions(total_expected_goods); - ret &= good_categories.expect_item_dictionary( - [this](GoodCategory& good_category, ast::NodeCPtr good_category_value) -> bool { - return expect_dictionary( - [this, &good_category](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = colour_t::null(); - fixed_point_t base_price; - bool is_available_from_start = true, is_tradeable = true; - bool is_money = false, has_overseas_penalty = false; - - bool ret = expect_dictionary_keys( - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_price)), - "available_from_start", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_available_from_start)), - "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_tradeable)), - "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_money)), - "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(has_overseas_penalty)) - )(value); - - ret &= add_good_definition( - key, colour, good_category, base_price, is_available_from_start, is_tradeable, is_money, - has_overseas_penalty - ); - - return ret; - } - )(good_category_value); - } - )(root); + ret &= good_categories.expect_item_dictionary([this](GoodCategory& good_category, ast::NodeCPtr good_category_value) -> bool { + return expect_dictionary([this, &good_category](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = colour_t::null(); + fixed_point_t base_price; + bool is_available_from_start = true, is_tradeable = true; + bool is_money = false, has_overseas_penalty = false; + + bool + ret = expect_dictionary_keys("color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), "cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base_price)), "available_from_start", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_available_from_start)), "tradeable", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_tradeable)), "money", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_money)), "overseas_penalty", ZERO_OR_ONE, expect_bool(assign_variable_callback(has_overseas_penalty)))( + value + ); + + ret &= add_good_definition( + key, colour, good_category, base_price, is_available_from_start, is_tradeable, is_money, has_overseas_penalty + ); + + return ret; + })(good_category_value); + })(root); lock_good_definitions(); @@ -141,12 +141,10 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager using enum ModifierEffect::format_t; using enum ModifierEffect::target_t; - memory::FixedVector& good_effects = modifier_manager.modifier_effect_cache.good_effects; + memory::FixedVector& good_effects = + modifier_manager.modifier_effect_cache.good_effects; good_effects = std::move( - decltype(ModifierEffectCache::good_effects) { - generate_values, - good_index_t(get_good_definition_count()) - } + decltype(ModifierEffectCache::good_effects) { generate_values, good_index_t(get_good_definition_count()) } ); bool ret = true; @@ -166,62 +164,86 @@ bool GoodDefinitionManager::generate_modifiers(ModifierManager& modifier_manager const std::string_view good_identifier = good.get_identifier(); ModifierEffectCache::good_effects_t& this_good_effects = good_effects[good.index]; - const auto good_modifier = [&modifier_manager, &ret, &good_identifier]( - ModifierEffect const*& effect_cache, std::string_view name, ModifierEffect::format_t format, - std::string_view localisation_key, bool has_no_effect = false - ) -> void { + const auto good_modifier = + [&modifier_manager, &ret, &good_identifier]( + ModifierEffect const*& effect_cache, + std::string_view name, + ModifierEffect::format_t format, + std::string_view localisation_key, + bool has_no_effect = false + ) -> void { ret &= modifier_manager.register_technology_modifier_effect( - effect_cache, ModifierManager::get_flat_identifier(name, good_identifier), - format, localisation_key, has_no_effect + effect_cache, + ModifierManager::get_flat_identifier(name, good_identifier), + format, + localisation_key, + has_no_effect ); }; - const auto make_production_localisation_suffix = [&good]( - std::string_view localisation_suffix - ) -> memory::string { + const auto make_production_localisation_suffix = [&good](std::string_view localisation_suffix) -> memory::string { return memory::fmt::format("${}$ ${}$", good, localisation_suffix); }; good_modifier( - this_good_effects.rgo_goods_input, "rgo_goods_input", FORMAT_x100_1DP_PC_NEG, - make_production_localisation_suffix("TECH_INPUT"), HAS_NO_EFFECT - ); - good_modifier( - this_good_effects.rgo_goods_output, "rgo_goods_output", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_OUTPUT") + this_good_effects.rgo_goods_input, + "rgo_goods_input", + FORMAT_x100_1DP_PC_NEG, + make_production_localisation_suffix("TECH_INPUT"), + HAS_NO_EFFECT ); good_modifier( - this_good_effects.rgo_goods_throughput, "rgo_goods_throughput", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_THROUGHPUT") + this_good_effects.rgo_goods_output, + "rgo_goods_output", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_OUTPUT") ); good_modifier( - this_good_effects.factory_goods_input, "factory_goods_input", FORMAT_x100_1DP_PC_NEG, - make_production_localisation_suffix("TECH_INPUT") + this_good_effects.rgo_goods_throughput, + "rgo_goods_throughput", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_THROUGHPUT") ); good_modifier( - this_good_effects.factory_goods_output, "factory_goods_output", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_OUTPUT") + this_good_effects.factory_goods_input, + "factory_goods_input", + FORMAT_x100_1DP_PC_NEG, + make_production_localisation_suffix("TECH_INPUT") ); good_modifier( - this_good_effects.factory_goods_throughput, "factory_goods_throughput", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_THROUGHPUT") + this_good_effects.factory_goods_output, + "factory_goods_output", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_OUTPUT") ); good_modifier( - this_good_effects.artisan_goods_input, "artisan_goods_input", FORMAT_x100_1DP_PC_NEG, - make_production_localisation_suffix("TECH_INPUT"), HAS_NO_EFFECT + this_good_effects.factory_goods_throughput, + "factory_goods_throughput", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_THROUGHPUT") ); good_modifier( - this_good_effects.artisan_goods_output, "artisan_goods_output", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_OUTPUT"), HAS_NO_EFFECT + this_good_effects.artisan_goods_input, + "artisan_goods_input", + FORMAT_x100_1DP_PC_NEG, + make_production_localisation_suffix("TECH_INPUT"), + HAS_NO_EFFECT ); good_modifier( - this_good_effects.artisan_goods_throughput, "artisan_goods_throughput", FORMAT_x100_1DP_PC_POS, - make_production_localisation_suffix("TECH_THROUGHPUT"), HAS_NO_EFFECT + this_good_effects.artisan_goods_output, + "artisan_goods_output", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_OUTPUT"), + HAS_NO_EFFECT ); good_modifier( - this_good_effects.rgo_size, "rgo_size", FORMAT_x100_2DP_PC_POS, - memory::fmt::format("{}_RGO_SIZE", good) + this_good_effects.artisan_goods_throughput, + "artisan_goods_throughput", + FORMAT_x100_1DP_PC_POS, + make_production_localisation_suffix("TECH_THROUGHPUT"), + HAS_NO_EFFECT ); + good_modifier(this_good_effects.rgo_size, "rgo_size", FORMAT_x100_2DP_PC_POS, memory::fmt::format("{}_RGO_SIZE", good)); } return ret; diff --git a/src/openvic-simulation/economy/GoodDefinition.hpp b/src/openvic-simulation/economy/GoodDefinition.hpp index 80d48b0a8..0b297ab22 100644 --- a/src/openvic-simulation/economy/GoodDefinition.hpp +++ b/src/openvic-simulation/economy/GoodDefinition.hpp @@ -17,6 +17,7 @@ namespace OpenVic { private: memory::vector> SPAN_PROPERTY(good_definitions); + public: GoodCategory(std::string_view new_identifier, index_t new_index); GoodCategory(GoodCategory&&) = default; @@ -45,9 +46,15 @@ namespace OpenVic { const bool counters_overseas_penalty; GoodDefinition( - std::string_view new_identifier, colour_t new_colour, index_t new_index, GoodCategory const& new_category, - fixed_point_t new_base_price, bool new_is_available_from_start, bool new_is_tradeable, bool new_is_money, - bool new_counters_overseas_penalty + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + GoodCategory const& new_category, + fixed_point_t new_base_price, + bool new_is_available_from_start, + bool new_is_tradeable, + bool new_is_money, + bool new_counters_overseas_penalty ); GoodDefinition(GoodDefinition&&) = default; }; @@ -63,8 +70,14 @@ namespace OpenVic { bool add_good_category(std::string_view identifier, size_t expected_goods_in_category); bool add_good_definition( - std::string_view identifier, colour_t colour, GoodCategory& category, fixed_point_t base_price, - bool is_available_from_start, bool is_tradeable, bool is_money, bool has_overseas_penalty + std::string_view identifier, + colour_t colour, + GoodCategory& category, + fixed_point_t base_price, + bool is_available_from_start, + bool is_tradeable, + bool is_money, + bool has_overseas_penalty ); bool load_goods_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/economy/GoodInstance.cpp b/src/openvic-simulation/economy/GoodInstance.cpp index 34ab86a35..b84412838 100644 --- a/src/openvic-simulation/economy/GoodInstance.cpp +++ b/src/openvic-simulation/economy/GoodInstance.cpp @@ -6,24 +6,21 @@ using namespace OpenVic; -GoodInstance::GoodInstance( - GoodDefinition const* new_good_definition, - GameRulesManager const* new_game_rules_manager -) : HasIdentifierAndColour { *new_good_definition }, - HasIndex { new_good_definition->index }, - GoodMarket { *new_game_rules_manager, *new_good_definition } - {} +GoodInstance::GoodInstance(GoodDefinition const* new_good_definition, GameRulesManager const* new_game_rules_manager) : + HasIdentifierAndColour { *new_good_definition }, HasIndex { new_good_definition->index }, + GoodMarket { *new_game_rules_manager, *new_good_definition } {} GoodInstanceManager::GoodInstanceManager( - GoodDefinitionManager const& new_good_definition_manager, - GameRulesManager const& game_rules_manager -) : good_definition_manager { new_good_definition_manager }, - good_instance_by_definition { - new_good_definition_manager.get_good_definitions(), - [game_rules_manager_ptr=&game_rules_manager](GoodDefinition const& good_definition) -> auto { - return std::make_tuple(&good_definition, game_rules_manager_ptr); - } - } { assert(new_good_definition_manager.good_definitions_are_locked()); } + GoodDefinitionManager const& new_good_definition_manager, GameRulesManager const& game_rules_manager +) : + good_definition_manager { new_good_definition_manager }, good_instance_by_definition { + new_good_definition_manager.get_good_definitions(), + [game_rules_manager_ptr = &game_rules_manager](GoodDefinition const& good_definition) -> auto { + return std::make_tuple(&good_definition, game_rules_manager_ptr); + } + } { + assert(new_good_definition_manager.good_definitions_are_locked()); +} bool GoodInstance::is_trading_good() const { return is_available && !good_definition.is_money; @@ -31,25 +28,17 @@ bool GoodInstance::is_trading_good() const { GoodInstance* GoodInstanceManager::get_good_instance_by_identifier(std::string_view identifier) { GoodDefinition const* good_definition = good_definition_manager.get_good_definition_by_identifier(identifier); - return good_definition == nullptr - ? nullptr - : &get_good_instance_by_definition(*good_definition); + return good_definition == nullptr ? nullptr : &get_good_instance_by_definition(*good_definition); } GoodInstance const* GoodInstanceManager::get_good_instance_by_identifier(std::string_view identifier) const { GoodDefinition const* good_definition = good_definition_manager.get_good_definition_by_identifier(identifier); - return good_definition == nullptr - ? nullptr - : &get_good_instance_by_definition(*good_definition); + return good_definition == nullptr ? nullptr : &get_good_instance_by_definition(*good_definition); } GoodInstance* GoodInstanceManager::get_good_instance_by_index(typename GoodInstance::index_t index) { - return good_instance_by_definition.contains_index(index) - ? &good_instance_by_definition.at_index(index) - : nullptr; + return good_instance_by_definition.contains_index(index) ? &good_instance_by_definition.at_index(index) : nullptr; } GoodInstance const* GoodInstanceManager::get_good_instance_by_index(typename GoodInstance::index_t index) const { - return good_instance_by_definition.contains_index(index) - ? &good_instance_by_definition.at_index(index) - : nullptr; + return good_instance_by_definition.contains_index(index) ? &good_instance_by_definition.at_index(index) : nullptr; } GoodInstance& GoodInstanceManager::get_good_instance_by_definition(GoodDefinition const& good_definition) { return good_instance_by_definition.at(good_definition); diff --git a/src/openvic-simulation/economy/GoodInstance.hpp b/src/openvic-simulation/economy/GoodInstance.hpp index b51194321..ac49706ec 100644 --- a/src/openvic-simulation/economy/GoodInstance.hpp +++ b/src/openvic-simulation/economy/GoodInstance.hpp @@ -1,8 +1,8 @@ #pragma once #include "openvic-simulation/economy/trading/GoodMarket.hpp" -#include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" +#include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/TypedIndices.hpp" @@ -15,11 +15,8 @@ namespace OpenVic { friend struct GoodInstanceManager; public: - //pointers instead of references to allow construction via std::tuple - GoodInstance( - GoodDefinition const* new_good_definition, - GameRulesManager const* new_game_rules_manager - ); + // pointers instead of references to allow construction via std::tuple + GoodInstance(GoodDefinition const* new_good_definition, GameRulesManager const* new_game_rules_manager); GoodInstance(GoodInstance const&) = delete; GoodInstance& operator=(GoodInstance const&) = delete; GoodInstance(GoodInstance&&) = delete; @@ -37,8 +34,7 @@ namespace OpenVic { public: GoodInstanceManager( - GoodDefinitionManager const& new_good_definition_manager, - GameRulesManager const& game_rules_manager + GoodDefinitionManager const& new_good_definition_manager, GameRulesManager const& game_rules_manager ); constexpr forwardable_span get_good_instances() { diff --git a/src/openvic-simulation/economy/production/ArtisanalProducer.cpp b/src/openvic-simulation/economy/production/ArtisanalProducer.cpp index dff574119..92c596371 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducer.cpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducer.cpp @@ -5,11 +5,11 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/random/RandomGenerator.hpp" #include "openvic-simulation/core/random/WeightedSampling.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/defines/EconomyDefines.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" @@ -26,29 +26,28 @@ using namespace OpenVic; -ArtisanalProducer::ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps) : ArtisanalProducer( - artisanal_producer_deps, - IndexedFlatMap { artisanal_producer_deps.good_keys }, - nullptr, - nullptr, - fixed_point_t::_0 -) { }; +ArtisanalProducer::ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps) : + ArtisanalProducer( + artisanal_producer_deps, + IndexedFlatMap { artisanal_producer_deps.good_keys }, + nullptr, + nullptr, + fixed_point_t::_0 + ) {}; ArtisanalProducer::ArtisanalProducer( - ArtisanalProducerDeps const& artisanal_producer_deps, - IndexedFlatMap&& new_stockpile, - ProductionType const* const new_production_type, - GoodDefinition const* const new_last_produced_good, - fixed_point_t new_current_production -) : economy_defines { artisanal_producer_deps.economy_defines }, - modifier_effect_cache { artisanal_producer_deps.modifier_effect_cache }, - stockpile { std::move(new_stockpile) }, - production_type_nullable { nullptr }, - last_produced_good { new_last_produced_good }, - current_production { new_current_production } - { - set_production_type(new_production_type); - } + ArtisanalProducerDeps const& artisanal_producer_deps, + IndexedFlatMap&& new_stockpile, + ProductionType const* const new_production_type, + GoodDefinition const* const new_last_produced_good, + fixed_point_t new_current_production +) : + economy_defines { artisanal_producer_deps.economy_defines }, + modifier_effect_cache { artisanal_producer_deps.modifier_effect_cache }, stockpile { std::move(new_stockpile) }, + production_type_nullable { nullptr }, last_produced_good { new_last_produced_good }, + current_production { new_current_production } { + set_production_type(new_production_type); +} void ArtisanalProducer::set_production_type(ProductionType const* const new_production_type) { if (production_type_nullable == new_production_type) { @@ -66,17 +65,17 @@ void ArtisanalProducer::set_production_type(ProductionType const* const new_prod } void ArtisanalProducer::artisan_tick_handler::calculate_inputs( - IndexedFlatMap const& stockpile, - const bool should_report_input_demand + IndexedFlatMap const& stockpile, const bool should_report_input_demand ) { fixed_point_map_t const& input_goods = production_type.input_goods; - //throughput scalar, the minimum of stockpile / base_desired_quantity - //inputs_bought_fraction uses base_desired_quantity as population size is cancelled in the production and input calculations. + // throughput scalar, the minimum of stockpile / base_desired_quantity + // inputs_bought_fraction uses base_desired_quantity as population size is cancelled in the production and input + // calculations. const pop_size_t pop_size = pop.get_size(); fixed_point_t inputs_bought_numerator = type_safe::get(pop_size), - inputs_bought_denominator = type_safe::get(production_type.base_workforce_size), - inputs_bought_fraction_v = inputs_bought_numerator / inputs_bought_denominator; + inputs_bought_denominator = type_safe::get(production_type.base_workforce_size), + inputs_bought_fraction_v = inputs_bought_numerator / inputs_bought_denominator; distinct_goods_to_buy = 0; std::fill(wants_more_mask.begin(), wants_more_mask.end(), false); @@ -85,17 +84,14 @@ void ArtisanalProducer::artisan_tick_handler::calculate_inputs( GoodDefinition const& input_good = *it.key(); const fixed_point_t base_desired_quantity = it.value(); const ptrdiff_t i = it - input_goods.begin(); - const fixed_point_t desired_quantity = demand_per_input[i] = base_desired_quantity * pop_size / production_type.base_workforce_size; + const fixed_point_t desired_quantity = demand_per_input[i] = + base_desired_quantity * pop_size / production_type.base_workforce_size; if (desired_quantity == 0) { continue; } if (should_report_input_demand && country_to_report_economy_nullable != nullptr) { - country_to_report_economy_nullable->report_input_demand( - production_type, - input_good.index, - desired_quantity - ); + country_to_report_economy_nullable->report_input_demand(production_type, input_good.index, desired_quantity); } const fixed_point_t stockpiled_quantity = stockpile.at(input_good); @@ -111,16 +107,13 @@ void ArtisanalProducer::artisan_tick_handler::calculate_inputs( distinct_goods_to_buy++; } - inputs_bought_fraction = Fraction { - inputs_bought_numerator, - inputs_bought_denominator - }; + inputs_bought_fraction = Fraction { inputs_bought_numerator, inputs_bought_denominator }; } void ArtisanalProducer::artisan_tick_handler::produce( - fixed_point_t& costs_of_production, - fixed_point_t& current_production, - IndexedFlatMap& stockpile + fixed_point_t& costs_of_production, + fixed_point_t& current_production, + IndexedFlatMap& stockpile ) { fixed_point_t produce_left_to_sell = current_production = production_type.base_output_quantity * inputs_bought_fraction; @@ -140,16 +133,12 @@ void ArtisanalProducer::artisan_tick_handler::produce( const ptrdiff_t i = it - input_goods.begin(); fixed_point_t& good_stockpile = stockpile.at(input_good); - //Consume input good + // Consume input good fixed_point_t consumed_quantity = base_desired_quantity * inputs_bought_fraction; costs_of_production += consumed_quantity * market_instance.get_good_instance(input_good.index).get_price(); if (country_to_report_economy_nullable != nullptr) { - country_to_report_economy_nullable->report_input_consumption( - production_type, - input_good.index, - consumed_quantity - ); + country_to_report_economy_nullable->report_input_consumption(production_type, input_good.index, consumed_quantity); } if (input_good == production_type.output_good) { @@ -162,10 +151,7 @@ void ArtisanalProducer::artisan_tick_handler::produce( } } - good_stockpile = std::max( - fixed_point_t::_0, - good_stockpile - consumed_quantity - ); + good_stockpile = std::max(fixed_point_t::_0, good_stockpile - consumed_quantity); if (good_stockpile >= demand_per_input[i]) { wants_more_mask[input_good.index] = false; @@ -177,22 +163,22 @@ void ArtisanalProducer::artisan_tick_handler::produce( } void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( - fixed_point_map_t& max_quantity_to_buy_per_good, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - IndexedFlatMap const& stockpile, - PopValuesFromProvince const& values_from_province + fixed_point_map_t& max_quantity_to_buy_per_good, + memory::vector& pop_max_quantity_to_buy_per_good, + memory::vector& pop_money_to_spend_per_good, + IndexedFlatMap const& stockpile, + PopValuesFromProvince const& values_from_province ) { - //executed once per pop while nothing else uses it. - const fixed_point_t total_cash_to_spend = pop.get_cash().get_copy_of_value() / values_from_province.get_max_cost_multiplier(); + // executed once per pop while nothing else uses it. + const fixed_point_t total_cash_to_spend = + pop.get_cash().get_copy_of_value() / values_from_province.get_max_cost_multiplier(); if (total_cash_to_spend <= 0 || distinct_goods_to_buy <= 0) { return; } - //Figure out the optimal amount of goods to buy based on their price, stockpiled quantity & demand - fixed_point_t max_possible_satisfaction_numerator= 1, - max_possible_satisfaction_denominator= 1; + // Figure out the optimal amount of goods to buy based on their price, stockpiled quantity & demand + fixed_point_t max_possible_satisfaction_numerator = 1, max_possible_satisfaction_denominator = 1; fixed_point_map_t const& input_goods = production_type.input_goods; bool at_or_below_optimum = false; @@ -211,11 +197,11 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( total_stockpile_value += max_price * stockpile.at(input_good); } - if ( total_demand_value == 0) { + if (total_demand_value == 0) { max_possible_satisfaction_numerator = 1; max_possible_satisfaction_denominator = 1; } else { - //epsilon is the minimum costs for a trade. + // epsilon is the minimum costs for a trade. const fixed_point_t flat_costs = fixed_point_t::epsilon * distinct_goods_to_buy; max_possible_satisfaction_numerator = total_stockpile_value + total_cash_to_spend - flat_costs; max_possible_satisfaction_denominator = total_demand_value + flat_costs; @@ -234,9 +220,7 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( const ptrdiff_t i = it - input_goods.begin(); const fixed_point_t optimal_quantity = fp::mul_div( - demand_per_input[i], - max_possible_satisfaction_numerator, - max_possible_satisfaction_denominator + demand_per_input[i], max_possible_satisfaction_numerator, max_possible_satisfaction_denominator ); const fixed_point_t stockpiled_quantity = stockpile.at(input_good); @@ -249,7 +233,7 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( } fixed_point_t debug_cash_left = total_cash_to_spend; - //Place buy orders for each input + // Place buy orders for each input for (auto it = input_goods.begin(); it < input_goods.end(); it++) { GoodDefinition const& input_good = *it.key(); if (!wants_more_mask[input_good.index]) { @@ -262,13 +246,10 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( const fixed_point_t max_quantity_to_buy = good_demand - stockpiled_quantity; if (max_quantity_to_buy > 0) { const fixed_point_t optimal_quantity = fp::mul_div( - good_demand, - max_possible_satisfaction_numerator, - max_possible_satisfaction_denominator + good_demand, max_possible_satisfaction_numerator, max_possible_satisfaction_denominator ); const fixed_point_t money_to_spend = market_instance.get_max_money_to_allocate_to_buy_quantity( - input_good.index, - optimal_quantity - stockpiled_quantity + input_good.index, optimal_quantity - stockpiled_quantity ); max_quantity_to_buy_per_good[&input_good] = max_quantity_to_buy; pop.allocate_cash_for_artisanal_spending(money_to_spend); @@ -285,16 +266,16 @@ void ArtisanalProducer::artisan_tick_handler::allocate_money_for_inputs( } void ArtisanalProducer::artisan_tick( - MarketInstance const& market_instance, - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - memory::vector& reusable_map_0, - memory::vector& reusable_map_1, - fixed_point_map_t& goods_to_sell + MarketInstance const& market_instance, + Pop& pop, + PopValuesFromProvince const& values_from_province, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + memory::vector& pop_max_quantity_to_buy_per_good, + memory::vector& pop_money_to_spend_per_good, + memory::vector& reusable_map_0, + memory::vector& reusable_map_1, + fixed_point_map_t& goods_to_sell ) { CountryInstance* const country_to_report_economy_nullable = pop.get_location().get_country_to_report_economy(); max_quantity_to_buy_per_good.clear(); @@ -317,13 +298,9 @@ void ArtisanalProducer::artisan_tick( } } - ProductionType const* new_production_type_ptr = pick_production_type( - pop, - values_from_province, - random_number_generator - ); + ProductionType const* new_production_type_ptr = pick_production_type(pop, values_from_province, random_number_generator); - //if there is no valid production type, keep doing what we were doing, like in Vic2. + // if there is no valid production type, keep doing what we were doing, like in Vic2. if (new_production_type_ptr == nullptr) { new_production_type_ptr = old_production_type_ptr; } @@ -350,11 +327,11 @@ void ArtisanalProducer::artisan_tick( last_produced_good = &old_production_type.output_good; if (old_production_type_ptr == new_production_type_ptr) { tick_handler.allocate_money_for_inputs( - max_quantity_to_buy_per_good, - pop_max_quantity_to_buy_per_good, - pop_money_to_spend_per_good, - stockpile, - values_from_province + max_quantity_to_buy_per_good, + pop_max_quantity_to_buy_per_good, + pop_money_to_spend_per_good, + stockpile, + values_from_province ); } } @@ -380,11 +357,11 @@ void ArtisanalProducer::artisan_tick( constexpr bool should_report_input_demand = true; tick_handler.calculate_inputs(stockpile, should_report_input_demand); tick_handler.allocate_money_for_inputs( - max_quantity_to_buy_per_good, - pop_max_quantity_to_buy_per_good, - pop_money_to_spend_per_good, - stockpile, - values_from_province + max_quantity_to_buy_per_good, + pop_max_quantity_to_buy_per_good, + pop_money_to_spend_per_good, + stockpile, + values_from_province ); } @@ -403,10 +380,7 @@ void ArtisanalProducer::artisan_tick( fixed_point_t ArtisanalProducer::add_to_stockpile(const good_index_t good_index, const fixed_point_t quantity) { if (OV_unlikely(quantity < 0)) { - spdlog::error_s( - "Attempted to add negative quantity {} of {} to artisan stockpile.", - quantity, good_index - ); + spdlog::error_s("Attempted to add negative quantity {} of {} to artisan stockpile.", quantity, good_index); return 0; } @@ -425,18 +399,17 @@ fixed_point_t ArtisanalProducer::add_to_stockpile(const good_index_t good_index, void ArtisanalProducer::subtract_from_stockpile(const good_index_t good_index, const fixed_point_t sold_quantity) { if (OV_unlikely(sold_quantity < 0)) { - spdlog::error_s( - "Attempted to subtract negative quantity {} of {} to artisan stockpile.", - sold_quantity, good_index - ); + spdlog::error_s("Attempted to subtract negative quantity {} of {} to artisan stockpile.", sold_quantity, good_index); return; } fixed_point_t& stockpiled_quantity = stockpile.at_index(good_index); if (OV_unlikely(stockpiled_quantity < sold_quantity)) { spdlog::error_s( - "Attempted to subtract more {} of {} from artisan stockpile than it has {}.", - sold_quantity, good_index, stockpiled_quantity + "Attempted to subtract more {} of {} from artisan stockpile than it has {}.", + sold_quantity, + good_index, + stockpiled_quantity ); stockpiled_quantity = 0; @@ -447,10 +420,10 @@ void ArtisanalProducer::subtract_from_stockpile(const good_index_t good_index, c } std::optional ArtisanalProducer::estimate_production_type_score( - GoodInstanceManager const& good_instance_manager, - ProductionType const& production_type, - ProvinceInstance& location, - const fixed_point_t max_cost_multiplier + GoodInstanceManager const& good_instance_manager, + ProductionType const& production_type, + ProvinceInstance& location, + const fixed_point_t max_cost_multiplier ) { if (production_type.template_type != ProductionType::template_type_t::ARTISAN) { return std::nullopt; @@ -472,42 +445,30 @@ std::optional ArtisanalProducer::estimate_production_type_score( estimated_costs *= max_cost_multiplier; const fixed_point_t estimated_revenue = production_type.base_output_quantity * output_good.get_price(); - return calculate_production_type_score( - estimated_revenue, - estimated_costs, - production_type.base_workforce_size - ); + return calculate_production_type_score(estimated_revenue, estimated_costs, production_type.base_workforce_size); } fixed_point_t ArtisanalProducer::calculate_production_type_score( - const fixed_point_t revenue, - const fixed_point_t costs, - const pop_size_t workforce + const fixed_point_t revenue, const fixed_point_t costs, const pop_size_t workforce ) { if (costs >= revenue) { return 0; } - //the score penalty at 0 margin + // the score penalty at 0 margin constexpr fixed_point_t k = fixed_point_t::_0_50; static_assert(0 <= k); static_assert(k <= 1); return fp::mul_div( - ( - k * fp::mul_div(costs, costs, revenue) - -(1+k)*costs - + revenue - ), - Pop::size_denominator, - workforce - ); //factor out pop size without making values too small + (k * fp::mul_div(costs, costs, revenue) - (1 + k) * costs + revenue), + Pop::size_denominator, + workforce + ); // factor out pop size without making values too small } ProductionType const* ArtisanalProducer::pick_production_type( - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator + Pop& pop, PopValuesFromProvince const& values_from_province, RandomU32& random_number_generator ) const { bool should_pick_new_production_type; const auto ranked_artisanal_production_types = values_from_province.get_ranked_artisanal_production_types(); @@ -522,11 +483,7 @@ ProductionType const* ArtisanalProducer::pick_production_type( if (production_type_nullable == nullptr || (revenue <= costs)) { should_pick_new_production_type = true; } else if (base_chance_to_switch_while_profitable > 0) { - const fixed_point_t current_score = calculate_production_type_score( - revenue, - costs, - pop.get_size() - ); + const fixed_point_t current_score = calculate_production_type_score(revenue, costs, pop.get_size()); fixed_point_t relative_score = ranked_artisanal_production_types.empty() ? fixed_point_t::_1 : fixed_point_t::_0; assert(ranked_artisanal_production_types.size() < std::numeric_limits::max()); @@ -537,25 +494,23 @@ ProductionType const* ArtisanalProducer::pick_production_type( if (i == 0) { relative_score = fixed_point_t::_1; } else { - const fixed_point_t previous_score_estimate = ranked_artisanal_production_types[i-1].second; - relative_score = ( - (current_score - score_estimate) - / (previous_score_estimate - score_estimate) - + static_cast(ranked_artisanal_production_types.size() - i) - ) / static_cast(1 + ranked_artisanal_production_types.size()); + const fixed_point_t previous_score_estimate = ranked_artisanal_production_types[i - 1].second; + relative_score = ((current_score - score_estimate) / (previous_score_estimate - score_estimate) + + static_cast(ranked_artisanal_production_types.size() - i)) / + static_cast(1 + ranked_artisanal_production_types.size()); } break; } if (current_score == score_estimate) { - relative_score = fixed_point_t(static_cast(ranked_artisanal_production_types.size() - i)) - / static_cast(1 + ranked_artisanal_production_types.size()); + relative_score = fixed_point_t(static_cast(ranked_artisanal_production_types.size() - i)) / + static_cast(1 + ranked_artisanal_production_types.size()); } } - //picked so the line hits 0 at relative_score = 2/3 and the area under the curve equals 1 - //2/3 was picked as being in the top 1/3 of production types makes it very unlikely you'll profit from switching. - constexpr fixed_point_t slope = fixed_point_t{-9} / 2; + // picked so the line hits 0 at relative_score = 2/3 and the area under the curve equals 1 + // 2/3 was picked as being in the top 1/3 of production types makes it very unlikely you'll profit from switching. + constexpr fixed_point_t slope = fixed_point_t { -9 } / 2; constexpr fixed_point_t offset = 3; const fixed_point_t change_modifier_from_relative_score = std::max(fixed_point_t::_0, slope * relative_score + offset); @@ -566,11 +521,7 @@ ProductionType const* ArtisanalProducer::pick_production_type( constexpr fixed_point_t weights_sum = 1; const fixed_point_t keep_current_chance = weights_sum - switch_chance; const std::array weights { keep_current_chance, switch_chance }; - const size_t should_switch = sample_weighted_index( - random_number_generator(), - weights, - weights_sum - ); + const size_t should_switch = sample_weighted_index(random_number_generator(), weights, weights_sum); should_pick_new_production_type = should_switch == 1; } } @@ -583,17 +534,13 @@ ProductionType const* ArtisanalProducer::pick_production_type( memory::vector weights {}; weights.reserve(ranked_artisanal_production_types.size()); for (auto const& [production_type, score_estimate] : ranked_artisanal_production_types) { - //TODO calculate actual scores including availability of goods + // TODO calculate actual scores including availability of goods const fixed_point_t weight = score_estimate * score_estimate; weights.push_back(weight); weights_sum += weight; } - const size_t sample_index = sample_weighted_index( - random_number_generator(), - weights, - weights_sum - ); + const size_t sample_index = sample_weighted_index(random_number_generator(), weights, weights_sum); assert(sample_index >= 0 && sample_index < ranked_artisanal_production_types.size()); return ranked_artisanal_production_types[sample_index].first; diff --git a/src/openvic-simulation/economy/production/ArtisanalProducer.hpp b/src/openvic-simulation/economy/production/ArtisanalProducer.hpp index 12e6ed9b2..a5bbf359e 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducer.hpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducer.hpp @@ -4,12 +4,12 @@ #include #include "openvic-simulation/core/memory/Vector.hpp" -#include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Fraction.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" +#include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -33,7 +33,7 @@ namespace OpenVic { ModifierEffectCache const& modifier_effect_cache; IndexedFlatMap stockpile; - //only used during day tick (from artisan_tick() until MarketInstance.execute_orders()) + // only used during day tick (from artisan_tick() until MarketInstance.execute_orders()) fixed_point_map_t max_quantity_to_buy_per_good; ProductionType const* PROPERTY(production_type_nullable); @@ -43,53 +43,49 @@ namespace OpenVic { void set_production_type(ProductionType const* const new_production_type); ProductionType const* pick_production_type( - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator + Pop& pop, PopValuesFromProvince const& values_from_province, RandomU32& random_number_generator ) const; static fixed_point_t calculate_production_type_score( - const fixed_point_t revenue, - const fixed_point_t costs, - const pop_size_t workforce + const fixed_point_t revenue, const fixed_point_t costs, const pop_size_t workforce ); public: ArtisanalProducer(ArtisanalProducerDeps const& artisanal_producer_deps); ArtisanalProducer( - ArtisanalProducerDeps const& artisanal_producer_deps, - IndexedFlatMap&& new_stockpile, - ProductionType const* const new_production_type, - GoodDefinition const* const new_last_produced_good, - const fixed_point_t new_current_production + ArtisanalProducerDeps const& artisanal_producer_deps, + IndexedFlatMap&& new_stockpile, + ProductionType const* const new_production_type, + GoodDefinition const* const new_last_produced_good, + const fixed_point_t new_current_production ); void artisan_tick( - MarketInstance const& market_instance, - Pop& pop, - PopValuesFromProvince const& values_from_province, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - memory::vector& reusable_map_0, - memory::vector& reusable_map_1, - fixed_point_map_t& goods_to_sell + MarketInstance const& market_instance, + Pop& pop, + PopValuesFromProvince const& values_from_province, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + memory::vector& pop_max_quantity_to_buy_per_good, + memory::vector& pop_money_to_spend_per_good, + memory::vector& reusable_map_0, + memory::vector& reusable_map_1, + fixed_point_map_t& goods_to_sell ); - //thread safe if called once per good and stockpile already has an entry. - //adds to stockpile up to max_quantity_to_buy and returns quantity added to stockpile + // thread safe if called once per good and stockpile already has an entry. + // adds to stockpile up to max_quantity_to_buy and returns quantity added to stockpile fixed_point_t add_to_stockpile(const good_index_t good_index, const fixed_point_t quantity); void subtract_from_stockpile(const good_index_t good_index, const fixed_point_t sold_quantity); - //optional to handle invalid + // optional to handle invalid static std::optional estimate_production_type_score( - GoodInstanceManager const& good_instance_manager, - ProductionType const& production_type, - ProvinceInstance& location, - const fixed_point_t max_cost_multiplier + GoodInstanceManager const& good_instance_manager, + ProductionType const& production_type, + ProvinceInstance& location, + const fixed_point_t max_cost_multiplier ); - + private: struct artisan_tick_handler { private: @@ -105,36 +101,33 @@ namespace OpenVic { public: artisan_tick_handler( - CountryInstance* const new_country_to_report_economy_nullable, - memory::vector& new_demand_per_input, - MarketInstance const& new_market_instance, - memory::vector& new_max_price_per_input, - Pop& new_pop, - ProductionType const& new_production_type, - TypedSpan new_wants_more_mask - ) : country_to_report_economy_nullable { new_country_to_report_economy_nullable }, - demand_per_input { new_demand_per_input }, - market_instance { new_market_instance }, - max_price_per_input { new_max_price_per_input }, - pop { new_pop }, - production_type { new_production_type }, - wants_more_mask { new_wants_more_mask } {} + CountryInstance* const new_country_to_report_economy_nullable, + memory::vector& new_demand_per_input, + MarketInstance const& new_market_instance, + memory::vector& new_max_price_per_input, + Pop& new_pop, + ProductionType const& new_production_type, + TypedSpan new_wants_more_mask + ) : + country_to_report_economy_nullable { new_country_to_report_economy_nullable }, + demand_per_input { new_demand_per_input }, market_instance { new_market_instance }, + max_price_per_input { new_max_price_per_input }, pop { new_pop }, production_type { new_production_type }, + wants_more_mask { new_wants_more_mask } {} void calculate_inputs( - IndexedFlatMap const& stockpile, - const bool should_report_input_demand + IndexedFlatMap const& stockpile, const bool should_report_input_demand ); void produce( - fixed_point_t& costs_of_production, - fixed_point_t& current_production, - IndexedFlatMap& stockpile + fixed_point_t& costs_of_production, + fixed_point_t& current_production, + IndexedFlatMap& stockpile ); void allocate_money_for_inputs( - fixed_point_map_t& max_quantity_to_buy_per_good, - memory::vector& pop_max_quantity_to_buy_per_good, - memory::vector& pop_money_to_spend_per_good, - IndexedFlatMap const& stockpile, - PopValuesFromProvince const& values_from_province + fixed_point_map_t& max_quantity_to_buy_per_good, + memory::vector& pop_max_quantity_to_buy_per_good, + memory::vector& pop_money_to_spend_per_good, + IndexedFlatMap const& stockpile, + PopValuesFromProvince const& values_from_province ); }; }; diff --git a/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp b/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp index e949c7513..2780d5d49 100644 --- a/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp +++ b/src/openvic-simulation/economy/production/ArtisanalProducerDeps.hpp @@ -12,4 +12,4 @@ namespace OpenVic { forwardable_span good_keys; ModifierEffectCache const& modifier_effect_cache; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/Employee.cpp b/src/openvic-simulation/economy/production/Employee.cpp index 5568563ad..71d5300d8 100644 --- a/src/openvic-simulation/economy/production/Employee.cpp +++ b/src/openvic-simulation/economy/production/Employee.cpp @@ -5,12 +5,9 @@ using namespace OpenVic; -Employee::Employee(Pop& new_pop, const pop_size_t new_size) - : pop { new_pop }, - size { new_size } - {} +Employee::Employee(Pop& new_pop, const pop_size_t new_size) : pop { new_pop }, size { new_size } {} fixed_point_t Employee::update_minimum_wage(CountryInstance& country_to_report_economy) { const fixed_point_t minimum_wage_base = country_to_report_economy.calculate_minimum_wage_base(pop.get_type()); return minimum_wage_cached = minimum_wage_base * size / Pop::size_denominator; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/Employee.hpp b/src/openvic-simulation/economy/production/Employee.hpp index 084d7ed30..c1850a2fb 100644 --- a/src/openvic-simulation/economy/production/Employee.hpp +++ b/src/openvic-simulation/economy/production/Employee.hpp @@ -13,8 +13,9 @@ namespace OpenVic { Pop& PROPERTY_MOD(pop); pop_size_t PROPERTY_RW(size); fixed_point_t PROPERTY_RW(minimum_wage_cached); + public: Employee(Pop& new_pop, const pop_size_t new_size); fixed_point_t update_minimum_wage(CountryInstance& country_to_report_economy); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/FactoryProducer.cpp b/src/openvic-simulation/economy/production/FactoryProducer.cpp index 333f67a9e..dcc4fa112 100644 --- a/src/openvic-simulation/economy/production/FactoryProducer.cpp +++ b/src/openvic-simulation/economy/production/FactoryProducer.cpp @@ -3,45 +3,37 @@ using namespace OpenVic; FactoryProducer::FactoryProducer( - ProductionType const& new_production_type, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - ordered_map&& new_employees, - fixed_point_map_t&& new_stockpile, - fixed_point_t new_budget, - fixed_point_t new_balance_yesterday, - fixed_point_t new_received_investments_yesterday, - fixed_point_t new_market_spendings_yesterday, - fixed_point_t new_paychecks_yesterday, - uint32_t new_unprofitable_days, - uint32_t new_subsidised_days, - uint32_t new_days_without_input, - uint8_t new_hiring_priority, - uint8_t new_profit_history_current, - daily_profit_history_t&& new_daily_profit_history -) : production_type { new_production_type }, - size_multiplier { new_size_multiplier }, - revenue_yesterday { new_revenue_yesterday }, - output_quantity_yesterday { new_output_quantity_yesterday }, - unsold_quantity_yesterday { new_unsold_quantity_yesterday }, - employees { std::move(new_employees) }, - stockpile { std::move(new_stockpile) }, - budget { new_budget }, - balance_yesterday { new_balance_yesterday }, - received_investments_yesterday { new_received_investments_yesterday }, - market_spendings_yesterday { new_market_spendings_yesterday }, - paychecks_yesterday { new_paychecks_yesterday }, - unprofitable_days { new_unprofitable_days }, - subsidised_days { new_subsidised_days }, - days_without_input { new_days_without_input }, - hiring_priority { new_hiring_priority }, - profit_history_current { new_profit_history_current }, - daily_profit_history { std::move(new_daily_profit_history) } {} + ProductionType const& new_production_type, + fixed_point_t new_size_multiplier, + fixed_point_t new_revenue_yesterday, + fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, + ordered_map&& new_employees, + fixed_point_map_t&& new_stockpile, + fixed_point_t new_budget, + fixed_point_t new_balance_yesterday, + fixed_point_t new_received_investments_yesterday, + fixed_point_t new_market_spendings_yesterday, + fixed_point_t new_paychecks_yesterday, + uint32_t new_unprofitable_days, + uint32_t new_subsidised_days, + uint32_t new_days_without_input, + uint8_t new_hiring_priority, + uint8_t new_profit_history_current, + daily_profit_history_t&& new_daily_profit_history +) : + production_type { new_production_type }, size_multiplier { new_size_multiplier }, + revenue_yesterday { new_revenue_yesterday }, output_quantity_yesterday { new_output_quantity_yesterday }, + unsold_quantity_yesterday { new_unsold_quantity_yesterday }, employees { std::move(new_employees) }, + stockpile { std::move(new_stockpile) }, budget { new_budget }, balance_yesterday { new_balance_yesterday }, + received_investments_yesterday { new_received_investments_yesterday }, + market_spendings_yesterday { new_market_spendings_yesterday }, paychecks_yesterday { new_paychecks_yesterday }, + unprofitable_days { new_unprofitable_days }, subsidised_days { new_subsidised_days }, + days_without_input { new_days_without_input }, hiring_priority { new_hiring_priority }, + profit_history_current { new_profit_history_current }, daily_profit_history { std::move(new_daily_profit_history) } {} -FactoryProducer::FactoryProducer(ProductionType const& new_production_type, fixed_point_t new_size_multiplier) - : FactoryProducer { new_production_type, new_size_multiplier, 0, 0, 0, {}, {}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {} } {} +FactoryProducer::FactoryProducer(ProductionType const& new_production_type, fixed_point_t new_size_multiplier) : + FactoryProducer { new_production_type, new_size_multiplier, 0, 0, 0, {}, {}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {} } {} fixed_point_t FactoryProducer::get_profitability_yesterday() const { return daily_profit_history[profit_history_current]; diff --git a/src/openvic-simulation/economy/production/FactoryProducer.hpp b/src/openvic-simulation/economy/production/FactoryProducer.hpp index 677316506..9fe5539eb 100644 --- a/src/openvic-simulation/economy/production/FactoryProducer.hpp +++ b/src/openvic-simulation/economy/production/FactoryProducer.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/core/object/FixedPoint.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/population/PopSize.hpp" +#include "openvic-simulation/types/OrderedContainers.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -40,13 +40,24 @@ namespace OpenVic { ProductionType const& production_type; FactoryProducer( - ProductionType const& new_production_type, fixed_point_t new_size_multiplier, fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, fixed_point_t new_unsold_quantity_yesterday, - ordered_map&& new_employees, fixed_point_map_t&& new_stockpile, - fixed_point_t new_budget, fixed_point_t new_balance_yesterday, fixed_point_t new_received_investments_yesterday, - fixed_point_t new_market_spendings_yesterday, fixed_point_t new_paychecks_yesterday, uint32_t new_unprofitable_days, - uint32_t new_subsidised_days, uint32_t new_days_without_input, uint8_t new_hiring_priority, - uint8_t new_profit_history_current, daily_profit_history_t&& new_daily_profit_history + ProductionType const& new_production_type, + fixed_point_t new_size_multiplier, + fixed_point_t new_revenue_yesterday, + fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, + ordered_map&& new_employees, + fixed_point_map_t&& new_stockpile, + fixed_point_t new_budget, + fixed_point_t new_balance_yesterday, + fixed_point_t new_received_investments_yesterday, + fixed_point_t new_market_spendings_yesterday, + fixed_point_t new_paychecks_yesterday, + uint32_t new_unprofitable_days, + uint32_t new_subsidised_days, + uint32_t new_days_without_input, + uint8_t new_hiring_priority, + uint8_t new_profit_history_current, + daily_profit_history_t&& new_daily_profit_history ); FactoryProducer(ProductionType const& new_production_type, fixed_point_t new_size_multiplier); diff --git a/src/openvic-simulation/economy/production/ProductionType.cpp b/src/openvic-simulation/economy/production/ProductionType.cpp index b9a57f14e..271716cb3 100644 --- a/src/openvic-simulation/economy/production/ProductionType.cpp +++ b/src/openvic-simulation/economy/production/ProductionType.cpp @@ -15,34 +15,27 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; ProductionType::ProductionType( - GameRulesManager const& new_game_rules_manager, - const std::string_view new_identifier, - std::optional&& new_owner, - memory::vector&& new_jobs, - const template_type_t new_template_type, - const pop_size_t new_base_workforce_size, - fixed_point_map_t&& new_input_goods, - GoodDefinition const& new_output_good, - const fixed_point_t new_base_output_quantity, - memory::vector&& new_bonuses, - fixed_point_map_t&& new_maintenance_requirements, - const bool new_is_coastal, - const bool new_is_farm, - const bool new_is_mine -) : HasIdentifier { new_identifier }, - game_rules_manager { new_game_rules_manager }, - owner { std::move(new_owner) }, - jobs { std::move(new_jobs) }, - template_type { new_template_type }, - base_workforce_size { new_base_workforce_size }, - input_goods { std::move(new_input_goods) }, - output_good { new_output_good }, - base_output_quantity { new_base_output_quantity }, - bonuses { std::move(new_bonuses) }, - maintenance_requirements { std::move(new_maintenance_requirements) }, - is_coastal { new_is_coastal }, - _is_farm { new_is_farm }, - _is_mine { new_is_mine } {} + GameRulesManager const& new_game_rules_manager, + const std::string_view new_identifier, + std::optional&& new_owner, + memory::vector&& new_jobs, + const template_type_t new_template_type, + const pop_size_t new_base_workforce_size, + fixed_point_map_t&& new_input_goods, + GoodDefinition const& new_output_good, + const fixed_point_t new_base_output_quantity, + memory::vector&& new_bonuses, + fixed_point_map_t&& new_maintenance_requirements, + const bool new_is_coastal, + const bool new_is_farm, + const bool new_is_mine +) : + HasIdentifier { new_identifier }, game_rules_manager { new_game_rules_manager }, owner { std::move(new_owner) }, + jobs { std::move(new_jobs) }, template_type { new_template_type }, base_workforce_size { new_base_workforce_size }, + input_goods { std::move(new_input_goods) }, output_good { new_output_good }, + base_output_quantity { new_base_output_quantity }, bonuses { std::move(new_bonuses) }, + maintenance_requirements { std::move(new_maintenance_requirements) }, is_coastal { new_is_coastal }, + _is_farm { new_is_farm }, _is_mine { new_is_mine } {} bool ProductionType::get_is_farm_for_tech() const { @@ -60,14 +53,14 @@ bool ProductionType::get_is_mine_for_non_tech() const { return !_is_farm; } -bool ProductionType::is_valid_for_artisan_in(ProvinceInstance& province) const{ +bool ProductionType::is_valid_for_artisan_in(ProvinceInstance& province) const { if (template_type != template_type_t::ARTISAN) { return false; } return !is_coastal || game_rules_manager.may_use_coastal_artisanal_production_types(province); } -bool ProductionType::is_valid_for_factory_in(State& state) const{ +bool ProductionType::is_valid_for_factory_in(State& state) const { if (template_type != template_type_t::FACTORY) { return false; } @@ -87,14 +80,9 @@ ProductionType const* ProductionTypeManager::get_good_to_rgo_production_type(Goo } node_callback_t ProductionTypeManager::_expect_job( - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - NodeTools::callback_t< - pop_type_index_t, - Job::effect_t, - fixed_point_t, - fixed_point_t - > emplace_callback + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + NodeTools::callback_t emplace_callback ) { return [this, &good_definition_manager, &pop_manager, emplace_callback](ast::NodeCPtr node) mutable -> bool { using enum Job::effect_t; @@ -107,59 +95,51 @@ node_callback_t ProductionTypeManager::_expect_job( { "input", INPUT }, { "output", OUTPUT }, { "throughput", THROUGHPUT } }; - if(!expect_dictionary_keys( - "poptype", ONE_EXACTLY, expect_identifier(assign_variable_callback(pop_type_identifier)), - "effect", ONE_EXACTLY, expect_identifier(expect_mapped_string(effect_map, assign_variable_callback(effect_type))), - "effect_multiplier", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(effect_multiplier)), - "amount", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(desired_workforce_share)) - )(node)) { + if (!expect_dictionary_keys("poptype", ONE_EXACTLY, expect_identifier(assign_variable_callback(pop_type_identifier)), "effect", ONE_EXACTLY, expect_identifier(expect_mapped_string(effect_map, assign_variable_callback(effect_type))), "effect_multiplier", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(effect_multiplier)), "amount", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(desired_workforce_share)))( + node + )) { return false; } PopType const* const found_pop_type = pop_manager.get_pop_type_by_identifier(pop_type_identifier); if (found_pop_type == nullptr) { return pop_type_identifier == "artisan" // Victoria 2 misconfiguration - ? true - : false; + ? true + : false; } return emplace_callback(found_pop_type->index, effect_type, effect_multiplier, desired_workforce_share); }; } node_callback_t ProductionTypeManager::_expect_job_list( - GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, - callback_t&&> callback + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + callback_t&&> callback ) { return [this, &good_definition_manager, &pop_manager, callback](ast::NodeCPtr node) mutable -> bool { memory::vector jobs; - bool ret = expect_list( - _expect_job( - good_definition_manager, - pop_manager, - vector_emplace_callback(jobs) - ) - )(node); + bool ret = expect_list(_expect_job(good_definition_manager, pop_manager, vector_emplace_callback(jobs)))(node); ret &= callback(std::move(jobs)); return ret; }; } bool ProductionTypeManager::add_production_type( - GameRulesManager const& game_rules_manager, - TypedSpan pop_types, - const std::string_view identifier, - std::optional&& owner_before_move, - memory::vector&& jobs, - const ProductionType::template_type_t template_type, - const pop_size_t base_workforce_size, - fixed_point_map_t&& input_goods, - GoodDefinition const* const output_good, - const fixed_point_t base_output_quantity, - memory::vector&& bonuses, - fixed_point_map_t&& maintenance_requirements, - const bool is_coastal, - const bool is_farm, - const bool is_mine + GameRulesManager const& game_rules_manager, + TypedSpan pop_types, + const std::string_view identifier, + std::optional&& owner_before_move, + memory::vector&& jobs, + const ProductionType::template_type_t template_type, + const pop_size_t base_workforce_size, + fixed_point_map_t&& input_goods, + GoodDefinition const* const output_good, + const fixed_point_t base_output_quantity, + memory::vector&& bonuses, + fixed_point_map_t&& maintenance_requirements, + const bool is_coastal, + const bool is_farm, + const bool is_mine ) { if (identifier.empty()) { spdlog::error_s("Invalid production type identifier - empty!"); @@ -185,16 +165,13 @@ bool ProductionTypeManager::add_production_type( if (template_type == ARTISAN) { if (owner_before_move.has_value()) { - spdlog::warn_s( - "Artisanal production type {} should not have an owner - it is being ignored.", identifier - ); + spdlog::warn_s("Artisanal production type {} should not have an owner - it is being ignored.", identifier); owner_before_move.reset(); } if (!jobs.empty()) { spdlog::warn_s( - "Artisanal production type {} should not have employees - {} are being ignored.", - identifier, jobs.size() + "Artisanal production type {} should not have employees - {} are being ignored.", identifier, jobs.size() ); jobs.clear(); } @@ -211,29 +188,35 @@ bool ProductionTypeManager::add_production_type( } const bool ret = production_types.emplace_item( - identifier, - game_rules_manager, identifier, std::move(owner_before_move), std::move(jobs), template_type, base_workforce_size, std::move(input_goods), *output_good, - base_output_quantity, std::move(bonuses), std::move(maintenance_requirements), is_coastal, is_farm, is_mine + identifier, + game_rules_manager, + identifier, + std::move(owner_before_move), + std::move(jobs), + template_type, + base_workforce_size, + std::move(input_goods), + *output_good, + base_output_quantity, + std::move(bonuses), + std::move(maintenance_requirements), + is_coastal, + is_farm, + is_mine ); if (ret && (template_type == RGO)) { ProductionType const& production_type = production_types.back(); ProductionType const*& current_rgo_pt = good_to_rgo_production_type.at(*output_good); - if (current_rgo_pt == nullptr || ( - (is_farm && !is_mine) - && (!current_rgo_pt->_is_farm || current_rgo_pt->_is_mine) - )) { + if (current_rgo_pt == nullptr || ((is_farm && !is_mine) && (!current_rgo_pt->_is_farm || current_rgo_pt->_is_mine))) { // pure farms are preferred over alternatives. Use first pt otherwise. current_rgo_pt = &get_back_production_type(); } - //else ignore, we already have an rgo pt + // else ignore, we already have an rgo pt std::optional const& owner_after_move = production_type.owner; - if (rgo_owner_sprite <= 0 - && template_type == RGO - && owner_after_move.has_value() - ) { + if (rgo_owner_sprite <= 0 && template_type == RGO && owner_after_move.has_value()) { /* Set rgo owner sprite to that of the first RGO owner we find. */ rgo_owner_sprite = pop_types[owner_after_move->pop_type_index].sprite; } @@ -243,10 +226,10 @@ bool ProductionTypeManager::add_production_type( } bool ProductionTypeManager::load_production_types_file( - GameRulesManager const& game_rules_manager, - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + ovdl::v2script::Parser const& parser ) { using namespace std::string_view_literals; auto template_symbol = parser.find_intern("template"sv); @@ -263,151 +246,170 @@ bool ProductionTypeManager::load_production_types_file( /* Pass #1: find and store template identifiers */ ordered_set templates; ordered_map template_target_map; - bool ret = expect_dictionary( - [this, &expected_types, &templates, &template_target_map, &template_symbol, &output_goods_symbol] - (std::string_view key, ast::NodeCPtr value) -> bool { - expected_types++; - - std::string_view template_id = ""; - bool has_found_template = false; - const bool is_parsing_template_success = expect_key( - template_symbol, - expect_identifier(assign_variable_callback(template_id)), - &has_found_template - )(value); - - if (has_found_template) { - OV_ERR_FAIL_COND_V_MSG( - !is_parsing_template_success, - false, - memory::fmt::format("Failed get template identifier for {}", key) - ); - templates.emplace(template_id); - template_target_map.emplace(key, template_id); - } else { - bool has_found_output_goods = false; - expect_key( - output_goods_symbol, - success_callback, - &has_found_output_goods - )(value); - if (!has_found_output_goods) { - //assume it's a template - templates.emplace(key); - } - } - - return true; - } - )(parser.get_file_node()); + bool ret = + expect_dictionary([this, &expected_types, &templates, &template_target_map, &template_symbol, &output_goods_symbol](std::string_view key, ast::NodeCPtr value) -> bool { + expected_types++; + + std::string_view template_id = ""; + bool has_found_template = false; + const bool is_parsing_template_success = + expect_key(template_symbol, expect_identifier(assign_variable_callback(template_id)), &has_found_template)( + value + ); + + if (has_found_template) { + OV_ERR_FAIL_COND_V_MSG( + !is_parsing_template_success, false, memory::fmt::format("Failed get template identifier for {}", key) + ); + templates.emplace(template_id); + template_target_map.emplace(key, template_id); + } else { + bool has_found_output_goods = false; + expect_key(output_goods_symbol, success_callback, &has_found_output_goods)(value); + if (!has_found_output_goods) { + // assume it's a template + templates.emplace(key); + } + } + + return true; + })(parser.get_file_node()); /* Pass #2: create and populate the template map */ ordered_map template_node_map; - ret &= expect_dictionary( - [this, &expected_types, &templates, &template_node_map](std::string_view key, ast::NodeCPtr value) -> bool { - if (templates.contains(key)) { - template_node_map.emplace(key, value); - expected_types--; - } - return true; - } - )(parser.get_file_node()); + ret &= + expect_dictionary([this, &expected_types, &templates, &template_node_map](std::string_view key, ast::NodeCPtr value) -> bool { + if (templates.contains(key)) { + template_node_map.emplace(key, value); + expected_types--; + } + return true; + })(parser.get_file_node()); /* Pass #3: actually load production types */ - good_to_rgo_production_type = std::move(decltype(good_to_rgo_production_type){good_definition_manager.get_good_definitions()}); + good_to_rgo_production_type = std::move( + decltype(good_to_rgo_production_type) { good_definition_manager.get_good_definitions() } + ); reserve_more_production_types(expected_types); - ret &= expect_dictionary( - [this, &game_rules_manager, &good_definition_manager, &pop_manager, &template_target_map, &template_node_map]( - std::string_view key, ast::NodeCPtr node) -> bool { - using enum ProductionType::template_type_t; - - if (template_node_map.contains(key)) { - return true; - } - - std::optional owner; - memory::vector jobs; - ProductionType::template_type_t template_type { FACTORY }; - GoodDefinition const* output_good = nullptr; - pop_size_t base_workforce_size = 0; - fixed_point_map_t input_goods, maintenance_requirements; - fixed_point_t base_output_quantity = 0; - memory::vector bonuses; - bool is_coastal = false, is_farm = false, is_mine = false; - - bool ret = true; - - static const string_map_t template_type_map = { - { "factory", FACTORY }, { "rgo", RGO }, { "artisan", ARTISAN } - }; - - auto parse_node = expect_dictionary_keys( - "template", ZERO_OR_ONE, success_callback, /* Already parsed using expect_key in Pass #1 above. */ - "bonus", ZERO_OR_MORE, [&bonuses](ast::NodeCPtr bonus_node) -> bool { - using enum scope_type_t; - - ConditionScript trigger { STATE, NO_SCOPE, NO_SCOPE }; - fixed_point_t bonus_value {}; - - const bool ret = expect_dictionary_keys( - "trigger", ONE_EXACTLY, trigger.expect_script(), - "value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bonus_value)) - )(bonus_node); - - bonuses.emplace_back(std::move(trigger), bonus_value); - - return ret; - }, - "owner", ZERO_OR_ONE, _expect_job(good_definition_manager, pop_manager, emplace_opt_callback(owner)), - "employees", ZERO_OR_ONE, _expect_job_list(good_definition_manager, pop_manager, move_variable_callback(jobs)), - "type", ZERO_OR_ONE, - expect_identifier(expect_mapped_string(template_type_map, assign_variable_callback(template_type))), - "workforce", ZERO_OR_ONE, expect_strong_typedef(assign_variable_callback(base_workforce_size)), - "input_goods", ZERO_OR_ONE, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(input_goods)), - "output_goods", ZERO_OR_ONE, - good_definition_manager.expect_good_definition_identifier(assign_variable_callback_pointer(output_good)), - "value", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(base_output_quantity)), - "efficiency", ZERO_OR_ONE, good_definition_manager.expect_good_definition_decimal_map( - move_variable_callback(maintenance_requirements) - ), - "is_coastal", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_coastal)), - "farm", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_farm)), - "mine", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_mine)) - ); - - /* Check if this ProductionType has a template, and if so parse it. */ - { - const typename decltype(template_target_map)::const_iterator target_it = template_target_map.find(key); - if (target_it != template_target_map.end()) { - const std::string_view template_id = target_it->second; - const typename decltype(template_node_map)::const_iterator node_it = template_node_map.find(template_id); - if (node_it != template_node_map.end()) { - ret &= parse_node(node_it->second); - } else { - spdlog::error_s( - "Missing template {} for production type {}!", - template_id, key - ); - ret = false; - } - } - } - - /* Parse the ProductionType's own entries, over those of its template if necessary. */ - ret &= parse_node(node); - - ret &= add_production_type( - game_rules_manager, - pop_manager.get_pop_types(), - key, std::move(owner), std::move(jobs), template_type, base_workforce_size, std::move(input_goods), output_good, - base_output_quantity, std::move(bonuses), std::move(maintenance_requirements), is_coastal, is_farm, is_mine - ); - - return ret; - } - )(parser.get_file_node()); + ret &= + expect_dictionary([this, &game_rules_manager, &good_definition_manager, &pop_manager, &template_target_map, &template_node_map](std::string_view key, ast::NodeCPtr node) -> bool { + using enum ProductionType::template_type_t; + + if (template_node_map.contains(key)) { + return true; + } + + std::optional owner; + memory::vector jobs; + ProductionType::template_type_t template_type { FACTORY }; + GoodDefinition const* output_good = nullptr; + pop_size_t base_workforce_size = 0; + fixed_point_map_t input_goods, maintenance_requirements; + fixed_point_t base_output_quantity = 0; + memory::vector bonuses; + bool is_coastal = false, is_farm = false, is_mine = false; + + bool ret = true; + + static const string_map_t template_type_map = { + { "factory", FACTORY }, { "rgo", RGO }, { "artisan", ARTISAN } + }; + + auto parse_node = expect_dictionary_keys( + "template", + ZERO_OR_ONE, + success_callback, /* Already parsed using expect_key in Pass #1 above. */ + "bonus", + ZERO_OR_MORE, + [&bonuses](ast::NodeCPtr bonus_node) -> bool { + using enum scope_type_t; + + ConditionScript trigger { STATE, NO_SCOPE, NO_SCOPE }; + fixed_point_t bonus_value {}; + + const bool ret = + expect_dictionary_keys("trigger", ONE_EXACTLY, trigger.expect_script(), "value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(bonus_value)))( + bonus_node + ); + + bonuses.emplace_back(std::move(trigger), bonus_value); + + return ret; + }, + "owner", + ZERO_OR_ONE, + _expect_job(good_definition_manager, pop_manager, emplace_opt_callback(owner)), + "employees", + ZERO_OR_ONE, + _expect_job_list(good_definition_manager, pop_manager, move_variable_callback(jobs)), + "type", + ZERO_OR_ONE, + expect_identifier(expect_mapped_string(template_type_map, assign_variable_callback(template_type))), + "workforce", + ZERO_OR_ONE, + expect_strong_typedef(assign_variable_callback(base_workforce_size)), + "input_goods", + ZERO_OR_ONE, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(input_goods)), + "output_goods", + ZERO_OR_ONE, + good_definition_manager.expect_good_definition_identifier(assign_variable_callback_pointer(output_good)), + "value", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(base_output_quantity)), + "efficiency", + ZERO_OR_ONE, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(maintenance_requirements)), + "is_coastal", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_coastal)), + "farm", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_farm)), + "mine", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_mine)) + ); + + /* Check if this ProductionType has a template, and if so parse it. */ + { + const typename decltype(template_target_map)::const_iterator target_it = template_target_map.find(key); + if (target_it != template_target_map.end()) { + const std::string_view template_id = target_it->second; + const typename decltype(template_node_map)::const_iterator node_it = template_node_map.find(template_id); + if (node_it != template_node_map.end()) { + ret &= parse_node(node_it->second); + } else { + spdlog::error_s("Missing template {} for production type {}!", template_id, key); + ret = false; + } + } + } + + /* Parse the ProductionType's own entries, over those of its template if necessary. */ + ret &= parse_node(node); + + ret &= add_production_type( + game_rules_manager, + pop_manager.get_pop_types(), + key, + std::move(owner), + std::move(jobs), + template_type, + base_workforce_size, + std::move(input_goods), + output_good, + base_output_quantity, + std::move(bonuses), + std::move(maintenance_requirements), + is_coastal, + is_farm, + is_mine + ); + + return ret; + })(parser.get_file_node()); production_types.lock(); diff --git a/src/openvic-simulation/economy/production/ProductionType.hpp b/src/openvic-simulation/economy/production/ProductionType.hpp index e12dc14bf..e184987dd 100644 --- a/src/openvic-simulation/economy/production/ProductionType.hpp +++ b/src/openvic-simulation/economy/production/ProductionType.hpp @@ -16,23 +16,26 @@ namespace OpenVic { struct PopType; struct Job { - enum struct effect_t { THROUGHPUT, INPUT, OUTPUT }; + enum struct effect_t { + THROUGHPUT, + INPUT, + OUTPUT + }; public: const pop_type_index_t pop_type_index; const effect_t effect_type; const fixed_point_t effect_multiplier; const fixed_point_t amount; - + constexpr Job( - const pop_type_index_t new_pop_type_index, - const effect_t new_effect_type, - const fixed_point_t new_effect_multiplier, - const fixed_point_t new_amount - ) : pop_type_index { new_pop_type_index }, - effect_type { new_effect_type }, - effect_multiplier { new_effect_multiplier }, - amount { new_amount } {} + const pop_type_index_t new_pop_type_index, + const effect_t new_effect_type, + const fixed_point_t new_effect_multiplier, + const fixed_point_t new_amount + ) : + pop_type_index { new_pop_type_index }, effect_type { new_effect_type }, effect_multiplier { new_effect_multiplier }, + amount { new_amount } {} constexpr Job() : Job({}, effect_t::THROUGHPUT, fixed_point_t::_0, fixed_point_t::_0) {}; }; @@ -47,7 +50,11 @@ namespace OpenVic { struct ProductionType : HasIdentifier { friend struct ProductionTypeManager; - enum struct template_type_t { FACTORY, RGO, ARTISAN }; + enum struct template_type_t { + FACTORY, + RGO, + ARTISAN + }; using bonus_t = std::pair; @@ -70,20 +77,20 @@ namespace OpenVic { const fixed_point_t base_output_quantity; ProductionType( - GameRulesManager const& new_game_rules_manager, - const std::string_view new_identifier, - std::optional&& new_owner, - memory::vector&& new_jobs, - const template_type_t new_template_type, - const pop_size_t new_base_workforce_size, - fixed_point_map_t&& new_input_goods, - GoodDefinition const& new_output_good, - const fixed_point_t new_base_output_quantity, - memory::vector&& new_bonuses, - fixed_point_map_t&& new_maintenance_requirements, - const bool new_is_coastal, - const bool new_is_farm, - const bool new_is_mine + GameRulesManager const& new_game_rules_manager, + const std::string_view new_identifier, + std::optional&& new_owner, + memory::vector&& new_jobs, + const template_type_t new_template_type, + const pop_size_t new_base_workforce_size, + fixed_point_map_t&& new_input_goods, + GoodDefinition const& new_output_good, + const fixed_point_t new_base_output_quantity, + memory::vector&& new_bonuses, + fixed_point_map_t&& new_maintenance_requirements, + const bool new_is_coastal, + const bool new_is_farm, + const bool new_is_mine ); constexpr bool get_is_farm_for_non_tech() const { @@ -106,48 +113,45 @@ namespace OpenVic { OV_IFLATMAP_PROPERTY(GoodDefinition, ProductionType const*, good_to_rgo_production_type); NodeTools::node_callback_t _expect_job( - GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, - NodeTools::callback_t< - pop_type_index_t, - Job::effect_t, - fixed_point_t, - fixed_point_t - > emplace_callback + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + NodeTools::callback_t emplace_callback ); NodeTools::node_callback_t _expect_job_list( - GoodDefinitionManager const& good_definition_manager, PopManager const& pop_manager, - NodeTools::callback_t&&> callback + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + NodeTools::callback_t&&> callback ); public: - constexpr ProductionTypeManager() - : good_to_rgo_production_type { decltype(good_to_rgo_production_type){create_empty} } {} + constexpr ProductionTypeManager() : + good_to_rgo_production_type { decltype(good_to_rgo_production_type) { create_empty } } {} bool add_production_type( - GameRulesManager const& game_rules_manager, - TypedSpan pop_types, - const std::string_view identifier, - std::optional&& owner, - memory::vector&& jobs, - const ProductionType::template_type_t template_type, - const pop_size_t base_workforce_size, - fixed_point_map_t&& input_goods, - GoodDefinition const* const output_good, - const fixed_point_t base_output_quantity, - memory::vector&& bonuses, - fixed_point_map_t&& maintenance_requirements, - const bool is_coastal, - const bool is_farm, - const bool is_mine + GameRulesManager const& game_rules_manager, + TypedSpan pop_types, + const std::string_view identifier, + std::optional&& owner, + memory::vector&& jobs, + const ProductionType::template_type_t template_type, + const pop_size_t base_workforce_size, + fixed_point_map_t&& input_goods, + GoodDefinition const* const output_good, + const fixed_point_t base_output_quantity, + memory::vector&& bonuses, + fixed_point_map_t&& maintenance_requirements, + const bool is_coastal, + const bool is_farm, + const bool is_mine ); bool load_production_types_file( - GameRulesManager const& game_rules_manager, - GoodDefinitionManager const& good_definition_manager, - PopManager const& pop_manager, - ovdl::v2script::Parser const& parser + GameRulesManager const& game_rules_manager, + GoodDefinitionManager const& good_definition_manager, + PopManager const& pop_manager, + ovdl::v2script::Parser const& parser ); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp index 7984a6575..710838742 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperation.cpp @@ -26,32 +26,22 @@ using namespace OpenVic; ResourceGatheringOperation::ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps, - ProductionType const* new_production_type_nullable, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - memory::vector&& new_employees -) - : market_instance { rgo_deps.market_instance }, - modifier_effect_cache { rgo_deps.modifier_effect_cache }, - production_type_nullable { new_production_type_nullable }, - revenue_yesterday { new_revenue_yesterday }, - output_quantity_yesterday { new_output_quantity_yesterday }, - unsold_quantity_yesterday { new_unsold_quantity_yesterday }, - size_multiplier { new_size_multiplier }, - employees { std::move(new_employees) }, - employee_count_per_type_cache { generate_values, rgo_deps.pop_type_count } {} - -ResourceGatheringOperation::ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps -) : ResourceGatheringOperation { - rgo_deps, - nullptr, 0, - 0, 0, - 0, {} -} {} + ResourceGatheringOperationDeps const& rgo_deps, + ProductionType const* new_production_type_nullable, + fixed_point_t new_size_multiplier, + fixed_point_t new_revenue_yesterday, + fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, + memory::vector&& new_employees +) : + market_instance { rgo_deps.market_instance }, modifier_effect_cache { rgo_deps.modifier_effect_cache }, + production_type_nullable { new_production_type_nullable }, revenue_yesterday { new_revenue_yesterday }, + output_quantity_yesterday { new_output_quantity_yesterday }, unsold_quantity_yesterday { new_unsold_quantity_yesterday }, + size_multiplier { new_size_multiplier }, employees { std::move(new_employees) }, + employee_count_per_type_cache { generate_values, rgo_deps.pop_type_count } {} + +ResourceGatheringOperation::ResourceGatheringOperation(ResourceGatheringOperationDeps const& rgo_deps) : + ResourceGatheringOperation { rgo_deps, nullptr, 0, 0, 0, 0, {} } {} void ResourceGatheringOperation::setup_location_ptr(ProvinceInstance& location) { if (location_ptr != nullptr) { @@ -72,7 +62,7 @@ void ResourceGatheringOperation::initialise_rgo_size_multiplier() { ProductionType const& production_type = *production_type_nullable; std::span jobs = production_type.get_jobs(); - pop_sum_t total_worker_count_in_province = 0; //not counting equivalents + pop_sum_t total_worker_count_in_province = 0; // not counting equivalents for (Job const& job : jobs) { total_worker_count_in_province += location.get_population_by_type()[job.pop_type_index]; } @@ -82,18 +72,14 @@ void ResourceGatheringOperation::initialise_rgo_size_multiplier() { if (size_modifier == 0) { size_multiplier = 0; } else { - size_multiplier = ( - ( - fp::from_fraction( - total_worker_count_in_province, - base_workforce_size - ) / size_modifier - ).ceil() - * fixed_point_t::_1_50 - ).floor(); + size_multiplier = + ((fp::from_fraction(total_worker_count_in_province, base_workforce_size) / size_modifier).ceil() * + fixed_point_t::_1_50) + .floor(); } - max_employee_count_cache = (size_modifier * size_multiplier * base_workforce_size).floor>(); + max_employee_count_cache = + (size_modifier * size_multiplier * base_workforce_size).floor>(); } fixed_point_t ResourceGatheringOperation::calculate_size_modifier() const { @@ -121,7 +107,7 @@ fixed_point_t ResourceGatheringOperation::calculate_size_modifier() const { } size_modifier += location.get_modifier_effect_value( - *modifier_effect_cache.get_good_effects(production_type.output_good).get_rgo_size() + *modifier_effect_cache.get_good_effects(production_type.output_good).get_rgo_size() ); return size_modifier > 0 ? size_modifier : fixed_point_t::_0; } @@ -137,7 +123,7 @@ void ResourceGatheringOperation::rgo_tick(memory::vector& reusabl ProductionType const& production_type = *production_type_nullable; std::span jobs = production_type.get_jobs(); - total_worker_count_in_province_cache = 0; //not counting equivalents + total_worker_count_in_province_cache = 0; // not counting equivalents for (Job const& job : jobs) { total_worker_count_in_province_cache += location.get_population_by_type()[job.pop_type_index]; } @@ -161,21 +147,23 @@ void ResourceGatheringOperation::rgo_tick(memory::vector& reusabl } market_instance.place_market_sell_order( - { - production_type.output_good.index, - country_to_report_economy_nullable == nullptr - ? std::nullopt - : std::optional{country_to_report_economy_nullable->index}, - output_quantity_yesterday, - this, - after_sell, - }, - reusable_vector + { + production_type.output_good.index, + country_to_report_economy_nullable == nullptr + ? std::nullopt + : std::optional { country_to_report_economy_nullable->index }, + output_quantity_yesterday, + this, + after_sell, + }, + reusable_vector ); } } -void ResourceGatheringOperation::after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { +void ResourceGatheringOperation::after_sell( + void* actor, SellResult const& sell_result, memory::vector& reusable_vector +) { ResourceGatheringOperation& rgo = *static_cast(actor); rgo.revenue_yesterday = sell_result.money_gained; rgo.pay_employees(reusable_vector); @@ -185,7 +173,7 @@ void ResourceGatheringOperation::hire() { pop_sum_t const& available_worker_count = total_worker_count_in_province_cache; total_employees_count_cache = 0; total_paid_employees_count_cache = 0; - employees.clear(); //TODO implement Victoria 2 hiring logic + employees.clear(); // TODO implement Victoria 2 hiring logic std::fill(employee_count_per_type_cache.begin(), employee_count_per_type_cache.end(), 0); if (production_type_nullable == nullptr) { return; @@ -193,25 +181,30 @@ void ResourceGatheringOperation::hire() { ProvinceInstance& location = *location_ptr; ProductionType const& production_type = *production_type_nullable; - if (max_employee_count_cache <= 0) { return; } - if (available_worker_count <= 0) { return; } + if (max_employee_count_cache <= 0) { + return; + } + if (available_worker_count <= 0) { + return; + } fixed_point_t proportion_to_hire; if (max_employee_count_cache >= available_worker_count) { - //hire everyone + // hire everyone proportion_to_hire = 1; } else { - //hire all pops proportionally + // hire all pops proportionally proportion_to_hire = fp::from_fraction(max_employee_count_cache, available_worker_count); } std::span jobs = production_type.get_jobs(); - for (Pop& pop : location.get_mutable_pops()){ + for (Pop& pop : location.get_mutable_pops()) { PopType const& pop_type = pop.get_type(); for (Job const& job : jobs) { const pop_type_index_t job_pop_type_index = job.pop_type_index; if (job_pop_type_index == pop_type.index) { - const pop_size_t pop_size_to_hire = (proportion_to_hire * pop.get_size()).floor>(); + const pop_size_t pop_size_to_hire = + (proportion_to_hire * pop.get_size()).floor>(); if (pop_size_to_hire <= 0) { continue; } @@ -231,7 +224,7 @@ void ResourceGatheringOperation::hire() { fixed_point_t ResourceGatheringOperation::produce() { const fixed_point_t size_modifier = calculate_size_modifier(); - if (size_modifier == 0){ + if (size_modifier == 0) { return 0; } @@ -259,58 +252,56 @@ fixed_point_t ResourceGatheringOperation::produce() { if (total_owner_count_in_state_cache > 0) { switch (owner_job.effect_type) { - case Job::effect_t::OUTPUT: - output_multiplier += fp::mul_div( - owner_job.effect_multiplier, - total_owner_count_in_state_cache, - state_population - ); - break; - case Job::effect_t::THROUGHPUT: - throughput_multiplier += fp::mul_div( - owner_job.effect_multiplier, - total_owner_count_in_state_cache, - state_population - ); - break; - default: - spdlog::error_s("Invalid job effect in RGO {}", production_type); - break; + case Job::effect_t::OUTPUT: + output_multiplier += fp::mul_div( + owner_job.effect_multiplier, total_owner_count_in_state_cache, state_population + ); + break; + case Job::effect_t::THROUGHPUT: + throughput_multiplier += fp::mul_div( + owner_job.effect_multiplier, total_owner_count_in_state_cache, state_population + ); + break; + default: spdlog::error_s("Invalid job effect in RGO {}", production_type); break; } } } // TODO - work out how best to avoid repeated lookups of the same effects, // e.g. by caching total non-local effect values at the CountryInstance level - throughput_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_tech()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_country()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_throughput()); - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_country()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_output()); + throughput_multiplier += + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_tech()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_throughput_country()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_throughput()); + output_multiplier += + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_tech()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_rgo_output_country()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_local_rgo_output()); if (production_type.get_is_farm_for_tech()) { - const fixed_point_t farm_rgo_throughput_and_output = - location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_throughput_and_output()); + const fixed_point_t farm_rgo_throughput_and_output = location.get_modifier_effect_value( + *modifier_effect_cache.get_farm_rgo_throughput_and_output() + ); throughput_multiplier += farm_rgo_throughput_and_output; output_multiplier += farm_rgo_throughput_and_output; } if (production_type.get_is_farm_for_non_tech()) { - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_global()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_local()); + output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_global()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_farm_rgo_output_local()); } if (production_type.get_is_mine_for_tech()) { - const fixed_point_t mine_rgo_throughput_and_output = - location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_throughput_and_output()); + const fixed_point_t mine_rgo_throughput_and_output = location.get_modifier_effect_value( + *modifier_effect_cache.get_mine_rgo_throughput_and_output() + ); throughput_multiplier += mine_rgo_throughput_and_output; output_multiplier += mine_rgo_throughput_and_output; } if (production_type.get_is_mine_for_non_tech()) { - output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_global()) - + location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_local()); + output_multiplier += location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_global()) + + location.get_modifier_effect_value(*modifier_effect_cache.get_mine_rgo_output_local()); } auto const& good_effects = modifier_effect_cache.get_good_effects(production_type.output_good); @@ -330,33 +321,26 @@ fixed_point_t ResourceGatheringOperation::produce() { const fixed_point_t effect_multiplier = job.effect_multiplier; const fixed_point_t amount = job.amount; - const fixed_point_t effect = effect_multiplier != fixed_point_t::_1 - && fp::from_fraction(employees_of_type, max_employee_count_cache) > amount - ? effect_multiplier * amount //special Vic2 logic - : fp::mul_div(effect_multiplier, employees_of_type, max_employee_count_cache); + const fixed_point_t effect = + effect_multiplier != fixed_point_t::_1 && + fp::from_fraction(employees_of_type, max_employee_count_cache) > amount + ? effect_multiplier * amount // special Vic2 logic + : fp::mul_div(effect_multiplier, employees_of_type, max_employee_count_cache); switch (job.effect_type) { - case Job::effect_t::OUTPUT: - output_from_workers += effect; - break; - case Job::effect_t::THROUGHPUT: - throughput_from_workers += effect; - break; - default: - spdlog::error_s("Invalid job effect in RGO {}", production_type); - break; + case Job::effect_t::OUTPUT: output_from_workers += effect; break; + case Job::effect_t::THROUGHPUT: throughput_from_workers += effect; break; + default: spdlog::error_s("Invalid job effect in RGO {}", production_type); break; } } ++pop_type_index; } } - //if province is overseas multiply by (1 + overseas penalty) + // if province is overseas multiply by (1 + overseas penalty) - return production_type.base_output_quantity - * size_modifier * size_multiplier - * throughput_multiplier * throughput_from_workers - * output_multiplier * output_from_workers; + return production_type.base_output_quantity * size_modifier * size_multiplier * throughput_multiplier * + throughput_from_workers * output_multiplier * output_from_workers; } void ResourceGatheringOperation::pay_employees(memory::vector& reusable_vector) { @@ -387,12 +371,8 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re if (revenue <= total_minimum_wage) { for (Employee& employee : employees) { const fixed_point_t income_for_this_pop = std::max( - fp::mul_div( - revenue, - employee.get_minimum_wage_cached(), - total_minimum_wage - ), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + fp::mul_div(revenue, employee.get_minimum_wage_cached(), total_minimum_wage), + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); Pop& employee_pop = employee.get_pop(); employee_pop.add_rgo_worker_income(income_for_this_pop); @@ -402,22 +382,16 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re fixed_point_t revenue_left = revenue; if (total_owner_count_in_state_cache > 0) { const fixed_point_t upper_limit = std::min( - fixed_point_t::_0_50, - fixed_point_t::_1 - total_minimum_wage / revenue_left + fixed_point_t::_0_50, fixed_point_t::_1 - total_minimum_wage / revenue_left ); const fixed_point_t owner_share = std::min( - fp::from_fraction(2 * total_owner_count_in_state_cache, total_worker_count_in_province_cache), - upper_limit + fp::from_fraction(2 * total_owner_count_in_state_cache, total_worker_count_in_province_cache), upper_limit ); for (Pop& owner_pop : *owner_pops_cache_nullable) { const fixed_point_t income_for_this_pop = std::max( - revenue_left * fp::mul_div( - owner_share, - owner_pop.get_size(), - total_owner_count_in_state_cache - ), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + revenue_left * fp::mul_div(owner_share, owner_pop.get_size(), total_owner_count_in_state_cache), + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); owner_pop.add_rgo_owner_income(income_for_this_pop); total_owner_income_cache += income_for_this_pop; @@ -426,8 +400,8 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re } if (total_paid_employees_count_cache == 0) { - //scenario slaves only - //Money is removed from system in Victoria 2. + // scenario slaves only + // Money is removed from system in Victoria 2. } else { memory::vector& incomes = reusable_vector; incomes.resize(employees.size()); @@ -449,19 +423,15 @@ void ResourceGatheringOperation::pay_employees(memory::vector& re const pop_size_t employee_size = employee.get_size(); const fixed_point_t income_for_this_pop = std::max( - fp::mul_div( - revenue_left, - employee_size, - count_workers_to_be_paid - ), - fixed_point_t::epsilon //revenue > 0 is already checked, so rounding up + fp::mul_div(revenue_left, employee_size, count_workers_to_be_paid), + fixed_point_t::epsilon // revenue > 0 is already checked, so rounding up ); if (income_for_this_pop < minimum_wage) { incomes[i] = minimum_wage; revenue_left -= minimum_wage; count_workers_to_be_paid -= employee_size; - i = -1; //Restart loop and skip minimum incomes. This is required to spread the remaining revenue again. + i = -1; // Restart loop and skip minimum incomes. This is required to spread the remaining revenue again. } else { incomes[i] = income_for_this_pop; } diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp b/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp index edf8fc04d..549fc28a7 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperation.hpp @@ -41,10 +41,7 @@ namespace OpenVic { pop_size_t PROPERTY(total_paid_employees_count_cache, 0); fixed_point_t PROPERTY(total_owner_income_cache); fixed_point_t PROPERTY(total_employee_income_cache); - memory::FixedVector< - pop_size_t, - pop_type_index_t - > SPAN_PROPERTY(employee_count_per_type_cache); + memory::FixedVector SPAN_PROPERTY(employee_count_per_type_cache); fixed_point_t calculate_size_modifier() const; void hire(); @@ -54,13 +51,13 @@ namespace OpenVic { public: ResourceGatheringOperation( - ResourceGatheringOperationDeps const& rgo_deps, - ProductionType const* new_production_type_nullable, - fixed_point_t new_size_multiplier, - fixed_point_t new_revenue_yesterday, - fixed_point_t new_output_quantity_yesterday, - fixed_point_t new_unsold_quantity_yesterday, - memory::vector&& new_employees + ResourceGatheringOperationDeps const& rgo_deps, + ProductionType const* new_production_type_nullable, + fixed_point_t new_size_multiplier, + fixed_point_t new_revenue_yesterday, + fixed_point_t new_output_quantity_yesterday, + fixed_point_t new_unsold_quantity_yesterday, + memory::vector&& new_employees ); ResourceGatheringOperation(ResourceGatheringOperationDeps const& rgo_deps); @@ -73,4 +70,4 @@ namespace OpenVic { static constexpr size_t VECTORS_FOR_RGO_TICK = 1; void rgo_tick(memory::vector& reusable_vector); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp b/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp index dd313c406..34cb1542b 100644 --- a/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp +++ b/src/openvic-simulation/economy/production/ResourceGatheringOperationDeps.hpp @@ -11,4 +11,4 @@ namespace OpenVic { ModifierEffectCache const& modifier_effect_cache; pop_type_index_t pop_type_count; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/BuyResult.hpp b/src/openvic-simulation/economy/trading/BuyResult.hpp index e0d7ffd10..cab7df000 100644 --- a/src/openvic-simulation/economy/trading/BuyResult.hpp +++ b/src/openvic-simulation/economy/trading/BuyResult.hpp @@ -12,17 +12,16 @@ namespace OpenVic { const fixed_point_t money_spent_on_imports; constexpr BuyResult( - const good_index_t new_good_index, - const fixed_point_t new_quantity_bought, - const fixed_point_t new_money_spent_total, - const fixed_point_t new_money_spent_on_imports - ) : good_index { new_good_index }, - quantity_bought { new_quantity_bought }, - money_spent_total { new_money_spent_total }, - money_spent_on_imports { new_money_spent_on_imports } {} + const good_index_t new_good_index, + const fixed_point_t new_quantity_bought, + const fixed_point_t new_money_spent_total, + const fixed_point_t new_money_spent_on_imports + ) : + good_index { new_good_index }, quantity_bought { new_quantity_bought }, money_spent_total { new_money_spent_total }, + money_spent_on_imports { new_money_spent_on_imports } {} static constexpr BuyResult no_purchase_result(const good_index_t good_index) { return { good_index, 0, 0, 0 }; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp b/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp index 8d0f5a799..9e002348d 100644 --- a/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp +++ b/src/openvic-simulation/economy/trading/BuyUpToOrder.hpp @@ -8,7 +8,7 @@ namespace OpenVic { struct GoodBuyUpToOrder { using actor_t = void*; - using callback_t = void(*)(const actor_t, BuyResult const&); + using callback_t = void (*)(const actor_t, BuyResult const&); private: const actor_t actor; @@ -20,23 +20,20 @@ namespace OpenVic { const fixed_point_t money_to_spend; constexpr GoodBuyUpToOrder( - const std::optional new_country_index_optional, - const fixed_point_t new_max_quantity, - const fixed_point_t new_money_to_spend, - const actor_t new_actor, - const callback_t new_after_trade - ) : country_index_optional { new_country_index_optional }, - max_quantity { new_max_quantity }, - money_to_spend { new_money_to_spend }, - actor { new_actor }, - after_trade { new_after_trade } - {} + const std::optional new_country_index_optional, + const fixed_point_t new_max_quantity, + const fixed_point_t new_money_to_spend, + const actor_t new_actor, + const callback_t new_after_trade + ) : + country_index_optional { new_country_index_optional }, max_quantity { new_max_quantity }, + money_to_spend { new_money_to_spend }, actor { new_actor }, after_trade { new_after_trade } {} constexpr void call_after_trade(BuyResult const& buy_result) const { after_trade(actor, buy_result); } - //highest price per unit at which the buyer can afford max_quantity + // highest price per unit at which the buyer can afford max_quantity constexpr fixed_point_t get_affordable_price() const { return money_to_spend / max_quantity; } @@ -47,24 +44,18 @@ namespace OpenVic { const good_index_t good_index; constexpr BuyUpToOrder( - const good_index_t new_good_index, - const std::optional new_country_index_optional, - const fixed_point_t new_max_quantity, - const fixed_point_t new_money_to_spend, - const actor_t new_actor, - const callback_t new_after_trade - ) : GoodBuyUpToOrder { - new_country_index_optional, - new_max_quantity, - new_money_to_spend, - new_actor, - new_after_trade - }, - good_index { new_good_index } - {} + const good_index_t new_good_index, + const std::optional new_country_index_optional, + const fixed_point_t new_max_quantity, + const fixed_point_t new_money_to_spend, + const actor_t new_actor, + const callback_t new_after_trade + ) : + GoodBuyUpToOrder { new_country_index_optional, new_max_quantity, new_money_to_spend, new_actor, new_after_trade }, + good_index { new_good_index } {} - constexpr void call_after_trade(BuyResult const& buy_result) const { - GoodBuyUpToOrder::call_after_trade(buy_result); - } + constexpr void call_after_trade(BuyResult const& buy_result) const { + GoodBuyUpToOrder::call_after_trade(buy_result); + } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/GoodMarket.cpp b/src/openvic-simulation/economy/trading/GoodMarket.cpp index 0ca423743..2c91bf000 100644 --- a/src/openvic-simulation/economy/trading/GoodMarket.cpp +++ b/src/openvic-simulation/economy/trading/GoodMarket.cpp @@ -13,46 +13,30 @@ using namespace OpenVic; static constexpr size_t MONTHS_OF_PRICE_HISTORY = 36; -GoodMarket::GoodMarket(GameRulesManager const& new_game_rules_manager, GoodDefinition const& new_good_definition) - : game_rules_manager { new_game_rules_manager }, - good_definition { new_good_definition }, - price { new_good_definition.base_price }, - is_available { new_good_definition.is_available_from_start }, - price_history { MONTHS_OF_PRICE_HISTORY, new_good_definition.base_price } - { - on_use_exponential_price_changes_changed(); - update_next_price_limits(); - } +GoodMarket::GoodMarket(GameRulesManager const& new_game_rules_manager, GoodDefinition const& new_good_definition) : + game_rules_manager { new_game_rules_manager }, good_definition { new_good_definition }, + price { new_good_definition.base_price }, is_available { new_good_definition.is_available_from_start }, + price_history { MONTHS_OF_PRICE_HISTORY, new_good_definition.base_price } { + on_use_exponential_price_changes_changed(); + update_next_price_limits(); +} void GoodMarket::on_use_exponential_price_changes_changed() { if (game_rules_manager.get_use_exponential_price_changes()) { absolute_maximum_price = fixed_point_t::usable_max; absolute_minimum_price = fixed_point_t::epsilon << exponential_price_change_shift; } else { - absolute_maximum_price = std::min( - good_definition.base_price * 5, - fixed_point_t::usable_max - ); - absolute_minimum_price = std::max( - good_definition.base_price * 22 / 100, - fixed_point_t::epsilon - ); + absolute_maximum_price = std::min(good_definition.base_price * 5, fixed_point_t::usable_max); + absolute_minimum_price = std::max(good_definition.base_price * 22 / 100, fixed_point_t::epsilon); } } void GoodMarket::update_next_price_limits() { - const fixed_point_t max_price_change = game_rules_manager.get_use_exponential_price_changes() - ? price >> exponential_price_change_shift - : fixed_point_t::_0_01; - - max_next_price = std::min( - absolute_maximum_price, - price + max_price_change - ); - min_next_price = std::max( - absolute_minimum_price, - price - max_price_change - ); + const fixed_point_t max_price_change = + game_rules_manager.get_use_exponential_price_changes() ? price >> exponential_price_change_shift : fixed_point_t::_0_01; + + max_next_price = std::min(absolute_maximum_price, price + max_price_change); + min_next_price = std::max(absolute_minimum_price, price - max_price_change); price_inverse = fixed_point_t::_1 / price; } @@ -68,20 +52,13 @@ void GoodMarket::add_market_sell_order(GoodMarketSellOrder&& market_sell_order) } void GoodMarket::execute_orders( - TypedSpan reusable_country_map_0, - TypedSpan reusable_country_map_1, - std::span< - memory::vector, - VECTORS_FOR_EXECUTE_ORDERS - > reusable_vectors + TypedSpan reusable_country_map_0, + TypedSpan reusable_country_map_1, + std::span, VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors ) { if (!is_available) { - //price remains the same - price_change_yesterday - = quantity_traded_yesterday - = total_demand_yesterday - = total_supply_yesterday - = 0; + // price remains the same + price_change_yesterday = quantity_traded_yesterday = total_demand_yesterday = total_supply_yesterday = 0; for (GoodBuyUpToOrder const& buy_up_to_order : buy_up_to_orders) { buy_up_to_order.call_after_trade(BuyResult::no_purchase_result(good_definition.index)); @@ -90,17 +67,16 @@ void GoodMarket::execute_orders( for (GoodMarketSellOrder const& market_sell_order : market_sell_orders) { market_sell_order.call_after_trade(SellResult::no_sales_result(good_definition.index), reusable_vectors[0]); - } + } market_sell_orders.clear(); - + return; } fixed_point_t new_price; - //MarketInstance ensured only orders with quantity > 0 are added. - //So running total > 0 unless orders are empty. - fixed_point_t demand_sum = 0, - supply_sum = 0; + // MarketInstance ensured only orders with quantity > 0 are added. + // So running total > 0 unless orders are empty. + fixed_point_t demand_sum = 0, supply_sum = 0; if (market_sell_orders.empty()) { quantity_traded_yesterday = 0; fixed_point_t max_affordable_price = price; @@ -117,7 +93,7 @@ void GoodMarket::execute_orders( if (game_rules_manager.get_use_optimal_pricing()) { new_price = std::min(max_next_price, max_affordable_price); } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 if (demand_sum > 0) { new_price = max_next_price; } else { @@ -139,7 +115,7 @@ void GoodMarket::execute_orders( quantity_bought_per_order.resize(buy_up_to_orders.size()); purchasing_power_per_order.resize(buy_up_to_orders.size()); - fixed_point_t money_left_to_spend_sum = 0; //sum of money_to_spend for all buyers that can't afford their max_quantity + fixed_point_t money_left_to_spend_sum = 0; // sum of money_to_spend for all buyers that can't afford their max_quantity fixed_point_t max_quantity_to_buy_sum = 0; fixed_point_t purchasing_power_sum = 0; for (size_t i = 0; i < buy_up_to_orders.size(); i++) { @@ -150,7 +126,7 @@ void GoodMarket::execute_orders( if (game_rules_manager.get_use_optimal_pricing()) { const fixed_point_t affordable_price = buy_up_to_order.get_affordable_price(); if (affordable_price > min_next_price) { - //no point selling lower as it would not attract more buyers + // no point selling lower as it would not attract more buyers min_next_price = affordable_price; } } @@ -177,11 +153,11 @@ void GoodMarket::execute_orders( fixed_point_t remaining_supply = supply_sum; const bool is_selling_for_max_price = max_quantity_to_buy_sum >= supply_sum; if (is_selling_for_max_price) { - //sell for max_next_price + // sell for max_next_price if (game_rules_manager.get_use_optimal_pricing()) { new_price = max_next_price; } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 new_price = max_next_price; } @@ -198,15 +174,11 @@ void GoodMarket::execute_orders( const std::optional country_index_optional = buy_up_to_order.country_index_optional; if (country_index_optional.has_value()) { - //subtract as it might be updated below + // subtract as it might be updated below actual_bought_per_country[country_index_optional.value()] -= distributed_supply; } - distributed_supply = fp::mul_div( - remaining_supply, - purchasing_power_per_order[i], - purchasing_power_sum - ); + distributed_supply = fp::mul_div(remaining_supply, purchasing_power_per_order[i], purchasing_power_sum); if (distributed_supply >= max_quantity) { someone_bought_max_quantity = true; @@ -225,23 +197,18 @@ void GoodMarket::execute_orders( } } while (someone_bought_max_quantity); - execute_buy_orders( - new_price, - actual_bought_per_country, - supply_per_country, - quantity_bought_per_order - ); + execute_buy_orders(new_price, actual_bought_per_country, supply_per_country, quantity_bought_per_order); } else { - //sell below max_next_price + // sell below max_next_price if (game_rules_manager.get_use_optimal_pricing()) { new_price = price; - //drop price while remaining_supply > 0 && new_price > min_next_price + // drop price while remaining_supply > 0 && new_price > min_next_price while (remaining_supply > 0) { const fixed_point_t possible_price = money_left_to_spend_sum / remaining_supply; if (possible_price >= new_price) { - //use previous new_price + // use previous new_price break; } @@ -266,7 +233,7 @@ void GoodMarket::execute_orders( } } } else { - //TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 + // TODO use Victoria 2's square root mechanic, see https://github.com/OpenVicProject/OpenVic/issues/288 if (supply_sum > demand_sum) { new_price = min_next_price; } else { @@ -274,15 +241,12 @@ void GoodMarket::execute_orders( } } - //figure out how much every buyer bought + // figure out how much every buyer bought for (size_t i = 0; i < buy_up_to_orders.size(); i++) { GoodBuyUpToOrder const& buy_up_to_order = buy_up_to_orders[i]; - const fixed_point_t quantity_bought - = quantity_bought_per_order[i] - = std::min( - buy_up_to_order.max_quantity, - buy_up_to_order.money_to_spend / new_price + const fixed_point_t quantity_bought = quantity_bought_per_order[i] = std::min( + buy_up_to_order.max_quantity, buy_up_to_order.money_to_spend / new_price ); const std::optional country_index_optional = buy_up_to_order.country_index_optional; @@ -291,21 +255,16 @@ void GoodMarket::execute_orders( } } - execute_buy_orders( - new_price, - actual_bought_per_country, - supply_per_country, - quantity_bought_per_order - ); + execute_buy_orders(new_price, actual_bought_per_country, supply_per_country, quantity_bought_per_order); } for (auto& reusable_vector : reusable_vectors) { reusable_vector.clear(); } - //figure out how much of each order was sold + // figure out how much of each order was sold if (quantity_traded_yesterday == supply_sum) { - //everything was sold + // everything was sold for (GoodMarketSellOrder const& market_sell_order : market_sell_orders) { const fixed_point_t quantity_sold = market_sell_order.quantity; fixed_point_t money_gained; @@ -313,21 +272,14 @@ void GoodMarket::execute_orders( money_gained = 0; } else { money_gained = std::max( - quantity_sold * new_price, - fixed_point_t::epsilon //round up + quantity_sold * new_price, + fixed_point_t::epsilon // round up ); } - market_sell_order.call_after_trade( - { - good_definition.index, - quantity_sold, - money_gained - }, - reusable_vectors[0] - ); + market_sell_order.call_after_trade({ good_definition.index, quantity_sold, money_gained }, reusable_vectors[0]); } } else { - //quantity is evenly divided after taking domestic buyers into account + // quantity is evenly divided after taking domestic buyers into account fixed_point_t total_quantity_traded_domestically = 0; for (country_index_t country_index(0); country_index < actual_bought_per_country.size(); ++country_index) { const fixed_point_t actual_bought = actual_bought_per_country[country_index]; @@ -336,7 +288,8 @@ void GoodMarket::execute_orders( total_quantity_traded_domestically += traded_domestically; } - const fixed_point_t total_quantity_traded_as_export = quantity_traded_yesterday - total_quantity_traded_domestically; + const fixed_point_t total_quantity_traded_as_export = + quantity_traded_yesterday - total_quantity_traded_domestically; const fixed_point_t total_quantity_offered_as_export = supply_sum - total_quantity_traded_domestically; for (GoodMarketSellOrder const& market_sell_order : market_sell_orders) { const fixed_point_t quantity_offered = market_sell_order.quantity; @@ -351,20 +304,19 @@ void GoodMarket::execute_orders( const country_index_t country_index = country_index_optional.value(); const fixed_point_t total_bought_domestically = actual_bought_per_country[country_index]; const fixed_point_t total_domestic_supply = supply_per_country[country_index]; - quantity_sold_domestically = total_bought_domestically >= total_domestic_supply - ? quantity_offered - : fp::mul_div( - quantity_offered, - total_bought_domestically, - total_domestic_supply //> 0 as we're selling - ); + quantity_sold_domestically = + total_bought_domestically >= total_domestic_supply + ? quantity_offered + : fp::mul_div( + quantity_offered, + total_bought_domestically, + total_domestic_supply //> 0 as we're selling + ); quantity_offered_as_export = quantity_offered - quantity_sold_domestically; } const fixed_point_t fair_share_of_exports = fp::mul_div( - quantity_offered_as_export, - total_quantity_traded_as_export, - total_quantity_offered_as_export + quantity_offered_as_export, total_quantity_traded_as_export, total_quantity_offered_as_export ); const fixed_point_t quantity_sold = quantity_sold_domestically + fair_share_of_exports; @@ -373,18 +325,11 @@ void GoodMarket::execute_orders( money_gained = 0; } else { money_gained = std::max( - quantity_sold * new_price, - fixed_point_t::epsilon //round up + quantity_sold * new_price, + fixed_point_t::epsilon // round up ); } - market_sell_order.call_after_trade( - { - good_definition.index, - quantity_sold, - money_gained - }, - reusable_vectors[0] - ); + market_sell_order.call_after_trade({ good_definition.index, quantity_sold, money_gained }, reusable_vectors[0]); } } @@ -406,10 +351,10 @@ void GoodMarket::execute_orders( } void GoodMarket::execute_buy_orders( - const fixed_point_t new_price, - TypedSpan actual_bought_per_country, - TypedSpan supply_per_country, - std::span quantity_bought_per_order + const fixed_point_t new_price, + TypedSpan actual_bought_per_country, + TypedSpan supply_per_country, + std::span quantity_bought_per_order ) { quantity_traded_yesterday = 0; for (size_t i = 0; i < buy_up_to_orders.size(); i++) { @@ -421,44 +366,39 @@ void GoodMarket::execute_buy_orders( } else { quantity_traded_yesterday += quantity_bought; const fixed_point_t money_spent_total = std::max( - quantity_bought * new_price, - fixed_point_t::epsilon //we know from purchasing power that you can afford it. + quantity_bought * new_price, + fixed_point_t::epsilon // we know from purchasing power that you can afford it. ); fixed_point_t money_spent_on_imports; const std::optional country_index_optional = buy_up_to_order.country_index_optional; if (!country_index_optional.has_value()) { - //could be trade between native Americans and tribal Africa, so it's all imported + // could be trade between native Americans and tribal Africa, so it's all imported money_spent_on_imports = money_spent_total; } else { const country_index_t country_index = country_index_optional.value(); - //must be > 0, since quantity_bought > 0 + // must be > 0, since quantity_bought > 0 const fixed_point_t actual_bought_in_my_country = actual_bought_per_country[country_index]; const fixed_point_t supply_in_my_country = supply_per_country[country_index]; if (supply_in_my_country >= actual_bought_in_my_country) { - //no imports + // no imports money_spent_on_imports = 0; } else { const fixed_point_t money_spent_domestically = fp::mul_div( - money_spent_total, - supply_in_my_country, - actual_bought_in_my_country + money_spent_total, supply_in_my_country, actual_bought_in_my_country ); money_spent_on_imports = money_spent_total - money_spent_domestically; } } - buy_up_to_order.call_after_trade({ - good_definition.index, - quantity_bought, - money_spent_total, - money_spent_on_imports - }); + buy_up_to_order.call_after_trade( + { good_definition.index, quantity_bought, money_spent_total, money_spent_on_imports } + ); } } } void GoodMarket::record_price_history() { price_history.push_back(price); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/GoodMarket.hpp b/src/openvic-simulation/economy/trading/GoodMarket.hpp index 5b663d9a8..57ad09445 100644 --- a/src/openvic-simulation/economy/trading/GoodMarket.hpp +++ b/src/openvic-simulation/economy/trading/GoodMarket.hpp @@ -25,15 +25,15 @@ namespace OpenVic { fixed_point_t absolute_maximum_price; fixed_point_t absolute_minimum_price; - //only used during day tick (from actors placing order until execute_orders()) + // only used during day tick (from actors placing order until execute_orders()) memory::vector buy_up_to_orders; memory::vector market_sell_orders; void execute_buy_orders( - const fixed_point_t new_price, - TypedSpan actual_bought_per_country, - TypedSpan supply_per_country, - std::span quantity_bought_per_order + const fixed_point_t new_price, + TypedSpan actual_bought_per_country, + TypedSpan supply_per_country, + std::span quantity_bought_per_order ); protected: @@ -51,6 +51,7 @@ namespace OpenVic { ValueHistory PROPERTY(price_history); void update_next_price_limits(); + public: GoodDefinition const& good_definition; @@ -60,21 +61,18 @@ namespace OpenVic { GoodMarket(GoodMarket&&) = delete; GoodMarket& operator=(GoodMarket&&) = delete; - //thread safe + // thread safe void add_buy_up_to_order(GoodBuyUpToOrder&& buy_up_to_order); void add_market_sell_order(GoodMarketSellOrder&& market_sell_order); - //not thread safe + // not thread safe static constexpr size_t VECTORS_FOR_EXECUTE_ORDERS = 2; void execute_orders( - TypedSpan reusable_country_map_0, - TypedSpan reusable_country_map_1, - std::span< - memory::vector, - VECTORS_FOR_EXECUTE_ORDERS - > reusable_vectors + TypedSpan reusable_country_map_0, + TypedSpan reusable_country_map_1, + std::span, VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors ); void on_use_exponential_price_changes_changed(); void record_price_history(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/MarketInstance.cpp b/src/openvic-simulation/economy/trading/MarketInstance.cpp index 1cced2ad4..6df29bd61 100644 --- a/src/openvic-simulation/economy/trading/MarketInstance.cpp +++ b/src/openvic-simulation/economy/trading/MarketInstance.cpp @@ -1,5 +1,6 @@ #include "MarketInstance.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/defines/CountryDefines.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" @@ -7,7 +8,6 @@ #include "openvic-simulation/economy/trading/BuyUpToOrder.hpp" #include "openvic-simulation/economy/trading/MarketSellOrder.hpp" #include "openvic-simulation/utility/ThreadPool.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; @@ -23,9 +23,11 @@ fixed_point_t MarketInstance::get_min_next_price(const good_index_t good_index) return good_instance_manager.get_good_instance_by_index(good_index)->get_min_next_price(); } -fixed_point_t MarketInstance::get_max_money_to_allocate_to_buy_quantity(const good_index_t good_index, const fixed_point_t quantity) const { - //round up so money_to_spend >= max_next_price * max_quantity_to_buy; - //always add epsilon as money_to_spend == max_next_price * max_quantity_to_buy is rare and this is cheaper for performance. +fixed_point_t MarketInstance::get_max_money_to_allocate_to_buy_quantity( + const good_index_t good_index, const fixed_point_t quantity +) const { + // round up so money_to_spend >= max_next_price * max_quantity_to_buy; + // always add epsilon as money_to_spend == max_next_price * max_quantity_to_buy is rare and this is cheaper for performance. return quantity * get_max_next_price(good_index) + fixed_point_t::epsilon; } @@ -36,10 +38,7 @@ GoodInstance const& MarketInstance::get_good_instance(const good_index_t good_in void MarketInstance::place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order) { const good_index_t good_index = buy_up_to_order.good_index; if (OV_unlikely(buy_up_to_order.max_quantity <= 0)) { - spdlog::error_s( - "Received BuyUpToOrder for {} with max quantity {}", - good_index, buy_up_to_order.max_quantity - ); + spdlog::error_s("Received BuyUpToOrder for {} with max quantity {}", good_index, buy_up_to_order.max_quantity); buy_up_to_order.call_after_trade(BuyResult::no_purchase_result(good_index)); return; } @@ -48,15 +47,14 @@ void MarketInstance::place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order) { good_instance.add_buy_up_to_order(std::move(buy_up_to_order)); } -void MarketInstance::place_market_sell_order(MarketSellOrder&& market_sell_order, memory::vector& reusable_vector) { +void MarketInstance::place_market_sell_order( + MarketSellOrder&& market_sell_order, memory::vector& reusable_vector +) { const good_index_t good_index = market_sell_order.good_index; const fixed_point_t quantity = market_sell_order.quantity; if (OV_unlikely(quantity <= 0)) { - spdlog::error_s( - "Received MarketSellOrder for {} with quantity {}", - good_index, quantity - ); + spdlog::error_s("Received MarketSellOrder for {} with quantity {}", good_index, quantity); market_sell_order.call_after_trade(SellResult::no_sales_result(good_index), reusable_vector); return; } @@ -64,12 +62,10 @@ void MarketInstance::place_market_sell_order(MarketSellOrder&& market_sell_order GoodMarket& good_instance = *good_instance_manager.get_good_instance_by_index(good_index); if (good_instance.good_definition.is_money) { market_sell_order.call_after_trade( - { - market_sell_order.good_index, - quantity, - quantity * country_defines.get_gold_to_worker_pay_rate() * good_instance.good_definition.base_price - }, - reusable_vector + { market_sell_order.good_index, + quantity, + quantity * country_defines.get_gold_to_worker_pay_rate() * good_instance.good_definition.base_price }, + reusable_vector ); return; } diff --git a/src/openvic-simulation/economy/trading/MarketInstance.hpp b/src/openvic-simulation/economy/trading/MarketInstance.hpp index 038ddfbae..bdf14218a 100644 --- a/src/openvic-simulation/economy/trading/MarketInstance.hpp +++ b/src/openvic-simulation/economy/trading/MarketInstance.hpp @@ -17,19 +17,22 @@ namespace OpenVic { ThreadPool& thread_pool; CountryDefines const& country_defines; GoodInstanceManager& good_instance_manager; + public: constexpr MarketInstance( - ThreadPool& new_thread_pool, - CountryDefines const& new_country_defines, - GoodInstanceManager& new_good_instance_manager - ) : thread_pool { new_thread_pool }, - country_defines { new_country_defines }, - good_instance_manager { new_good_instance_manager } {} + ThreadPool& new_thread_pool, + CountryDefines const& new_country_defines, + GoodInstanceManager& new_good_instance_manager + ) : + thread_pool { new_thread_pool }, country_defines { new_country_defines }, + good_instance_manager { new_good_instance_manager } {} bool get_is_available(const good_index_t good_index) const; fixed_point_t get_max_next_price(const good_index_t good_index) const; fixed_point_t get_min_next_price(const good_index_t good_index) const; - fixed_point_t get_max_money_to_allocate_to_buy_quantity(const good_index_t good_index, const fixed_point_t quantity) const; + fixed_point_t get_max_money_to_allocate_to_buy_quantity( + const good_index_t good_index, const fixed_point_t quantity + ) const; GoodInstance const& get_good_instance(const good_index_t good_index) const; void place_buy_up_to_order(BuyUpToOrder&& buy_up_to_order); void place_market_sell_order(MarketSellOrder&& market_sell_order, memory::vector& reusable_vector); diff --git a/src/openvic-simulation/economy/trading/MarketSellOrder.hpp b/src/openvic-simulation/economy/trading/MarketSellOrder.hpp index 0fa1f96d0..6f49d2a00 100644 --- a/src/openvic-simulation/economy/trading/MarketSellOrder.hpp +++ b/src/openvic-simulation/economy/trading/MarketSellOrder.hpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/economy/trading/SellResult.hpp" #include "openvic-simulation/core/memory/Vector.hpp" +#include "openvic-simulation/economy/trading/SellResult.hpp" #include "openvic-simulation/types/TypedIndices.hpp" namespace OpenVic { @@ -20,15 +20,13 @@ namespace OpenVic { const fixed_point_t quantity; constexpr GoodMarketSellOrder( - const std::optional new_country_index_optional, - const fixed_point_t new_quantity, - const actor_t new_actor, - const callback_t new_after_trade - ) : country_index_optional { new_country_index_optional }, - quantity { new_quantity }, - actor { new_actor }, - after_trade { new_after_trade } - {} + const std::optional new_country_index_optional, + const fixed_point_t new_quantity, + const actor_t new_actor, + const callback_t new_after_trade + ) : + country_index_optional { new_country_index_optional }, quantity { new_quantity }, actor { new_actor }, + after_trade { new_after_trade } {} constexpr void call_after_trade(SellResult const& sell_result, memory::vector& reusable_vector) const { after_trade(actor, sell_result, reusable_vector); @@ -40,18 +38,13 @@ namespace OpenVic { const good_index_t good_index; constexpr MarketSellOrder( - const good_index_t new_good_index, - const std::optional new_country_index_optional, - const fixed_point_t new_quantity, - const actor_t new_actor, - const callback_t new_after_trade - ) : GoodMarketSellOrder { - new_country_index_optional, - new_quantity, - new_actor, - new_after_trade - }, - good_index { new_good_index } - {} + const good_index_t new_good_index, + const std::optional new_country_index_optional, + const fixed_point_t new_quantity, + const actor_t new_actor, + const callback_t new_after_trade + ) : + GoodMarketSellOrder { new_country_index_optional, new_quantity, new_actor, new_after_trade }, + good_index { new_good_index } {} }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/economy/trading/SellResult.hpp b/src/openvic-simulation/economy/trading/SellResult.hpp index 54b75fd2c..01db400c6 100644 --- a/src/openvic-simulation/economy/trading/SellResult.hpp +++ b/src/openvic-simulation/economy/trading/SellResult.hpp @@ -11,15 +11,11 @@ namespace OpenVic { const fixed_point_t money_gained; constexpr SellResult( - const good_index_t new_good_index, - const fixed_point_t new_quantity_sold, - const fixed_point_t new_money_gained - ) : good_index { new_good_index }, - quantity_sold { new_quantity_sold }, - money_gained { new_money_gained } {} + const good_index_t new_good_index, const fixed_point_t new_quantity_sold, const fixed_point_t new_money_gained + ) : good_index { new_good_index }, quantity_sold { new_quantity_sold }, money_gained { new_money_gained } {} static constexpr SellResult no_sales_result(const good_index_t good_index) { return { good_index, 0, 0 }; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/Bookmark.cpp b/src/openvic-simulation/history/Bookmark.cpp index e1f4e3d47..77f6e41bf 100644 --- a/src/openvic-simulation/history/Bookmark.cpp +++ b/src/openvic-simulation/history/Bookmark.cpp @@ -13,41 +13,36 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Bookmark::Bookmark( - index_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, - fvec2_t new_initial_camera_position -) : HasIdentifier { std::to_string(type_safe::get(new_index)) }, - HasIndex { new_index }, - name { new_name }, - description { new_description }, - date { new_date }, - initial_camera_position { new_initial_camera_position } {} + index_t new_index, + std::string_view new_name, + std::string_view new_description, + Date new_date, + fvec2_t new_initial_camera_position +) : + HasIdentifier { std::to_string(type_safe::get(new_index)) }, HasIndex { new_index }, name { new_name }, + description { new_description }, date { new_date }, initial_camera_position { new_initial_camera_position } {} bool BookmarkManager::add_bookmark( - std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position + std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position ) { return bookmarks.emplace_item( - name, - index_from_count(bookmarks.size()), name, description, date, initial_camera_position + name, index_from_count(bookmarks.size()), name, description, date, initial_camera_position ); } bool BookmarkManager::load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - bookmarks, - [this, map_height](std::string_view key, ast::NodeCPtr value) -> bool { - if (key != "bookmark") { - spdlog::error_s("Invalid bookmark declaration {}", key); - return false; - } + const bool ret = + expect_dictionary_reserve_length(bookmarks, [this, map_height](std::string_view key, ast::NodeCPtr value) -> bool { + if (key != "bookmark") { + spdlog::error_s("Invalid bookmark declaration {}", key); + return false; + } - std::string_view name, description; - Date date; - fvec2_t initial_camera_position; + std::string_view name, description; + Date date; + fvec2_t initial_camera_position; - bool ret = expect_dictionary_keys( + bool ret = expect_dictionary_keys( "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), "desc", ONE_EXACTLY, expect_string(assign_variable_callback(description)), "date", ONE_EXACTLY, expect_date(assign_variable_callback(date)), @@ -56,10 +51,9 @@ bool BookmarkManager::load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr expect_fixed_point(flip_height_callback(assign_variable_callback(initial_camera_position.y), map_height)) )(value); - ret &= add_bookmark(name, description, date, initial_camera_position); - return ret; - } - )(root); + ret &= add_bookmark(name, description, date, initial_camera_position); + return ret; + })(root); lock_bookmarks(); return ret; diff --git a/src/openvic-simulation/history/Bookmark.hpp b/src/openvic-simulation/history/Bookmark.hpp index 4584d628e..0ca6ed21e 100644 --- a/src/openvic-simulation/history/Bookmark.hpp +++ b/src/openvic-simulation/history/Bookmark.hpp @@ -21,11 +21,11 @@ namespace OpenVic { const fvec2_t initial_camera_position; Bookmark( - index_t new_index, - std::string_view new_name, - std::string_view new_description, - Date new_date, - fvec2_t new_initial_camera_position + index_t new_index, + std::string_view new_name, + std::string_view new_description, + Date new_date, + fvec2_t new_initial_camera_position ); Bookmark(Bookmark&&) = default; }; @@ -35,9 +35,7 @@ namespace OpenVic { IdentifierRegistry IDENTIFIER_REGISTRY(bookmark); public: - bool add_bookmark( - std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position - ); + bool add_bookmark(std::string_view name, std::string_view description, Date date, fvec2_t initial_camera_position); bool load_bookmark_file(fixed_point_t map_height, ast::NodeCPtr root); Date get_last_bookmark_date() const; @@ -51,4 +49,4 @@ struct fmt::formatter : formatter { format_context::iterator format(Bookmark const&, format_context& ctx) const { return ctx.out(); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/history/CountryHistory.cpp b/src/openvic-simulation/history/CountryHistory.cpp index 4c3697266..bf7b91711 100644 --- a/src/openvic-simulation/history/CountryHistory.cpp +++ b/src/openvic-simulation/history/CountryHistory.cpp @@ -1,20 +1,23 @@ #include "CountryHistory.hpp" +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/politics/Government.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; CountryHistoryEntry::CountryHistoryEntry( - CountryDefinition const& new_country, Date new_date, decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, - decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys -) : HistoryEntry { new_date }, country { new_country }, upper_house_proportion_by_ideology { ideology_keys }, - flag_overrides_by_government_type { government_type_keys } {} + CountryDefinition const& new_country, + Date new_date, + decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, + decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys +) : + HistoryEntry { new_date }, country { new_country }, upper_house_proportion_by_ideology { ideology_keys }, + flag_overrides_by_government_type { government_type_keys } {} fixed_point_t CountryHistoryEntry::get_upper_house_proportion_by_ideology(Ideology const& key) const { return upper_house_proportion_by_ideology.at(key); @@ -25,8 +28,9 @@ GovernmentType const* CountryHistoryEntry::get_flag_overrides_by_government_type } CountryHistoryMap::CountryHistoryMap( - CountryDefinition const& new_country, decltype(ideology_keys) new_ideology_keys, - decltype(government_type_keys) new_government_type_keys + CountryDefinition const& new_country, + decltype(ideology_keys) new_ideology_keys, + decltype(government_type_keys) new_government_type_keys ) : country { new_country }, ideology_keys { new_ideology_keys }, government_type_keys { new_government_type_keys } {} memory::unique_ptr CountryHistoryMap::_make_entry(Date date) const { @@ -44,8 +48,11 @@ static constexpr auto _flag_callback(string_map_t& flags, bool value) { } bool CountryHistoryMap::_load_history_entry( - DefinitionManager const& definition_manager, Dataloader const& dataloader, DeploymentManager& deployment_manager, - CountryHistoryEntry& entry, ast::NodeCPtr root + DefinitionManager const& definition_manager, + Dataloader const& dataloader, + DeploymentManager& deployment_manager, + CountryHistoryEntry& entry, + ast::NodeCPtr root ) { PoliticsManager const& politics_manager = definition_manager.get_politics_manager(); IssueManager const& issue_manager = politics_manager.get_issue_manager(); @@ -65,20 +72,23 @@ bool CountryHistoryMap::_load_history_entry( } else if (it->second == add) { // Desired culture instruction already exists spdlog::warn_s( - "Duplicate attempt to {} accepted culture {} {} country history of {}", - add ? "add" : "remove", add ? "to" : "from", culture, entry.country + "Duplicate attempt to {} accepted culture {} {} country history of {}", + add ? "add" : "remove", + add ? "to" : "from", + culture, + entry.country ); return true; } else { // Opposite culture instruction exists entry.accepted_cultures.erase(it); spdlog::warn_s( - "Attempted to {} accepted culture {} {} country history of {} after previously {} it", - add ? "add" : "remove", - culture, - add ? "to" : "from", - entry.country, - add ? "removing" : "adding" + "Attempted to {} accepted culture {} {} country history of {} after previously {} it", + add ? "add" : "remove", + culture, + add ? "to" : "from", + entry.country, + add ? "removing" : "adding" ); return true; } @@ -328,9 +338,12 @@ CountryHistoryMap const* CountryHistoryManager::get_country_history(CountryDefin } bool CountryHistoryManager::load_country_history_file( - DefinitionManager& definition_manager, Dataloader const& dataloader, CountryDefinition const& country, - decltype(CountryHistoryMap::ideology_keys) ideology_keys, - decltype(CountryHistoryMap::government_type_keys) government_type_keys, ast::NodeCPtr root + DefinitionManager& definition_manager, + Dataloader const& dataloader, + CountryDefinition const& country, + decltype(CountryHistoryMap::ideology_keys) ideology_keys, + decltype(CountryHistoryMap::government_type_keys) government_type_keys, + ast::NodeCPtr root ) { if (locked) { spdlog::error_s("Attempted to load country history file for {} after country history registry was locked!", country); @@ -343,8 +356,9 @@ bool CountryHistoryManager::load_country_history_file( decltype(country_histories)::iterator it = country_histories.find(&country); if (it == country_histories.end()) { - const std::pair result = - country_histories.emplace(&country, CountryHistoryMap { country, ideology_keys, government_type_keys }); + const std::pair result = country_histories.emplace( + &country, CountryHistoryMap { country, ideology_keys, government_type_keys } + ); if (result.second) { it = result.first; } else { @@ -355,6 +369,6 @@ bool CountryHistoryManager::load_country_history_file( CountryHistoryMap& country_history = it.value(); return country_history._load_history_file( - definition_manager, dataloader, definition_manager.get_military_manager().get_deployment_manager(), root + definition_manager, dataloader, definition_manager.get_military_manager().get_deployment_manager(), root ); } diff --git a/src/openvic-simulation/history/CountryHistory.hpp b/src/openvic-simulation/history/CountryHistory.hpp index 01cac766e..87ecc89e7 100644 --- a/src/openvic-simulation/history/CountryHistory.hpp +++ b/src/openvic-simulation/history/CountryHistory.hpp @@ -5,10 +5,10 @@ #include "openvic-simulation/core/memory/SmartPtr.hpp" #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/history/HistoryMap.hpp" +#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/research/TechnologyUnlockLevel.hpp" namespace OpenVic { struct CountryHistoryMap; @@ -29,6 +29,7 @@ namespace OpenVic { struct CountryHistoryEntry : HistoryEntry { friend struct CountryHistoryMap; + private: std::optional PROPERTY(primary_culture); ordered_map PROPERTY(accepted_cultures); @@ -64,8 +65,10 @@ namespace OpenVic { CountryDefinition const& country; CountryHistoryEntry( - CountryDefinition const& new_country, const Date new_date, decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, - decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys + CountryDefinition const& new_country, + const Date new_date, + decltype(upper_house_proportion_by_ideology)::keys_span_type ideology_keys, + decltype(flag_overrides_by_government_type)::keys_span_type government_type_keys ); }; @@ -83,14 +86,18 @@ namespace OpenVic { protected: CountryHistoryMap( - CountryDefinition const& new_country, decltype(ideology_keys) new_ideology_keys, - decltype(government_type_keys) new_government_type_keys + CountryDefinition const& new_country, + decltype(ideology_keys) new_ideology_keys, + decltype(government_type_keys) new_government_type_keys ); memory::unique_ptr _make_entry(Date date) const override; bool _load_history_entry( - DefinitionManager const& definition_manager, Dataloader const& dataloader, DeploymentManager& deployment_manager, - CountryHistoryEntry& entry, ast::NodeCPtr root + DefinitionManager const& definition_manager, + Dataloader const& dataloader, + DeploymentManager& deployment_manager, + CountryHistoryEntry& entry, + ast::NodeCPtr root ) override; }; @@ -109,9 +116,12 @@ namespace OpenVic { CountryHistoryMap const* get_country_history(CountryDefinition const& country) const; bool load_country_history_file( - DefinitionManager& definition_manager, Dataloader const& dataloader, CountryDefinition const& country, - decltype(CountryHistoryMap::ideology_keys) ideology_keys, - decltype(CountryHistoryMap::government_type_keys) government_type_keys, ast::NodeCPtr root + DefinitionManager& definition_manager, + Dataloader const& dataloader, + CountryDefinition const& country, + decltype(CountryHistoryMap::ideology_keys) ideology_keys, + decltype(CountryHistoryMap::government_type_keys) government_type_keys, + ast::NodeCPtr root ); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/DiplomaticHistory.cpp b/src/openvic-simulation/history/DiplomaticHistory.cpp index 1b4f20d86..3bb1c549a 100644 --- a/src/openvic-simulation/history/DiplomaticHistory.cpp +++ b/src/openvic-simulation/history/DiplomaticHistory.cpp @@ -16,7 +16,7 @@ void DiplomaticHistoryManager::reserve_more_wars(size_t size) { void DiplomaticHistoryManager::lock_diplomatic_history() { SPDLOG_INFO( - "Locked diplomacy history registry after registering {} items", alliances.size() + subjects.size() + wars.size() + "Locked diplomacy history registry after registering {} items", alliances.size() + subjects.size() + wars.size() ); locked = true; } @@ -38,7 +38,7 @@ memory::vector> DiplomaticHistoryManage } bool DiplomaticHistoryManager::load_diplomacy_history_file( - CountryDefinitionManager const& country_definition_manager, ast::NodeCPtr root + CountryDefinitionManager const& country_definition_manager, ast::NodeCPtr root ) { // Default vanilla alliances is 2, 54 is the max I've seen in mods // Eliminates reallocations at the cost of memory usage diff --git a/src/openvic-simulation/history/DiplomaticHistory.hpp b/src/openvic-simulation/history/DiplomaticHistory.hpp index 96620b8d8..3d1a72d64 100644 --- a/src/openvic-simulation/history/DiplomaticHistory.hpp +++ b/src/openvic-simulation/history/DiplomaticHistory.hpp @@ -24,8 +24,7 @@ namespace OpenVic { template static memory::vector> filter_by_date( - std::span items, - const Date date + std::span items, const Date date ) { memory::vector> ret; for (HistoryType const& item : items) { @@ -51,7 +50,7 @@ namespace OpenVic { [[nodiscard]] memory::vector> get_reparations(Date date) const { return filter_by_date(reparations, date); } - [[nodiscard]] memory::vector> get_subjects(Date date) const{ + [[nodiscard]] memory::vector> get_subjects(Date date) const { return filter_by_date(subjects, date); } /* Returns all wars that begin before date. NOTE: Some wargoals may be added or countries may join after date, diff --git a/src/openvic-simulation/history/HistoryManager.hpp b/src/openvic-simulation/history/HistoryManager.hpp index 80be9647a..e36ed7bd1 100644 --- a/src/openvic-simulation/history/HistoryManager.hpp +++ b/src/openvic-simulation/history/HistoryManager.hpp @@ -14,6 +14,7 @@ namespace OpenVic { CountryHistoryManager PROPERTY_REF(country_manager); ProvinceHistoryManager PROPERTY_REF(province_manager); DiplomaticHistoryManager PROPERTY_REF(diplomacy_manager); + public: HistoryManager(DefinitionManager const& definition_manager) : province_manager { definition_manager } {} }; diff --git a/src/openvic-simulation/history/HistoryMap.hpp b/src/openvic-simulation/history/HistoryMap.hpp index b80b8c0fb..7ed6fbd2f 100644 --- a/src/openvic-simulation/history/HistoryMap.hpp +++ b/src/openvic-simulation/history/HistoryMap.hpp @@ -14,6 +14,7 @@ namespace OpenVic { struct HistoryEntry { protected: constexpr HistoryEntry(const Date new_date) : date { new_date } {} + public: const Date date; }; @@ -33,10 +34,8 @@ namespace OpenVic { private: ordered_map> PROPERTY(entries); - bool _try_load_history_entry( - DefinitionManager const& definition_manager, Args... args, Date date, ast::NodeCPtr root - ) { - entry_type *const entry = _get_or_make_entry(definition_manager, date); + bool _try_load_history_entry(DefinitionManager const& definition_manager, Args... args, Date date, ast::NodeCPtr root) { + entry_type* const entry = _get_or_make_entry(definition_manager, date); if (entry != nullptr) { return _load_history_entry(definition_manager, args..., *entry, root); } else { @@ -50,28 +49,28 @@ namespace OpenVic { virtual memory::unique_ptr _make_entry(Date date) const = 0; virtual bool _load_history_entry( - DefinitionManager const& definition_manager, Args... args, entry_type& entry, ast::NodeCPtr root + DefinitionManager const& definition_manager, Args... args, entry_type& entry, ast::NodeCPtr root ) = 0; bool _load_history_file(DefinitionManager const& definition_manager, Args... args, ast::NodeCPtr root) { return _try_load_history_entry( - definition_manager, args..., _HistoryMapHelperFuncs::_get_start_date(definition_manager), root + definition_manager, args..., _HistoryMapHelperFuncs::_get_start_date(definition_manager), root ); } bool _load_history_sub_entry_callback( - DefinitionManager const& definition_manager, - Args... args, - Date date, - ast::NodeCPtr root, - NodeTools::template_key_map_t const& key_map, - std::string_view key, - ast::NodeCPtr value + DefinitionManager const& definition_manager, + Args... args, + Date date, + ast::NodeCPtr root, + NodeTools::template_key_map_t const& key_map, + std::string_view key, + ast::NodeCPtr value ) { /* Date blocks (loaded into the corresponding HistoryEntry) */ Date::from_chars_result result; const Date sub_date { Date::from_string(key, &result) }; - if (result.ec == std::errc{}) { + if (result.ec == std::errc {}) { if (sub_date < date) { spdlog::warn_s("History entry {} defined before parent entry date {}", sub_date, date); } @@ -85,8 +84,10 @@ namespace OpenVic { return false; } } - - return NodeTools::map_key_value_invalid_callback>(key_map, key, value); + + return NodeTools::map_key_value_invalid_callback>( + key_map, key, value + ); } /* Returns history entry at specific date, if date doesn't have an entry creates one, if that fails returns nullptr. */ diff --git a/src/openvic-simulation/history/Period.hpp b/src/openvic-simulation/history/Period.hpp index 7d8661b16..a6910c0af 100644 --- a/src/openvic-simulation/history/Period.hpp +++ b/src/openvic-simulation/history/Period.hpp @@ -11,8 +11,8 @@ namespace OpenVic { std::optional end_date; public: - constexpr Period(const Date new_start_date, const std::optional new_end_date) - : start_date { new_start_date }, end_date { new_end_date } {} + constexpr Period(const Date new_start_date, const std::optional new_end_date) : + start_date { new_start_date }, end_date { new_end_date } {} bool is_date_in_period(Date date) const; bool try_set_end(Date date); diff --git a/src/openvic-simulation/history/ProvinceHistory.cpp b/src/openvic-simulation/history/ProvinceHistory.cpp index 530c3698e..ede856898 100644 --- a/src/openvic-simulation/history/ProvinceHistory.cpp +++ b/src/openvic-simulation/history/ProvinceHistory.cpp @@ -15,40 +15,32 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; ProvinceHistoryEntry::ProvinceHistoryEntry( - BuildingTypeManager const& building_type_manager, - ProvinceDefinition const& new_province, - Date new_date -) : HistoryEntry { new_date }, - province { new_province }, - province_building_levels { - province_building_index_t(building_type_manager.get_province_building_types().size()), - building_level_t(0) - } -{} + BuildingTypeManager const& building_type_manager, ProvinceDefinition const& new_province, Date new_date +) : + HistoryEntry { new_date }, province { new_province }, province_building_levels { + province_building_index_t(building_type_manager.get_province_building_types().size()), building_level_t(0) + } {} -ProvinceHistoryMap::ProvinceHistoryMap(ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager) - : province { new_province }, - building_type_manager { new_building_type_manager } - {} +ProvinceHistoryMap::ProvinceHistoryMap( + ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager +) : province { new_province }, building_type_manager { new_building_type_manager } {} memory::unique_ptr ProvinceHistoryMap::_make_entry(Date date) const { return memory::make_unique(building_type_manager, province, date); } bool ProvinceHistoryMap::_load_history_entry( - DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root + DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root ) { BuildingTypeManager const& building_type_manager = definition_manager.get_economy_manager().get_building_type_manager(); CountryDefinitionManager const& country_definition_manager = definition_manager.get_country_definition_manager(); GoodDefinitionManager const& good_definition_manager = - definition_manager.get_economy_manager().get_good_definition_manager(); + definition_manager.get_economy_manager().get_good_definition_manager(); IdeologyManager const& ideology_manager = definition_manager.get_politics_manager().get_ideology_manager(); TerrainTypeManager const& terrain_type_manager = definition_manager.get_map_definition().get_terrain_type_manager(); using enum colony_status_t; - static const string_map_t colony_status_map { - { "0", STATE }, { "1", PROTECTORATE }, { "2", COLONY } - }; + static const string_map_t colony_status_map { { "0", STATE }, { "1", PROTECTORATE }, { "2", COLONY } }; const auto set_core_instruction = [&entry](bool add) { return [&entry, add](CountryDefinition const& country) -> bool { @@ -60,23 +52,23 @@ bool ProvinceHistoryMap::_load_history_entry( } else if (it->second == add) { // Desired core instruction already exists spdlog::warn_s( - "Duplicate attempt to {} core of country {} {} province history of {}", - add ? "add" : "remove", - country, - add ? "to" : "from", - entry.province + "Duplicate attempt to {} core of country {} {} province history of {}", + add ? "add" : "remove", + country, + add ? "to" : "from", + entry.province ); return true; } else { // Opposite core instruction exists entry.cores.erase(it); spdlog::warn_s( - "Attempted to {} core of country {} {} province history of {} after previously {} it", - add ? "add" : "remove", - country, - add ? "to" : "from", - entry.province, - add ? "removing" : "adding" + "Attempted to {} core of country {} {} province history of {} after previously {} it", + add ? "add" : "remove", + country, + add ? "to" : "from", + entry.province, + add ? "removing" : "adding" ); return true; } @@ -276,14 +268,9 @@ ProvinceHistoryMap const* ProvinceHistoryManager::get_province_history(ProvinceD ProvinceHistoryMap* ProvinceHistoryManager::_get_or_make_province_history(ProvinceDefinition const& province) { decltype(province_histories)::iterator it = province_histories.find(&province); if (it == province_histories.end()) { - const std::pair result = - province_histories.emplace( - &province, - ProvinceHistoryMap { - province, - definition_manager.get_economy_manager().get_building_type_manager() - } - ); + const std::pair result = province_histories.emplace( + &province, ProvinceHistoryMap { province, definition_manager.get_economy_manager().get_building_type_manager() } + ); if (result.second) { it = result.first; } else { @@ -295,13 +282,10 @@ ProvinceHistoryMap* ProvinceHistoryManager::_get_or_make_province_history(Provin } bool ProvinceHistoryManager::load_province_history_file( - DefinitionManager const& definition_manager, ProvinceDefinition const& province, ast::NodeCPtr root + DefinitionManager const& definition_manager, ProvinceDefinition const& province, ast::NodeCPtr root ) { if (locked) { - spdlog::error_s( - "Attempted to load province history file for {} after province history registry was locked!", - province - ); + spdlog::error_s("Attempted to load province history file for {} after province history registry was locked!", province); return false; } @@ -314,20 +298,18 @@ bool ProvinceHistoryManager::load_province_history_file( } bool ProvinceHistoryEntry::_load_province_pop_history( - DefinitionManager const& definition_manager, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, ast::NodeCPtr root, bool* non_integer_size ) { PopManager const& pop_manager = definition_manager.get_pop_manager(); RebelManager const& rebel_manager = definition_manager.get_politics_manager().get_rebel_manager(); - return pop_manager.expect_pop_type_dictionary_reserve_length( - pops, - [this, &pop_manager, &rebel_manager, non_integer_size](PopType const& pop_type, ast::NodeCPtr pop_node) -> bool { - return pop_manager.load_pop_bases_into_vector(rebel_manager, pops, pop_type, pop_node, non_integer_size); - } - )(root); + return pop_manager + .expect_pop_type_dictionary_reserve_length(pops, [this, &pop_manager, &rebel_manager, non_integer_size](PopType const& pop_type, ast::NodeCPtr pop_node) -> bool { + return pop_manager.load_pop_bases_into_vector(rebel_manager, pops, pop_type, pop_node, non_integer_size); + })(root); } bool ProvinceHistoryMap::_load_province_pop_history( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ) { ProvinceHistoryEntry* entry = _get_or_make_entry(definition_manager, date); if (entry != nullptr) { @@ -338,20 +320,19 @@ bool ProvinceHistoryMap::_load_province_pop_history( } bool ProvinceHistoryManager::load_pop_history_file( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ) { if (locked) { spdlog::error_s("Attempted to load pop history file after province history registry was locked!"); return false; } - return definition_manager.get_map_definition().expect_province_definition_dictionary( - [this, &definition_manager, date, non_integer_size](ProvinceDefinition const& province, ast::NodeCPtr node) -> bool { - ProvinceHistoryMap* province_history = _get_or_make_province_history(province); - if (province_history != nullptr) { - return province_history->_load_province_pop_history(definition_manager, date, node, non_integer_size); - } else { - return false; - } - } - )(root); + return definition_manager.get_map_definition() + .expect_province_definition_dictionary([this, &definition_manager, date, non_integer_size](ProvinceDefinition const& province, ast::NodeCPtr node) -> bool { + ProvinceHistoryMap* province_history = _get_or_make_province_history(province); + if (province_history != nullptr) { + return province_history->_load_province_pop_history(definition_manager, date, node, non_integer_size); + } else { + return false; + } + })(root); } diff --git a/src/openvic-simulation/history/ProvinceHistory.hpp b/src/openvic-simulation/history/ProvinceHistory.hpp index 21501dbc1..a1d8d6e6e 100644 --- a/src/openvic-simulation/history/ProvinceHistory.hpp +++ b/src/openvic-simulation/history/ProvinceHistory.hpp @@ -6,15 +6,15 @@ #include "openvic-simulation/core/memory/SmartPtr.hpp" #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" +#include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/economy/BuildingType.hpp" #include "openvic-simulation/history/HistoryMap.hpp" +#include "openvic-simulation/map/LifeRating.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/economy/BuildingLevel.hpp" #include "openvic-simulation/types/ColonyStatus.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -#include "openvic-simulation/map/LifeRating.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -30,10 +30,9 @@ namespace OpenVic { friend struct ProvinceHistoryMap; ProvinceHistoryEntry( - BuildingTypeManager const& building_type_manager, - ProvinceDefinition const& new_province, - Date new_date + BuildingTypeManager const& building_type_manager, ProvinceDefinition const& new_province, Date new_date ); + private: std::optional PROPERTY(owner); std::optional PROPERTY(controller); @@ -44,18 +43,21 @@ namespace OpenVic { std::optional PROPERTY(life_rating); std::optional PROPERTY(terrain_type); memory::FixedVector province_building_levels; + public: constexpr TypedSpan get_province_building_levels() const { return province_building_levels; } + private: ordered_map PROPERTY(state_buildings); fixed_point_map_t PROPERTY(party_loyalties); memory::vector SPAN_PROPERTY(pops); bool _load_province_pop_history( - DefinitionManager const& definition_manager, ast::NodeCPtr root, bool *non_integer_size + DefinitionManager const& definition_manager, ast::NodeCPtr root, bool* non_integer_size ); + public: ProvinceDefinition const& province; }; @@ -73,12 +75,13 @@ namespace OpenVic { ProvinceHistoryMap(ProvinceDefinition const& new_province, BuildingTypeManager const& new_building_type_manager); memory::unique_ptr _make_entry(Date date) const override; - bool _load_history_entry(DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root) - override; + bool _load_history_entry( + DefinitionManager const& definition_manager, ProvinceHistoryEntry& entry, ast::NodeCPtr root + ) override; private: bool _load_province_pop_history( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ); }; @@ -93,7 +96,8 @@ namespace OpenVic { ProvinceHistoryMap* _get_or_make_province_history(ProvinceDefinition const& province); public: - ProvinceHistoryManager(DefinitionManager const& new_definition_manager) : definition_manager { new_definition_manager } {}; + ProvinceHistoryManager(DefinitionManager const& new_definition_manager) : + definition_manager { new_definition_manager } {}; void reserve_more_province_histories(size_t size); void lock_province_histories(MapDefinition const& map_definition, bool detailed_errors); @@ -102,10 +106,10 @@ namespace OpenVic { ProvinceHistoryMap const* get_province_history(ProvinceDefinition const* province) const; bool load_province_history_file( - DefinitionManager const& definition_manager, ProvinceDefinition const& province, ast::NodeCPtr root + DefinitionManager const& definition_manager, ProvinceDefinition const& province, ast::NodeCPtr root ); bool load_pop_history_file( - DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size + DefinitionManager const& definition_manager, Date date, ast::NodeCPtr root, bool* non_integer_size ); }; } diff --git a/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp b/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp index 353246f48..6a0be0797 100644 --- a/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/AllianceHistory.hpp @@ -13,10 +13,8 @@ namespace OpenVic { const Period period; constexpr AllianceHistory( - CountryDefinition const& new_first, - CountryDefinition const& new_second, - const Period new_period + CountryDefinition const& new_first, CountryDefinition const& new_second, const Period new_period ) : first { new_first }, second { new_second }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp b/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp index dd1afdfc3..fe8c365b7 100644 --- a/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/ReparationsHistory.hpp @@ -13,10 +13,8 @@ namespace OpenVic { const Period period; constexpr ReparationsHistory( - CountryDefinition const& new_receiver, - CountryDefinition const& new_sender, - const Period new_period + CountryDefinition const& new_receiver, CountryDefinition const& new_sender, const Period new_period ) : receiver { new_receiver }, sender { new_sender }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp b/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp index 70f8fd726..e7aaa720f 100644 --- a/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/SubjectHistory.hpp @@ -19,11 +19,11 @@ namespace OpenVic { const Period period; constexpr SubjectHistory( - CountryDefinition const& new_overlord, - CountryDefinition const& new_subject, - const type_t new_subject_type, - const Period new_period + CountryDefinition const& new_overlord, + CountryDefinition const& new_subject, + const type_t new_subject_type, + const Period new_period ) : overlord { new_overlord }, subject { new_subject }, subject_type { new_subject_type }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/history/diplomacy/WarHistory.cpp b/src/openvic-simulation/history/diplomacy/WarHistory.cpp index c9f363371..277279658 100644 --- a/src/openvic-simulation/history/diplomacy/WarHistory.cpp +++ b/src/openvic-simulation/history/diplomacy/WarHistory.cpp @@ -3,9 +3,10 @@ using namespace OpenVic; WarHistory::WarHistory( - std::string_view new_war_name, - memory::vector&& new_attackers, - memory::vector&& new_defenders, - memory::vector&& new_wargoals -) : war_name { new_war_name }, attackers { std::move(new_attackers) }, defenders { std::move(new_defenders) }, - wargoals { std::move(new_wargoals) } {} \ No newline at end of file + std::string_view new_war_name, + memory::vector&& new_attackers, + memory::vector&& new_defenders, + memory::vector&& new_wargoals +) : + war_name { new_war_name }, attackers { std::move(new_attackers) }, defenders { std::move(new_defenders) }, + wargoals { std::move(new_wargoals) } {} diff --git a/src/openvic-simulation/history/diplomacy/WarHistory.hpp b/src/openvic-simulation/history/diplomacy/WarHistory.hpp index 06b2b7e7f..123fccbc2 100644 --- a/src/openvic-simulation/history/diplomacy/WarHistory.hpp +++ b/src/openvic-simulation/history/diplomacy/WarHistory.hpp @@ -12,11 +12,11 @@ namespace OpenVic { struct CountryDefinition; struct ProvinceDefinition; struct WargoalType; - + struct WarHistory { friend struct DiplomaticHistoryManager; - struct added_wargoal_t { + struct added_wargoal_t { public: const Date date_added; CountryDefinition const& actor; @@ -26,20 +26,17 @@ namespace OpenVic { // TODO - could these just be nullptr when unset rather than using optionals? const std::optional third_party; const std::optional target; - + constexpr added_wargoal_t( - const Date new_date_added, - CountryDefinition const& new_actor, - CountryDefinition const& new_receiver, - WargoalType const& new_wargoal, - std::optional new_third_party, - std::optional new_target - ) : date_added { new_date_added }, - actor { new_actor }, - receiver { new_receiver }, - wargoal { new_wargoal }, - third_party { new_third_party }, - target { new_target } {} + const Date new_date_added, + CountryDefinition const& new_actor, + CountryDefinition const& new_receiver, + WargoalType const& new_wargoal, + std::optional new_third_party, + std::optional new_target + ) : + date_added { new_date_added }, actor { new_actor }, receiver { new_receiver }, wargoal { new_wargoal }, + third_party { new_third_party }, target { new_target } {} }; static_assert(std::is_trivially_move_constructible_v); @@ -50,15 +47,17 @@ namespace OpenVic { public: CountryDefinition const& country; - - constexpr war_participant_t(CountryDefinition const& new_country, const Period new_period) - : country { new_country }, period { new_period } {} + + constexpr war_participant_t(CountryDefinition const& new_country, const Period new_period) : + country { new_country }, period { new_period } {} }; static_assert(std::is_trivially_move_constructible_v); WarHistory( - std::string_view new_war_name, memory::vector&& new_attackers, - memory::vector&& new_defenders, memory::vector&& new_wargoals + std::string_view new_war_name, + memory::vector&& new_attackers, + memory::vector&& new_defenders, + memory::vector&& new_wargoals ); private: @@ -69,4 +68,4 @@ namespace OpenVic { memory::vector SPAN_PROPERTY(defenders); memory::vector SPAN_PROPERTY(wargoals); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXObject.cpp b/src/openvic-simulation/interface/GFXObject.cpp index c889bfbd3..554462447 100644 --- a/src/openvic-simulation/interface/GFXObject.cpp +++ b/src/openvic-simulation/interface/GFXObject.cpp @@ -7,53 +7,71 @@ using namespace OpenVic; using namespace OpenVic::GFX; using namespace OpenVic::NodeTools; -node_callback_t Object::expect_objects(length_callback_t length_callback, callback_t&&> callback) { +node_callback_t Object::expect_objects( + length_callback_t length_callback, callback_t&&> callback +) { return expect_dictionary_keys_and_length( - length_callback, - - "EMFXActorType", ZERO_OR_MORE, _expect_instance(callback), - - /* arrows.gfx */ - "arrowType", ZERO_OR_MORE, _expect_instance(callback), - - /* battlearrow.gfx */ - "battlearrow", ZERO_OR_MORE, _expect_instance(callback), - "mapinfo", ZERO_OR_MORE, _expect_instance(callback), - - /* mapitems.gfx */ - "projectionType", ZERO_OR_MORE, _expect_instance(callback), - "progressbar3dType", ZERO_OR_MORE, _expect_instance(callback), - "billboardType", ZERO_OR_MORE, _expect_instance(callback), - "unitstatsBillboardType", ZERO_OR_MORE, success_callback, - - /* core.gfx */ - "animatedmaptext", ZERO_OR_MORE, _expect_instance(callback), - - "flagType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback, - "size", ONE_EXACTLY, success_callback - ), - "provinceType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "provinceWaterType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "mapTextType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback - ), - "meshType", ZERO_OR_MORE, expect_dictionary_keys( - "name", ONE_EXACTLY, success_callback, - "xfile", ONE_EXACTLY, success_callback - ) + length_callback, + + "EMFXActorType", + ZERO_OR_MORE, + _expect_instance(callback), + + /* arrows.gfx */ + "arrowType", + ZERO_OR_MORE, + _expect_instance(callback), + + /* battlearrow.gfx */ + "battlearrow", + ZERO_OR_MORE, + _expect_instance(callback), + "mapinfo", + ZERO_OR_MORE, + _expect_instance(callback), + + /* mapitems.gfx */ + "projectionType", + ZERO_OR_MORE, + _expect_instance(callback), + "progressbar3dType", + ZERO_OR_MORE, + _expect_instance(callback), + "billboardType", + ZERO_OR_MORE, + _expect_instance(callback), + "unitstatsBillboardType", + ZERO_OR_MORE, + success_callback, + + /* core.gfx */ + "animatedmaptext", + ZERO_OR_MORE, + _expect_instance(callback), + + "flagType", + ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback, "size", ONE_EXACTLY, success_callback), + "provinceType", + ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback), + "provinceWaterType", + ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback), + "mapTextType", + ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback), + "meshType", + ZERO_OR_MORE, + expect_dictionary_keys("name", ONE_EXACTLY, success_callback, "xfile", ONE_EXACTLY, success_callback) ); } -Actor::Attachment::Attachment(std::string_view new_actor_name, std::string_view new_attach_node, attach_id_t new_attach_id) - : actor_name { new_actor_name }, attach_node { new_attach_node }, attach_id { new_attach_id } {} +Actor::Attachment::Attachment(std::string_view new_actor_name, std::string_view new_attach_node, attach_id_t new_attach_id) : + actor_name { new_actor_name }, attach_node { new_attach_node }, attach_id { new_attach_id } {} -Actor::Animation::Animation(std::string_view new_file, fixed_point_t new_scroll_time) - : file { new_file }, scroll_time { new_scroll_time } {} +Actor::Animation::Animation(std::string_view new_file, fixed_point_t new_scroll_time) : + file { new_file }, scroll_time { new_scroll_time } {} Actor::Actor() {} @@ -68,16 +86,20 @@ bool Actor::_set_animation(std::string_view name, std::string_view file, fixed_p animation = &attack_animation; } else { spdlog::error_s( - "Unknown animation type \"{}\" for actor {} (with file {} and scroll time {})", - name, get_name(), file, scroll_time + "Unknown animation type \"{}\" for actor {} (with file {} and scroll time {})", name, get_name(), file, scroll_time ); return false; } if (animation->has_value()) { spdlog::error_s( - "Duplicate {} animation for actor {}: {} with scroll time {} (already set to {} with scroll time {})", - name, get_name(), file, scroll_time, (*animation)->file, (*animation)->scroll_time + "Duplicate {} animation for actor {}: {} with scroll time {} (already set to {} with scroll time {})", + name, + get_name(), + file, + scroll_time, + (*animation)->file, + (*animation)->scroll_time ); return false; } @@ -97,51 +119,66 @@ bool Actor::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { using namespace std::string_view_literals; static const auto bind_set_animation = [](Actor* self, std::string_view name) { - return [self, name](std::string_view file){ return self->_set_animation(name, file, 0); }; + return [self, name](std::string_view file) { + return self->_set_animation(name, file, 0); + }; }; // Default max vanilla attachments is 1, 3 is the max I've seen in mods attachments.reserve(1); - ret &= add_key_map_entries(key_map, - "actorfile", ONE_EXACTLY, expect_string(assign_variable_callback_string(model_file)), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), - - "attach", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { - std::string_view actor_name {}, attach_node {}; - Attachment::attach_id_t attach_id = 0; - - if (!expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(actor_name)), - "node", ONE_EXACTLY, expect_string(assign_variable_callback(attach_node)), - "attachId", ONE_EXACTLY, expect_uint(assign_variable_callback(attach_id)) - )(node)) { - spdlog::error_s("Failed to load attachment for actor {}", get_name()); - return false; - } - - attachments.emplace_back(actor_name, attach_node, attach_id); - return true; - }, - - "idle", ZERO_OR_ONE, expect_string(bind_set_animation(this, "idle"sv)), - "move", ZERO_OR_ONE, expect_string(bind_set_animation(this, "move"sv)), - "attack", ZERO_OR_ONE, expect_string(bind_set_animation(this, "attack"sv)), - "animation", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { - std::string_view name {}, file {}; - fixed_point_t scroll_time = 0; - - if (!expect_dictionary_keys( - "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), - "file", ONE_EXACTLY, expect_string(assign_variable_callback(file)), - "defaultAnimationTime", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scroll_time)) - )(node)) { - spdlog::error_s("Failed to load animation for actor {}", get_name()); - return false; - } - - return _set_animation(name, file, scroll_time); - } + ret &= add_key_map_entries( + key_map, + "actorfile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(model_file)), + "scale", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(scale)), + + "attach", + ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { + std::string_view actor_name {}, attach_node {}; + Attachment::attach_id_t attach_id = 0; + + if (!expect_dictionary_keys< + StringMapCaseInsensitive>("name", ONE_EXACTLY, expect_string(assign_variable_callback(actor_name)), "node", ONE_EXACTLY, expect_string(assign_variable_callback(attach_node)), "attachId", ONE_EXACTLY, expect_uint(assign_variable_callback(attach_id)))( + node + )) { + spdlog::error_s("Failed to load attachment for actor {}", get_name()); + return false; + } + + attachments.emplace_back(actor_name, attach_node, attach_id); + return true; + }, + + "idle", + ZERO_OR_ONE, + expect_string(bind_set_animation(this, "idle"sv)), + "move", + ZERO_OR_ONE, + expect_string(bind_set_animation(this, "move"sv)), + "attack", + ZERO_OR_ONE, + expect_string(bind_set_animation(this, "attack"sv)), + "animation", + ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { + std::string_view name {}, file {}; + fixed_point_t scroll_time = 0; + + if (!expect_dictionary_keys< + StringMapCaseInsensitive>("name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), "file", ONE_EXACTLY, expect_string(assign_variable_callback(file)), "defaultAnimationTime", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scroll_time)))( + node + )) { + spdlog::error_s("Failed to load animation for actor {}", get_name()); + return false; + } + + return _set_animation(name, file, scroll_time); + } ); return ret; @@ -153,17 +190,38 @@ ArrowType::ArrowType() {} bool ArrowType::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(size)), - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "bodytexture", ONE_EXACTLY, expect_string(assign_variable_callback_string(body_texture_file)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "endAt", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(end_at)), - "height", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(height)), - "type", ONE_EXACTLY, expect_int64(assign_variable_callback(arrow_type)), - "heading", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(heading)), - "effect", ONE_EXACTLY, expect_string(assign_variable_callback_string(effect_file)) + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(size)), + "textureFile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_file)), + "bodytexture", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(body_texture_file)), + "color", + ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), + "colortwo", + ONE_EXACTLY, + expect_colour(assign_variable_callback(progress_colour)), + "endAt", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(end_at)), + "height", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(height)), + "type", + ONE_EXACTLY, + expect_int64(assign_variable_callback(arrow_type)), + "heading", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(heading)), + "effect", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(effect_file)) ); return ret; @@ -175,17 +233,38 @@ BattleArrow::BattleArrow() {} bool BattleArrow::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_body)), - "textureFile1", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_arrow_head)), - "start", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(start)), - "stop", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(stop)), - "x", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(dims.x)), - "y", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(dims.y)), - "font", ONE_EXACTLY, expect_string(assign_variable_callback_string(font)), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), - "nofade", ZERO_OR_ONE, expect_bool(assign_variable_callback(no_fade)), - "textureloop", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(texture_loop)) + ret &= add_key_map_entries( + key_map, + "textureFile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_arrow_body)), + "textureFile1", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_arrow_head)), + "start", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(start)), + "stop", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(stop)), + "x", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(dims.x)), + "y", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(dims.y)), + "font", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(font)), + "scale", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(scale)), + "nofade", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(no_fade)), + "textureloop", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(texture_loop)) ); return ret; @@ -196,9 +275,14 @@ MapInfo::MapInfo() {} bool MapInfo::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)) + ret &= add_key_map_entries( + key_map, + "textureFile", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file)), + "scale", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)) ); return ret; @@ -207,25 +291,46 @@ bool MapInfo::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { /* MapItems.gfx */ Projection::Projection() {} -//TODO: Verify... -// whether pulseSpeed is fixedpoint_t or int -// pulseSpeed doesn't seem to do anything, so assume fixed_point_t since its a speed -//fadeout could be int, expect_int_bool, or fixed_point_t -//fadeout seems not to do anything +// TODO: Verify... +// whether pulseSpeed is fixedpoint_t or int +// pulseSpeed doesn't seem to do anything, so assume fixed_point_t since its a speed +// fadeout could be int, expect_int_bool, or fixed_point_t +// fadeout seems not to do anything bool Projection::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "size", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(size)), - "spin", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spin)), - "pulsating", ONE_EXACTLY, expect_bool(assign_variable_callback(pulsating)), - "pulseLowest", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pulse_lowest)), - "pulseSpeed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pulse_speed)), - "additative", ONE_EXACTLY, expect_bool(assign_variable_callback(additative)), - "expanding", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(expanding)), - "duration", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(duration)), - "fadeout", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(fadeout)) + ret &= add_key_map_entries( + key_map, + "textureFile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_file)), + "size", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(size)), + "spin", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spin)), + "pulsating", + ONE_EXACTLY, + expect_bool(assign_variable_callback(pulsating)), + "pulseLowest", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pulse_lowest)), + "pulseSpeed", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(pulse_speed)), + "additative", + ONE_EXACTLY, + expect_bool(assign_variable_callback(additative)), + "expanding", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(expanding)), + "duration", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(duration)), + "fadeout", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(fadeout)) ); return ret; @@ -237,24 +342,38 @@ Billboard::Billboard() {} bool Billboard::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "texturefile", ONE_EXACTLY, expect_string(assign_variable_callback_string(texture_file)), - "noOfFrames", ZERO_OR_ONE, expect_uint((callback_t)[this](frame_t frames_read) -> bool { - if (frames_read < 1) { - spdlog::error_s( - "Billboard {} had an invalid number of frames {}, setting number of frames to 1", - this->get_name(), frames_read - ); - no_of_frames = 1; - return false; - } - no_of_frames = frames_read; - return true; - }), - "scale", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(scale)), - "font_size", ZERO_OR_ONE, success_callback, - "offset2", ZERO_OR_ONE, success_callback, - "font", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "texturefile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(texture_file)), + "noOfFrames", + ZERO_OR_ONE, + expect_uint((callback_t)[this](frame_t frames_read) -> bool { + if (frames_read < 1) { + spdlog::error_s( + "Billboard {} had an invalid number of frames {}, setting number of frames to 1", + this->get_name(), + frames_read + ); + no_of_frames = 1; + return false; + } + no_of_frames = frames_read; + return true; + }), + "scale", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(scale)), + "font_size", + ZERO_OR_ONE, + success_callback, + "offset2", + ZERO_OR_ONE, + success_callback, + "font", + ZERO_OR_ONE, + success_callback ); return ret; @@ -265,11 +384,20 @@ ProgressBar3d::ProgressBar3d() {} bool ProgressBar3d::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - "effectFile", ONE_EXACTLY, expect_string(assign_variable_callback_string(effect_file)) + ret &= add_key_map_entries( + key_map, + "color", + ONE_EXACTLY, + expect_colour(assign_variable_callback(progress_colour)), + "colortwo", + ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), + "size", + ONE_EXACTLY, + expect_ivec2(assign_variable_callback(size)), + "effectFile", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(effect_file)) ); return ret; @@ -282,19 +410,40 @@ AnimatedMapText::AnimatedMapText() {} bool AnimatedMapText::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Object::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "speed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(speed)), - "position", ZERO_OR_ONE, expect_fvec3(assign_variable_callback(position)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)), - "textblock", ONE_EXACTLY, expect_dictionary_keys( - "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "font", ONE_EXACTLY, expect_string(assign_variable_callback_string(font)), - "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(text_position)), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "format", ONE_EXACTLY, expect_text_format(assign_variable_callback(format)) - ) + ret &= add_key_map_entries( + key_map, + "speed", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(speed)), + "position", + ZERO_OR_ONE, + expect_fvec3(assign_variable_callback(position)), + "scale", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)), + "textblock", + ONE_EXACTLY, + expect_dictionary_keys( + "text", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(text)), + "color", + ONE_EXACTLY, + expect_colour(assign_variable_callback(colour)), + "font", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(font)), + "position", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(text_position)), + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "format", + ONE_EXACTLY, + expect_text_format(assign_variable_callback(format)) + ) ); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXObject.hpp b/src/openvic-simulation/interface/GFXObject.hpp index 842bdb4cd..31f1d5636 100644 --- a/src/openvic-simulation/interface/GFXObject.hpp +++ b/src/openvic-simulation/interface/GFXObject.hpp @@ -21,7 +21,7 @@ namespace OpenVic::GFX { OV_DETAIL_GET_TYPE static NodeTools::node_callback_t expect_objects( - NodeTools::length_callback_t length_callback, NodeTools::callback_t&&> callback + NodeTools::length_callback_t length_callback, NodeTools::callback_t&&> callback ); }; @@ -77,20 +77,20 @@ namespace OpenVic::GFX { /* arrows.gfx */ class ArrowType final : public Object { - //Named<> already handles the name property + // Named<> already handles the name property fixed_point_t PROPERTY(size, 5); - //texture_file is unused, body_texture_file determines the appearance of the arrow - memory::string PROPERTY(texture_file); //unused + // texture_file is unused, body_texture_file determines the appearance of the arrow + memory::string PROPERTY(texture_file); // unused memory::string PROPERTY(body_texture_file); - //colours dont appear to be used - //TODO: Verify these property names for color and colortwo are correct + // colours dont appear to be used + // TODO: Verify these property names for color and colortwo are correct colour_t PROPERTY(back_colour); colour_t PROPERTY(progress_colour); - fixed_point_t PROPERTY(end_at, 1); //how should float be repd? >> fixed_point handles it + fixed_point_t PROPERTY(end_at, 1); // how should float be repd? >> fixed_point handles it fixed_point_t PROPERTY(height, 1); - uint64_t PROPERTY(arrow_type, 0); //TODO: what does this do? - fixed_point_t PROPERTY(heading, 1); //also float + uint64_t PROPERTY(arrow_type, 0); // TODO: what does this do? + fixed_point_t PROPERTY(heading, 1); // also float memory::string PROPERTY(effect_file); @@ -111,10 +111,10 @@ namespace OpenVic::GFX { memory::string PROPERTY(texture_arrow_body); memory::string PROPERTY(texture_arrow_head); - fixed_point_t PROPERTY(start, 1); //labelled 'body start width' in file - fixed_point_t PROPERTY(stop, 1); //labelled 'body end width' in file + fixed_point_t PROPERTY(start, 1); // labelled 'body start width' in file + fixed_point_t PROPERTY(stop, 1); // labelled 'body end width' in file - fvec2_t PROPERTY(dims, { 1, 1 }); //x,y labelled 'arrow length','arrow height' in file + fvec2_t PROPERTY(dims, { 1, 1 }); // x,y labelled 'arrow length','arrow height' in file memory::string PROPERTY(font); fixed_point_t PROPERTY(scale, 1); bool PROPERTY(no_fade, false); @@ -149,7 +149,7 @@ namespace OpenVic::GFX { /* mapitems.gfx */ class Projection final : public Object { memory::string PROPERTY(texture_file); - //TODO: pulseSpeed, fadeout be ints or fixed points? assume fixed_point_t to start + // TODO: pulseSpeed, fadeout be ints or fixed points? assume fixed_point_t to start fixed_point_t PROPERTY(size, 1); fixed_point_t PROPERTY(spin, 1); bool PROPERTY(pulsating, false); @@ -157,8 +157,8 @@ namespace OpenVic::GFX { fixed_point_t PROPERTY(pulse_speed, 1); bool PROPERTY(additative, false); fixed_point_t PROPERTY(expanding, 1); - fixed_point_t PROPERTY(duration, 0); //0 means it stays indefinitely (also the default value) - fixed_point_t PROPERTY(fadeout, 0); //appears to have no effect + fixed_point_t PROPERTY(duration, 0); // 0 means it stays indefinitely (also the default value) + fixed_point_t PROPERTY(fadeout, 0); // appears to have no effect protected: bool _fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) override; @@ -211,7 +211,7 @@ namespace OpenVic::GFX { using enum text_format_t; private: - //textblock + // textblock memory::string PROPERTY(text); colour_t PROPERTY(colour); memory::string PROPERTY(font); @@ -220,7 +220,7 @@ namespace OpenVic::GFX { fvec2_t PROPERTY(size); text_format_t PROPERTY(format, text_format_t::left); - //end textblock + // end textblock fixed_point_t PROPERTY(speed, 1); fixed_point_t PROPERTY(scale, 1); @@ -237,4 +237,4 @@ namespace OpenVic::GFX { OV_DETAIL_GET_TYPE }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/interface/GFXSprite.cpp b/src/openvic-simulation/interface/GFXSprite.cpp index c488d0439..f264c0299 100644 --- a/src/openvic-simulation/interface/GFXSprite.cpp +++ b/src/openvic-simulation/interface/GFXSprite.cpp @@ -5,26 +5,53 @@ using namespace OpenVic::GFX; using namespace OpenVic::NodeTools; Font::Font( - std::string_view new_identifier, colour_argb_t new_colour, std::string_view new_fontname, std::string_view new_charset, - uint32_t new_height, colour_codes_t&& new_colour_codes -) : HasIdentifierAndAlphaColour { new_identifier, new_colour, false }, fontname { new_fontname }, charset { new_charset }, - height { new_height }, colour_codes { std::move(new_colour_codes) } {} - -node_callback_t Sprite::expect_sprites(length_callback_t length_callback, callback_t&&> callback) { + std::string_view new_identifier, + colour_argb_t new_colour, + std::string_view new_fontname, + std::string_view new_charset, + uint32_t new_height, + colour_codes_t&& new_colour_codes +) : + HasIdentifierAndAlphaColour { new_identifier, new_colour, false }, fontname { new_fontname }, charset { new_charset }, + height { new_height }, colour_codes { std::move(new_colour_codes) } {} + +node_callback_t Sprite::expect_sprites( + length_callback_t length_callback, callback_t&&> callback +) { return expect_dictionary_keys_and_length( - length_callback, - "spriteType", ZERO_OR_MORE, _expect_instance(callback), - "progressbartype", ZERO_OR_MORE, _expect_instance(callback), - "PieChartType", ZERO_OR_MORE, _expect_instance(callback), - "LineChartType", ZERO_OR_MORE, _expect_instance(callback), - "textSpriteType", ZERO_OR_MORE, _expect_instance(callback), - "maskedShieldType", ZERO_OR_MORE, _expect_instance(callback), - "tileSpriteType", ZERO_OR_MORE, _expect_instance(callback), - "corneredTileSpriteType", ZERO_OR_MORE, _expect_instance(callback), - - /* Each only has one vanilla instance which isn't used anywhere. */ - "BarChartType", ZERO_OR_MORE, success_callback, - "scrollingSprite", ZERO_OR_MORE, success_callback + length_callback, + "spriteType", + ZERO_OR_MORE, + _expect_instance(callback), + "progressbartype", + ZERO_OR_MORE, + _expect_instance(callback), + "PieChartType", + ZERO_OR_MORE, + _expect_instance(callback), + "LineChartType", + ZERO_OR_MORE, + _expect_instance(callback), + "textSpriteType", + ZERO_OR_MORE, + _expect_instance(callback), + "maskedShieldType", + ZERO_OR_MORE, + _expect_instance(callback), + "tileSpriteType", + ZERO_OR_MORE, + _expect_instance(callback), + "corneredTileSpriteType", + ZERO_OR_MORE, + _expect_instance(callback), + + /* Each only has one vanilla instance which isn't used anywhere. */ + "BarChartType", + ZERO_OR_MORE, + success_callback, + "scrollingSprite", + ZERO_OR_MORE, + success_callback ); } @@ -32,12 +59,21 @@ TextureSprite::TextureSprite() {} bool TextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "texturefile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file)), - - "norefcount", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "loadType", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "texturefile", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file)), + + "norefcount", + ZERO_OR_ONE, + success_callback, + "allwaystransparent", + ZERO_OR_ONE, + success_callback, + "loadType", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -46,12 +82,21 @@ IconTextureSprite::IconTextureSprite() {} bool IconTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "noOfFrames", ZERO_OR_ONE, expect_uint(assign_variable_callback(no_of_frames)), - - "effectFile", ZERO_OR_ONE, success_callback, - "transparencecheck", ZERO_OR_ONE, success_callback, - "clicksound", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "noOfFrames", + ZERO_OR_ONE, + expect_uint(assign_variable_callback(no_of_frames)), + + "effectFile", + ZERO_OR_ONE, + success_callback, + "transparencecheck", + ZERO_OR_ONE, + success_callback, + "clicksound", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -60,9 +105,7 @@ TileTextureSprite::TileTextureSprite() {} bool TileTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)) - ); + ret &= add_key_map_entries(key_map, "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size))); return ret; } @@ -70,9 +113,14 @@ CorneredTileTextureSprite::CorneredTileTextureSprite() {} bool CorneredTileTextureSprite::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = TextureSprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - "borderSize", ONE_EXACTLY, expect_ivec2(assign_variable_callback(border_size)) + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_ivec2(assign_variable_callback(size)), + "borderSize", + ONE_EXACTLY, + expect_ivec2(assign_variable_callback(border_size)) ); return ret; } @@ -81,17 +129,36 @@ ProgressBar::ProgressBar() {} bool ProgressBar::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(progress_colour)), - "colortwo", ONE_EXACTLY, expect_colour(assign_variable_callback(back_colour)), - "textureFile1", ZERO_OR_ONE, expect_string(assign_variable_callback_string(progress_texture_file)), - "textureFile2", ZERO_OR_ONE, expect_string(assign_variable_callback_string(back_texture_file)), - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - - "effectFile", ONE_EXACTLY, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "loadType", ZERO_OR_ONE, success_callback, - "horizontal", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "color", + ONE_EXACTLY, + expect_colour(assign_variable_callback(progress_colour)), + "colortwo", + ONE_EXACTLY, + expect_colour(assign_variable_callback(back_colour)), + "textureFile1", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(progress_texture_file)), + "textureFile2", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(back_texture_file)), + "size", + ONE_EXACTLY, + expect_ivec2(assign_variable_callback(size)), + + "effectFile", + ONE_EXACTLY, + success_callback, + "allwaystransparent", + ZERO_OR_ONE, + success_callback, + "loadType", + ZERO_OR_ONE, + success_callback, + "horizontal", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -108,11 +175,18 @@ LineChart::LineChart() {} bool LineChart::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_ivec2(assign_variable_callback(size)), - "linewidth", ONE_EXACTLY, expect_uint(assign_variable_callback(linewidth)), - - "allwaystransparent", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_ivec2(assign_variable_callback(size)), + "linewidth", + ONE_EXACTLY, + expect_uint(assign_variable_callback(linewidth)), + + "allwaystransparent", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -121,13 +195,24 @@ MaskedFlag::MaskedFlag() {} bool MaskedFlag::_fill_key_map(case_insensitive_key_map_t& key_map) { bool ret = Sprite::_fill_key_map(key_map); - ret &= add_key_map_entries(key_map, - "textureFile1", ONE_EXACTLY, expect_string(assign_variable_callback_string(overlay_file)), - "textureFile2", ONE_EXACTLY, expect_string(assign_variable_callback_string(mask_file)), - - "effectFile", ONE_EXACTLY, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback, - "flipv", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "textureFile1", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(overlay_file)), + "textureFile2", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(mask_file)), + + "effectFile", + ONE_EXACTLY, + success_callback, + "allwaystransparent", + ZERO_OR_ONE, + success_callback, + "flipv", + ZERO_OR_ONE, + success_callback ); return ret; } diff --git a/src/openvic-simulation/interface/GFXSprite.hpp b/src/openvic-simulation/interface/GFXSprite.hpp index 8c8e963e4..259b89f75 100644 --- a/src/openvic-simulation/interface/GFXSprite.hpp +++ b/src/openvic-simulation/interface/GFXSprite.hpp @@ -20,8 +20,12 @@ namespace OpenVic::GFX { public: Font( - std::string_view new_identifier, colour_argb_t new_colour, std::string_view new_fontname, - std::string_view new_charset, uint32_t new_height, colour_codes_t&& new_colour_codes + std::string_view new_identifier, + colour_argb_t new_colour, + std::string_view new_fontname, + std::string_view new_charset, + uint32_t new_height, + colour_codes_t&& new_colour_codes ); Font(Font&&) = default; }; @@ -41,7 +45,7 @@ namespace OpenVic::GFX { OV_DETAIL_GET_TYPE static NodeTools::node_callback_t expect_sprites( - NodeTools::length_callback_t length_callback, NodeTools::callback_t&&> callback + NodeTools::length_callback_t length_callback, NodeTools::callback_t&&> callback ); }; diff --git a/src/openvic-simulation/interface/GUI.cpp b/src/openvic-simulation/interface/GUI.cpp index 1e9dffbdf..fbd13dfb4 100644 --- a/src/openvic-simulation/interface/GUI.cpp +++ b/src/openvic-simulation/interface/GUI.cpp @@ -14,9 +14,7 @@ Position::Position() {} bool Position::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map) { bool ret = Named::_fill_key_map(key_map); - ret &= add_key_map_entry(key_map, - "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(position)) - ); + ret &= add_key_map_entry(key_map, "position", ONE_EXACTLY, expect_fvec2(assign_variable_callback(position))); return ret; } @@ -26,80 +24,143 @@ bool Element::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIMa bool ret = Named::_fill_key_map(key_map, ui_manager); using enum orientation_t; static const string_map_t orientation_map = { - { "UPPER_LEFT", UPPER_LEFT }, { "LOWER_LEFT", LOWER_LEFT }, - { "LOWER_RIGHT", LOWER_RIGHT }, { "UPPER_RIGHT", UPPER_RIGHT }, - { "CENTER", CENTER }, { "CENTER_UP", CENTER_UP }, { "CENTER_DOWN", CENTER_DOWN } + { "UPPER_LEFT", UPPER_LEFT }, { "LOWER_LEFT", LOWER_LEFT }, { "LOWER_RIGHT", LOWER_RIGHT }, + { "UPPER_RIGHT", UPPER_RIGHT }, { "CENTER", CENTER }, { "CENTER_UP", CENTER_UP }, + { "CENTER_DOWN", CENTER_DOWN } }; - ret &= add_key_map_entries(key_map, - "position", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(position)), - "orientation", ZERO_OR_ONE, expect_identifier_or_string(expect_mapped_string( - orientation_map, assign_variable_callback(orientation), - true /* Warn if the key here is invalid, leaving the default orientation UPPER_LEFT unchanged. */ - )) + ret &= add_key_map_entries( + key_map, + "position", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(position)), + "orientation", + ZERO_OR_ONE, + expect_identifier_or_string(expect_mapped_string( + orientation_map, + assign_variable_callback(orientation), + true /* Warn if the key here is invalid, leaving the default orientation UPPER_LEFT unchanged. */ + )) ); return ret; } bool Element::_fill_elements_key_map( - NodeTools::case_insensitive_key_map_t& key_map, callback_t&&> callback, UIManager const& ui_manager + NodeTools::case_insensitive_key_map_t& key_map, + callback_t&&> callback, + UIManager const& ui_manager ) { bool ret = true; - ret &= add_key_map_entries(key_map, - "iconType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "shieldtype", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "guiButtonType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "checkboxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "textBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "instantTextBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "OverlappingElementsBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "listboxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "editBoxType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "scrollbarType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "windowType", ZERO_OR_MORE, _expect_instance(callback, ui_manager), - "eu3dialogtype", ZERO_OR_MORE, _expect_instance(callback, ui_manager) + ret &= add_key_map_entries( + key_map, + "iconType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "shieldtype", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "guiButtonType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "checkboxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "textBoxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "instantTextBoxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "OverlappingElementsBoxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "listboxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "editBoxType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "scrollbarType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "windowType", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager), + "eu3dialogtype", + ZERO_OR_MORE, + _expect_instance(callback, ui_manager) ); return ret; } bool Scene::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { - bool ret = Element::_fill_elements_key_map(key_map, [this](memory::unique_base_ptr&& element) -> bool { - return scene_elements.emplace_via_move(std::move(element)); - }, ui_manager); - ret &= add_key_map_entry(key_map, - "positionType", ZERO_OR_MORE, Position::_expect_value([this](Position&& position) -> bool { - return scene_positions.emplace_via_move(std::move(position)); - }) + bool ret = Element::_fill_elements_key_map( + key_map, + [this](memory::unique_base_ptr&& element) -> bool { + return scene_elements.emplace_via_move(std::move(element)); + }, + ui_manager + ); + ret &= add_key_map_entry( + key_map, "positionType", ZERO_OR_MORE, Position::_expect_value([this](Position&& position) -> bool { + return scene_positions.emplace_via_move(std::move(position)); + }) ); return ret; } node_callback_t Scene::expect_scene( - std::string_view scene_name, callback_t&&> callback, UIManager const& ui_manager + std::string_view scene_name, callback_t&&> callback, UIManager const& ui_manager ) { - return _expect_instance([scene_name, callback](memory::unique_base_ptr&& scene) mutable -> bool { - scene->_set_name(scene_name); - return callback(std::move(scene)); - }, ui_manager); + return _expect_instance( + [scene_name, callback](memory::unique_base_ptr&& scene) mutable -> bool { + scene->_set_name(scene_name); + return callback(std::move(scene)); + }, + ui_manager + ); } Window::Window() {} bool Window::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { - bool ret = Element::_fill_elements_key_map(key_map, [this](memory::unique_base_ptr&& element) -> bool { - return window_elements.emplace_via_move(std::move(element), duplicate_warning_callback); - }, ui_manager); + bool ret = Element::_fill_elements_key_map( + key_map, + [this](memory::unique_base_ptr&& element) -> bool { + return window_elements.emplace_via_move(std::move(element), duplicate_warning_callback); + }, + ui_manager + ); ret &= Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "moveable", ZERO_OR_ONE, expect_int_bool(assign_variable_callback(moveable)), - "fullScreen", ZERO_OR_ONE, expect_bool(assign_variable_callback(fullscreen)), - "backGround", ZERO_OR_ONE, expect_string(assign_variable_callback_string(background), true), - - "dontRender", ZERO_OR_ONE, success_callback, // always empty string? - "horizontalBorder", ZERO_OR_ONE, success_callback, - "verticalBorder", ZERO_OR_ONE, success_callback, - "upsound", ZERO_OR_ONE, success_callback, - "downsound", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "moveable", + ZERO_OR_ONE, + expect_int_bool(assign_variable_callback(moveable)), + "fullScreen", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(fullscreen)), + "backGround", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(background), true), + + "dontRender", + ZERO_OR_ONE, + success_callback, // always empty string? + "horizontalBorder", + ZERO_OR_ONE, + success_callback, + "verticalBorder", + ZERO_OR_ONE, + success_callback, + "upsound", + ZERO_OR_ONE, + success_callback, + "downsound", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -108,14 +169,25 @@ Icon::Icon() {} bool Icon::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - // TODO - make these share a ONE_EXACTLY count - "spriteType", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), - "buttonMesh", ZERO_OR_ONE, ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), - - "frame", ZERO_OR_ONE, expect_uint(assign_variable_callback(frame)), - "scale", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(scale)), - "rotation", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(rotation)) + ret &= add_key_map_entries( + key_map, + // TODO - make these share a ONE_EXACTLY count + "spriteType", + ZERO_OR_ONE, + ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), + "buttonMesh", + ZERO_OR_ONE, + ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), + + "frame", + ZERO_OR_ONE, + expect_uint(assign_variable_callback(frame)), + "scale", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(scale)), + "rotation", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(rotation)) ); return ret; } @@ -125,21 +197,36 @@ BaseButton::BaseButton() {} bool BaseButton::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); // look up sprite registry for texture sprite with name... - ret &= add_key_map_entries(key_map, - // TODO - make these share a ONE_EXACTLY count - "quadTextureSprite", ZERO_OR_ONE, - ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite), true), - "spriteType", ZERO_OR_ONE, - ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), - - "buttonText", ZERO_OR_ONE, expect_string(assign_variable_callback_string(text), true), - /* Some buttons have multiple fonts listed with the last one being used. */ - "buttonFont", ZERO_OR_MORE, ui_manager.expect_font_string(assign_variable_callback_pointer(font), true), - "shortcut", ZERO_OR_ONE, expect_string(assign_variable_callback_string(shortcut), true), - - "tooltip", ZERO_OR_ONE, success_callback, - "tooltipText", ZERO_OR_ONE, success_callback, - "delayedTooltipText", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + // TODO - make these share a ONE_EXACTLY count + "quadTextureSprite", + ZERO_OR_ONE, + ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite), true), + "spriteType", + ZERO_OR_ONE, + ui_manager.expect_sprite_string(assign_variable_callback_pointer(sprite)), + + "buttonText", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(text), true), + /* Some buttons have multiple fonts listed with the last one being used. */ + "buttonFont", + ZERO_OR_MORE, + ui_manager.expect_font_string(assign_variable_callback_pointer(font), true), + "shortcut", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(shortcut), true), + + "tooltip", + ZERO_OR_ONE, + success_callback, + "tooltipText", + ZERO_OR_ONE, + success_callback, + "delayedTooltipText", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -148,13 +235,26 @@ Button::Button() {} bool Button::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = BaseButton::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(size)), - "rotation", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(rotation)), - - "format", ZERO_OR_ONE, success_callback, /* Is always left from what I've seen. */ - "clicksound", ZERO_OR_ONE, ui_manager.definition_manager.get_sound_effect_manager().expect_sound_effect_identifier_or_string(assign_variable_callback_pointer(clicksound), true, true), - "parent", ZERO_OR_ONE, success_callback /* Links buttons to a scrollbar, not needed thanks to contextual info. */ + ret &= add_key_map_entries( + key_map, + "size", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(size)), + "rotation", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(rotation)), + + "format", + ZERO_OR_ONE, + success_callback, /* Is always left from what I've seen. */ + "clicksound", + ZERO_OR_ONE, + ui_manager.definition_manager.get_sound_effect_manager().expect_sound_effect_identifier_or_string( + assign_variable_callback_pointer(clicksound), true, true + ), + "parent", + ZERO_OR_ONE, + success_callback /* Links buttons to a scrollbar, not needed thanks to contextual info. */ ); return ret; } @@ -168,9 +268,7 @@ AlignedElement::AlignedElement() {} bool AlignedElement::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "format", ZERO_OR_ONE, expect_text_format(assign_variable_callback(format)) - ); + ret &= add_key_map_entries(key_map, "format", ZERO_OR_ONE, expect_text_format(assign_variable_callback(format))); return ret; } @@ -178,16 +276,33 @@ Text::Text() {} bool Text::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = AlignedElement::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "text", ZERO_OR_ONE, expect_string(assign_variable_callback_string(text), true), - "font", ONE_EXACTLY, ui_manager.expect_font_string(assign_variable_callback_pointer(font)), - "maxWidth", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(max_size.x)), - "maxHeight", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(max_size.y)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(border_size)), - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file), true), - - "fixedsize", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "text", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(text), true), + "font", + ONE_EXACTLY, + ui_manager.expect_font_string(assign_variable_callback_pointer(font)), + "maxWidth", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(max_size.x)), + "maxHeight", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(max_size.y)), + "borderSize", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(border_size)), + "textureFile", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file), true), + + "fixedsize", + ZERO_OR_ONE, + success_callback, + "allwaystransparent", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -196,9 +311,14 @@ OverlappingElementsBox::OverlappingElementsBox() {} bool OverlappingElementsBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = AlignedElement::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "spacing", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(spacing)) + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "spacing", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(spacing)) ); return ret; } @@ -207,17 +327,36 @@ ListBox::ListBox() {} bool ListBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "offset", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(scrollbar_offset)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(items_offset)), - "spacing", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(spacing)), - "scrollbartype", ZERO_OR_ONE, expect_string(assign_variable_callback_string(scrollbar_name)), - - "backGround", ZERO_OR_ONE, success_callback, - "horizontal", ZERO_OR_ONE, success_callback, - "priority", ZERO_OR_ONE, success_callback, - "allwaystransparent", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "offset", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(scrollbar_offset)), + "borderSize", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(items_offset)), + "spacing", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(spacing)), + "scrollbartype", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(scrollbar_name)), + + "backGround", + ZERO_OR_ONE, + success_callback, + "horizontal", + ZERO_OR_ONE, + success_callback, + "priority", + ZERO_OR_ONE, + success_callback, + "allwaystransparent", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -226,12 +365,23 @@ TextEditBox::TextEditBox() {} bool TextEditBox::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) { bool ret = Element::_fill_key_map(key_map, ui_manager); - ret &= add_key_map_entries(key_map, - "text", ONE_EXACTLY, expect_string(assign_variable_callback_string(text), true), - "font", ONE_EXACTLY, ui_manager.expect_font_string(assign_variable_callback_pointer(font)), - "textureFile", ZERO_OR_ONE, expect_string(assign_variable_callback_string(texture_file), true), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "borderSize", ONE_EXACTLY, expect_fvec2(assign_variable_callback(border_size)) + ret &= add_key_map_entries( + key_map, + "text", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(text), true), + "font", + ONE_EXACTLY, + ui_manager.expect_font_string(assign_variable_callback_pointer(font)), + "textureFile", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(texture_file), true), + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "borderSize", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(border_size)) ); return ret; } @@ -245,28 +395,67 @@ bool Scrollbar::_fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UI const auto add_element = [this](memory::unique_base_ptr&& element) -> bool { return scrollbar_elements.emplace_via_move(std::move(element)); }; - ret &= add_key_map_entries(key_map, - "slider", ONE_EXACTLY, expect_string(assign_variable_callback_string(slider_button_name)), - "track", ONE_EXACTLY, expect_string(assign_variable_callback_string(track_button_name)), - "leftbutton", ONE_EXACTLY, expect_string(assign_variable_callback_string(less_button_name)), - "rightbutton", ONE_EXACTLY, expect_string(assign_variable_callback_string(more_button_name)), - "size", ONE_EXACTLY, expect_fvec2(assign_variable_callback(size)), - "borderSize", ZERO_OR_ONE, expect_fvec2(assign_variable_callback(border_size)), - "minValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(min_value)), - "maxValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(max_value)), - "stepSize", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(step_size)), - "startValue", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(start_value)), - "horizontal", ONE_EXACTLY, expect_int_bool(assign_variable_callback(horizontal)), - "useRangeLimit", ZERO_OR_ONE, expect_bool(assign_variable_callback(range_limited)), - "rangeLimitMin", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(range_limit_min)), - "rangeLimitMax", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(range_limit_max)), - "rangeLimitMinIcon", ZERO_OR_ONE, expect_string(assign_variable_callback_string(range_limit_min_icon_name)), - "rangeLimitMaxIcon", ZERO_OR_ONE, expect_string(assign_variable_callback_string(range_limit_max_icon_name)), - - "guiButtonType", ONE_OR_MORE, _expect_instance(add_element, ui_manager), - "iconType", ZERO_OR_MORE, _expect_instance(add_element, ui_manager), - - "priority", ZERO_OR_ONE, success_callback + ret &= add_key_map_entries( + key_map, + "slider", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(slider_button_name)), + "track", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(track_button_name)), + "leftbutton", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(less_button_name)), + "rightbutton", + ONE_EXACTLY, + expect_string(assign_variable_callback_string(more_button_name)), + "size", + ONE_EXACTLY, + expect_fvec2(assign_variable_callback(size)), + "borderSize", + ZERO_OR_ONE, + expect_fvec2(assign_variable_callback(border_size)), + "minValue", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(min_value)), + "maxValue", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(max_value)), + "stepSize", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(step_size)), + "startValue", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(start_value)), + "horizontal", + ONE_EXACTLY, + expect_int_bool(assign_variable_callback(horizontal)), + "useRangeLimit", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(range_limited)), + "rangeLimitMin", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(range_limit_min)), + "rangeLimitMax", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(range_limit_max)), + "rangeLimitMinIcon", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(range_limit_min_icon_name)), + "rangeLimitMaxIcon", + ZERO_OR_ONE, + expect_string(assign_variable_callback_string(range_limit_max_icon_name)), + + "guiButtonType", + ONE_OR_MORE, + _expect_instance(add_element, ui_manager), + "iconType", + ZERO_OR_MORE, + _expect_instance(add_element, ui_manager), + + "priority", + ZERO_OR_ONE, + success_callback ); return ret; } @@ -280,16 +469,17 @@ T const* Scrollbar::get_element(std::string_view name, std::string_view type) co return cast_element; } else { spdlog::error_s( - "GUI Scrollbar {} {} element {} has wrong type: {} (expected {})", - get_name(), type, name, element->get_type(), T::get_type_static() + "GUI Scrollbar {} {} element {} has wrong type: {} (expected {})", + get_name(), + type, + name, + element->get_type(), + T::get_type_static() ); return nullptr; } } else { - spdlog::error_s( - "GUI Scrollbar {} has no {} element named {}!", - get_name(), type, name - ); + spdlog::error_s("GUI Scrollbar {} has no {} element named {}!", get_name(), type, name); return nullptr; } } diff --git a/src/openvic-simulation/interface/GUI.hpp b/src/openvic-simulation/interface/GUI.hpp index 200912b0b..b953213bf 100644 --- a/src/openvic-simulation/interface/GUI.hpp +++ b/src/openvic-simulation/interface/GUI.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/interface/GFXSprite.hpp" #include "openvic-simulation/core/ui/TextFormat.hpp" +#include "openvic-simulation/interface/GFXSprite.hpp" #include "openvic-simulation/misc/SoundEffect.hpp" namespace OpenVic { @@ -30,7 +30,13 @@ namespace OpenVic::GUI { public: enum class orientation_t { - UPPER_LEFT, LOWER_LEFT, LOWER_RIGHT, UPPER_RIGHT, CENTER, CENTER_UP, CENTER_DOWN + UPPER_LEFT, + LOWER_LEFT, + LOWER_RIGHT, + UPPER_RIGHT, + CENTER, + CENTER_UP, + CENTER_DOWN }; private: @@ -42,8 +48,9 @@ namespace OpenVic::GUI { bool _fill_key_map(NodeTools::case_insensitive_key_map_t& key_map, UIManager const& ui_manager) override; static bool _fill_elements_key_map( - NodeTools::case_insensitive_key_map_t& key_map, NodeTools::callback_t&&> callback, - UIManager const& ui_manager + NodeTools::case_insensitive_key_map_t& key_map, + NodeTools::callback_t&&> callback, + UIManager const& ui_manager ); public: @@ -71,9 +78,10 @@ namespace OpenVic::GUI { OV_DETAIL_GET_TYPE static NodeTools::node_callback_t expect_scene( - std::string_view scene_name, NodeTools::callback_t&&> callback, UIManager const& ui_manager + std::string_view scene_name, + NodeTools::callback_t&&> callback, + UIManager const& ui_manager ); - }; class Window final : public Element { @@ -268,7 +276,7 @@ namespace OpenVic::GUI { fixed_point_t PROPERTY(start_value); bool PROPERTY_CUSTOM_PREFIX(horizontal, is, false) - bool PROPERTY_CUSTOM_PREFIX(range_limited, is, false); + bool PROPERTY_CUSTOM_PREFIX(range_limited, is, false); fixed_point_t PROPERTY(range_limit_min); fixed_point_t PROPERTY(range_limit_max); memory::string PROPERTY(range_limit_min_icon_name); diff --git a/src/openvic-simulation/interface/LoadBase.hpp b/src/openvic-simulation/interface/LoadBase.hpp index e787ef501..4c8ac954b 100644 --- a/src/openvic-simulation/interface/LoadBase.hpp +++ b/src/openvic-simulation/interface/LoadBase.hpp @@ -24,9 +24,7 @@ namespace OpenVic { } template> T> - static NodeTools::node_callback_t _expect_value( - NodeTools::callback_t callback, Context... context - ) { + static NodeTools::node_callback_t _expect_value(NodeTools::callback_t callback, Context... context) { return [callback, &context...](ast::NodeCPtr node) mutable -> bool { T value {}; bool ret = value.load(node, context...); @@ -37,7 +35,7 @@ namespace OpenVic { template> T, std::derived_from U> static NodeTools::node_callback_t _expect_instance( - NodeTools::callback_t&&> callback, Context... context + NodeTools::callback_t&&> callback, Context... context ) { return [callback, &context...](ast::NodeCPtr node) mutable -> bool { memory::unique_base_ptr instance { memory::make_unique() }; diff --git a/src/openvic-simulation/interface/UI.cpp b/src/openvic-simulation/interface/UI.cpp index 8143dc56a..9db68e702 100644 --- a/src/openvic-simulation/interface/UI.cpp +++ b/src/openvic-simulation/interface/UI.cpp @@ -13,18 +13,19 @@ using namespace OpenVic::GUI; UIManager::UIManager(DefinitionManager const& manager) : definition_manager(manager) {} bool UIManager::add_font( - std::string_view identifier, colour_argb_t colour, std::string_view fontname, std::string_view charset, uint32_t height, - Font::colour_codes_t&& colour_codes + std::string_view identifier, + colour_argb_t colour, + std::string_view fontname, + std::string_view charset, + uint32_t height, + Font::colour_codes_t&& colour_codes ) { if (identifier.empty()) { spdlog::error_s("Invalid font identifier - empty!"); return false; } if (colour.alpha == colour_argb_t::colour_traits::null) { - spdlog::error_s( - "Invalid colour for font {} - completely transparent! ({})", - identifier, colour - ); + spdlog::error_s("Invalid colour for font {} - completely transparent! ({})", identifier, colour); return false; } if (fontname.empty()) { @@ -32,9 +33,7 @@ bool UIManager::add_font( return false; } const bool ret = fonts.emplace_item( - identifier, - duplicate_warning_callback, - identifier, colour, fontname, charset, height, std::move(colour_codes) + identifier, duplicate_warning_callback, identifier, colour, fontname, charset, height, std::move(colour_codes) ); if (universal_colour_codes.empty() && ret) { @@ -78,19 +77,13 @@ bool UIManager::_load_font(ast::NodeCPtr node) { } NodeCallback auto UIManager::_load_fonts(std::string_view font_key) { - return expect_dictionary_reserve_length( - fonts, - [this, font_key](std::string_view key, ast::NodeCPtr node) -> bool { - if (key != font_key) { - spdlog::error_s( - "Invalid key: \"{}\" (expected {})", - key, font_key - ); - return false; - } - return _load_font(node); + return expect_dictionary_reserve_length(fonts, [this, font_key](std::string_view key, ast::NodeCPtr node) -> bool { + if (key != font_key) { + spdlog::error_s("Invalid key: \"{}\" (expected {})", key, font_key); + return false; } - ); + return _load_font(node); + }); } void UIManager::lock_gfx_registries() { diff --git a/src/openvic-simulation/interface/UI.hpp b/src/openvic-simulation/interface/UI.hpp index 33a776427..42484474f 100644 --- a/src/openvic-simulation/interface/UI.hpp +++ b/src/openvic-simulation/interface/UI.hpp @@ -13,7 +13,7 @@ namespace OpenVic { NamedBaseInstanceRegistry IDENTIFIER_REGISTRY(object); NamedBaseInstanceRegistry IDENTIFIER_REGISTRY(scene); - + bool _load_font(ast::NodeCPtr node); NodeTools::NodeCallback auto _load_fonts(std::string_view font_key); @@ -23,8 +23,12 @@ namespace OpenVic { UIManager(DefinitionManager const& manager); bool add_font( - std::string_view identifier, colour_argb_t colour, std::string_view fontname, std::string_view charset, - uint32_t height, GFX::Font::colour_codes_t&& colour_codes + std::string_view identifier, + colour_argb_t colour, + std::string_view fontname, + std::string_view charset, + uint32_t height, + GFX::Font::colour_codes_t&& colour_codes ); void lock_gfx_registries(); diff --git a/src/openvic-simulation/map/Crime.cpp b/src/openvic-simulation/map/Crime.cpp index 162b78050..83766c0c3 100644 --- a/src/openvic-simulation/map/Crime.cpp +++ b/src/openvic-simulation/map/Crime.cpp @@ -7,19 +7,23 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Crime::Crime( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - icon_t new_icon, - ConditionScript&& new_trigger, - bool new_default_active -) : HasIndex { new_index }, - TriggeredModifier { new_identifier, std::move(new_values), modifier_type_t::CRIME, new_icon, std::move(new_trigger) }, - is_default_active { new_default_active } {} + index_t new_index, + std::string_view new_identifier, + ModifierValue&& new_values, + icon_t new_icon, + ConditionScript&& new_trigger, + bool new_default_active +) : + HasIndex { new_index }, + TriggeredModifier { new_identifier, std::move(new_values), modifier_type_t::CRIME, new_icon, std::move(new_trigger) }, + is_default_active { new_default_active } {} bool CrimeManager::add_crime_modifier( - std::string_view identifier, ModifierValue&& values, IconModifier::icon_t icon, ConditionScript&& trigger, - bool default_active + std::string_view identifier, + ModifierValue&& values, + IconModifier::icon_t icon, + ConditionScript&& trigger, + bool default_active ) { if (identifier.empty()) { spdlog::error_s("Invalid crime modifier effect identifier - empty!"); @@ -27,36 +31,38 @@ bool CrimeManager::add_crime_modifier( } return crime_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - index_from_count(get_crime_modifier_count()), identifier, std::move(values), icon, - std::move(trigger), default_active + identifier, + duplicate_warning_callback, + index_from_count(get_crime_modifier_count()), + identifier, + std::move(values), + icon, + std::move(trigger), + default_active ); } bool CrimeManager::load_crime_modifiers(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - crime_modifiers, - [this, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { - using enum scope_type_t; + const bool ret = + expect_dictionary_reserve_length(crime_modifiers, [this, &modifier_manager](std::string_view key, ast::NodeCPtr value) -> bool { + using enum scope_type_t; - ModifierValue modifier_value; - IconModifier::icon_t icon = 0; - ConditionScript trigger { PROVINCE, NO_SCOPE, NO_SCOPE }; - bool default_active = false; + ModifierValue modifier_value; + IconModifier::icon_t icon = 0; + ConditionScript trigger { PROVINCE, NO_SCOPE, NO_SCOPE }; + bool default_active = false; - bool ret = NodeTools::expect_dictionary_keys_and_default( + bool ret = NodeTools::expect_dictionary_keys_and_default( modifier_manager.expect_base_province_modifier(modifier_value), "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)), "trigger", ZERO_OR_ONE, trigger.expect_script(), "active", ZERO_OR_ONE, expect_bool(assign_variable_callback(default_active)) )(value); - ret &= add_crime_modifier(key, std::move(modifier_value), icon, std::move(trigger), default_active); + ret &= add_crime_modifier(key, std::move(modifier_value), icon, std::move(trigger), default_active); - return ret; - } - )(root); + return ret; + })(root); lock_crime_modifiers(); @@ -68,8 +74,8 @@ bool CrimeManager::parse_scripts(DefinitionManager const& definition_manager) { for (Crime& crime : crime_modifiers.get_items()) { ret &= crime.parse_scripts( - definition_manager, - true // Script can be null, meaning this won't emit an error message if the crime has no trigger in its definition + definition_manager, + true // Script can be null, meaning this won't emit an error message if the crime has no trigger in its definition ); } diff --git a/src/openvic-simulation/map/Crime.hpp b/src/openvic-simulation/map/Crime.hpp index b4430feeb..86719582f 100644 --- a/src/openvic-simulation/map/Crime.hpp +++ b/src/openvic-simulation/map/Crime.hpp @@ -9,16 +9,17 @@ namespace OpenVic { struct Crime final : HasIndex, TriggeredModifier { friend struct CrimeManager; + public: bool is_default_active; Crime( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - icon_t new_icon, - ConditionScript&& new_trigger, - bool new_default_active + index_t new_index, + std::string_view new_identifier, + ModifierValue&& new_values, + icon_t new_icon, + ConditionScript&& new_trigger, + bool new_default_active ); Crime(Crime&&) = default; }; @@ -29,8 +30,11 @@ namespace OpenVic { public: bool add_crime_modifier( - std::string_view identifier, ModifierValue&& values, IconModifier::icon_t icon, ConditionScript&& trigger, - bool default_active + std::string_view identifier, + ModifierValue&& values, + IconModifier::icon_t icon, + ConditionScript&& trigger, + bool default_active ); bool load_crime_modifiers(ModifierManager const& modifier_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/map/LifeRating.hpp b/src/openvic-simulation/map/LifeRating.hpp index 7c6c5fbe1..8f4d3dddf 100644 --- a/src/openvic-simulation/map/LifeRating.hpp +++ b/src/openvic-simulation/map/LifeRating.hpp @@ -8,12 +8,13 @@ #include namespace OpenVic { - struct life_rating_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + struct life_rating_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } diff --git a/src/openvic-simulation/map/MapDefinition.cpp b/src/openvic-simulation/map/MapDefinition.cpp index a901a79f7..23d45f54a 100644 --- a/src/openvic-simulation/map/MapDefinition.cpp +++ b/src/openvic-simulation/map/MapDefinition.cpp @@ -17,6 +17,7 @@ #include #include "openvic-simulation/core/FormatValidate.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/io/BMP.hpp" #include "openvic-simulation/core/object/Colour.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" @@ -24,7 +25,6 @@ #include "openvic-simulation/core/object/Vector.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" #include "openvic-simulation/core/string/CharConv.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" @@ -37,27 +37,28 @@ using namespace OpenVic::NodeTools; MapDefinition::MapDefinition() {} ProvinceDefinition* MapDefinition::get_province_definition_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) { return province_definitions.get_item_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } ProvinceDefinition const* MapDefinition::get_province_definition_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const { return province_definitions.get_item_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } -RiverSegment::RiverSegment(uint8_t new_size, memory::vector&& new_points) - : size { new_size }, points { std::move(new_points) } {} +RiverSegment::RiverSegment(uint8_t new_size, memory::vector&& new_points) : + size { new_size }, points { std::move(new_points) } {} -//1 entry reserved for null province +// 1 entry reserved for null province static constexpr province_index_t MAX_PROVINCE_COUNT = std::numeric_limits().max() - 1; bool MapDefinition::add_province_definition(std::string_view identifier, colour_t colour) { if (province_definitions.size() >= type_safe::get(max_provinces)) { spdlog::error_s( - "The map's province list is full - maximum number of provinces is {} (this can be at most {})", - max_provinces, MAX_PROVINCE_COUNT + "The map's province list is full - maximum number of provinces is {} (this can be at most {})", + max_provinces, + MAX_PROVINCE_COUNT ); return false; } @@ -66,10 +67,10 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ return false; } // Victoria 2 CTDs on non-numeric province numbers - if (!ranges::all_of(identifier, [](char c) -> bool { return std::isdigit(c); })) { - spdlog::error_s( - "Invalid province identifier: {} (can only contain numeric characters)", identifier - ); + if (!ranges::all_of(identifier, [](char c) -> bool { + return std::isdigit(c); + })) { + spdlog::error_s("Invalid province identifier: {} (can only contain numeric characters)", identifier); return false; } if (colour.is_null()) { @@ -79,16 +80,14 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ const ProvinceDefinition::province_number_t province_number = get_province_number_from_colour(colour); if (province_number != ProvinceDefinition::NULL_PROVINCE_NUMBER) { spdlog::error_s( - "Duplicate province colours: {} and {}", - get_province_definition_from_number(province_number)->to_string(), identifier + "Duplicate province colours: {} and {}", + get_province_definition_from_number(province_number)->to_string(), + identifier ); return false; } - if (!province_definitions.emplace_item( - identifier, - identifier, colour, province_index_t(get_province_definition_count()) - )) { + if (!province_definitions.emplace_item(identifier, identifier, colour, province_index_t(get_province_definition_count()))) { return false; } @@ -98,22 +97,17 @@ bool MapDefinition::add_province_definition(std::string_view identifier, colour_ } ProvinceDefinition::distance_t MapDefinition::calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to + ProvinceDefinition const& from, ProvinceDefinition const& to ) const { const fvec2_t to_pos = to.get_unit_position(); const fvec2_t from_pos = from.get_unit_position(); const fixed_point_t min_x = std::min( - (to_pos.x - from_pos.x).abs(), - std::min( - (to_pos.x - from_pos.x + get_width()).abs(), - (to_pos.x - from_pos.x - get_width()).abs() - ) + (to_pos.x - from_pos.x).abs(), + std::min((to_pos.x - from_pos.x + get_width()).abs(), (to_pos.x - from_pos.x - get_width()).abs()) ); - return fp::sqrt( - fvec2_t { min_x, to_pos.y - from_pos.y }.length_squared() - ); + return fp::sqrt(fvec2_t { min_x, to_pos.y - from_pos.y }.length_squared()); } using adjacency_t = ProvinceDefinition::adjacency_t; @@ -196,14 +190,14 @@ bool MapDefinition::add_standard_adjacency(ProvinceDefinition& from, ProvinceDef } bool MapDefinition::add_special_adjacency( - ProvinceDefinition& from, ProvinceDefinition& to, adjacency_t::type_t type, ProvinceDefinition const* through, - adjacency_t::data_t data + ProvinceDefinition& from, + ProvinceDefinition& to, + adjacency_t::type_t type, + ProvinceDefinition const* through, + adjacency_t::data_t data ) { if (from == to) { - spdlog::error_s( - "Trying to add {} adjacency from province {} to itself!", - adjacency_t::get_type_name(type), from - ); + spdlog::error_s("Trying to add {} adjacency from province {} to itself!", adjacency_t::get_type_name(type), from); return false; } @@ -214,20 +208,14 @@ bool MapDefinition::add_special_adjacency( case LAND: case STRAIT: if (from.is_water() || to.is_water()) { - spdlog::error_s( - "{} adjacency from {} to {} has water endpoint(s)!", - adjacency_t::get_type_name(type), from, to - ); + spdlog::error_s("{} adjacency from {} to {} has water endpoint(s)!", adjacency_t::get_type_name(type), from, to); return false; } break; case WATER: case CANAL: if (!from.is_water() || !to.is_water()) { - spdlog::error_s( - "{} adjacency from {} to {} has land endpoint(s)!", - adjacency_t::get_type_name(type), from, to - ); + spdlog::error_s("{} adjacency from {} to {} has land endpoint(s)!", adjacency_t::get_type_name(type), from, to); return false; } break; @@ -243,9 +231,7 @@ bool MapDefinition::add_special_adjacency( * - land-water = delete existing coastal adjacency, preventing armies and navies from moving between the provinces * - water-water = delete existing water adjacency, preventing navies from moving between the provinces */ break; - default: - spdlog::error_s("Invalid adjacency type {}", static_cast(type)); - return false; + default: spdlog::error_s("Invalid adjacency type {}", static_cast(type)); return false; } /* Check through province */ @@ -253,19 +239,22 @@ bool MapDefinition::add_special_adjacency( const bool water_expected = type == STRAIT; if (through == nullptr || through->is_water() != water_expected) { spdlog::error_s( - "{} adjacency from {} to {} has a {} through province {}", - adjacency_t::get_type_name(type), - from, - to, - through == nullptr ? "null" : (water_expected ? "land" : "water"), - ovfmt::validate(through) + "{} adjacency from {} to {} has a {} through province {}", + adjacency_t::get_type_name(type), + from, + to, + through == nullptr ? "null" : (water_expected ? "land" : "water"), + ovfmt::validate(through) ); return false; } } else if (through != nullptr) { spdlog::warn_s( - "{} adjacency from {} to {} has a non-null through province {}", - adjacency_t::get_type_name(type), from, to, *through + "{} adjacency from {} to {} has a non-null through province {}", + adjacency_t::get_type_name(type), + from, + to, + *through ); through = nullptr; } @@ -273,27 +262,27 @@ bool MapDefinition::add_special_adjacency( /* Check canal data */ if (data != adjacency_t::DEFAULT_DATA && type != CANAL) { spdlog::warn_s( - "{} adjacency from {} to {} has invalid data {}", - adjacency_t::get_type_name(type), from, to, static_cast(data) + "{} adjacency from {} to {} has invalid data {}", + adjacency_t::get_type_name(type), + from, + to, + static_cast(data) ); data = adjacency_t::DEFAULT_DATA; } const ProvinceDefinition::distance_t distance = calculate_distance_between(from, to); - const auto add_adjacency = [this, distance, type, through, data]( - ProvinceDefinition& from, ProvinceDefinition const& to - ) -> bool { + const auto add_adjacency = + [this, distance, type, through, data](ProvinceDefinition& from, ProvinceDefinition const& to) -> bool { const memory::vector::iterator existing_adjacency = std::find_if( - from.adjacencies.begin(), from.adjacencies.end(), - [&to](adjacency_t const& adj) -> bool { return adj.get_to() == to; } + from.adjacencies.begin(), from.adjacencies.end(), [&to](adjacency_t const& adj) -> bool { + return adj.get_to() == to; + } ); if (existing_adjacency != from.adjacencies.end()) { if (type == existing_adjacency->get_type()) { - spdlog::warn_s( - "Adjacency from {} to {} already has type {}!", - from, to, adjacency_t::get_type_name(type) - ); + spdlog::warn_s("Adjacency from {} to {} already has type {}!", from, to, adjacency_t::get_type_name(type)); if (type != STRAIT && type != CANAL) { /* Straits and canals might change through or data, otherwise we can exit early */ return true; @@ -307,17 +296,22 @@ bool MapDefinition::add_special_adjacency( } else { if (type != STRAIT && type != CANAL) { spdlog::error_s( - "Provinces {} and {} already have an existing {} adjacency, cannot create a {} adjacency!", - from, to, adjacency_t::get_type_name(existing_adjacency->get_type()), adjacency_t::get_type_name(type) + "Provinces {} and {} already have an existing {} adjacency, cannot create a {} adjacency!", + from, + to, + adjacency_t::get_type_name(existing_adjacency->get_type()), + adjacency_t::get_type_name(type) ); return false; } - if ( - type != existing_adjacency->get_type() && existing_adjacency->get_type() != (type == CANAL ? WATER : LAND) - ) { + if (type != existing_adjacency->get_type() && + existing_adjacency->get_type() != (type == CANAL ? WATER : LAND)) { spdlog::error_s( - "Cannot convert {} adjacency from {} to {} to type {}!", - adjacency_t::get_type_name(existing_adjacency->get_type()), from, to, adjacency_t::get_type_name(type) + "Cannot convert {} adjacency from {} to {} to type {}!", + adjacency_t::get_type_name(existing_adjacency->get_type()), + from, + to, + adjacency_t::get_type_name(type) ); return false; } @@ -339,10 +333,7 @@ bool MapDefinition::add_special_adjacency( } return true; } else if (type == IMPASSABLE) { - spdlog::warn_s( - "Provinces {} and {} do not have an existing adjacency to make impassable!", - from, to - ); + spdlog::warn_s("Provinces {} and {} do not have an existing adjacency to make impassable!", from, to); return true; } else { from.adjacencies.emplace_back(to, distance, type, through, data); @@ -390,8 +381,7 @@ bool MapDefinition::set_water_province(std::string_view identifier) { } province.water = true; path_map_sea.try_add_point( - province.get_province_number(), - path_map_land.get_point_position(province.get_province_number()) + province.get_province_number(), path_map_land.get_point_position(province.get_province_number()) ); return true; } @@ -424,9 +414,7 @@ size_t MapDefinition::get_water_province_count() const { } bool MapDefinition::add_region( - std::string_view identifier, - memory::vector>&& provinces, - colour_t colour + std::string_view identifier, memory::vector>&& provinces, colour_t colour ) { if (identifier.empty()) { spdlog::error_s("Invalid region identifier - empty!"); @@ -441,10 +429,10 @@ bool MapDefinition::add_region( for (ProvinceDefinition const& province_definition : provinces) { if (OV_unlikely(province_definition.has_region())) { spdlog::warn_s( - "Province {} is assigned to multiple regions, including {} and {}. First defined region wins.", - province_definition, - *province_definition.get_region(), - identifier + "Province {} is assigned to multiple regions, including {} and {}. First defined region wins.", + province_definition, + *province_definition.get_region(), + identifier ); valid_provinces_count--; } @@ -452,10 +440,7 @@ bool MapDefinition::add_region( is_meta |= province_definition.is_water(); } - if (!regions.emplace_item( - identifier, - identifier, colour, is_meta - )) { + if (!regions.emplace_item(identifier, identifier, colour, is_meta)) { return false; } @@ -508,23 +493,18 @@ ProvinceDefinition const* MapDefinition::get_province_definition_at(ivec2_t pos) bool MapDefinition::set_max_provinces(province_index_t new_max_provinces) { if (new_max_provinces <= province_index_t(0)) { - spdlog::error_s( - "Trying to set max province count to an invalid value {} (must be greater than 0)", - new_max_provinces - ); + spdlog::error_s("Trying to set max province count to an invalid value {} (must be greater than 0)", new_max_provinces); return false; } if (new_max_provinces > MAX_PROVINCE_COUNT) { spdlog::error_s( - "Trying to set max province count to an invalid value {} (must <= {})", - new_max_provinces, - MAX_PROVINCE_COUNT + "Trying to set max province count to an invalid value {} (must <= {})", new_max_provinces, MAX_PROVINCE_COUNT ); return false; } if (!province_definitions.empty() || province_definitions.is_locked()) { spdlog::error_s( - "Trying to set max province count to {} after provinces have already been added and/or locked", new_max_provinces + "Trying to set max province count to {} after provinces have already been added and/or locked", new_max_provinces ); return false; } @@ -560,7 +540,7 @@ static bool _parse_province_colour(colour_t& colour, std::array lines) LineObject const& header = lines.front(); if (!_validate_province_definitions_header(header)) { spdlog::error_s( - "Non-standard province definition file header - make sure this is not a province definition: {}", - header + "Non-standard province definition file header - make sure this is not a province definition: {}", header ); } @@ -596,11 +575,10 @@ bool MapDefinition::load_province_definitions(std::span lines) const std::string_view identifier = line.get_value_for(0); if (!identifier.empty()) { colour_t colour = colour_t::null(); - if (!_parse_province_colour(colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) })) { - spdlog::error_s( - "Error reading colour in province definition: {}", - line - ); + if (!_parse_province_colour( + colour, { line.get_value_for(1), line.get_value_for(2), line.get_value_for(3) } + )) { + spdlog::error_s("Error reading colour in province definition: {}", line); ret = false; } ret &= add_province_definition(identifier, colour); @@ -609,7 +587,9 @@ bool MapDefinition::load_province_definitions(std::span lines) } ProvinceDefinition const& definition = province_definitions.back(); - ret &= path_map_land.try_add_point(definition.get_province_number(), { definition.centre.x.round(), definition.centre.y.round() }); + ret &= path_map_land.try_add_point( + definition.get_province_number(), { definition.centre.x.round(), definition.centre.y.round() } + ); if (!ret) { spdlog::error_s("Province {} could not be added to " _OV_STR(path_map_land), identifier); } @@ -626,40 +606,35 @@ bool MapDefinition::load_province_definitions(std::span lines) } bool MapDefinition::load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root) { - return expect_province_definition_dictionary( - [this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { - return province.load_positions(*this, building_type_manager, node); - } - )(root); + return expect_province_definition_dictionary([this, &building_type_manager](ProvinceDefinition& province, ast::NodeCPtr node) -> bool { + return province.load_positions(*this, building_type_manager, node); + })(root); } bool MapDefinition::load_region_colours(ast::NodeCPtr root, memory::vector& colours) { - return expect_dictionary_reserve_length( - colours, - [&colours](std::string_view key, ast::NodeCPtr value) -> bool { - if (key != "color") { - spdlog::error_s("Invalid key in region colours: \"{}\"", key); - return false; - } - return expect_colour(vector_callback(colours))(value); + return expect_dictionary_reserve_length(colours, [&colours](std::string_view key, ast::NodeCPtr value) -> bool { + if (key != "color") { + spdlog::error_s("Invalid key in region colours: \"{}\"", key); + return false; + } + return expect_colour(vector_callback(colours))(value); })(root); } bool MapDefinition::load_region_file(ast::NodeCPtr root, std::span colours) { - const bool ret = expect_dictionary_reserve_length( - regions, - [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { - memory::vector> provinces; + const bool ret = + expect_dictionary_reserve_length(regions, [this, &colours](std::string_view region_identifier, ast::NodeCPtr region_node) -> bool { + memory::vector> provinces; - bool ret = expect_list_reserve_length( - provinces, expect_province_definition_identifier(vector_emplace_callback(provinces)) - )(region_node); + bool ret = + expect_list_reserve_length(provinces, expect_province_definition_identifier(vector_emplace_callback(provinces)))( + region_node + ); - ret &= add_region(region_identifier, std::move(provinces), colours[regions.size() % colours.size()]); + ret &= add_region(region_identifier, std::move(provinces), colours[regions.size() % colours.size()]); - return ret; - } - )(root); + return ret; + })(root); lock_regions(); @@ -684,7 +659,13 @@ static constexpr uint8_t RIVER_SIZE_MAX = 11; static constexpr size_t RIVER_RECURSION_LIMIT = 4096; void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) { - enum struct direction_t : uint8_t { START, UP, DOWN, LEFT, RIGHT }; + enum struct direction_t : uint8_t { + START, + UP, + DOWN, + LEFT, + RIGHT + }; using enum direction_t; struct TraceSegment { ivec2_t point; @@ -700,14 +681,15 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) TraceSegment segment = stack.top(); stack.pop(); - // Force heap initialiser elision - memory::vector points{ segment.point }; - uint8_t size = river_data[segment.point.x + segment.point.y * rivers_bmp.get_width()] - 1; // determine river size by colour + // Force heap initialiser elision + memory::vector points { segment.point }; + uint8_t size = river_data[segment.point.x + segment.point.y * rivers_bmp.get_width()] - + 1; // determine river size by colour bool river_complete = false; size_t recursion_limit = 0; size_t limit; - for(limit = 0; limit < RIVER_RECURSION_LIMIT; ++limit) { + for (limit = 0; limit < RIVER_RECURSION_LIMIT; ++limit) { size_t idx = segment.point.x + segment.point.y * rivers_bmp.get_width(); ivec2_t merge_point; @@ -722,17 +704,17 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) direction_t old_direction; direction_t new_direction; }; - alignas(64) static constexpr std::array neighbours = {{ - { {0, -1}, UP, DOWN }, // Down - { {1, 0}, LEFT, RIGHT }, // Right - { {0, 1}, DOWN, UP }, // Up - { {-1, 0}, RIGHT, LEFT }, // Left - }}; + alignas(64) static constexpr std::array neighbours = { { + { { 0, -1 }, UP, DOWN }, // Down + { { 1, 0 }, LEFT, RIGHT }, // Right + { { 0, 1 }, DOWN, UP }, // Up + { { -1, 0 }, RIGHT, LEFT }, // Left + } }; for (const auto& neighbour : neighbours) { ivec2_t neighbour_pos = { segment.point.x + neighbour.offset.x, segment.point.y + neighbour.offset.y }; if (neighbour_pos.x < 0 || neighbour_pos.y < 0 || neighbour_pos.x >= rivers_bmp.get_width() || - neighbour_pos.y >= rivers_bmp.get_height() || segment.direction == neighbour.old_direction) { + neighbour_pos.y >= rivers_bmp.get_height() || segment.direction == neighbour.old_direction) { continue; } @@ -767,14 +749,17 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) if (limit == RIVER_RECURSION_LIMIT) { spdlog::error_s( - "River segment starting @ ({}, {}) exceeded limit of {} pixels. Check for a misplaced pixel or circular river.", - points.front().x, points.front().y, RIVER_RECURSION_LIMIT + "River segment starting @ ({}, {}) exceeded limit of {} pixels. Check for a misplaced pixel or circular river.", + points.front().x, + points.front().y, + RIVER_RECURSION_LIMIT ); } // simplify points to only include first, last, and corners const auto is_corner_point = [](ivec2_t previous, ivec2_t current, ivec2_t next) -> bool { - return ((current.x - previous.x) * (next.y - current.y)) != ((current.y - previous.y) * (next.x - current.x)); //slope is fun! + return ((current.x - previous.x) * (next.y - current.y)) != + ((current.y - previous.y) * (next.x - current.x)); // slope is fun! }; memory::vector simplified_points; simplified_points.emplace_back(points.front()); @@ -791,7 +776,9 @@ void MapDefinition::_trace_river(BMP& rivers_bmp, ivec2_t start, river_t& river) } } -bool MapDefinition::load_map_images(fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors) { +bool MapDefinition::load_map_images( + fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors +) { if (!province_definitions_are_locked()) { spdlog::error_s("Province index image cannot be generated until after provinces are locked!"); return false; @@ -811,8 +798,7 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (province_bmp.get_bits_per_pixel() != expected_province_bpp) { spdlog::error_s( - "Invalid province BMP bits per pixel: {} (expected {})", - province_bmp.get_bits_per_pixel(), expected_province_bpp + "Invalid province BMP bits per pixel: {} (expected {})", province_bmp.get_bits_per_pixel(), expected_province_bpp ); return false; } @@ -824,8 +810,9 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (terrain_bmp.get_bits_per_pixel() != expected_terrain_rivers_bpp) { spdlog::error_s( - "Invalid terrain BMP bits per pixel: {} (expected {})", - terrain_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp + "Invalid terrain BMP bits per pixel: {} (expected {})", + terrain_bmp.get_bits_per_pixel(), + expected_terrain_rivers_bpp ); return false; } @@ -837,22 +824,21 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } if (rivers_bmp.get_bits_per_pixel() != expected_terrain_rivers_bpp) { spdlog::error_s( - "Invalid rivers BMP bits per pixel: {} (expected {})", - rivers_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp + "Invalid rivers BMP bits per pixel: {} (expected {})", rivers_bmp.get_bits_per_pixel(), expected_terrain_rivers_bpp ); return false; } - if (province_bmp.get_width() != terrain_bmp.get_width() || - province_bmp.get_height() != terrain_bmp.get_height() || - province_bmp.get_width() != rivers_bmp.get_width() || - province_bmp.get_height() != rivers_bmp.get_height() - ) { + if (province_bmp.get_width() != terrain_bmp.get_width() || province_bmp.get_height() != terrain_bmp.get_height() || + province_bmp.get_width() != rivers_bmp.get_width() || province_bmp.get_height() != rivers_bmp.get_height()) { spdlog::error_s( - "Mismatched map BMP dims: provinces:{}x{}, terrain: {}x{}, rivers: {}x{}", - province_bmp.get_width(), province_bmp.get_height(), - terrain_bmp.get_width(), terrain_bmp.get_height(), - rivers_bmp.get_width(), rivers_bmp.get_height() + "Mismatched map BMP dims: provinces:{}x{}, terrain: {}x{}, rivers: {}x{}", + province_bmp.get_width(), + province_bmp.get_height(), + terrain_bmp.get_width(), + terrain_bmp.get_height(), + rivers_bmp.get_width(), + rivers_bmp.get_height() ); return false; } @@ -866,20 +852,21 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons const province_index_t province_count(province_definitions.size()); memory::FixedVector, province_index_t> terrain_type_pixels_list( - province_count, - [](const province_index_t i) { return fixed_point_map_t{}; } + province_count, [](const province_index_t i) { + return fixed_point_map_t {}; + } ); bool ret = true; ordered_set unrecognised_province_colours; - memory::FixedVector pixels_per_province( - province_count, - [](const province_index_t i) { return fixed_point_t::_0; } - ); + memory::FixedVector pixels_per_province(province_count, [](const province_index_t i) { + return fixed_point_t::_0; + }); memory::FixedVector pixel_position_sum_per_province( - province_count, - [](const province_index_t i) { return fvec2_t{}; } + province_count, [](const province_index_t i) { + return fvec2_t {}; + } ); for (ivec2_t pos {}; pos.y < get_height(); ++pos.y) { @@ -906,13 +893,11 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons province_number = get_province_number_from_colour(province_colour); - if (province_number == ProvinceDefinition::NULL_PROVINCE_NUMBER && !unrecognised_province_colours.contains(province_colour)) { + if (province_number == ProvinceDefinition::NULL_PROVINCE_NUMBER && + !unrecognised_province_colours.contains(province_colour)) { unrecognised_province_colours.insert(province_colour); if (detailed_errors) { - spdlog::warn_s( - "Unrecognised province colour {} at {}", - province_colour, pos - ); + spdlog::warn_s("Unrecognised province colour {} at {}", province_colour, pos); } } @@ -971,19 +956,19 @@ bool MapDefinition::load_map_images(fs::path const& province_path, fs::path cons } /** Generating River Segments - 1. check pixels up, right, down, and left from last_segment_end for a colour <12 - 2. add first point - 3. set size of segment based on color value at first point - 4. loop, adding adjacent points until the colour value changes - no backtracking - last_segment_direction: - 0 -> start, ignore nothing - 1 -> ignore up - 2 -> ignore down - 3 -> ignore left - 4 -> ignore right - 5. if the colour value changes to MERGE_COLOUR, add the point & finish the segment - 6. if there is no further point, finish the segment - 7. if the colour value changes to a different river size (>1 && <12), add a new stack frame with this segment + 1. check pixels up, right, down, and left from last_segment_end for a colour <12 + 2. add first point + 3. set size of segment based on color value at first point + 4. loop, adding adjacent points until the colour value changes - no backtracking + last_segment_direction: + 0 -> start, ignore nothing + 1 -> ignore up + 2 -> ignore down + 3 -> ignore left + 4 -> ignore right + 5. if the colour value changes to MERGE_COLOUR, add the point & finish the segment + 6. if there is no further point, finish the segment + 7. if the colour value changes to a different river size (>1 && <12), add a new stack frame with this segment */ uint8_t const* river_data = rivers_bmp.get_pixel_data().data(); @@ -1043,55 +1028,55 @@ bool MapDefinition::generate_and_load_province_adjacencies(std::span void { - const std::string_view from_str = adjacency.get_value_for(0); - if (from_str.empty() || from_str.front() == '#') { - return; - } - ProvinceDefinition* const from = get_province_definition_by_identifier(from_str); - if (from == nullptr) { - spdlog::error_s("Unrecognised adjacency from province identifier: \"{}\"", from_str); - ret = false; - return; - } - - const std::string_view to_str = adjacency.get_value_for(1); - ProvinceDefinition* const to = get_province_definition_by_identifier(to_str); - if (to == nullptr) { - spdlog::error_s("Unrecognised adjacency to province identifier: \"{}\"", to_str); - ret = false; - return; - } - - using enum adjacency_t::type_t; - static const string_map_t type_map { - { "land", LAND }, { "sea", STRAIT }, { "impassable", IMPASSABLE }, { "canal", CANAL } - }; - const std::string_view type_str = adjacency.get_value_for(2); - const string_map_t::const_iterator it = type_map.find(type_str); - if (it == type_map.end()) { - spdlog::error_s("Invalid adjacency type: \"{}\"", type_str); - ret = false; - return; - } - const adjacency_t::type_t type = it->second; - - ProvinceDefinition const* const through = get_province_definition_by_identifier(adjacency.get_value_for(3)); - - const std::string_view data_str = adjacency.get_value_for(4); - bool successful = false; - uint64_t data_uint; - std::from_chars_result result = string_to_uint64(data_str, data_uint); - successful = result.ec == std::errc{}; - if (!successful || data_uint > std::numeric_limits::max()) { - spdlog::error_s("Invalid adjacency data: \"{}\"", data_str); - ret = false; - return; - } - const adjacency_t::data_t data = data_uint; - - ret &= add_special_adjacency(*from, *to, type, through, data); - } + additional_adjacencies.begin() + 1, additional_adjacencies.end(), [this, &ret](LineObject const& adjacency) -> void { + const std::string_view from_str = adjacency.get_value_for(0); + if (from_str.empty() || from_str.front() == '#') { + return; + } + ProvinceDefinition* const from = get_province_definition_by_identifier(from_str); + if (from == nullptr) { + spdlog::error_s("Unrecognised adjacency from province identifier: \"{}\"", from_str); + ret = false; + return; + } + + const std::string_view to_str = adjacency.get_value_for(1); + ProvinceDefinition* const to = get_province_definition_by_identifier(to_str); + if (to == nullptr) { + spdlog::error_s("Unrecognised adjacency to province identifier: \"{}\"", to_str); + ret = false; + return; + } + + using enum adjacency_t::type_t; + static const string_map_t type_map { + { "land", LAND }, { "sea", STRAIT }, { "impassable", IMPASSABLE }, { "canal", CANAL } + }; + const std::string_view type_str = adjacency.get_value_for(2); + const string_map_t::const_iterator it = type_map.find(type_str); + if (it == type_map.end()) { + spdlog::error_s("Invalid adjacency type: \"{}\"", type_str); + ret = false; + return; + } + const adjacency_t::type_t type = it->second; + + ProvinceDefinition const* const through = get_province_definition_by_identifier(adjacency.get_value_for(3)); + + const std::string_view data_str = adjacency.get_value_for(4); + bool successful = false; + uint64_t data_uint; + std::from_chars_result result = string_to_uint64(data_str, data_uint); + successful = result.ec == std::errc {}; + if (!successful || data_uint > std::numeric_limits::max()) { + spdlog::error_s("Invalid adjacency data: \"{}\"", data_str); + ret = false; + return; + } + const adjacency_t::data_t data = data_uint; + + ret &= add_special_adjacency(*from, *to, type, through, data); + } ); path_map_land.shrink_to_fit(); @@ -1100,54 +1085,41 @@ bool MapDefinition::generate_and_load_province_adjacencies(std::span bool { - if (identifier.empty()) { - spdlog::error_s("Invalid climate identifier - empty!"); - return false; - } + bool ret = expect_dictionary_reserve_length(climates, [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + if (identifier.empty()) { + spdlog::error_s("Invalid climate identifier - empty!"); + return false; + } - bool ret = true; - Climate* cur_climate = climates.get_item_by_identifier(identifier); - if (cur_climate == nullptr) { - ModifierValue values; + bool ret = true; + Climate* cur_climate = climates.get_item_by_identifier(identifier); + if (cur_climate == nullptr) { + ModifierValue values; - ret &= NodeTools::expect_dictionary( - modifier_manager.expect_base_province_modifier(values) - )(node); + ret &= NodeTools::expect_dictionary(modifier_manager.expect_base_province_modifier(values))(node); - ret &= climates.emplace_item( - identifier, - identifier, std::move(values), Modifier::modifier_type_t::CLIMATE - ); - } else { - ret &= expect_list_reserve_length(*cur_climate, expect_province_definition_identifier( - [this, cur_climate, &identifier](ProvinceDefinition& province) { - if (province.climate != cur_climate) { - cur_climate->add_province(province); - if (province.climate != nullptr) { - Climate* old_climate = climates.get_item_by_identifier(province.climate->get_identifier()); - old_climate->remove_province(province); - spdlog::warn_s( - "Province with id {} found in multiple climates: {} and {}", - province, identifier, *old_climate - ); - } - province.climate = cur_climate; - } else { - spdlog::warn_s( - "Province with id {} defined twice in climate {}", - province, identifier - ); - } - return true; - } - ))(node); - } - return ret; + ret &= climates.emplace_item(identifier, identifier, std::move(values), Modifier::modifier_type_t::CLIMATE); + } else { + ret &= + expect_list_reserve_length(*cur_climate, expect_province_definition_identifier([this, cur_climate, &identifier](ProvinceDefinition& province) { + if (province.climate != cur_climate) { + cur_climate->add_province(province); + if (province.climate != nullptr) { + Climate* old_climate = climates.get_item_by_identifier(province.climate->get_identifier()); + old_climate->remove_province(province); + spdlog::warn_s( + "Province with id {} found in multiple climates: {} and {}", province, identifier, *old_climate + ); + } + province.climate = cur_climate; + } else { + spdlog::warn_s("Province with id {} defined twice in climate {}", province, identifier); + } + return true; + }))(node); } - )(root); + return ret; + })(root); for (Climate& climate : climates.get_items()) { climate.lock(); @@ -1159,49 +1131,50 @@ bool MapDefinition::load_climate_file(ModifierManager const& modifier_manager, a } bool MapDefinition::load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { - bool ret = expect_dictionary_reserve_length( - continents, - [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { - - if (identifier.empty()) { - spdlog::error_s("Invalid continent identifier - empty!"); - return false; - } - - ModifierValue values; - memory::vector> prov_list; - bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_base_province_modifier(values), - "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier( - [&prov_list](ProvinceDefinition const& province) -> bool { - if (province.continent == nullptr) { - prov_list.emplace_back(province); - } else { - spdlog::warn_s("Province {} found in multiple continents", province); - } - return true; - } - )) - )(node); - - if (!continents.emplace_item( - identifier, - identifier, std::move(values), Modifier::modifier_type_t::CONTINENT - )) { - return false; - } + bool ret = expect_dictionary_reserve_length(continents, [this, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + if (identifier.empty()) { + spdlog::error_s("Invalid continent identifier - empty!"); + return false; + } - Continent& continent = continents.back(); - continent.add_provinces(prov_list); - continent.lock(); + ModifierValue values; + memory::vector> prov_list; + bool ret = NodeTools:: + expect_dictionary_keys_and_default(modifier_manager.expect_base_province_modifier(values), "provinces", ONE_EXACTLY, expect_list_reserve_length(prov_list, expect_province_definition_identifier([&prov_list](ProvinceDefinition const& province) -> bool { + if ( + province + .continent == + nullptr + ) { + prov_list + .emplace_back( + province + ); + } else { + spdlog::warn_s( + "Province {} found in multiple continents", + province + ); + } + return true; + })))( + node + ); + + if (!continents.emplace_item(identifier, identifier, std::move(values), Modifier::modifier_type_t::CONTINENT)) { + return false; + } - for (ProvinceDefinition const& prov : continent.get_provinces()) { - get_mutable_province_definition(prov).continent = &continent; - } + Continent& continent = continents.back(); + continent.add_provinces(prov_list); + continent.lock(); - return ret; + for (ProvinceDefinition const& prov : continent.get_provinces()) { + get_mutable_province_definition(prov).continent = &continent; } - )(root); + + return ret; + })(root); lock_continents(); diff --git a/src/openvic-simulation/map/MapDefinition.hpp b/src/openvic-simulation/map/MapDefinition.hpp index c212a6e24..4cf69375c 100644 --- a/src/openvic-simulation/map/MapDefinition.hpp +++ b/src/openvic-simulation/map/MapDefinition.hpp @@ -78,29 +78,34 @@ namespace OpenVic { } IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(province_definition); - ProvinceDefinition* get_province_definition_from_number( - const ProvinceDefinition::province_number_t province_number - ); + ProvinceDefinition* get_province_definition_from_number(const ProvinceDefinition::province_number_t province_number); public: MapDefinition(); ProvinceDefinition const* get_province_definition_from_number( - const ProvinceDefinition::province_number_t province_number + const ProvinceDefinition::province_number_t province_number ) const; - inline constexpr int32_t get_width() const { return dims.x; } - inline constexpr int32_t get_height() const { return dims.y; } + inline constexpr int32_t get_width() const { + return dims.x; + } + inline constexpr int32_t get_height() const { + return dims.y; + } bool add_province_definition(std::string_view identifier, colour_t colour); ProvinceDefinition::distance_t calculate_distance_between( - ProvinceDefinition const& from, ProvinceDefinition const& to + ProvinceDefinition const& from, ProvinceDefinition const& to ) const; bool add_standard_adjacency(ProvinceDefinition& from, ProvinceDefinition& to); bool add_special_adjacency( - ProvinceDefinition& from, ProvinceDefinition& to, ProvinceDefinition::adjacency_t::type_t type, - ProvinceDefinition const* through, ProvinceDefinition::adjacency_t::data_t data + ProvinceDefinition& from, + ProvinceDefinition& to, + ProvinceDefinition::adjacency_t::type_t type, + ProvinceDefinition const* through, + ProvinceDefinition::adjacency_t::data_t data ); bool set_water_province(std::string_view identifier); @@ -116,9 +121,9 @@ namespace OpenVic { ProvinceDefinition* get_province_definition_at(ivec2_t pos); /* This provides a safe way to remove the const qualifier of a ProvinceDefinition const&, via a non-const Map. - * It looks up the ProvinceDefinition& using the ProvinceDefinition const&'s index. Requiring a non-const Map ensures that this - * function can only be used where the ProvinceDefinition& could already be accessed by other means, such as the - * index method, preventing misleading code, or in the worst case undefined behaviour. */ + * It looks up the ProvinceDefinition& using the ProvinceDefinition const&'s index. Requiring a non-const Map ensures + * that this function can only be used where the ProvinceDefinition& could already be accessed by other means, such as + * the index method, preventing misleading code, or in the worst case undefined behaviour. */ constexpr ProvinceDefinition& get_mutable_province_definition(ProvinceDefinition const& province) { return *province_definitions.get_item_by_index(province.index); } @@ -128,9 +133,9 @@ namespace OpenVic { bool set_max_provinces(ProvinceDefinition::index_t new_max_provinces); bool add_region( - std::string_view identifier, - memory::vector>&& provinces, - colour_t colour + std::string_view identifier, + memory::vector>&& provinces, + colour_t colour ); bool load_province_definitions(std::span lines); @@ -138,7 +143,9 @@ namespace OpenVic { bool load_province_positions(BuildingTypeManager const& building_type_manager, ast::NodeCPtr root); static bool load_region_colours(ast::NodeCPtr root, memory::vector& colours); bool load_region_file(ast::NodeCPtr root, std::span colours); - bool load_map_images(fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors); + bool load_map_images( + fs::path const& province_path, fs::path const& terrain_path, fs::path const& rivers_path, bool detailed_errors + ); bool generate_and_load_province_adjacencies(std::span additional_adjacencies); bool load_climate_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); bool load_continent_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/map/MapInstance.cpp b/src/openvic-simulation/map/MapInstance.cpp index 5a9b50270..b716383e5 100644 --- a/src/openvic-simulation/map/MapInstance.cpp +++ b/src/openvic-simulation/map/MapInstance.cpp @@ -15,46 +15,32 @@ using namespace OpenVic; MapInstance::MapInstance( - MapDefinition const& new_map_definition, - ProvinceInstanceDeps const& province_instance_deps, - ThreadPool& new_thread_pool -) : map_definition { new_map_definition }, - thread_pool { new_thread_pool }, - land_pathing { new_map_definition, *this }, - sea_pathing { new_map_definition, *this }, - province_instance_by_definition( - new_map_definition.get_province_definitions(), - [&province_instance_deps]( - ProvinceDefinition const& province_definition - ) -> auto { - return std::make_tuple( - std::ref(province_definition), - std::ref(province_instance_deps) - ); - } - ) { assert(new_map_definition.province_definitions_are_locked()); } + MapDefinition const& new_map_definition, ProvinceInstanceDeps const& province_instance_deps, ThreadPool& new_thread_pool +) : + map_definition { new_map_definition }, thread_pool { new_thread_pool }, land_pathing { new_map_definition, *this }, + sea_pathing { new_map_definition, *this }, + province_instance_by_definition( + new_map_definition.get_province_definitions(), + [&province_instance_deps](ProvinceDefinition const& province_definition) -> auto { + return std::make_tuple(std::ref(province_definition), std::ref(province_instance_deps)); + } + ) { + assert(new_map_definition.province_definitions_are_locked()); +} ProvinceInstance* MapInstance::get_province_instance_by_identifier(std::string_view identifier) { ProvinceDefinition const* province_definition = map_definition.get_province_definition_by_identifier(identifier); - return province_definition == nullptr - ? nullptr - : &get_province_instance_by_definition(*province_definition); + return province_definition == nullptr ? nullptr : &get_province_instance_by_definition(*province_definition); } ProvinceInstance const* MapInstance::get_province_instance_by_identifier(std::string_view identifier) const { ProvinceDefinition const* province_definition = map_definition.get_province_definition_by_identifier(identifier); - return province_definition == nullptr - ? nullptr - : &get_province_instance_by_definition(*province_definition); + return province_definition == nullptr ? nullptr : &get_province_instance_by_definition(*province_definition); } ProvinceInstance* MapInstance::get_province_instance_by_index(typename ProvinceInstance::index_t index) { - return province_instance_by_definition.contains_index(index) - ? &province_instance_by_definition.at_index(index) - : nullptr; + return province_instance_by_definition.contains_index(index) ? &province_instance_by_definition.at_index(index) : nullptr; } ProvinceInstance const* MapInstance::get_province_instance_by_index(typename ProvinceInstance::index_t index) const { - return province_instance_by_definition.contains_index(index) - ? &province_instance_by_definition.at_index(index) - : nullptr; + return province_instance_by_definition.contains_index(index) ? &province_instance_by_definition.at_index(index) : nullptr; } ProvinceInstance& MapInstance::get_province_instance_by_definition(ProvinceDefinition const& province_definition) { return province_instance_by_definition.at(province_definition); @@ -64,12 +50,12 @@ ProvinceInstance const& MapInstance::get_province_instance_by_definition(Provinc } ProvinceInstance* MapInstance::get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) { return get_province_instance_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } ProvinceInstance const* MapInstance::get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const { return get_province_instance_by_index(ProvinceDefinition::get_index_from_province_number(province_number)); } @@ -83,13 +69,13 @@ bool MapInstance::is_canal_enabled(canal_index_t canal_index) const { } bool MapInstance::apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, - const Date date, - CountryInstanceManager& country_manager, - MilitaryDefines const& military_defines, - PopDeps const& pop_deps, - TypedSpan pop_types, - TypedSpan reforms + ProvinceHistoryManager const& history_manager, + const Date date, + CountryInstanceManager& country_manager, + MilitaryDefines const& military_defines, + PopDeps const& pop_deps, + TypedSpan pop_types, + TypedSpan reforms ) { bool ret = true; @@ -110,7 +96,7 @@ bool MapInstance::apply_history_to_provinces( } else { province.apply_history_to_province(*entry, country_manager); std::optional const& rgo_production_type_nullable_optional = - entry->get_rgo_production_type_nullable(); + entry->get_rgo_production_type_nullable(); if (rgo_production_type_nullable_optional.has_value()) { rgo_production_type_nullable = rgo_production_type_nullable_optional.value(); } @@ -124,20 +110,14 @@ bool MapInstance::apply_history_to_provinces( if (pop_history_entry == nullptr) { spdlog::warn_s("No pop history entry for province {} for date {}", province, date); } else { - ret &= province.add_pop_vec( - pop_history_entry->get_pops(), - pop_deps - ); + ret &= province.add_pop_vec(pop_history_entry->get_pops(), pop_deps); province.setup_pop_test_values(reforms); - //update pops so OOB can use up to date max_supported_regiments + // update pops so OOB can use up to date max_supported_regiments province._update_pops(military_defines); } - ret &= province.set_rgo_production_type_nullable( - pop_types, - rgo_production_type_nullable - ); + ret &= province.set_rgo_production_type_nullable(pop_types, rgo_production_type_nullable); } } } @@ -175,12 +155,12 @@ void MapInstance::update_gamestate(InstanceManager const& instance_manager) { void MapInstance::map_tick() { thread_pool.process_province_ticks(); - //state tick - //after province tick as province tick sets pop employment to 0 - //state tick will update pop employment via factories + // state tick + // after province tick as province tick sets pop employment to 0 + // state tick will update pop employment via factories } void MapInstance::initialise_for_new_game(InstanceManager const& instance_manager) { update_gamestate(instance_manager); thread_pool.process_province_initialise_for_new_game(); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/MapInstance.hpp b/src/openvic-simulation/map/MapInstance.hpp index 0658d5dc1..0bdbafaac 100644 --- a/src/openvic-simulation/map/MapInstance.hpp +++ b/src/openvic-simulation/map/MapInstance.hpp @@ -44,9 +44,9 @@ namespace OpenVic { public: MapInstance( - MapDefinition const& new_map_definition, - ProvinceInstanceDeps const& province_instance_deps, - ThreadPool& new_thread_pool + MapDefinition const& new_map_definition, + ProvinceInstanceDeps const& province_instance_deps, + ThreadPool& new_thread_pool ); inline explicit constexpr operator MapDefinition const&() const { @@ -66,23 +66,23 @@ namespace OpenVic { ProvinceInstance const* get_province_instance_by_index(typename ProvinceInstance::index_t index) const; ProvinceInstance& get_province_instance_by_definition(ProvinceDefinition const& province_definition); ProvinceInstance* get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ); ProvinceInstance const* get_province_instance_from_number( - decltype(std::declval().get_province_number())province_number + decltype(std::declval().get_province_number()) province_number ) const; void enable_canal(canal_index_t canal_index); bool is_canal_enabled(canal_index_t canal_index) const; bool apply_history_to_provinces( - ProvinceHistoryManager const& history_manager, - const Date date, - CountryInstanceManager& country_manager, - MilitaryDefines const& military_defines, - PopDeps const& pop_deps, - TypedSpan pop_types, - TypedSpan reforms + ProvinceHistoryManager const& history_manager, + const Date date, + CountryInstanceManager& country_manager, + MilitaryDefines const& military_defines, + PopDeps const& pop_deps, + TypedSpan pop_types, + TypedSpan reforms ); void update_modifier_sums(const Date today, StaticModifierCache const& static_modifier_cache); diff --git a/src/openvic-simulation/map/Mapmode.cpp b/src/openvic-simulation/map/Mapmode.cpp index f90f9a89c..3e464f8de 100644 --- a/src/openvic-simulation/map/Mapmode.cpp +++ b/src/openvic-simulation/map/Mapmode.cpp @@ -20,38 +20,41 @@ using namespace OpenVic; using namespace OpenVic::colour_literals; Mapmode::Mapmode( - std::string_view new_identifier, - index_t new_index, - colour_func_t new_colour_func, - std::string_view new_localisation_key, - bool new_is_parchment_mapmode_allowed -) : HasIdentifier { new_identifier }, - HasIndex { new_index }, - colour_func { std::move(new_colour_func) }, - localisation_key { new_localisation_key.empty() ? new_identifier : new_localisation_key }, - is_parchment_mapmode_allowed { new_is_parchment_mapmode_allowed } {} + std::string_view new_identifier, + index_t new_index, + colour_func_t new_colour_func, + std::string_view new_localisation_key, + bool new_is_parchment_mapmode_allowed +) : + HasIdentifier { new_identifier }, HasIndex { new_index }, colour_func { std::move(new_colour_func) }, + localisation_key { new_localisation_key.empty() ? new_identifier : new_localisation_key }, + is_parchment_mapmode_allowed { new_is_parchment_mapmode_allowed } {} const Mapmode Mapmode::ERROR_MAPMODE { - "mapmode_error", Mapmode::ERROR_INDEX, []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> base_stripe_t { - return { 0xFFFF0000_argb, colour_argb_t::null() }; + "mapmode_error", + Mapmode::ERROR_INDEX, + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> base_stripe_t { + return { 0xFFFF0000_argb, colour_argb_t::null() }; } }; Mapmode::base_stripe_t Mapmode::get_base_stripe_colours( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province ) const { return colour_func ? colour_func(map_instance, province, player_country, selected_province) : colour_argb_t::null(); } bool MapmodeManager::add_mapmode( - std::string_view identifier, - Mapmode::colour_func_t colour_func, - std::string_view localisation_key, - bool parchment_mapmode_allowed + std::string_view identifier, + Mapmode::colour_func_t colour_func, + std::string_view localisation_key, + bool parchment_mapmode_allowed ) { if (identifier.empty()) { spdlog::error_s("Invalid mapmode identifier - empty!"); @@ -62,16 +65,21 @@ bool MapmodeManager::add_mapmode( return false; } return mapmodes.emplace_item( - identifier, - identifier, index_from_count(get_mapmode_count()), colour_func, localisation_key, - parchment_mapmode_allowed + identifier, + identifier, + index_from_count(get_mapmode_count()), + colour_func, + localisation_key, + parchment_mapmode_allowed ); } bool MapmodeManager::generate_mapmode_colours( - MapInstance const& map_instance, Mapmode const* mapmode, - CountryInstance const* player_country, ProvinceInstance const* selected_province, - uint8_t* target + MapInstance const& map_instance, + Mapmode const* mapmode, + CountryInstance const* player_country, + ProvinceInstance const* selected_province, + uint8_t* target ) const { if (target == nullptr) { spdlog::error_s("Mapmode colour target pointer is null!"); @@ -81,9 +89,7 @@ bool MapmodeManager::generate_mapmode_colours( bool ret = true; if (mapmode == nullptr) { mapmode = &Mapmode::ERROR_MAPMODE; - spdlog::error_s( - "Trying to generate mapmode colours using null mapmode! Defaulting to \"{}\"", *mapmode - ); + spdlog::error_s("Trying to generate mapmode colours using null mapmode! Defaulting to \"{}\"", *mapmode); ret = false; } @@ -93,7 +99,7 @@ bool MapmodeManager::generate_mapmode_colours( for (ProvinceInstance const& province : map_instance.get_province_instances()) { target_stripes[province.province_definition.get_province_number()] = mapmode->get_base_stripe_colours( - map_instance, province, player_country, selected_province + map_instance, province, player_country, selected_province ); } @@ -109,11 +115,13 @@ static constexpr colour_argb_t DEFAULT_COLOUR_GREY = (0x7F7F7F_argb).with_alpha( template requires(std::same_as || std::same_as) -static constexpr auto get_colour_mapmode(T const*(P::*get_item)() const) { +static constexpr auto get_colour_mapmode(T const* (P::*get_item)() const) { return [get_item]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.province_definition; T const* item = ([&province, &province_definition]() -> P const& { @@ -137,12 +145,14 @@ static constexpr auto get_colour_mapmode(T const*(P::*get_item)() const) { template requires(std::same_as || std::same_as) static constexpr auto get_colour_mapmode( - BASE_T const*(P::*get_base_item)() const, STRIPE_T const*(P::*get_stripe_item)() const + BASE_T const* (P::*get_base_item)() const, STRIPE_T const* (P::*get_stripe_item)() const ) { return [get_base_item, get_stripe_item]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { ProvinceDefinition const& province_definition = province.province_definition; P const& p = [&province, &province_definition]() -> P const& { @@ -170,9 +180,7 @@ static constexpr auto get_colour_mapmode( } template -static constexpr Mapmode::base_stripe_t shaded_mapmode( - ordered_map const& map -) { +static constexpr Mapmode::base_stripe_t shaded_mapmode(ordered_map const& map) { const auto largest = get_largest_two_items(map); if (largest.first != map.end()) { const colour_argb_t base_colour = colour_argb_t { largest.first->first->get_colour(), ALPHA_VALUE }; @@ -189,11 +197,13 @@ static constexpr Mapmode::base_stripe_t shaded_mapmode( } template -static constexpr auto shaded_mapmode(ordered_map const&(ProvinceInstance::*get_map)() const) { +static constexpr auto shaded_mapmode(ordered_map const& (ProvinceInstance::*get_map)() const) { return [get_map]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { return shaded_mapmode((province.*get_map)()); }; } @@ -211,19 +221,19 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin // The order of mapmodes matches their numbering, but is different from the order in which their buttons appear ret &= add_mapmode( - "mapmode_terrain", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - return colour_argb_t::null(); - }, - "MAPMODE_1", - false // Parchment mapmode not allowed + "mapmode_terrain", + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { + return colour_argb_t::null(); + }, + "MAPMODE_1", + false // Parchment mapmode not allowed + ); + ret &= add_mapmode( + "mapmode_political", get_colour_mapmode(&ProvinceInstance::get_owner, &ProvinceInstance::get_controller), "MAPMODE_2" ); - ret &= add_mapmode("mapmode_political", get_colour_mapmode( - &ProvinceInstance::get_owner, &ProvinceInstance::get_controller - ), "MAPMODE_2"); ret &= add_mapmode("mapmode_militancy", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_3"); ret &= add_mapmode("mapmode_diplomatic", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_4"); ret &= add_mapmode("mapmode_region", get_colour_mapmode(&ProvinceDefinition::get_region), "MAPMODE_5"); @@ -232,34 +242,39 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin spdlog::error_s("Cannot setup infrastructure mapmode because infrastructure_building_type is null."); ret = false; } else if (!infrastructure_building_type_ptr->province_building_index.has_value()) { - spdlog::error_s("Cannot setup infrastructure mapmode because infrastructure_building_type has no province_building_index."); + spdlog::error_s( + "Cannot setup infrastructure mapmode because infrastructure_building_type has no province_building_index." + ); ret = false; } else { ret &= add_mapmode( - "mapmode_infrastructure", - [&building_type_manager, infrastructure_building_type_ptr]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - if (province.province_definition.is_water()) { - return colour_argb_t::null(); - } - - BuildingType const& infrastructure_building_type = *infrastructure_building_type_ptr; - BuildingInstance const& infrastructure = province.get_buildings()[infrastructure_building_type.province_building_index.value()]; - const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( - type_safe::get(infrastructure.get_level()), type_safe::get(infrastructure_building_type.max_level) + 1, 0.5f, 1.0f - ); - switch (infrastructure.get_expansion_state()) { - case BuildingInstance::ExpansionState::CannotExpand: - return colour_argb_t { val, 0, 0, ALPHA_VALUE }; - case BuildingInstance::ExpansionState::CanExpand: - return colour_argb_t { 0, 0, val, ALPHA_VALUE }; - default: - return colour_argb_t { 0, val, 0, ALPHA_VALUE }; - } - }, - "MAPMODE_6" + "mapmode_infrastructure", + [&building_type_manager, infrastructure_building_type_ptr]( + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { + if (province.province_definition.is_water()) { + return colour_argb_t::null(); + } + + BuildingType const& infrastructure_building_type = *infrastructure_building_type_ptr; + BuildingInstance const& infrastructure = + province.get_buildings()[infrastructure_building_type.province_building_index.value()]; + const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( + type_safe::get(infrastructure.get_level()), + type_safe::get(infrastructure_building_type.max_level) + 1, + 0.5f, + 1.0f + ); + switch (infrastructure.get_expansion_state()) { + case BuildingInstance::ExpansionState::CannotExpand: return colour_argb_t { val, 0, 0, ALPHA_VALUE }; + case BuildingInstance::ExpansionState::CanExpand: return colour_argb_t { 0, 0, val, ALPHA_VALUE }; + default: return colour_argb_t { 0, val, 0, ALPHA_VALUE }; + } + }, + "MAPMODE_6" ); } ret &= add_mapmode("mapmode_colonial", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_7"); @@ -268,26 +283,31 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin ret &= add_mapmode("mapmode_national_focus", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_10"); ret &= add_mapmode("mapmode_rgo", get_colour_mapmode(&ProvinceInstance::get_rgo_good), "MAPMODE_11"); ret &= add_mapmode( - "mapmode_population", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - // TODO - explore non-linear scaling to have more variation among non-massive provinces - // TODO - when selecting a province, only show the population of provinces controlled (or owned?) - // by the same country, relative to the most populous province in that set of provinces - if (!province.province_definition.is_water()) { - const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( - type_safe::get(province.get_total_population()), type_safe::get(map_instance.get_highest_province_population()) + 1, 0.1f, 1.0f - ); - return colour_argb_t { 0, val, 0, ALPHA_VALUE }; - } else { - return colour_argb_t::null(); - } - }, - "MAPMODE_12" + "mapmode_population", + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { + // TODO - explore non-linear scaling to have more variation among non-massive provinces + // TODO - when selecting a province, only show the population of provinces controlled (or owned?) + // by the same country, relative to the most populous province in that set of provinces + if (!province.province_definition.is_water()) { + const colour_argb_t::value_type val = colour_argb_t::colour_traits::component_from_fraction( + type_safe::get(province.get_total_population()), + type_safe::get(map_instance.get_highest_province_population()) + 1, + 0.1f, + 1.0f + ); + return colour_argb_t { 0, val, 0, ALPHA_VALUE }; + } else { + return colour_argb_t::null(); + } + }, + "MAPMODE_12" + ); + ret &= add_mapmode( + "mapmode_culture", shaded_mapmode(&ProvinceInstance::get_population_by_culture), "MAPMODE_13" ); - ret &= add_mapmode("mapmode_culture", shaded_mapmode(&ProvinceInstance::get_population_by_culture), "MAPMODE_13"); ret &= add_mapmode("mapmode_sphere", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_14"); ret &= add_mapmode("mapmode_supply", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_15"); ret &= add_mapmode("mapmode_party_loyalty", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_16"); @@ -297,97 +317,102 @@ bool MapmodeManager::setup_mapmodes(MapDefinition const& map_definition, Buildin ret &= add_mapmode("mapmode_relations", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_20"); ret &= add_mapmode("mapmode_crisis", Mapmode::ERROR_MAPMODE.get_colour_func(), "MAPMODE_21"); ret &= add_mapmode( - "mapmode_naval", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - ProvinceDefinition const& province_definition = province.province_definition; - - if (province_definition.has_port()) { - return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); - } else if (!province_definition.is_water()) { - return (0x333333_argb).with_alpha(ALPHA_VALUE); - } else { - return colour_argb_t::null(); - } - }, - "MAPMODE_22" + "mapmode_naval", + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { + ProvinceDefinition const& province_definition = province.province_definition; + + if (province_definition.has_port()) { + return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); + } else if (!province_definition.is_water()) { + return (0x333333_argb).with_alpha(ALPHA_VALUE); + } else { + return colour_argb_t::null(); + } + }, + "MAPMODE_22" ); /* - *** CUSTOM MAPMODES FOR TESTING *** - - For these mapmodes to have a button in-game you either need to remove the same number of default mapmodes - or add more mapmode buttons (GUIIconButton nodes with path ^".../Menubar/menubar/mapmode_") + *** CUSTOM MAPMODES FOR TESTING *** + - For these mapmodes to have a button in-game you either need to remove the same number of default mapmodes + or add more mapmode buttons (GUIIconButton nodes with path ^".../Menubar/menubar/mapmode_") */ if constexpr (false) { ret &= add_mapmode( - "mapmode_province", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - return colour_argb_t { province.province_definition.get_colour(), ALPHA_VALUE }; - } + "mapmode_province", + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { + return colour_argb_t { province.province_definition.get_colour(), ALPHA_VALUE }; + } ); ret &= add_mapmode( - "mapmode_index", - [&map_definition]( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - const colour_argb_t::value_type f = colour_argb_t::colour_traits::component_from_fraction( - province.province_definition.get_province_number(), map_definition.get_province_definition_count() + 1 - ); - return colour_argb_t::fill_as(f).with_alpha(ALPHA_VALUE); - } + "mapmode_index", + [&map_definition]( + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province + ) -> Mapmode::base_stripe_t { + const colour_argb_t::value_type f = colour_argb_t::colour_traits::component_from_fraction( + province.province_definition.get_province_number(), map_definition.get_province_definition_count() + 1 + ); + return colour_argb_t::fill_as(f).with_alpha(ALPHA_VALUE); + } + ); + ret &= add_mapmode( + "mapmode_religion", shaded_mapmode(&ProvinceInstance::get_population_by_religion) ); - ret &= add_mapmode("mapmode_religion", shaded_mapmode(&ProvinceInstance::get_population_by_religion)); ret &= add_mapmode("mapmode_terrain_type", get_colour_mapmode(&ProvinceInstance::get_terrain_type)); ret &= add_mapmode( - "mapmode_adjacencies", - []( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province - ) -> Mapmode::base_stripe_t { - if (selected_province != nullptr) { - ProvinceDefinition const& selected_province_definition = selected_province->province_definition; - - if (*selected_province == province) { - return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); - } - - ProvinceDefinition const& province_definition = province.province_definition; - - colour_argb_t base = colour_argb_t::null(), stripe = colour_argb_t::null(); - ProvinceDefinition::adjacency_t const* adj = - selected_province_definition.get_adjacency_to(province_definition); - - if (adj != nullptr) { - colour_argb_t::integer_type base_int; - switch (adj->get_type()) { - using enum ProvinceDefinition::adjacency_t::type_t; - case LAND: base_int = 0x00FF00; break; - case WATER: base_int = 0x0000FF; break; - case COASTAL: base_int = 0xF9D199; break; - case IMPASSABLE: base_int = 0x8B4513; break; - case STRAIT: base_int = 0x00FFFF; break; - case CANAL: base_int = 0x888888; break; - default: base_int = 0xFF0000; break; - } - base = colour_argb_t::from_integer(base_int).with_alpha(ALPHA_VALUE); - stripe = base; - } - - if (selected_province_definition.has_adjacency_going_through(province_definition)) { - stripe = (0xFFFF00_argb).with_alpha(ALPHA_VALUE); - } - - return { base, stripe }; - } - - return colour_argb_t::null(); - } + "mapmode_adjacencies", + [](MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province) -> Mapmode::base_stripe_t { + if (selected_province != nullptr) { + ProvinceDefinition const& selected_province_definition = selected_province->province_definition; + + if (*selected_province == province) { + return (0xFFFFFF_argb).with_alpha(ALPHA_VALUE); + } + + ProvinceDefinition const& province_definition = province.province_definition; + + colour_argb_t base = colour_argb_t::null(), stripe = colour_argb_t::null(); + ProvinceDefinition::adjacency_t const* adj = selected_province_definition.get_adjacency_to( + province_definition + ); + + if (adj != nullptr) { + colour_argb_t::integer_type base_int; + switch (adj->get_type()) { + using enum ProvinceDefinition::adjacency_t::type_t; + case LAND: base_int = 0x00FF00; break; + case WATER: base_int = 0x0000FF; break; + case COASTAL: base_int = 0xF9D199; break; + case IMPASSABLE: base_int = 0x8B4513; break; + case STRAIT: base_int = 0x00FFFF; break; + case CANAL: base_int = 0x888888; break; + default: base_int = 0xFF0000; break; + } + base = colour_argb_t::from_integer(base_int).with_alpha(ALPHA_VALUE); + stripe = base; + } + + if (selected_province_definition.has_adjacency_going_through(province_definition)) { + stripe = (0xFFFF00_argb).with_alpha(ALPHA_VALUE); + } + + return { base, stripe }; + } + + return colour_argb_t::null(); + } ); } diff --git a/src/openvic-simulation/map/Mapmode.hpp b/src/openvic-simulation/map/Mapmode.hpp index 174df84b2..667655365 100644 --- a/src/openvic-simulation/map/Mapmode.hpp +++ b/src/openvic-simulation/map/Mapmode.hpp @@ -26,13 +26,12 @@ namespace OpenVic { struct base_stripe_t { colour_argb_t base_colour; colour_argb_t stripe_colour; - constexpr base_stripe_t(colour_argb_t base, colour_argb_t stripe) - : base_colour { base }, stripe_colour { stripe } {} + constexpr base_stripe_t(colour_argb_t base, colour_argb_t stripe) : + base_colour { base }, stripe_colour { stripe } {} constexpr base_stripe_t(colour_argb_t both) : base_stripe_t { both, both } {} }; using colour_func_t = fu2::function< - base_stripe_t(MapInstance const&, ProvinceInstance const&, CountryInstance const*, ProvinceInstance const*) const - >; + base_stripe_t(MapInstance const&, ProvinceInstance const&, CountryInstance const*, ProvinceInstance const*) const>; private: // Not const so they don't have to be copied when the Mapmode is moved @@ -40,24 +39,24 @@ namespace OpenVic { memory::string PROPERTY(localisation_key); public: - static constexpr index_t ERROR_INDEX { - std::numeric_limits>::max() - }; + static constexpr index_t ERROR_INDEX { std::numeric_limits>::max() }; static const Mapmode ERROR_MAPMODE; const bool is_parchment_mapmode_allowed; Mapmode( - std::string_view new_identifier, - index_t new_index, - colour_func_t new_colour_func, - std::string_view new_localisation_key = {}, - bool new_is_parchment_mapmode_allowed = true + std::string_view new_identifier, + index_t new_index, + colour_func_t new_colour_func, + std::string_view new_localisation_key = {}, + bool new_is_parchment_mapmode_allowed = true ); Mapmode(Mapmode&&) = default; base_stripe_t get_base_stripe_colours( - MapInstance const& map_instance, ProvinceInstance const& province, - CountryInstance const* player_country, ProvinceInstance const* selected_province + MapInstance const& map_instance, + ProvinceInstance const& province, + CountryInstance const* player_country, + ProvinceInstance const* selected_province ) const; }; @@ -69,10 +68,10 @@ namespace OpenVic { constexpr MapmodeManager() {}; bool add_mapmode( - std::string_view identifier, - Mapmode::colour_func_t colour_func, - std::string_view localisation_key = {}, - bool parchment_mapmode_allowed = true + std::string_view identifier, + Mapmode::colour_func_t colour_func, + std::string_view localisation_key = {}, + bool parchment_mapmode_allowed = true ); /* The mapmode colour image contains of a list of base colours and stripe colours. Each colour is four bytes @@ -81,9 +80,11 @@ namespace OpenVic { * together adjacently, so each province's entry is 8 bytes long. * The list contains all provinces indexed by their number + index 0 for the "null province". */ bool generate_mapmode_colours( - MapInstance const& map_instance, Mapmode const* mapmode, - CountryInstance const* player_country, ProvinceInstance const* selected_province, - uint8_t* target + MapInstance const& map_instance, + Mapmode const* mapmode, + CountryInstance const* player_country, + ProvinceInstance const* selected_province, + uint8_t* target ) const; bool setup_mapmodes(MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager); diff --git a/src/openvic-simulation/map/ProvinceDefinition.cpp b/src/openvic-simulation/map/ProvinceDefinition.cpp index daa0dd0e1..c53c9052e 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.cpp +++ b/src/openvic-simulation/map/ProvinceDefinition.cpp @@ -10,19 +10,15 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -ProvinceDefinition::ProvinceDefinition( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index -) : HasIdentifierAndColour { new_identifier, new_colour, true }, - HasIndex { new_index } {} +ProvinceDefinition::ProvinceDefinition(std::string_view new_identifier, colour_t new_colour, index_t new_index) : + HasIdentifierAndColour { new_identifier, new_colour, true }, HasIndex { new_index } {} memory::string ProvinceDefinition::to_string() const { return memory::fmt::format("(#{}, {}, 0x{})", get_province_number(), get_identifier(), get_colour()); } bool ProvinceDefinition::load_positions( - MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root + MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root ) { const fixed_point_t map_height = map_definition.get_height(); @@ -64,10 +60,7 @@ bool ProvinceDefinition::load_positions( const fixed_point_t rotation = get_building_rotation(building_type_manager.get_port_building_type()); /* At 0 rotation the port faces west, as rotation increases the port rotates anti-clockwise. */ - const fvec2_t port_dir { - -fp::cos(rotation), - fp::sin(rotation) - }; + const fvec2_t port_dir { -fp::cos(rotation), fp::sin(rotation) }; const ivec2_t port_facing_position = static_cast(*port_position + port_dir / 4); ProvinceDefinition const* province_ptr = map_definition.get_province_definition_at(port_facing_position); @@ -80,8 +73,11 @@ bool ProvinceDefinition::load_positions( } else { /* Expected provinces with invalid ports: 39, 296, 1047, 1406, 2044 */ spdlog::warn_s( - "Invalid port for province {}: facing province {} which has: water = {}, adjacent = {}", - get_identifier(), province, province.is_water(), is_adjacent_to(province) + "Invalid port for province {}: facing province {} which has: water = {}, adjacent = {}", + get_identifier(), + province, + province.is_water(), + is_adjacent_to(province) ); } } else { @@ -129,19 +125,21 @@ fixed_point_t ProvinceDefinition::get_building_rotation(BuildingType const* buil std::string_view ProvinceDefinition::adjacency_t::get_type_name(type_t type) { switch (type) { - case type_t::LAND: return "Land"; - case type_t::WATER: return "Water"; - case type_t::COASTAL: return "Coastal"; + case type_t::LAND: return "Land"; + case type_t::WATER: return "Water"; + case type_t::COASTAL: return "Coastal"; case type_t::IMPASSABLE: return "Impassable"; - case type_t::STRAIT: return "Strait"; - case type_t::CANAL: return "Canal"; - default: return "Invalid Adjacency Type"; + case type_t::STRAIT: return "Strait"; + case type_t::CANAL: return "Canal"; + default: return "Invalid Adjacency Type"; } } ProvinceDefinition::adjacency_t const* ProvinceDefinition::get_adjacency_to(ProvinceDefinition const& province) const { - const memory::vector::const_iterator it = std::find_if(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { return adj.get_to() == province; } + const memory::vector::const_iterator it = std::find_if( + adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_to() == province; + } ); if (it != adjacencies.end()) { return &*it; @@ -151,13 +149,13 @@ ProvinceDefinition::adjacency_t const* ProvinceDefinition::get_adjacency_to(Prov } bool ProvinceDefinition::is_adjacent_to(ProvinceDefinition const& province) const { - return std::any_of(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { return adj.get_to() == province; } - ); + return std::any_of(adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_to() == province; + }); } memory::vector> ProvinceDefinition::get_adjacencies_going_through( - ProvinceDefinition const& province + ProvinceDefinition const& province ) const { memory::vector> ret; for (adjacency_t const& adj : adjacencies) { @@ -169,11 +167,9 @@ memory::vector> Pr } bool ProvinceDefinition::has_adjacency_going_through(ProvinceDefinition const& province) const { - return std::any_of(adjacencies.begin(), adjacencies.end(), - [&province](adjacency_t const& adj) -> bool { - return adj.get_through() != nullptr && *adj.get_through() == province; - } - ); + return std::any_of(adjacencies.begin(), adjacencies.end(), [&province](adjacency_t const& adj) -> bool { + return adj.get_through() != nullptr && *adj.get_through() == province; + }); } fvec2_t ProvinceDefinition::get_unit_position() const { diff --git a/src/openvic-simulation/map/ProvinceDefinition.hpp b/src/openvic-simulation/map/ProvinceDefinition.hpp index 2954fa53c..81a5f6cef 100644 --- a/src/openvic-simulation/map/ProvinceDefinition.hpp +++ b/src/openvic-simulation/map/ProvinceDefinition.hpp @@ -9,11 +9,11 @@ #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/Vector.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" namespace OpenVic { @@ -40,12 +40,12 @@ namespace OpenVic { static constexpr data_t DEFAULT_DATA = 0; enum struct type_t : uint8_t { - LAND, /* Between two land provinces */ - WATER, /* Between two water provinces */ - COASTAL, /* Between a land province and a water province */ + LAND, /* Between two land provinces */ + WATER, /* Between two water provinces */ + COASTAL, /* Between a land province and a water province */ IMPASSABLE, /* Between two land provinces (non-traversable) */ - STRAIT, /* Between two land provinces with a water through province */ - CANAL /* Between two water provinces with a land through province */ + STRAIT, /* Between two land provinces with a water through province */ + CANAL /* Between two water provinces with a land through province */ }; /* Type display name used for logging */ @@ -61,16 +61,12 @@ namespace OpenVic { public: constexpr adjacency_t( - ProvinceDefinition const& new_to, - const distance_t new_distance, - const type_t new_type, - ProvinceDefinition const* const new_through, - const data_t new_data - ) : to { new_to }, - through { new_through }, - distance { new_distance }, - type { new_type }, - data { new_data } {} + ProvinceDefinition const& new_to, + const distance_t new_distance, + const type_t new_type, + ProvinceDefinition const* const new_through, + const data_t new_data + ) : to { new_to }, through { new_through }, distance { new_distance }, type { new_type }, data { new_data } {} adjacency_t(adjacency_t const&) = delete; adjacency_t(adjacency_t&&) = default; @@ -138,7 +134,7 @@ namespace OpenVic { /* The positions' y coordinates need to be inverted. */ bool load_positions( - MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root + MapDefinition const& map_definition, BuildingTypeManager const& building_type_manager, ast::NodeCPtr root ); fvec2_t get_text_position() const; @@ -151,7 +147,9 @@ namespace OpenVic { adjacency_t const* get_adjacency_to(ProvinceDefinition const& province) const; bool is_adjacent_to(ProvinceDefinition const& province) const; - memory::vector> get_adjacencies_going_through(ProvinceDefinition const& province) const; + memory::vector> get_adjacencies_going_through( + ProvinceDefinition const& province + ) const; bool has_adjacency_going_through(ProvinceDefinition const& province) const; fvec2_t get_unit_position() const; diff --git a/src/openvic-simulation/map/ProvinceInstance.cpp b/src/openvic-simulation/map/ProvinceInstance.cpp index aa058883b..65cd4cc52 100644 --- a/src/openvic-simulation/map/ProvinceInstance.cpp +++ b/src/openvic-simulation/map/ProvinceInstance.cpp @@ -1,47 +1,42 @@ #include "ProvinceInstance.hpp" -#include "ProvinceInstanceDeps.hpp" -#include "population/PopsAggregateDeps.hpp" #include +#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/defines/MilitaryDefines.hpp" -#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/economy/BuildingInstance.hpp" #include "openvic-simulation/economy/BuildingType.hpp" #include "openvic-simulation/economy/production/Employee.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" -#include "openvic-simulation/InstanceManager.hpp" #include "openvic-simulation/map/ProvinceDefinition.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/modifier/StaticModifierCache.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "ProvinceInstanceDeps.hpp" +#include "population/PopsAggregateDeps.hpp" + using namespace OpenVic; ProvinceInstance::ProvinceInstance( - ProvinceDefinition const& new_province_definition, - ProvinceInstanceDeps const& province_instance_deps -) : HasIdentifierAndColour { new_province_definition }, - HasIndex { new_province_definition.index }, - FlagStrings { "province" }, - PopsAggregate { province_instance_deps.pops_aggregate_deps }, - province_definition { new_province_definition }, - game_rules_manager { province_instance_deps.game_rules_manager }, - terrain_type { new_province_definition.get_default_terrain_type() }, - rgo { province_instance_deps.rgo_deps }, - pops_cache_by_type { generate_values, province_instance_deps.pops_aggregate_deps.pop_type_count }, - buildings { - new_province_definition.is_water() - ? province_building_index_t(0) - : province_building_index_t(province_instance_deps.building_type_manager.get_province_building_types().size()), - [&province_instance_deps](const province_building_index_t i) -> BuildingType const& { - return province_instance_deps.building_type_manager.get_province_building_types()[i]; - } - } -{ + ProvinceDefinition const& new_province_definition, ProvinceInstanceDeps const& province_instance_deps +) : + HasIdentifierAndColour { new_province_definition }, HasIndex { new_province_definition.index }, FlagStrings { "province" }, + PopsAggregate { province_instance_deps.pops_aggregate_deps }, province_definition { new_province_definition }, + game_rules_manager { province_instance_deps.game_rules_manager }, + terrain_type { new_province_definition.get_default_terrain_type() }, rgo { province_instance_deps.rgo_deps }, + pops_cache_by_type { generate_values, province_instance_deps.pops_aggregate_deps.pop_type_count }, buildings { + new_province_definition.is_water() + ? province_building_index_t(0) + : province_building_index_t(province_instance_deps.building_type_manager.get_province_building_types().size()), + [&province_instance_deps](const province_building_index_t i) -> BuildingType const& { + return province_instance_deps.building_type_manager.get_province_building_types()[i]; + } + } { modifier_sum.set_this_source(this); rgo.setup_location_ptr(*this); } @@ -64,20 +59,18 @@ GoodDefinition const* ProvinceInstance::get_rgo_good() const { } bool ProvinceInstance::set_rgo_production_type_nullable( - TypedSpan pop_types, - ProductionType const* rgo_production_type_nullable + TypedSpan pop_types, ProductionType const* rgo_production_type_nullable ) { bool is_valid_operation = true; if (rgo_production_type_nullable != nullptr) { ProductionType const& rgo_production_type = *rgo_production_type_nullable; if (rgo_production_type.template_type != ProductionType::template_type_t::RGO) { spdlog::error_s( - "Tried setting province {} rgo to {} which is not of template_type RGO.", - *this, rgo_production_type + "Tried setting province {} rgo to {} which is not of template_type RGO.", *this, rgo_production_type ); is_valid_operation = false; } - is_valid_operation&=convert_rgo_worker_pops_to_equivalent(pop_types, rgo_production_type); + is_valid_operation &= convert_rgo_worker_pops_to_equivalent(pop_types, rgo_production_type); } rgo.set_production_type_nullable(rgo_production_type_nullable); @@ -106,9 +99,7 @@ bool ProvinceInstance::set_owner(CountryInstance* new_owner) { if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::Owner) { country_to_report_economy = new_owner; } else if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::NeitherWhenOccupied) { - country_to_report_economy = is_occupied() - ? nullptr - : owner; + country_to_report_economy = is_occupied() ? nullptr : owner; } } @@ -136,9 +127,7 @@ bool ProvinceInstance::set_controller(CountryInstance* new_controller) { if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::Controller) { country_to_report_economy = new_controller; } else if (game_rules_manager.get_country_to_report_economy() == country_to_report_economy_t::NeitherWhenOccupied) { - country_to_report_economy = is_occupied() - ? nullptr - : owner; + country_to_report_economy = is_occupied() ? nullptr : owner; } } @@ -149,10 +138,7 @@ bool ProvinceInstance::add_core(CountryInstance& new_core, bool warn) { if (cores.emplace(&new_core).second) { return new_core.add_core_province(*this); } else if (warn) { - spdlog::warn_s( - "Attempted to add core \"{}\" to province {}: already exists!", - new_core, *this - ); + spdlog::warn_s("Attempted to add core \"{}\" to province {}: already exists!", new_core, *this); } return true; } @@ -161,35 +147,22 @@ bool ProvinceInstance::remove_core(CountryInstance& core_to_remove, bool warn) { if (cores.erase(&core_to_remove) > 0) { return core_to_remove.remove_core_province(*this); } else if (warn) { - spdlog::warn_s( - "Attempted to remove core \"{}\" from province {}: does not exist!", - core_to_remove, *this - ); + spdlog::warn_s("Attempted to remove core \"{}\" from province {}: does not exist!", core_to_remove, *this); } return true; } bool ProvinceInstance::expand_building( - ModifierEffectCache const& modifier_effect_cache, - const province_building_index_t index, - CountryInstance& actor + ModifierEffectCache const& modifier_effect_cache, const province_building_index_t index, CountryInstance& actor ) { return buildings[index].expand(modifier_effect_cache, actor, *this); } -bool ProvinceInstance::add_pop_vec( - std::span pop_vec, - PopDeps const& pop_deps -) { +bool ProvinceInstance::add_pop_vec(std::span pop_vec, PopDeps const& pop_deps) { if (!province_definition.is_water()) { reserve_more(pops, pop_vec.size()); for (PopBase const& pop : pop_vec) { - pops.emplace( - *this, - pop, - pop_deps, - ++last_pop_id - ); + pops.emplace(*this, pop, pop_deps, ++last_pop_id); } return true; } else { @@ -217,9 +190,11 @@ void ProvinceInstance::_update_pops(MilitaryDefines const& military_defines) { using enum colony_status_t; const fixed_point_t pop_size_per_regiment_multiplier = - colony_status == PROTECTORATE ? military_defines.get_pop_size_per_regiment_protectorate_multiplier() - : colony_status == COLONY ? military_defines.get_pop_size_per_regiment_colony_multiplier() - : is_owner_core() ? fixed_point_t::_1 : military_defines.get_pop_size_per_regiment_non_core_multiplier(); + colony_status == PROTECTORATE ? military_defines.get_pop_size_per_regiment_protectorate_multiplier() + : colony_status == COLONY ? military_defines.get_pop_size_per_regiment_colony_multiplier() + : is_owner_core() + ? fixed_point_t::_1 + : military_defines.get_pop_size_per_regiment_non_core_multiplier(); for (Pop& pop : pops) { pops_cache_by_type[pop.get_type().index].push_back(pop); @@ -259,7 +234,7 @@ void ProvinceInstance::update_modifier_sum(Date today, StaticModifierCache const modifier_sum.add_modifier(static_modifier_cache.get_land_province()); modifier_sum.add_modifier( - province_definition.is_coastal() ? static_modifier_cache.get_coastal() : static_modifier_cache.get_non_coastal() + province_definition.is_coastal() ? static_modifier_cache.get_coastal() : static_modifier_cache.get_non_coastal() ); // TODO - overseas, blockaded, no_adjacent_controlled, has_siege, occupied, nationalism, infrastructure @@ -312,8 +287,7 @@ fixed_point_t ProvinceInstance::get_modifier_effect_value(ModifierEffect const& } bool ProvinceInstance::convert_rgo_worker_pops_to_equivalent( - TypedSpan pop_types, - ProductionType const& production_type + TypedSpan pop_types, ProductionType const& production_type ) { bool is_valid_operation = true; std::span jobs = production_type.get_jobs(); @@ -324,7 +298,7 @@ bool ProvinceInstance::convert_rgo_worker_pops_to_equivalent( if (job_pop_type != old_pop_type) { PopType const* const equivalent_ptr = old_pop_type.get_equivalent(); if (equivalent_ptr != nullptr && job_pop_type == *equivalent_ptr) { - is_valid_operation&=pop.convert_to_equivalent(); + is_valid_operation &= pop.convert_to_equivalent(); } } } @@ -372,14 +346,11 @@ void ProvinceInstance::update_gamestate(InstanceManager const& instance_manager) } void ProvinceInstance::province_tick( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + const Date today, + PopValuesFromProvince& reusable_pop_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ) { if (is_occupied()) { ++occupation_duration; @@ -388,12 +359,7 @@ void ProvinceInstance::province_tick( if (!pops.empty()) { reusable_pop_values.update_pop_values_from_province(*this); for (Pop& pop : pops) { - pop.pop_tick( - reusable_pop_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + pop.pop_tick(reusable_pop_values, random_number_generator, reusable_goods_mask, reusable_vectors); } } @@ -407,38 +373,35 @@ bool ProvinceInstance::add_unit_instance_group(UnitInstanceGroup& group) { using enum unit_branch_t; switch (group.branch) { - case LAND: - armies.emplace_back(static_cast(group)); - return true; - case NAVAL: - navies.emplace_back(static_cast(group)); - return true; + case LAND: armies.emplace_back(static_cast(group)); return true; + case NAVAL: navies.emplace_back(static_cast(group)); return true; default: spdlog::error_s( - "Trying to add unit group \"{}\" with invalid branch {} to province {}", - group.get_name(), static_cast(group.branch), *this + "Trying to add unit group \"{}\" with invalid branch {} to province {}", + group.get_name(), + static_cast(group.branch), + *this ); return false; } } bool ProvinceInstance::remove_unit_instance_group(UnitInstanceGroup const& group) { - const auto remove_from_vector = [this, &group]( - memory::vector>>& unit_instance_groups - ) -> bool { - auto it = std::find( - unit_instance_groups.begin(), - unit_instance_groups.end(), - group - ); + const auto remove_from_vector = + [this, &group]( + memory::vector>>& unit_instance_groups + ) -> bool { + auto it = std::find(unit_instance_groups.begin(), unit_instance_groups.end(), group); if (it != unit_instance_groups.end()) { unit_instance_groups.erase(it); return true; } else { spdlog::error_s( - "Trying to remove non-existent {} \"{}\" from province {}", - get_branched_unit_group_name(Branch), group.get_name(), *this + "Trying to remove non-existent {} \"{}\" from province {}", + get_branched_unit_group_name(Branch), + group.get_name(), + *this ); return false; } @@ -447,14 +410,14 @@ bool ProvinceInstance::remove_unit_instance_group(UnitInstanceGroup const& group using enum unit_branch_t; switch (group.branch) { - case LAND: - return remove_from_vector(armies); - case NAVAL: - return remove_from_vector(navies); + case LAND: return remove_from_vector(armies); + case NAVAL: return remove_from_vector(navies); default: spdlog::error_s( - "Trying to remove unit group \"{}\" with invalid branch {} from province {}", - group.get_name(), static_cast(group.branch), *this + "Trying to remove unit group \"{}\" with invalid branch {} from province {}", + group.get_name(), + static_cast(group.branch), + *this ); return false; } @@ -503,23 +466,14 @@ bool ProvinceInstance::apply_history_to_province(ProvinceHistoryEntry const& ent } void ProvinceInstance::initialise_for_new_game( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + const Date today, + PopValuesFromProvince& reusable_pop_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ) { initialise_rgo(); - province_tick( - today, - reusable_pop_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + province_tick(today, reusable_pop_values, random_number_generator, reusable_goods_mask, reusable_vectors); } void ProvinceInstance::initialise_rgo() { @@ -537,7 +491,9 @@ memory::colony& ProvinceInstance::get_mutable_pops() { } template -std::conditional_t, Pop const*, Pop*> ProvinceInstance::_find_pop_by_id(T& self, const pop_id_in_province_t pop_id) { +std::conditional_t, Pop const*, Pop*> ProvinceInstance::_find_pop_by_id( + T& self, const pop_id_in_province_t pop_id +) { if (pop_id.is_null()) { return nullptr; } @@ -550,5 +506,9 @@ std::conditional_t, Pop const*, Pop*> ProvinceInstance::_find return nullptr; } -Pop* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) { return _find_pop_by_id(*this, pop_id); } -Pop const* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) const { return _find_pop_by_id(*this, pop_id); } \ No newline at end of file +Pop* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) { + return _find_pop_by_id(*this, pop_id); +} +Pop const* ProvinceInstance::find_pop_by_id(const pop_id_in_province_t pop_id) const { + return _find_pop_by_id(*this, pop_id); +} diff --git a/src/openvic-simulation/map/ProvinceInstance.hpp b/src/openvic-simulation/map/ProvinceInstance.hpp index bde9c2034..696dac7f2 100644 --- a/src/openvic-simulation/map/ProvinceInstance.hpp +++ b/src/openvic-simulation/map/ProvinceInstance.hpp @@ -50,25 +50,17 @@ namespace OpenVic { struct TerrainType; struct UnitInstanceGroup; - //HasIndex index_t must match ProvinceDefinition's index_t - struct ProvinceInstance - : HasIdentifierAndColour, - HasIndex, - FlagStrings, - PopsAggregate { + // HasIndex index_t must match ProvinceDefinition's index_t + struct ProvinceInstance : HasIdentifierAndColour, HasIndex, FlagStrings, PopsAggregate { friend struct MapInstance; static constexpr std::string_view get_colony_status_string(colony_status_t colony_status) { using enum colony_status_t; switch (colony_status) { - case STATE: - return "state"; - case PROTECTORATE: - return "protectorate"; - case COLONY: - return "colony"; - default: - return "unknown colony status"; + case STATE: return "state"; + case PROTECTORATE: return "protectorate"; + case COLONY: return "colony"; + default: return "unknown colony status"; } } @@ -100,10 +92,12 @@ namespace OpenVic { Crime const* PROPERTY_RW(crime, nullptr); ResourceGatheringOperation PROPERTY(rgo); memory::FixedVector buildings; + public: constexpr TypedSpan get_buildings() const { return buildings; } + private: memory::vector> SPAN_PROPERTY(armies); memory::vector> SPAN_PROPERTY(navies); @@ -116,26 +110,20 @@ namespace OpenVic { OV_UNIT_BRANCHED_GETTER_CONST(get_unit_instance_groups, armies, navies); private: - pop_id_in_province_t last_pop_id{0}; + pop_id_in_province_t last_pop_id { 0 }; memory::colony PROPERTY(pops); // TODO - replace with a more easily vectorisable container? void _update_pops(MilitaryDefines const& military_defines); bool convert_rgo_worker_pops_to_equivalent( - TypedSpan pop_types, - ProductionType const& production_type + TypedSpan pop_types, ProductionType const& production_type ); void initialise_rgo(); - memory::FixedVector< - memory::vector>, - pop_type_index_t - > SPAN_PROPERTY(pops_cache_by_type); + memory::FixedVector>, pop_type_index_t> SPAN_PROPERTY(pops_cache_by_type); + public: ProvinceDefinition const& province_definition; - ProvinceInstance( - ProvinceDefinition const& new_province_definition, - ProvinceInstanceDeps const& province_instance_deps - ); + ProvinceInstance(ProvinceDefinition const& new_province_definition, ProvinceInstanceDeps const& province_instance_deps); ProvinceInstance(ProvinceInstance const&) = delete; ProvinceInstance& operator=(ProvinceInstance const&) = delete; ProvinceInstance(ProvinceInstance&&) = delete; @@ -149,8 +137,7 @@ namespace OpenVic { GoodDefinition const* get_rgo_good() const; bool set_rgo_production_type_nullable( - TypedSpan pop_types, - ProductionType const* rgo_production_type_nullable + TypedSpan pop_types, ProductionType const* rgo_production_type_nullable ); bool set_owner(CountryInstance* new_owner); @@ -179,15 +166,10 @@ namespace OpenVic { return !is_occupied(); } bool expand_building( - ModifierEffectCache const& modifier_effect_cache, - const province_building_index_t index, - CountryInstance& actor + ModifierEffectCache const& modifier_effect_cache, const province_building_index_t index, CountryInstance& actor ); - bool add_pop_vec( - std::span pop_vec, - PopDeps const& pop_deps - ); + bool add_pop_vec(std::span pop_vec, PopDeps const& pop_deps); size_t get_pop_count() const; void update_modifier_sum(Date today, StaticModifierCache const& static_modifier_cache); @@ -208,28 +190,21 @@ namespace OpenVic { } void update_gamestate(InstanceManager const& instance_manager); static constexpr size_t VECTORS_FOR_PROVINCE_TICK = std::max( - ResourceGatheringOperation::VECTORS_FOR_RGO_TICK, - Pop::VECTORS_FOR_POP_TICK + ResourceGatheringOperation::VECTORS_FOR_RGO_TICK, Pop::VECTORS_FOR_POP_TICK ); void province_tick( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + const Date today, + PopValuesFromProvince& reusable_pop_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ); void initialise_for_new_game( - const Date today, - PopValuesFromProvince& reusable_pop_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_PROVINCE_TICK - > reusable_vectors + const Date today, + PopValuesFromProvince& reusable_pop_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_PROVINCE_TICK> reusable_vectors ); bool add_unit_instance_group(UnitInstanceGroup& group); @@ -239,11 +214,15 @@ namespace OpenVic { void setup_pop_test_values(TypedSpan reforms); memory::colony& get_mutable_pops(); + private: template - static std::conditional_t, Pop const*, Pop*> _find_pop_by_id(T& self, const pop_id_in_province_t pop_id); + static std::conditional_t, Pop const*, Pop*> _find_pop_by_id( + T& self, const pop_id_in_province_t pop_id + ); + public: Pop* find_pop_by_id(const pop_id_in_province_t pop_id); Pop const* find_pop_by_id(const pop_id_in_province_t pop_id) const; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/ProvinceInstanceDeps.hpp b/src/openvic-simulation/map/ProvinceInstanceDeps.hpp index 99bdfeec1..800e6c1cb 100644 --- a/src/openvic-simulation/map/ProvinceInstanceDeps.hpp +++ b/src/openvic-simulation/map/ProvinceInstanceDeps.hpp @@ -17,4 +17,4 @@ namespace OpenVic { ResourceGatheringOperationDeps const& rgo_deps; forwardable_span stratas; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/Region.cpp b/src/openvic-simulation/map/Region.cpp index 328cb41b5..9bee8d7c7 100644 --- a/src/openvic-simulation/map/Region.cpp +++ b/src/openvic-simulation/map/Region.cpp @@ -86,8 +86,9 @@ bool ProvinceSet::contains_province(ProvinceDefinition const& province) const { return std::find(provinces.begin(), provinces.end(), province) != provinces.end(); } -ProvinceSetModifier::ProvinceSetModifier(std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type) - : Modifier { new_identifier, std::move(new_values), new_type } {} +ProvinceSetModifier::ProvinceSetModifier( + std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type +) : Modifier { new_identifier, std::move(new_values), new_type } {} -Region::Region(std::string_view new_identifier, colour_t new_colour, bool new_is_meta) - : HasIdentifierAndColour { new_identifier, new_colour, false }, is_meta { new_is_meta } {} +Region::Region(std::string_view new_identifier, colour_t new_colour, bool new_is_meta) : + HasIdentifierAndColour { new_identifier, new_colour, false }, is_meta { new_is_meta } {} diff --git a/src/openvic-simulation/map/State.cpp b/src/openvic-simulation/map/State.cpp index 6aa2acf70..60b21b29a 100644 --- a/src/openvic-simulation/map/State.cpp +++ b/src/openvic-simulation/map/State.cpp @@ -8,41 +8,36 @@ #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/map/Region.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" using namespace OpenVic; State::State( - StateSet const& new_state_set, - ProvinceInstance* new_capital, - memory::vector>&& new_provinces, - colony_status_t new_colony_status, - PopsAggregateDeps const& pops_aggregate_deps -) : PopsAggregate { pops_aggregate_deps }, - state_set { new_state_set }, - capital { new_capital }, - provinces { std::move(new_provinces) }, - colony_status { new_colony_status }, - pops_cache_by_type { generate_values, pops_aggregate_deps.pop_type_count } -{ + StateSet const& new_state_set, + ProvinceInstance* new_capital, + memory::vector>&& new_provinces, + colony_status_t new_colony_status, + PopsAggregateDeps const& pops_aggregate_deps +) : + PopsAggregate { pops_aggregate_deps }, state_set { new_state_set }, capital { new_capital }, + provinces { std::move(new_provinces) }, colony_status { new_colony_status }, + pops_cache_by_type { generate_values, pops_aggregate_deps.pop_type_count } { _update_country(); } memory::string State::get_identifier() const { return memory::fmt::format( - "{}_{}_{}", - state_set.region, - ovfmt::validate(get_owner(), "NoCountry"), - ProvinceInstance::get_colony_status_string(colony_status) + "{}_{}_{}", + state_set.region, + ovfmt::validate(get_owner(), "NoCountry"), + ProvinceInstance::get_colony_status_string(colony_status) ); } CountryInstance* State::get_owner() const { - return capital == nullptr - ? static_cast(nullptr) - : capital->get_owner(); + return capital == nullptr ? static_cast(nullptr) : capital->get_owner(); } void State::update_gamestate() { @@ -61,11 +56,7 @@ void State::update_gamestate() { pop_type_index_t pop_type_index {}; for (auto const& province_pops_of_type : province.get_pops_cache_by_type()) { memory::vector>& state_pops_of_type = pops_cache_by_type[pop_type_index]; - state_pops_of_type.insert( - state_pops_of_type.end(), - province_pops_of_type.begin(), - province_pops_of_type.end() - ); + state_pops_of_type.insert(state_pops_of_type.end(), province_pops_of_type.begin(), province_pops_of_type.end()); ++pop_type_index; } } @@ -85,8 +76,9 @@ void State::update_gamestate() { workforce_scalar = min_workforce_scalar; } else { workforce_scalar = std::clamp( - (fixed_point_t { potential_workforce_in_state } / 100).floor() * 400 / potential_employment_in_state, - min_workforce_scalar, max_workforce_scalar + (fixed_point_t { potential_workforce_in_state } / 100).floor() * 400 / potential_employment_in_state, + min_workforce_scalar, + max_workforce_scalar ); } @@ -96,10 +88,10 @@ void State::update_gamestate() { void State::_update_country() { CountryInstance* const owner_ptr = get_owner(); - if (owner_ptr == previous_country_ptr) { + if (owner_ptr == previous_country_ptr) { return; } - + update_parties_for_votes(owner_ptr); if (previous_country_ptr != nullptr) { previous_country_ptr->remove_state(*this); @@ -130,13 +122,18 @@ void StateSet::update_gamestate() { } bool StateManager::add_state_set( - MapInstance& map_instance, Region const& region, - PopsAggregateDeps const& pops_aggregate_deps, - forwardable_span strata_keys, - forwardable_span pop_type_keys + MapInstance& map_instance, + Region const& region, + PopsAggregateDeps const& pops_aggregate_deps, + forwardable_span strata_keys, + forwardable_span pop_type_keys ) { - OV_ERR_FAIL_COND_V_MSG(region.is_meta, false, memory::fmt::format("Cannot use meta region \"{}\" as state template!", region)); - OV_ERR_FAIL_COND_V_MSG(region.empty(), false, memory::fmt::format("Cannot use empty region \"{}\" as state template!", region)); + OV_ERR_FAIL_COND_V_MSG( + region.is_meta, false, memory::fmt::format("Cannot use meta region \"{}\" as state template!", region) + ); + OV_ERR_FAIL_COND_V_MSG( + region.empty(), false, memory::fmt::format("Cannot use empty region \"{}\" as state template!", region) + ); memory::vector>> temp_provinces; @@ -171,10 +168,12 @@ bool StateManager::add_state_set( ProvinceInstance& capital = provinces.front(); State& state = *state_set.states.emplace( - /* TODO: capital province logic */ - state_set, &capital, - std::move(provinces), capital.get_colony_status(), - pops_aggregate_deps + /* TODO: capital province logic */ + state_set, + &capital, + std::move(provinces), + capital.get_colony_status(), + pops_aggregate_deps ); for (ProvinceInstance& province : state.get_provinces()) { @@ -186,11 +185,11 @@ bool StateManager::add_state_set( } bool StateManager::generate_states( - MapDefinition const& map_definition, - MapInstance& map_instance, - PopsAggregateDeps const& pops_aggregate_deps, - forwardable_span strata_keys, - forwardable_span pop_type_keys + MapDefinition const& map_definition, + MapInstance& map_instance, + PopsAggregateDeps const& pops_aggregate_deps, + forwardable_span strata_keys, + forwardable_span pop_type_keys ) { state_sets.clear(); state_sets.reserve(map_definition.get_region_count()); @@ -200,13 +199,7 @@ bool StateManager::generate_states( for (Region const& region : map_definition.get_regions()) { if (!region.is_meta) { - if (add_state_set( - map_instance, - region, - pops_aggregate_deps, - strata_keys, - pop_type_keys - )) { + if (add_state_set(map_instance, region, pops_aggregate_deps, strata_keys, pop_type_keys)) { state_count += state_sets.back().get_state_count(); } else { ret = false; @@ -231,4 +224,4 @@ void StateManager::update_gamestate() { fmt::format_context::iterator fmt::formatter::format(State const& state, fmt::format_context& ctx) const { return formatter::format(state.get_identifier(), ctx); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/map/State.hpp b/src/openvic-simulation/map/State.hpp index b87c804a3..186cf1faa 100644 --- a/src/openvic-simulation/map/State.hpp +++ b/src/openvic-simulation/map/State.hpp @@ -41,10 +41,7 @@ namespace OpenVic { fixed_point_t PROPERTY(industrial_power); bool PROPERTY_CUSTOM_PREFIX(coastal, is, false); - memory::FixedVector< - memory::vector>, - pop_type_index_t - > SPAN_PROPERTY(pops_cache_by_type); + memory::FixedVector>, pop_type_index_t> SPAN_PROPERTY(pops_cache_by_type); void _update_country(); @@ -52,11 +49,11 @@ namespace OpenVic { StateSet const& state_set; State( - StateSet const& new_state_set, - ProvinceInstance* new_capital, - memory::vector>&& new_provinces, - colony_status_t new_colony_status, - PopsAggregateDeps const& pops_aggregate_deps + StateSet const& new_state_set, + ProvinceInstance* new_capital, + memory::vector>&& new_provinces, + colony_status_t new_colony_status, + PopsAggregateDeps const& pops_aggregate_deps ); State(State&&) = delete; State(State const&) = delete; @@ -101,10 +98,11 @@ namespace OpenVic { memory::vector SPAN_PROPERTY(state_sets); bool add_state_set( - MapInstance& map_instance, Region const& region, - PopsAggregateDeps const& pops_aggregate_deps, - forwardable_span strata_keys, - forwardable_span pop_type_keys + MapInstance& map_instance, + Region const& region, + PopsAggregateDeps const& pops_aggregate_deps, + forwardable_span strata_keys, + forwardable_span pop_type_keys ); public: @@ -112,11 +110,11 @@ namespace OpenVic { * After this function, the `regions` property is unmanaged and must be carefully updated and * validated by functions that modify it. */ bool generate_states( - MapDefinition const& map_definition, - MapInstance& map_instance, - PopsAggregateDeps const& pops_aggregate_deps, - forwardable_span strata_keys, - forwardable_span pop_type_keys + MapDefinition const& map_definition, + MapInstance& map_instance, + PopsAggregateDeps const& pops_aggregate_deps, + forwardable_span strata_keys, + forwardable_span pop_type_keys ); void reset(); diff --git a/src/openvic-simulation/map/TerrainType.cpp b/src/openvic-simulation/map/TerrainType.cpp index 8ce0aa849..0f527fabb 100644 --- a/src/openvic-simulation/map/TerrainType.cpp +++ b/src/openvic-simulation/map/TerrainType.cpp @@ -12,44 +12,36 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; TerrainType::TerrainType( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_modifier, - fixed_point_t new_movement_cost, - fixed_point_t new_defence_bonus, - fixed_point_t new_combat_width_percentage_change, - bool new_is_water -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(new_modifier), modifier_type_t::TERRAIN }, - HasColour { new_colour, false }, - movement_cost { new_movement_cost }, - defence_bonus { new_defence_bonus }, - combat_width_percentage_change { new_combat_width_percentage_change }, - is_water { new_is_water } {} + index_t new_index, + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_modifier, + fixed_point_t new_movement_cost, + fixed_point_t new_defence_bonus, + fixed_point_t new_combat_width_percentage_change, + bool new_is_water +) : + HasIndex { new_index }, Modifier { new_identifier, std::move(new_modifier), modifier_type_t::TERRAIN }, + HasColour { new_colour, false }, movement_cost { new_movement_cost }, defence_bonus { new_defence_bonus }, + combat_width_percentage_change { new_combat_width_percentage_change }, is_water { new_is_water } {} TerrainTypeMapping::TerrainTypeMapping( - std::string_view new_identifier, - TerrainType const& new_type, - memory::vector&& new_terrain_indices, - index_t new_priority, - bool new_has_texture -) : HasIdentifier { new_identifier }, - type { new_type }, - terrain_indices { std::move(new_terrain_indices) }, - priority { new_priority }, - has_texture { new_has_texture } {} + std::string_view new_identifier, + TerrainType const& new_type, + memory::vector&& new_terrain_indices, + index_t new_priority, + bool new_has_texture +) : + HasIdentifier { new_identifier }, type { new_type }, terrain_indices { std::move(new_terrain_indices) }, + priority { new_priority }, has_texture { new_has_texture } {} bool TerrainTypeManager::generate_modifiers(ModifierManager& modifier_manager) const { using enum ModifierEffect::format_t; memory::FixedVector& unit_terrain_effects = - modifier_manager.modifier_effect_cache.unit_terrain_effects; + modifier_manager.modifier_effect_cache.unit_terrain_effects; unit_terrain_effects = std::move( - decltype(ModifierEffectCache::unit_terrain_effects) { - generate_values, - terrain_type_index_t(get_terrain_type_count()) - } + decltype(ModifierEffectCache::unit_terrain_effects) { generate_values, terrain_type_index_t(get_terrain_type_count()) } ); bool ret = true; @@ -57,33 +49,41 @@ bool TerrainTypeManager::generate_modifiers(ModifierManager& modifier_manager) c const std::string_view identifier = terrain_type.get_identifier(); ModifierEffectCache::unit_terrain_effects_t& this_unit_terrain_effects = unit_terrain_effects[terrain_type.index]; ret &= modifier_manager.register_unit_terrain_modifier_effect( - this_unit_terrain_effects.attack, ModifierManager::get_flat_identifier("attack", identifier), - FORMAT_x100_1DP_PC_POS, "UA_ATTACK" + this_unit_terrain_effects.attack, + ModifierManager::get_flat_identifier("attack", identifier), + FORMAT_x100_1DP_PC_POS, + "UA_ATTACK" ); ret &= modifier_manager.register_unit_terrain_modifier_effect( - this_unit_terrain_effects.defence, ModifierManager::get_flat_identifier("defence", identifier), - FORMAT_x100_1DP_PC_POS, "UA_DEFENCE" + this_unit_terrain_effects.defence, + ModifierManager::get_flat_identifier("defence", identifier), + FORMAT_x100_1DP_PC_POS, + "UA_DEFENCE" ); ret &= modifier_manager.register_unit_terrain_modifier_effect( - this_unit_terrain_effects.movement, ModifierManager::get_flat_identifier("movement", identifier), - FORMAT_x100_1DP_PC_POS, "UA_MOVEMENT" + this_unit_terrain_effects.movement, + ModifierManager::get_flat_identifier("movement", identifier), + FORMAT_x100_1DP_PC_POS, + "UA_MOVEMENT" ); ret &= modifier_manager.register_unit_terrain_modifier_effect( - this_unit_terrain_effects.attrition, ModifierManager::get_flat_identifier("attrition", identifier), - FORMAT_x1_1DP_PC_NEG, "UA_ATTRITION" + this_unit_terrain_effects.attrition, + ModifierManager::get_flat_identifier("attrition", identifier), + FORMAT_x1_1DP_PC_NEG, + "UA_ATTRITION" ); } return ret; } bool TerrainTypeManager::add_terrain_type( - std::string_view identifier, - colour_t colour, - ModifierValue&& values, - fixed_point_t movement_cost, - fixed_point_t defence_bonus, - fixed_point_t combat_width_percentage_change, - bool is_water + std::string_view identifier, + colour_t colour, + ModifierValue&& values, + fixed_point_t movement_cost, + fixed_point_t defence_bonus, + fixed_point_t combat_width_percentage_change, + bool is_water ) { if (identifier.empty()) { spdlog::error_s("Invalid terrain type identifier - empty!"); @@ -91,26 +91,29 @@ bool TerrainTypeManager::add_terrain_type( } if (movement_cost < 0) { - spdlog::error_s( - "Invalid movement cost for terrain type \"{}\": {} (cannot be negative!)", - identifier, movement_cost - ); + spdlog::error_s("Invalid movement cost for terrain type \"{}\": {} (cannot be negative!)", identifier, movement_cost); return false; } return terrain_types.emplace_item( - identifier, - index_from_count(get_terrain_type_count()), identifier, - colour, std::move(values), movement_cost, defence_bonus, combat_width_percentage_change, is_water + identifier, + index_from_count(get_terrain_type_count()), + identifier, + colour, + std::move(values), + movement_cost, + defence_bonus, + combat_width_percentage_change, + is_water ); } bool TerrainTypeManager::add_terrain_type_mapping( - std::string_view identifier, - TerrainType const* type, - memory::vector&& terrain_indices, - TerrainTypeMapping::index_t priority, - bool has_texture + std::string_view identifier, + TerrainType const* type, + memory::vector&& terrain_indices, + TerrainTypeMapping::index_t priority, + bool has_texture ) { if (!terrain_types_are_locked()) { spdlog::error_s("Cannot register terrain type mappings until terrain types are locked!"); @@ -136,51 +139,54 @@ bool TerrainTypeManager::add_terrain_type_mapping( terrain_type_mappings_map.emplace(idx, terrain_type_mappings.size()); } else { spdlog::error_s( - "Terrain index {} cannot map to {} as it already maps to {}", - static_cast(idx), identifier, ovfmt::validate(terrain_type_mappings.get_item_by_index(it->second)) + "Terrain index {} cannot map to {} as it already maps to {}", + static_cast(idx), + identifier, + ovfmt::validate(terrain_type_mappings.get_item_by_index(it->second)) ); ret = false; } } - ret &= terrain_type_mappings.emplace_item( - identifier, - identifier, *type, std::move(terrain_indices), priority, has_texture - ); + ret &= terrain_type_mappings.emplace_item(identifier, identifier, *type, std::move(terrain_indices), priority, has_texture); return ret; } node_callback_t TerrainTypeManager::_load_terrain_type_categories(ModifierManager const& modifier_manager) { - return [this, &modifier_manager](ast::NodeCPtr root) -> bool { - const bool ret = expect_dictionary_reserve_length(terrain_types, - [this, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_node) -> bool { - ModifierValue values; - fixed_point_t movement_cost, defence_bonus, combat_width_percentage_change; - colour_t colour = colour_t::null(); - bool is_water = false; - - bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_terrain_modifier(values), - "movement_cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_cost)), - "defence", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(defence_bonus)), - "combat_width", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(combat_width_percentage_change)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "is_water", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_water)) - )(type_node); - - ret &= add_terrain_type( - type_key, colour, std::move(values), movement_cost, defence_bonus, combat_width_percentage_change, is_water - ); - - return ret; - } - )(root); - - lock_terrain_types(); - - return ret; - }; + return + [this, &modifier_manager](ast::NodeCPtr root) -> bool { + const bool ret = + expect_dictionary_reserve_length(terrain_types, [this, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_node) -> bool { + ModifierValue values; + fixed_point_t movement_cost, defence_bonus, combat_width_percentage_change; + colour_t colour = colour_t::null(); + bool is_water = false; + + bool + ret = + NodeTools:: + expect_dictionary_keys_and_default(modifier_manager.expect_terrain_modifier(values), "movement_cost", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(movement_cost)), "defence", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(defence_bonus)), "combat_width", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(combat_width_percentage_change)), "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), "is_water", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_water)))( + type_node + ); + + ret &= add_terrain_type( + type_key, + colour, + std::move(values), + movement_cost, + defence_bonus, + combat_width_percentage_change, + is_water + ); + + return ret; + })(root); + + lock_terrain_types(); + + return ret; + }; } bool TerrainTypeManager::_load_terrain_type_mapping(std::string_view mapping_key, ast::NodeCPtr mapping_value) { diff --git a/src/openvic-simulation/map/TerrainType.hpp b/src/openvic-simulation/map/TerrainType.hpp index 8527b8f45..5eed7ce79 100644 --- a/src/openvic-simulation/map/TerrainType.hpp +++ b/src/openvic-simulation/map/TerrainType.hpp @@ -21,14 +21,14 @@ namespace OpenVic { const bool is_water; TerrainType( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_modifier, - fixed_point_t new_movement_cost, - fixed_point_t new_defence_bonus, - fixed_point_t new_combat_width_percentage_change, - bool new_is_water + index_t new_index, + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_modifier, + fixed_point_t new_movement_cost, + fixed_point_t new_defence_bonus, + fixed_point_t new_combat_width_percentage_change, + bool new_is_water ); TerrainType(TerrainType&&) = default; }; @@ -45,11 +45,11 @@ namespace OpenVic { const bool has_texture; TerrainTypeMapping( - std::string_view new_identifier, - TerrainType const& new_type, - memory::vector&& new_terrain_indices, - index_t new_priority, - bool new_has_texture + std::string_view new_identifier, + TerrainType const& new_type, + memory::vector&& new_terrain_indices, + index_t new_priority, + bool new_has_texture ); TerrainTypeMapping(TerrainTypeMapping&&) = default; }; @@ -69,21 +69,21 @@ namespace OpenVic { public: bool add_terrain_type( - std::string_view identifier, - colour_t colour, - ModifierValue&& values, - fixed_point_t movement_cost, - fixed_point_t defence_bonus, - fixed_point_t combat_width_percentage_change, - bool is_water + std::string_view identifier, + colour_t colour, + ModifierValue&& values, + fixed_point_t movement_cost, + fixed_point_t defence_bonus, + fixed_point_t combat_width_percentage_change, + bool is_water ); bool add_terrain_type_mapping( - std::string_view identifier, - TerrainType const* type, - memory::vector&& terrain_indices, - TerrainTypeMapping::index_t priority, - bool has_texture + std::string_view identifier, + TerrainType const* type, + memory::vector&& terrain_indices, + TerrainTypeMapping::index_t priority, + bool has_texture ); TerrainTypeMapping const* get_terrain_type_mapping_for(TerrainTypeMapping::index_t idx) const; diff --git a/src/openvic-simulation/military/CombatWidth.hpp b/src/openvic-simulation/military/CombatWidth.hpp index c1ed14326..ab6454bc9 100644 --- a/src/openvic-simulation/military/CombatWidth.hpp +++ b/src/openvic-simulation/military/CombatWidth.hpp @@ -8,12 +8,13 @@ #include namespace OpenVic { - struct combat_width_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + struct combat_width_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } @@ -23,4 +24,4 @@ struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(OpenVic::combat_width_t const& value, fmt::format_context& ctx) const { return fmt::formatter::format(type_safe::get(value), ctx); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/military/Deployment.cpp b/src/openvic-simulation/military/Deployment.cpp index dfeba572d..5e14961b8 100644 --- a/src/openvic-simulation/military/Deployment.cpp +++ b/src/openvic-simulation/military/Deployment.cpp @@ -2,55 +2,59 @@ #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/map/MapDefinition.hpp" -#include "openvic-simulation/military/MilitaryManager.hpp" #include "openvic-simulation/military/Leader.hpp" #include "openvic-simulation/military/LeaderTrait.hpp" +#include "openvic-simulation/military/MilitaryManager.hpp" #include "openvic-simulation/military/UnitType.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; UnitDeployment::UnitDeployment( - std::string_view new_name, RegimentType const& new_type, ProvinceDefinition const* new_home + std::string_view new_name, RegimentType const& new_type, ProvinceDefinition const* new_home ) : name { new_name }, type { new_type }, home { new_home } {} -UnitDeployment::UnitDeployment(std::string_view new_name, ShipType const& new_type) - : name { new_name }, type { new_type } {} +UnitDeployment::UnitDeployment(std::string_view new_name, ShipType const& new_type) : + name { new_name }, type { new_type } {} template UnitDeploymentGroup::UnitDeploymentGroup( - std::string_view new_name, ProvinceDefinition const& new_location, memory::vector<_Unit>&& new_units, - std::optional new_leader_index + std::string_view new_name, + ProvinceDefinition const& new_location, + memory::vector<_Unit>&& new_units, + std::optional new_leader_index ) : name { new_name }, location { new_location }, units { std::move(new_units) }, leader_index { new_leader_index } {} Deployment::Deployment( - std::string_view new_path, memory::vector&& new_armies, memory::vector&& new_navies, - memory::vector&& new_leaders -) : HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, - leaders { std::move(new_leaders) } {} + std::string_view new_path, + memory::vector&& new_armies, + memory::vector&& new_navies, + memory::vector&& new_leaders +) : + HasIdentifier { new_path }, armies { std::move(new_armies) }, navies { std::move(new_navies) }, + leaders { std::move(new_leaders) } {} bool DeploymentManager::add_deployment( - std::string_view path, memory::vector&& armies, memory::vector&& navies, - memory::vector&& leaders + std::string_view path, + memory::vector&& armies, + memory::vector&& navies, + memory::vector&& leaders ) { if (path.empty()) { spdlog::error_s("Attempted to load order of battle with no path! Something is very wrong!"); return false; } - return deployments.emplace_item( - path, - path, std::move(armies), std::move(navies), std::move(leaders) - ); + return deployments.emplace_item(path, path, std::move(armies), std::move(navies), std::move(leaders)); } bool DeploymentManager::load_oob_file( - Dataloader const& dataloader, - MapDefinition const& map_definition, - MilitaryManager const& military_manager, - std::string_view history_path, - Deployment const*& deployment, - bool fail_on_missing + Dataloader const& dataloader, + MapDefinition const& map_definition, + MilitaryManager const& military_manager, + std::string_view history_path, + Deployment const*& deployment, + bool fail_on_missing ) { deployment = get_deployment_by_identifier(history_path); if (deployment != nullptr) { @@ -64,8 +68,7 @@ bool DeploymentManager::load_oob_file( static constexpr std::string_view oob_directory = "history/units/"; - const fs::path lookedup_path = - dataloader.lookup_file(append_string_views(oob_directory, history_path), false); + const fs::path lookedup_path = dataloader.lookup_file(append_string_views(oob_directory, history_path), false); if (lookedup_path.empty()) { missing_oob_files.emplace(history_path); @@ -95,7 +98,8 @@ bool DeploymentManager::load_oob_file( using enum unit_branch_t; - const auto leader_callback = [&map_definition, &military_manager, &general_count, &admiral_count](ast::NodeCPtr node) -> bool { + const auto leader_callback = + [&map_definition, &military_manager, &general_count, &admiral_count](ast::NodeCPtr node) -> bool { std::string_view leader_name {}; unit_branch_t leader_branch = INVALID_BRANCH; Date leader_date {}; @@ -126,33 +130,25 @@ bool DeploymentManager::load_oob_file( // Default cases for leader personality and background match vic2 behaviour of ignoring invalid traits. if (leader_personality != nullptr && !leader_personality->is_personality_trait()) { spdlog::warn_s( - "Leader {} has personality \"{}\" which is not a personality trait!", - leader_name, *leader_personality + "Leader {} has personality \"{}\" which is not a personality trait!", leader_name, *leader_personality ); leader_personality = nullptr; } if (leader_background != nullptr && !leader_background->is_background_trait()) { - spdlog::warn_s( - "Leader {} has background \"{}\" which is not a background trait!", - leader_name, *leader_background - ); + spdlog::warn_s("Leader {} has background \"{}\" which is not a background trait!", leader_name, *leader_background); leader_background = nullptr; } switch (leader_branch) { - case LAND: - ++general_count; - break; - case NAVAL: - ++admiral_count; - break; + case LAND: ++general_count; break; + case NAVAL: ++admiral_count; break; default: spdlog::error_s("Invalid branch {} for leader {}", static_cast(leader_branch), leader_name); return false; } leaders.emplace_back( - leader_name, leader_branch, leader_date, leader_personality, leader_background, leader_prestige, picture + leader_name, leader_branch, leader_date, leader_personality, leader_background, leader_prestige, picture ); return ret; @@ -266,12 +262,13 @@ bool DeploymentManager::load_oob_file( if (general_count + admiral_count != leaders.size()) { spdlog::error_s( - "Mismatch in sum (#{}) of general (#{}) and admiral (#{}) counts when compared to loaded leader count (#{}) for OOB file {}", - general_count + admiral_count, - general_count, - admiral_count, - leaders.size(), - history_path + "Mismatch in sum (#{}) of general (#{}) and admiral (#{}) counts when compared to loaded leader count (#{}) for " + "OOB file {}", + general_count + admiral_count, + general_count, + admiral_count, + leaders.size(), + history_path ); return false; } diff --git a/src/openvic-simulation/military/Deployment.hpp b/src/openvic-simulation/military/Deployment.hpp index c4c2574b7..9c0217675 100644 --- a/src/openvic-simulation/military/Deployment.hpp +++ b/src/openvic-simulation/military/Deployment.hpp @@ -68,8 +68,10 @@ namespace OpenVic { public: UnitDeploymentGroup( - std::string_view new_name, ProvinceDefinition const& new_location, memory::vector<_Unit>&& new_units, - std::optional new_leader_index + std::string_view new_name, + ProvinceDefinition const& new_location, + memory::vector<_Unit>&& new_units, + std::optional new_leader_index ); UnitDeploymentGroup(UnitDeploymentGroup&&) = default; }; @@ -85,10 +87,10 @@ namespace OpenVic { public: Deployment( - std::string_view new_path, - memory::vector&& new_armies, - memory::vector&& new_navies, - memory::vector&& new_leaders + std::string_view new_path, + memory::vector&& new_armies, + memory::vector&& new_navies, + memory::vector&& new_leaders ); Deployment(Deployment&&) = default; @@ -102,19 +104,19 @@ namespace OpenVic { public: bool add_deployment( - std::string_view path, - memory::vector&& armies, - memory::vector&& navies, - memory::vector&& leaders + std::string_view path, + memory::vector&& armies, + memory::vector&& navies, + memory::vector&& leaders ); bool load_oob_file( - Dataloader const& dataloader, - MapDefinition const& map_definition, - MilitaryManager const& military_manager, - std::string_view history_path, - Deployment const*& deployment, - bool fail_on_missing + Dataloader const& dataloader, + MapDefinition const& map_definition, + MilitaryManager const& military_manager, + std::string_view history_path, + Deployment const*& deployment, + bool fail_on_missing ); size_t get_missing_oob_file_count() const; diff --git a/src/openvic-simulation/military/Leader.cpp b/src/openvic-simulation/military/Leader.cpp index 41361dff3..4c3111d3a 100644 --- a/src/openvic-simulation/military/Leader.cpp +++ b/src/openvic-simulation/military/Leader.cpp @@ -3,24 +3,20 @@ using namespace OpenVic; LeaderBase::LeaderBase( - std::string_view new_name, - unit_branch_t new_branch, - Date new_date, - LeaderTrait const* new_personality, - LeaderTrait const* new_background, - fixed_point_t new_prestige, - std::string_view new_picture -) : name { new_name }, - branch { new_branch }, - date { new_date }, - personality { new_personality }, - background { new_background }, - prestige { new_prestige }, - picture { new_picture } {} + std::string_view new_name, + unit_branch_t new_branch, + Date new_date, + LeaderTrait const* new_personality, + LeaderTrait const* new_background, + fixed_point_t new_prestige, + std::string_view new_picture +) : + name { new_name }, branch { new_branch }, date { new_date }, personality { new_personality }, background { new_background }, + prestige { new_prestige }, picture { new_picture } {} void LeaderBase::set_picture(std::string_view new_picture) { picture = new_picture; } -LeaderInstance::LeaderInstance(unique_id_t new_unique_id, LeaderBase const& leader_base, CountryInstance const& new_country) - : LeaderBase { leader_base }, unique_id { new_unique_id }, country { new_country } {} +LeaderInstance::LeaderInstance(unique_id_t new_unique_id, LeaderBase const& leader_base, CountryInstance const& new_country) : + LeaderBase { leader_base }, unique_id { new_unique_id }, country { new_country } {} diff --git a/src/openvic-simulation/military/Leader.hpp b/src/openvic-simulation/military/Leader.hpp index cdaf47e3c..5a2252b5f 100644 --- a/src/openvic-simulation/military/Leader.hpp +++ b/src/openvic-simulation/military/Leader.hpp @@ -4,8 +4,8 @@ #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/UniqueId.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -32,8 +32,13 @@ namespace OpenVic { const Date date; LeaderBase( - std::string_view new_name, unit_branch_t new_branch, Date new_date, LeaderTrait const* new_personality, - LeaderTrait const* new_background, fixed_point_t new_prestige, std::string_view new_picture + std::string_view new_name, + unit_branch_t new_branch, + Date new_date, + LeaderTrait const* new_personality, + LeaderTrait const* new_background, + fixed_point_t new_prestige, + std::string_view new_picture ); LeaderBase(LeaderBase&&) = default; @@ -52,6 +57,7 @@ namespace OpenVic { private: UnitInstanceGroup* PROPERTY_PTR(unit_instance_group, nullptr); bool PROPERTY_RW(can_be_used, true); + public: const unique_id_t unique_id; diff --git a/src/openvic-simulation/military/LeaderTrait.cpp b/src/openvic-simulation/military/LeaderTrait.cpp index 972fd6131..bf12c7f7d 100644 --- a/src/openvic-simulation/military/LeaderTrait.cpp +++ b/src/openvic-simulation/military/LeaderTrait.cpp @@ -8,8 +8,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -LeaderTrait::LeaderTrait(std::string_view new_identifier, trait_type_t new_type, ModifierValue&& new_modifiers) - : Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::LEADER }, trait_type { new_type } {} +LeaderTrait::LeaderTrait(std::string_view new_identifier, trait_type_t new_type, ModifierValue&& new_modifiers) : + Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::LEADER }, trait_type { new_type } {} bool LeaderTrait::is_personality_trait() const { return trait_type == trait_type_t::PERSONALITY; @@ -19,11 +19,11 @@ bool LeaderTrait::is_background_trait() const { return trait_type == trait_type_t::BACKGROUND; } -LeaderTraitManager::LeaderTraitManager() - : leader_prestige_modifier { "leader_prestige", {}, Modifier::modifier_type_t::LEADER } {} +LeaderTraitManager::LeaderTraitManager() : + leader_prestige_modifier { "leader_prestige", {}, Modifier::modifier_type_t::LEADER } {} bool LeaderTraitManager::setup_leader_prestige_modifier( - ModifierEffectCache const& modifier_effect_cache, MilitaryDefines const& military_defines + ModifierEffectCache const& modifier_effect_cache, MilitaryDefines const& military_defines ) { if (!leader_prestige_modifier.empty()) { spdlog::error_s("Leader prestige modifier already set up!"); @@ -35,7 +35,7 @@ bool LeaderTraitManager::setup_leader_prestige_modifier( if (military_defines.get_leader_prestige_to_morale_factor() != 0) { if (modifier_effect_cache.get_morale_leader() != nullptr) { leader_prestige_modifier.set_effect( - *modifier_effect_cache.get_morale_leader(), military_defines.get_leader_prestige_to_morale_factor() + *modifier_effect_cache.get_morale_leader(), military_defines.get_leader_prestige_to_morale_factor() ); } else { spdlog::error_s("Cannot set leader prestige modifier morale effect - ModifierEffect is null!"); @@ -46,7 +46,7 @@ bool LeaderTraitManager::setup_leader_prestige_modifier( if (military_defines.get_leader_prestige_to_max_org_factor() != 0) { if (modifier_effect_cache.get_organisation() != nullptr) { leader_prestige_modifier.set_effect( - *modifier_effect_cache.get_organisation(), military_defines.get_leader_prestige_to_max_org_factor() + *modifier_effect_cache.get_organisation(), military_defines.get_leader_prestige_to_max_org_factor() ); } else { spdlog::error_s("Cannot set leader prestige modifier organisation effect - ModifierEffect is null!"); @@ -58,7 +58,7 @@ bool LeaderTraitManager::setup_leader_prestige_modifier( } bool LeaderTraitManager::add_leader_trait( - std::string_view identifier, LeaderTrait::trait_type_t type, ModifierValue&& modifiers + std::string_view identifier, LeaderTrait::trait_type_t type, ModifierValue&& modifiers ) { if (identifier.empty()) { spdlog::error_s("Invalid leader trait identifier - empty!"); @@ -101,24 +101,24 @@ bool LeaderTraitManager::load_leader_traits_file(ModifierManager const& modifier const auto trait_callback = [this, &modifier_manager](LeaderTrait::trait_type_t type) -> NodeCallback auto { return expect_dictionary( - [this, &modifier_manager, type](std::string_view trait_identifier, ast::NodeCPtr value) -> bool { - ModifierValue modifiers; + [this, &modifier_manager, type](std::string_view trait_identifier, ast::NodeCPtr value) -> bool { + ModifierValue modifiers; - bool ret = NodeTools::expect_dictionary(modifier_manager.expect_leader_modifier(modifiers))(value); + bool ret = NodeTools::expect_dictionary(modifier_manager.expect_leader_modifier(modifiers))(value); - ret &= add_leader_trait(trait_identifier, type, std::move(modifiers)); + ret &= add_leader_trait(trait_identifier, type, std::move(modifiers)); - return ret; - } + return ret; + } ); }; using enum LeaderTrait::trait_type_t; ret &= - expect_dictionary_keys("personality", ONE_EXACTLY, trait_callback(PERSONALITY), "background", ONE_EXACTLY, trait_callback(BACKGROUND))( - root - ); + expect_dictionary_keys("personality", ONE_EXACTLY, trait_callback(PERSONALITY), "background", ONE_EXACTLY, trait_callback(BACKGROUND))( + root + ); lock_leader_traits(); diff --git a/src/openvic-simulation/military/LeaderTrait.hpp b/src/openvic-simulation/military/LeaderTrait.hpp index f43d90e25..76519ac85 100644 --- a/src/openvic-simulation/military/LeaderTrait.hpp +++ b/src/openvic-simulation/military/LeaderTrait.hpp @@ -10,7 +10,10 @@ namespace OpenVic { struct LeaderTrait : Modifier { - enum class trait_type_t { PERSONALITY, BACKGROUND }; + enum class trait_type_t { + PERSONALITY, + BACKGROUND + }; public: const trait_type_t trait_type; @@ -51,7 +54,7 @@ namespace OpenVic { LeaderTraitManager(); bool setup_leader_prestige_modifier( - ModifierEffectCache const& modifier_effect_cache, MilitaryDefines const& military_defines + ModifierEffectCache const& modifier_effect_cache, MilitaryDefines const& military_defines ); bool add_leader_trait(std::string_view identifier, LeaderTrait::trait_type_t type, ModifierValue&& modifiers); diff --git a/src/openvic-simulation/military/UnitInstance.cpp b/src/openvic-simulation/military/UnitInstance.cpp index 99ee5c9f6..cb457d1de 100644 --- a/src/openvic-simulation/military/UnitInstance.cpp +++ b/src/openvic-simulation/military/UnitInstance.cpp @@ -2,33 +2,23 @@ using namespace OpenVic; -UnitInstance::UnitInstance( - unique_id_t new_unique_id, - std::string_view new_name, - UnitType const& new_unit_type -) : unique_id { new_unique_id }, - name { new_name }, - unit_type { new_unit_type }, - organisation { new_unit_type.default_organisation }, - max_organisation { organisation }, - strength { new_unit_type.max_strength } {} +UnitInstance::UnitInstance(unique_id_t new_unique_id, std::string_view new_name, UnitType const& new_unit_type) : + unique_id { new_unique_id }, name { new_name }, unit_type { new_unit_type }, + organisation { new_unit_type.default_organisation }, max_organisation { organisation }, + strength { new_unit_type.max_strength } {} void UnitInstance::set_name(std::string_view new_name) { name = new_name; } UnitInstanceBranched::UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - RegimentType const& new_regiment_type, - Pop* new_pop, - bool new_mobilised -) : UnitInstance { new_unique_id, new_name, new_regiment_type }, - pop { new_pop }, - mobilised { new_mobilised } {} + unique_id_t new_unique_id, + std::string_view new_name, + RegimentType const& new_regiment_type, + Pop* new_pop, + bool new_mobilised +) : UnitInstance { new_unique_id, new_name, new_regiment_type }, pop { new_pop }, mobilised { new_mobilised } {} UnitInstanceBranched::UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - ShipType const& new_ship_type + unique_id_t new_unique_id, std::string_view new_name, ShipType const& new_ship_type ) : UnitInstance { new_unique_id, new_name, new_ship_type } {} diff --git a/src/openvic-simulation/military/UnitInstance.hpp b/src/openvic-simulation/military/UnitInstance.hpp index b472ac3c3..2ee1d2d00 100644 --- a/src/openvic-simulation/military/UnitInstance.hpp +++ b/src/openvic-simulation/military/UnitInstance.hpp @@ -4,8 +4,8 @@ #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/military/UnitType.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/UniqueId.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { @@ -18,11 +18,7 @@ namespace OpenVic { fixed_point_t PROPERTY(strength); protected: - UnitInstance( - unique_id_t new_unique_id, - std::string_view new_name, - UnitType const& new_unit_type - ); + UnitInstance(unique_id_t new_unique_id, std::string_view new_name, UnitType const& new_unit_type); public: const unique_id_t unique_id; @@ -56,11 +52,11 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(mobilised, is); UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - RegimentType const& new_regiment_type, - Pop* new_pop, - bool new_mobilised + unique_id_t new_unique_id, + std::string_view new_name, + RegimentType const& new_regiment_type, + Pop* new_pop, + bool new_mobilised ); public: @@ -76,11 +72,7 @@ namespace OpenVic { friend struct UnitInstanceManager; private: - UnitInstanceBranched( - unique_id_t new_unique_id, - std::string_view new_name, - ShipType const& new_ship_type - ); + UnitInstanceBranched(unique_id_t new_unique_id, std::string_view new_name, ShipType const& new_ship_type); public: UnitInstanceBranched(UnitInstanceBranched&&) = default; diff --git a/src/openvic-simulation/military/UnitInstanceGroup.cpp b/src/openvic-simulation/military/UnitInstanceGroup.cpp index 08e336d85..10267a957 100644 --- a/src/openvic-simulation/military/UnitInstanceGroup.cpp +++ b/src/openvic-simulation/military/UnitInstanceGroup.cpp @@ -17,18 +17,14 @@ using namespace OpenVic; using enum unit_branch_t; UnitInstanceGroup::UnitInstanceGroup( - unique_id_t new_unique_id, - unit_branch_t new_branch, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location -) : unique_id { new_unique_id }, - branch { new_branch }, - name { new_name }, - country { new_country }, - location { new_location } { - new_country.add_unit_instance_group(*this); - } + unique_id_t new_unique_id, + unit_branch_t new_branch, + std::string_view new_name, + CountryInstance& new_country, + ProvinceInstance& new_location +) : unique_id { new_unique_id }, branch { new_branch }, name { new_name }, country { new_country }, location { new_location } { + new_country.add_unit_instance_group(*this); +} void UnitInstanceGroup::update_gamestate() { total_organisation = 0; @@ -44,9 +40,7 @@ void UnitInstanceGroup::update_gamestate() { } } -void UnitInstanceGroup::tick() { - -} +void UnitInstanceGroup::tick() {} size_t UnitInstanceGroup::get_unit_count() const { return units.size(); @@ -75,10 +69,9 @@ UnitType const* UnitInstanceGroup::get_display_unit_type() const { } return get_largest_item_tie_break( - weighted_unit_types, - [](UnitType const* lhs, UnitType const* rhs) -> bool { - return lhs->weighted_value < rhs->weighted_value; - } + weighted_unit_types, [](UnitType const* lhs, UnitType const* rhs) -> bool { + return lhs->weighted_value < rhs->weighted_value; + } )->first; } @@ -88,8 +81,11 @@ bool UnitInstanceGroup::add_unit(UnitInstance& unit) { return true; } else { spdlog::error_s( - "Trying to add {} unit \"{}\" to {} unit group \"{}\"", - get_branch_name(unit.get_branch()), unit.get_name(), get_branch_name(branch), get_name() + "Trying to add {} unit \"{}\" to {} unit group \"{}\"", + get_branch_name(unit.get_branch()), + unit.get_name(), + get_branch_name(branch), + get_name() ); return false; } @@ -102,10 +98,7 @@ bool UnitInstanceGroup::remove_unit(UnitInstance const& unit) { units.erase(it); return true; } else { - spdlog::error_s( - "Trying to remove non-existent unit \"{}\" from unit group \"{}\"", - unit.get_name(), get_name() - ); + spdlog::error_s("Trying to remove non-existent unit \"{}\" from unit group \"{}\"", unit.get_name(), get_name()); return false; } } @@ -147,10 +140,10 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { leader->unit_instance_group = nullptr; } else { spdlog::error_s( - "Mismatch between leader and unit instance group: group {} has leader {} but the leader has group {}", - name, - leader->get_name(), - leader->get_unit_instance_group() != nullptr ? leader->get_unit_instance_group()->get_name() : "NULL" + "Mismatch between leader and unit instance group: group {} has leader {} but the leader has group {}", + name, + leader->get_name(), + leader->get_unit_instance_group() != nullptr ? leader->get_unit_instance_group()->get_name() : "NULL" ); ret = false; } @@ -161,21 +154,24 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { if (new_leader != nullptr) { if (OV_unlikely(new_leader->branch != branch)) { spdlog::error_s( - "Trying to assign {} leader \"{}\" to {} unit group \"{}\"", - get_branch_name(new_leader->branch), new_leader->get_name(), get_branch_name(branch), name + "Trying to assign {} leader \"{}\" to {} unit group \"{}\"", + get_branch_name(new_leader->branch), + new_leader->get_name(), + get_branch_name(branch), + name ); return false; } if (OV_unlikely(new_leader->country != country)) { spdlog::error_s( - "Trying to assign {} \"{}\" of country \"{}\" to {} \"{}\" of country \"{}\"", - get_branched_leader_name(new_leader->branch), - new_leader->get_name(), - new_leader->country, - get_branched_unit_group_name(branch), - name, - country + "Trying to assign {} \"{}\" of country \"{}\" to {} \"{}\" of country \"{}\"", + get_branched_leader_name(new_leader->branch), + new_leader->get_name(), + new_leader->country, + get_branched_unit_group_name(branch), + name, + country ); return false; } @@ -185,8 +181,11 @@ bool UnitInstanceGroup::set_leader(LeaderInstance* new_leader) { ret &= new_leader->unit_instance_group->set_leader(nullptr); } else { spdlog::error_s( - "{} {} already leads {} {}!", - get_branched_leader_name(new_leader->branch), new_leader->get_name(),get_branched_unit_group_name(branch), name + "{} {} already leads {} {}!", + get_branched_leader_name(new_leader->branch), + new_leader->get_name(), + get_branched_unit_group_name(branch), + name ); ret = false; } @@ -236,10 +235,7 @@ bool UnitInstanceGroup::is_in_combat() const { } UnitInstanceGroupBranched::UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ) : UnitInstanceGroup { new_unique_id, LAND, new_name, new_country, new_location } {} void UnitInstanceGroupBranched::update_gamestate() { @@ -251,10 +247,7 @@ void UnitInstanceGroupBranched::tick() { } UnitInstanceGroupBranched::UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ) : UnitInstanceGroup { new_unique_id, NAVAL, new_name, new_country, new_location } {} void UnitInstanceGroupBranched::update_gamestate() { @@ -293,7 +286,7 @@ Pop* UnitInstanceManager::recruit_pop_in(ProvinceInstance& province, const bool } } - //fallback to understrength pops + // fallback to understrength pops if (is_rebel) { for (auto& pop : province.get_mutable_pops()) { if (pop.get_rebel_type() != nullptr && pop.try_recruit_understrength()) { @@ -316,37 +309,27 @@ Pop* UnitInstanceManager::recruit_pop_in(ProvinceInstance& province, const bool template UnitInstanceBranched& UnitInstanceManager::generate_unit_instance( - UnitDeployment const& unit_deployment, - MapInstance& map_instance, - const bool is_rebel + UnitDeployment const& unit_deployment, MapInstance& map_instance, const bool is_rebel ) { UnitInstanceBranched& unit_instance = *get_unit_instances().insert( - [this, &unit_deployment, &map_instance, is_rebel]() -> UnitInstanceBranched { - if constexpr (Branch == LAND) { - RegimentDeployment const& regiment_deployment = unit_deployment; - ProvinceInstance& province = map_instance.get_province_instance_by_definition(*regiment_deployment.get_home()); - Pop* const pop_ptr = recruit_pop_in(province, is_rebel); - if (pop_ptr == nullptr) { - spdlog::warn_s( - "Regiment {} in province {} lacks backing pop.", regiment_deployment.get_name(), province.get_identifier() - ); - } - - return { - unique_id_counter++, - unit_deployment.get_name(), - unit_deployment.type, - pop_ptr, - false - }; - } else if constexpr (Branch == NAVAL) { - return { - unique_id_counter++, - unit_deployment.get_name(), - unit_deployment.type - }; - } - }() + [this, &unit_deployment, &map_instance, is_rebel]() -> UnitInstanceBranched { + if constexpr (Branch == LAND) { + RegimentDeployment const& regiment_deployment = unit_deployment; + ProvinceInstance& province = map_instance.get_province_instance_by_definition(*regiment_deployment.get_home()); + Pop* const pop_ptr = recruit_pop_in(province, is_rebel); + if (pop_ptr == nullptr) { + spdlog::warn_s( + "Regiment {} in province {} lacks backing pop.", + regiment_deployment.get_name(), + province.get_identifier() + ); + } + + return { unique_id_counter++, unit_deployment.get_name(), unit_deployment.type, pop_ptr, false }; + } else if constexpr (Branch == NAVAL) { + return { unique_id_counter++, unit_deployment.get_name(), unit_deployment.type }; + } + }() ); unit_instance_map.emplace(unit_instance.unique_id, unit_instance); @@ -356,31 +339,25 @@ UnitInstanceBranched& UnitInstanceManager::generate_unit_instance( template bool UnitInstanceManager::generate_unit_instance_group( - MapInstance& map_instance, CountryInstance& country, UnitDeploymentGroup const& unit_deployment_group + MapInstance& map_instance, CountryInstance& country, UnitDeploymentGroup const& unit_deployment_group ) { if (unit_deployment_group.get_units().empty()) { spdlog::error_s( - "Trying to generate unit group \"{}\" with no units for country \"{}\"", - unit_deployment_group.get_name(), country + "Trying to generate unit group \"{}\" with no units for country \"{}\"", unit_deployment_group.get_name(), country ); return false; } - + ProvinceInstance& location = map_instance.get_province_instance_by_definition(unit_deployment_group.get_location()); UnitInstanceGroupBranched& unit_instance_group = *get_unit_instance_groups().emplace( - unique_id_counter++, - unit_deployment_group.get_name(), - country, - location + unique_id_counter++, unit_deployment_group.get_name(), country, location ); unit_instance_group_map.emplace(unit_instance_group.unique_id, unit_instance_group); bool ret = true; for (UnitDeployment const& unit_deployment : unit_deployment_group.get_units()) { - ret &= unit_instance_group.add_unit( - generate_unit_instance(unit_deployment, map_instance, country.is_rebel_country()) - ); + ret &= unit_instance_group.add_unit(generate_unit_instance(unit_deployment, map_instance, country.is_rebel_country())); } ret &= unit_instance_group.set_country(country); @@ -395,8 +372,10 @@ bool UnitInstanceManager::generate_unit_instance_group( ret &= unit_instance_group.set_leader(&it->get()); } else { spdlog::error_s( - "Invalid leader index {} for unit group \"{}\" for country \"{}\"", - *unit_deployment_group.get_leader_index(), unit_deployment_group.get_name(), country + "Invalid leader index {} for unit group \"{}\" for country \"{}\"", + *unit_deployment_group.get_leader_index(), + unit_deployment_group.get_name(), + country ); ret = false; } @@ -407,31 +386,27 @@ bool UnitInstanceManager::generate_unit_instance_group( template void UnitInstanceManager::generate_leader(CountryInstance& country, T&& leader_base) { - LeaderInstance& leader_instance = *leaders.emplace( - unique_id_counter++, - std::forward(leader_base), - country - ); + LeaderInstance& leader_instance = *leaders.emplace(unique_id_counter++, std::forward(leader_base), country); leader_instance_map.emplace(leader_instance.unique_id, leader_instance); country.add_leader(leader_instance); if (leader_instance.get_picture().empty() && country.get_primary_culture() != nullptr) { - leader_instance.set_picture(culture_manager.get_leader_picture_name( - country.get_primary_culture()->group.get_leader(), leader_instance.branch - )); + leader_instance.set_picture( + culture_manager.get_leader_picture_name(country.get_primary_culture()->group.get_leader(), leader_instance.branch) + ); } } UnitInstanceManager::UnitInstanceManager( - CultureManager const& new_culture_manager, - LeaderTraitManager const& new_leader_trait_manager, - MilitaryDefines const& new_military_defines -) : culture_manager { new_culture_manager }, - leader_trait_manager { new_leader_trait_manager }, - military_defines { new_military_defines } {} + CultureManager const& new_culture_manager, + LeaderTraitManager const& new_leader_trait_manager, + MilitaryDefines const& new_military_defines +) : + culture_manager { new_culture_manager }, leader_trait_manager { new_leader_trait_manager }, + military_defines { new_military_defines } {} bool UnitInstanceManager::generate_deployment( - MapInstance& map_instance, CountryInstance& country, Deployment const& deployment + MapInstance& map_instance, CountryInstance& country, Deployment const& deployment ) { bool ret = true; @@ -500,21 +475,21 @@ UnitInstanceGroup* UnitInstanceManager::get_unit_instance_group_by_unique_id(uni } bool UnitInstanceManager::create_leader( - CountryInstance& country, - unit_branch_t branch, - Date creation_date, - std::string_view name, - LeaderTrait const* personality, - LeaderTrait const* background + CountryInstance& country, + unit_branch_t branch, + Date creation_date, + std::string_view name, + LeaderTrait const* personality, + LeaderTrait const* background ) { const fixed_point_t leader_creation_cost = military_defines.get_leader_recruit_cost(); if (country.get_leadership_point_stockpile() < leader_creation_cost) { spdlog::error_s( - "Country \"{}\" does not have enough leadership points ({:.2}) to create a {} (cost: {:.2})", - country, - country.get_leadership_point_stockpile(), - get_branched_leader_name(branch), - leader_creation_cost + "Country \"{}\" does not have enough leadership points ({:.2}) to create a {} (cost: {:.2})", + country, + country.get_leadership_point_stockpile(), + get_branched_leader_name(branch), + leader_creation_cost ); return false; } @@ -552,30 +527,28 @@ bool UnitInstanceManager::create_leader( // TODO - use "noTrait" or "noPersonality" or "noBackground" if either is nullptr if (personality == nullptr && !leader_trait_manager.get_personality_traits().empty()) { - personality = leader_trait_manager.get_personality_traits()[ - item_selection_counter++ % leader_trait_manager.get_personality_traits().size() - ]; + personality = + leader_trait_manager + .get_personality_traits()[item_selection_counter++ % leader_trait_manager.get_personality_traits().size()]; } if (background == nullptr && !leader_trait_manager.get_background_traits().empty()) { - background = leader_trait_manager.get_background_traits()[ - item_selection_counter++ % leader_trait_manager.get_background_traits().size() - ]; + background = + leader_trait_manager + .get_background_traits()[item_selection_counter++ % leader_trait_manager.get_background_traits().size()]; } // TODO - make starting prestige a random proportion of the maximum random prestige const fixed_point_t starting_prestige = - military_defines.get_leader_max_random_prestige() * static_cast(item_selection_counter++ % 11) / 10; - - generate_leader(country, LeaderBase{ - name, - branch, - creation_date, - personality, - background, - starting_prestige, - {} // No picture, will be set up by generate_leader - }); + military_defines.get_leader_max_random_prestige() * static_cast(item_selection_counter++ % 11) / 10; + + generate_leader( + country, + LeaderBase { + name, branch, creation_date, personality, background, starting_prestige, {} // No picture, will be set up by + // generate_leader + } + ); return true; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/military/UnitInstanceGroup.hpp b/src/openvic-simulation/military/UnitInstanceGroup.hpp index aa3301cba..814592d5d 100644 --- a/src/openvic-simulation/military/UnitInstanceGroup.hpp +++ b/src/openvic-simulation/military/UnitInstanceGroup.hpp @@ -6,13 +6,12 @@ #include "openvic-simulation/core/memory/Colony.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/military/Leader.hpp" +#include "openvic-simulation/military/UnitBranchedGetterMacro.hpp" //below other imports that undef the macros #include "openvic-simulation/military/UnitInstance.hpp" #include "openvic-simulation/military/UnitType.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include "openvic-simulation/military/UnitBranchedGetterMacro.hpp" //below other imports that undef the macros - namespace OpenVic { struct ProvinceInstance; struct CountryInstance; @@ -41,11 +40,11 @@ namespace OpenVic { protected: UnitInstanceGroup( - unique_id_t new_unique_id, - unit_branch_t new_branch, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, + unit_branch_t new_branch, + std::string_view new_name, + CountryInstance& new_country, + ProvinceInstance& new_location ); void update_gamestate(); @@ -101,10 +100,7 @@ namespace OpenVic { public: UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ); UnitInstanceGroupBranched(UnitInstanceGroupBranched&&) = default; @@ -113,10 +109,12 @@ namespace OpenVic { // TODO - do these work fine when units is empty? std::span> get_regiment_instances() { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } std::span> get_regiment_instances() const { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } }; @@ -127,10 +125,7 @@ namespace OpenVic { public: UnitInstanceGroupBranched( - unique_id_t new_unique_id, - std::string_view new_name, - CountryInstance& new_country, - ProvinceInstance& new_location + unique_id_t new_unique_id, std::string_view new_name, CountryInstance& new_country, ProvinceInstance& new_location ); UnitInstanceGroupBranched(UnitInstanceGroupBranched&&) = default; @@ -141,7 +136,8 @@ namespace OpenVic { return { reinterpret_cast const*>(get_units().data()), get_units().size() }; } std::span> get_ship_instances() const { - return { reinterpret_cast const*>(get_units().data()), get_units().size() }; + return { reinterpret_cast const*>(get_units().data()), + get_units().size() }; } fixed_point_t get_total_consumed_supply() const; @@ -191,22 +187,20 @@ namespace OpenVic { Pop* recruit_pop_in(ProvinceInstance& province, const bool is_rebel) const; template UnitInstanceBranched& generate_unit_instance( - UnitDeployment const& unit_deployment, - MapInstance& map_instance, - const bool is_rebel + UnitDeployment const& unit_deployment, MapInstance& map_instance, const bool is_rebel ); template bool generate_unit_instance_group( - MapInstance& map_instance, CountryInstance& country, UnitDeploymentGroup const& unit_deployment_group + MapInstance& map_instance, CountryInstance& country, UnitDeploymentGroup const& unit_deployment_group ); template void generate_leader(CountryInstance& country, T&& leader_base); public: UnitInstanceManager( - CultureManager const& new_culture_manager, - LeaderTraitManager const& new_leader_trait_manager, - MilitaryDefines const& new_military_defines + CultureManager const& new_culture_manager, + LeaderTraitManager const& new_leader_trait_manager, + MilitaryDefines const& new_military_defines ); bool generate_deployment(MapInstance& map_instance, CountryInstance& country, Deployment const& deployment); @@ -223,12 +217,12 @@ namespace OpenVic { // leadership points will be checked and, if there are enough, have the leader creation cost subtracted from them. // If the country does not have enough leadership points, the function will return false and no leader will be created. bool create_leader( - CountryInstance& country, - unit_branch_t branch, - Date creation_date, - std::string_view name = {}, - LeaderTrait const* personality = nullptr, - LeaderTrait const* background = nullptr + CountryInstance& country, + unit_branch_t branch, + Date creation_date, + std::string_view name = {}, + LeaderTrait const* personality = nullptr, + LeaderTrait const* background = nullptr ); }; } diff --git a/src/openvic-simulation/military/UnitType.cpp b/src/openvic-simulation/military/UnitType.cpp index bf11abf1b..ace94b323 100644 --- a/src/openvic-simulation/military/UnitType.cpp +++ b/src/openvic-simulation/military/UnitType.cpp @@ -4,8 +4,8 @@ #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/map/TerrainType.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/modifier/ModifierEffectCache.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" @@ -16,74 +16,57 @@ using enum unit_branch_t; using enum UnitType::unit_category_t; UnitType::UnitType( - std::string_view new_identifier, unit_type_index_t new_unit_type_index, unit_branch_t new_branch, - unit_type_args_t& unit_args -) : HasIdentifier { new_identifier }, - unit_type_index { new_unit_type_index }, - branch { new_branch }, - icon { unit_args.icon }, - sprite { unit_args.sprite }, - starts_unlocked { unit_args.starts_unlocked }, - unit_category { unit_args.unit_category }, - has_floating_flag { unit_args.floating_flag }, - priority { unit_args.priority }, - max_strength { unit_args.max_strength }, - default_organisation { unit_args.default_organisation }, - maximum_speed { unit_args.maximum_speed }, - weighted_value { unit_args.weighted_value }, - move_sound { unit_args.move_sound }, - select_sound { unit_args.select_sound }, - build_time { unit_args.build_time }, - build_cost { std::move(unit_args.build_cost) }, - supply_consumption { unit_args.supply_consumption }, - supply_cost { std::move(unit_args.supply_cost) } { + std::string_view new_identifier, + unit_type_index_t new_unit_type_index, + unit_branch_t new_branch, + unit_type_args_t& unit_args +) : + HasIdentifier { new_identifier }, unit_type_index { new_unit_type_index }, branch { new_branch }, icon { unit_args.icon }, + sprite { unit_args.sprite }, starts_unlocked { unit_args.starts_unlocked }, unit_category { unit_args.unit_category }, + has_floating_flag { unit_args.floating_flag }, priority { unit_args.priority }, max_strength { unit_args.max_strength }, + default_organisation { unit_args.default_organisation }, maximum_speed { unit_args.maximum_speed }, + weighted_value { unit_args.weighted_value }, move_sound { unit_args.move_sound }, select_sound { unit_args.select_sound }, + build_time { unit_args.build_time }, build_cost { std::move(unit_args.build_cost) }, + supply_consumption { unit_args.supply_consumption }, supply_cost { std::move(unit_args.supply_cost) } { using enum Modifier::modifier_type_t; for (auto [terrain, modifier_value] : mutable_iterator(unit_args.terrain_modifier_values)) { - terrain_modifiers.emplace(terrain, Modifier { - memory::fmt::format("{} {}", new_identifier, *terrain), std::move(modifier_value), - UNIT_TERRAIN - }); + terrain_modifiers.emplace( + terrain, + Modifier { memory::fmt::format("{} {}", new_identifier, *terrain), std::move(modifier_value), UNIT_TERRAIN } + ); } } UnitTypeBranched::UnitTypeBranched( - index_t new_index, unit_type_index_t new_unit_type_index, std::string_view new_identifier, - unit_type_args_t& unit_args, regiment_type_args_t const& regiment_type_args -) : UnitType { new_identifier, new_unit_type_index, LAND, unit_args }, - HasIndex { new_index }, - allowed_cultures { regiment_type_args.allowed_cultures }, - sprite_override { regiment_type_args.sprite_override }, - sprite_mount { regiment_type_args.sprite_mount }, - sprite_mount_attach_node { regiment_type_args.sprite_mount_attach_node }, - reconnaissance { regiment_type_args.reconnaissance }, - attack { regiment_type_args.attack }, - defence { regiment_type_args.defence }, - discipline { regiment_type_args.discipline }, - support { regiment_type_args.support }, - maneuver { regiment_type_args.maneuver }, - siege { regiment_type_args.siege } {} + index_t new_index, + unit_type_index_t new_unit_type_index, + std::string_view new_identifier, + unit_type_args_t& unit_args, + regiment_type_args_t const& regiment_type_args +) : + UnitType { new_identifier, new_unit_type_index, LAND, unit_args }, HasIndex { new_index }, + allowed_cultures { regiment_type_args.allowed_cultures }, sprite_override { regiment_type_args.sprite_override }, + sprite_mount { regiment_type_args.sprite_mount }, sprite_mount_attach_node { regiment_type_args.sprite_mount_attach_node }, + reconnaissance { regiment_type_args.reconnaissance }, attack { regiment_type_args.attack }, + defence { regiment_type_args.defence }, discipline { regiment_type_args.discipline }, + support { regiment_type_args.support }, maneuver { regiment_type_args.maneuver }, siege { regiment_type_args.siege } {} UnitTypeBranched::UnitTypeBranched( - index_t new_index, unit_type_index_t new_unit_type_index, std::string_view new_identifier, - unit_type_args_t& unit_args, ship_type_args_t const& ship_type_args -) : UnitType { new_identifier, new_unit_type_index, NAVAL, unit_args }, - HasIndex { new_index }, - naval_icon { ship_type_args.naval_icon }, - can_sail { ship_type_args.sail }, - is_transport { ship_type_args.transport }, - is_capital { ship_type_args.capital }, - colonial_points { ship_type_args.colonial_points }, - can_build_overseas { ship_type_args.build_overseas }, - min_port_level { ship_type_args.min_port_level }, - limit_per_port { ship_type_args.limit_per_port }, - supply_consumption_score { ship_type_args.supply_consumption_score }, - hull { ship_type_args.hull }, - gun_power { ship_type_args.gun_power }, - fire_range { ship_type_args.fire_range }, - evasion { ship_type_args.evasion }, - torpedo_attack { ship_type_args.torpedo_attack } {} + index_t new_index, + unit_type_index_t new_unit_type_index, + std::string_view new_identifier, + unit_type_args_t& unit_args, + ship_type_args_t const& ship_type_args +) : + UnitType { new_identifier, new_unit_type_index, NAVAL, unit_args }, HasIndex { new_index }, + naval_icon { ship_type_args.naval_icon }, can_sail { ship_type_args.sail }, is_transport { ship_type_args.transport }, + is_capital { ship_type_args.capital }, colonial_points { ship_type_args.colonial_points }, + can_build_overseas { ship_type_args.build_overseas }, min_port_level { ship_type_args.min_port_level }, + limit_per_port { ship_type_args.limit_per_port }, supply_consumption_score { ship_type_args.supply_consumption_score }, + hull { ship_type_args.hull }, gun_power { ship_type_args.gun_power }, fire_range { ship_type_args.fire_range }, + evasion { ship_type_args.evasion }, torpedo_attack { ship_type_args.torpedo_attack } {} void UnitTypeManager::reserve_all_unit_types(size_t size) { reserve_more_unit_types(size); @@ -104,10 +87,7 @@ static bool _check_shared_parameters(std::string_view identifier, UnitType::unit } if (unit_args.icon < 0) { - spdlog::error_s( - "Invalid icon for unit {} - {} (must be >= 0)", - identifier, unit_args.icon - ); + spdlog::error_s("Invalid icon for unit {} - {} (must be >= 0)", identifier, unit_args.icon); return false; } @@ -122,7 +102,9 @@ static bool _check_shared_parameters(std::string_view identifier, UnitType::unit } bool UnitTypeManager::add_regiment_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, RegimentType::regiment_type_args_t const& regiment_type_args + std::string_view identifier, + UnitType::unit_type_args_t& unit_args, + RegimentType::regiment_type_args_t const& regiment_type_args ) { if (!_check_shared_parameters(identifier, unit_args)) { return false; @@ -136,10 +118,12 @@ bool UnitTypeManager::add_regiment_type( } bool ret = regiment_types.emplace_item( - identifier, - index_from_count(get_regiment_type_count()), - index_from_count(get_unit_type_count()), identifier, - unit_args, std::move(regiment_type_args) + identifier, + index_from_count(get_regiment_type_count()), + index_from_count(get_unit_type_count()), + identifier, + unit_args, + std::move(regiment_type_args) ); if (ret) { // Cannot use get_back_regiment_type() as we need non-const but don't want to generate all non-const functions. @@ -149,7 +133,7 @@ bool UnitTypeManager::add_regiment_type( } bool UnitTypeManager::add_ship_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, ShipType::ship_type_args_t const& ship_type_args + std::string_view identifier, UnitType::unit_type_args_t& unit_args, ShipType::ship_type_args_t const& ship_type_args ) { if (!_check_shared_parameters(identifier, unit_args)) { return false; @@ -170,10 +154,12 @@ bool UnitTypeManager::add_ship_type( } bool ret = ship_types.emplace_item( - identifier, - index_from_count(get_ship_type_count()), - index_from_count(get_unit_type_count()), identifier, - unit_args, ship_type_args + identifier, + index_from_count(get_ship_type_count()), + index_from_count(get_unit_type_count()), + identifier, + unit_args, + ship_type_args ); if (ret) { // Cannot use get_back_ship_type() as we need non-const but don't want to generate all non-const functions. @@ -183,8 +169,10 @@ bool UnitTypeManager::add_ship_type( } bool UnitTypeManager::load_unit_type_file( - GoodDefinitionManager const& good_definition_manager, TerrainTypeManager const& terrain_type_manager, - ModifierManager const& modifier_manager, ovdl::v2script::Parser const& parser + GoodDefinitionManager const& good_definition_manager, + TerrainTypeManager const& terrain_type_manager, + ModifierManager const& modifier_manager, + ovdl::v2script::Parser const& parser ) { using namespace std::string_view_literals; auto type_symbol = parser.find_intern("type"sv); @@ -192,10 +180,7 @@ bool UnitTypeManager::load_unit_type_file( spdlog::error_s("type could not be interned."); } - return expect_dictionary([this, &good_definition_manager, &terrain_type_manager, &modifier_manager, &type_symbol]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - + return expect_dictionary([this, &good_definition_manager, &terrain_type_manager, &modifier_manager, &type_symbol](std::string_view key, ast::NodeCPtr value) -> bool { unit_branch_t branch = INVALID_BRANCH; bool ret = expect_key(type_symbol, expect_branch_identifier(assign_variable_callback(branch)))(value); @@ -210,50 +195,79 @@ bool UnitTypeManager::load_unit_type_file( UnitType::unit_type_args_t unit_args {}; static const string_map_t unit_type_map { - { "infantry", INFANTRY }, - { "cavalry", CAVALRY }, - { "support", SUPPORT }, - { "special", SPECIAL }, - { "big_ship", BIG_SHIP }, - { "light_ship", LIGHT_SHIP }, - { "transport", TRANSPORT } + { "infantry", INFANTRY }, { "cavalry", CAVALRY }, { "support", SUPPORT }, { "special", SPECIAL }, + { "big_ship", BIG_SHIP }, { "light_ship", LIGHT_SHIP }, { "transport", TRANSPORT } }; key_map_t key_map {}; /* Shared dictionary entries */ - ret &= add_key_map_entries(key_map, - "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.icon)), - "type", ONE_EXACTLY, success_callback, /* Already loaded above using expect_key */ - "sprite", ONE_EXACTLY, expect_identifier(assign_variable_callback(unit_args.sprite)), - "active", ZERO_OR_ONE, expect_bool(assign_variable_callback(unit_args.starts_unlocked)), - "unit_type", ONE_EXACTLY, - expect_identifier(expect_mapped_string(unit_type_map, assign_variable_callback(unit_args.unit_category))), - "floating_flag", ONE_EXACTLY, expect_bool(assign_variable_callback(unit_args.floating_flag)), - "priority", ONE_EXACTLY, expect_uint(assign_variable_callback(unit_args.priority)), - "max_strength", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.max_strength)), - "default_organisation", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.default_organisation)), - "maximum_speed", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.maximum_speed)), - "weighted_value", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.weighted_value)), - "move_sound", ZERO_OR_ONE, expect_identifier(assign_variable_callback(unit_args.move_sound)), - "select_sound", ZERO_OR_ONE, expect_identifier(assign_variable_callback(unit_args.select_sound)), - "build_time", ONE_EXACTLY, expect_days(assign_variable_callback(unit_args.build_time)), - "build_cost", ONE_EXACTLY, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.build_cost)), - "supply_consumption", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(unit_args.supply_consumption)), - "supply_cost", ONE_EXACTLY, - good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.supply_cost)) + ret &= add_key_map_entries( + key_map, + "icon", + ONE_EXACTLY, + expect_uint(assign_variable_callback(unit_args.icon)), + "type", + ONE_EXACTLY, + success_callback, /* Already loaded above using expect_key */ + "sprite", + ONE_EXACTLY, + expect_identifier(assign_variable_callback(unit_args.sprite)), + "active", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(unit_args.starts_unlocked)), + "unit_type", + ONE_EXACTLY, + expect_identifier(expect_mapped_string(unit_type_map, assign_variable_callback(unit_args.unit_category))), + "floating_flag", + ONE_EXACTLY, + expect_bool(assign_variable_callback(unit_args.floating_flag)), + "priority", + ONE_EXACTLY, + expect_uint(assign_variable_callback(unit_args.priority)), + "max_strength", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.max_strength)), + "default_organisation", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.default_organisation)), + "maximum_speed", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.maximum_speed)), + "weighted_value", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.weighted_value)), + "move_sound", + ZERO_OR_ONE, + expect_identifier(assign_variable_callback(unit_args.move_sound)), + "select_sound", + ZERO_OR_ONE, + expect_identifier(assign_variable_callback(unit_args.select_sound)), + "build_time", + ONE_EXACTLY, + expect_days(assign_variable_callback(unit_args.build_time)), + "build_cost", + ONE_EXACTLY, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.build_cost)), + "supply_consumption", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(unit_args.supply_consumption)), + "supply_cost", + ONE_EXACTLY, + good_definition_manager.expect_good_definition_decimal_map(move_variable_callback(unit_args.supply_cost)) ); - auto add_terrain_modifier_value = [&unit_args, &terrain_type_manager, &modifier_manager]( - std::string_view default_key, ast::NodeCPtr default_value - ) -> bool { + auto add_terrain_modifier_value = + [&unit_args, + &terrain_type_manager, + &modifier_manager](std::string_view default_key, ast::NodeCPtr default_value) -> bool { TerrainType const* terrain_type = terrain_type_manager.get_terrain_type_by_identifier(default_key); if (terrain_type != nullptr) { ModifierValue& modifier_value = unit_args.terrain_modifier_values[terrain_type]; - return expect_dictionary( - modifier_manager.expect_unit_terrain_modifier(modifier_value, terrain_type->get_identifier()) - )(default_value); + return expect_dictionary(modifier_manager + .expect_unit_terrain_modifier(modifier_value, terrain_type->get_identifier()))( + default_value + ); } return key_value_invalid_callback(default_key, default_value); @@ -265,20 +279,44 @@ bool UnitTypeManager::load_unit_type_file( bool is_restricted_to_primary_culture = false; bool is_restricted_to_accepted_cultures = false; - ret &= add_key_map_entries(key_map, - "primary_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_restricted_to_primary_culture)), - "accepted_culture", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_restricted_to_accepted_cultures)), - "sprite_override", ZERO_OR_ONE, expect_identifier(assign_variable_callback(regiment_type_args.sprite_override)), - "sprite_mount", ZERO_OR_ONE, expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount)), - "sprite_mount_attach_node", ZERO_OR_ONE, - expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount_attach_node)), - "reconnaissance", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.reconnaissance)), - "attack", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.attack)), - "defence", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.defence)), - "discipline", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.discipline)), - "support", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.support)), - "maneuver", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(regiment_type_args.maneuver)), - "siege", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(regiment_type_args.siege)) + ret &= add_key_map_entries( + key_map, + "primary_culture", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_restricted_to_primary_culture)), + "accepted_culture", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(is_restricted_to_accepted_cultures)), + "sprite_override", + ZERO_OR_ONE, + expect_identifier(assign_variable_callback(regiment_type_args.sprite_override)), + "sprite_mount", + ZERO_OR_ONE, + expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount)), + "sprite_mount_attach_node", + ZERO_OR_ONE, + expect_identifier(assign_variable_callback(regiment_type_args.sprite_mount_attach_node)), + "reconnaissance", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.reconnaissance)), + "attack", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.attack)), + "defence", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.defence)), + "discipline", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.discipline)), + "support", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.support)), + "maneuver", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(regiment_type_args.maneuver)), + "siege", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(regiment_type_args.siege)) ); if (is_restricted_to_accepted_cultures) { @@ -298,22 +336,50 @@ bool UnitTypeManager::load_unit_type_file( case NAVAL: { ShipType::ship_type_args_t ship_type_args {}; - ret &= add_key_map_entries(key_map, - "naval_icon", ONE_EXACTLY, expect_uint(assign_variable_callback(ship_type_args.naval_icon)), - "sail", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.sail)), - "transport", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.transport)), - "capital", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.capital)), - "colonial_points", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(ship_type_args.colonial_points)), - "can_build_overseas", ZERO_OR_ONE, expect_bool(assign_variable_callback(ship_type_args.build_overseas)), - "min_port_level", ONE_EXACTLY, expect_uint(assign_variable_callback(ship_type_args.min_port_level)), - "limit_per_port", ONE_EXACTLY, expect_int(assign_variable_callback(ship_type_args.limit_per_port)), - "supply_consumption_score", ZERO_OR_ONE, - expect_fixed_point(assign_variable_callback(ship_type_args.supply_consumption_score)), - "hull", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.hull)), - "gun_power", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.gun_power)), - "fire_range", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.fire_range)), - "evasion", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(ship_type_args.evasion)), - "torpedo_attack", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(ship_type_args.torpedo_attack)) + ret &= add_key_map_entries( + key_map, + "naval_icon", + ONE_EXACTLY, + expect_uint(assign_variable_callback(ship_type_args.naval_icon)), + "sail", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.sail)), + "transport", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.transport)), + "capital", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.capital)), + "colonial_points", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.colonial_points)), + "can_build_overseas", + ZERO_OR_ONE, + expect_bool(assign_variable_callback(ship_type_args.build_overseas)), + "min_port_level", + ONE_EXACTLY, + expect_uint(assign_variable_callback(ship_type_args.min_port_level)), + "limit_per_port", + ONE_EXACTLY, + expect_int(assign_variable_callback(ship_type_args.limit_per_port)), + "supply_consumption_score", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.supply_consumption_score)), + "hull", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.hull)), + "gun_power", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.gun_power)), + "fire_range", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.fire_range)), + "evasion", + ONE_EXACTLY, + expect_fixed_point(assign_variable_callback(ship_type_args.evasion)), + "torpedo_attack", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(ship_type_args.torpedo_attack)) ); ret &= expect_dictionary_key_map_and_default(key_map, add_terrain_modifier_value)(value); @@ -333,18 +399,24 @@ bool UnitTypeManager::load_unit_type_file( bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) const { bool ret = true; - const auto generate_stat_modifiers = [&modifier_manager, &ret]( - std::derived_from auto unit_type_effects, std::string_view identifier - ) -> void { + const auto generate_stat_modifiers = + [&modifier_manager, &ret]( + std::derived_from auto unit_type_effects, std::string_view identifier + ) -> void { using enum ModifierEffect::format_t; - const auto stat_modifier = [&modifier_manager, &ret, &identifier]( - ModifierEffect const*& effect_cache, std::string_view suffix, - ModifierEffect::format_t format, std::string_view localisation_key - ) -> void { + const auto stat_modifier = + [&modifier_manager, &ret, &identifier]( + ModifierEffect const*& effect_cache, + std::string_view suffix, + ModifierEffect::format_t format, + std::string_view localisation_key + ) -> void { ret &= modifier_manager.register_technology_modifier_effect( - effect_cache, ModifierManager::get_flat_identifier(identifier, suffix), format, - memory::fmt::format("${}$: ${}$", identifier, localisation_key) + effect_cache, + ModifierManager::get_flat_identifier(identifier, suffix), + format, + memory::fmt::format("${}$: ${}$", identifier, localisation_key) ); }; @@ -355,7 +427,7 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons stat_modifier(unit_type_effects.build_time, "build_time", FORMAT_x1_0DP_DAYS_NEG, "BUILD_TIME"); if constexpr (std::same_as) { stat_modifier( - unit_type_effects.reconnaissance, "reconnaissance", FORMAT_x1_2DP_POS, "RECONAISSANCE" // paradox typo + unit_type_effects.reconnaissance, "reconnaissance", FORMAT_x1_2DP_POS, "RECONAISSANCE" // paradox typo ); stat_modifier(unit_type_effects.siege, "siege", FORMAT_x1_2DP_POS, "SIEGE"); } @@ -367,19 +439,17 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons stat_modifier(unit_type_effects.maneuver, "maneuver", FORMAT_x1_0DP_POS, "Maneuver"); } stat_modifier(unit_type_effects.maximum_speed, "maximum_speed", FORMAT_x1_2DP_SPEED_POS, "MAXIMUM_SPEED"); - if constexpr(std::same_as) { + if constexpr (std::same_as) { stat_modifier(unit_type_effects.gun_power, "gun_power", FORMAT_x1_2DP_POS, "GUN_POWER"); stat_modifier(unit_type_effects.torpedo_attack, "torpedo_attack", FORMAT_x1_2DP_POS, "TORPEDO_ATTACK"); stat_modifier(unit_type_effects.hull, "hull", FORMAT_x1_2DP_POS, "HULL"); stat_modifier(unit_type_effects.fire_range, "fire_range", FORMAT_x100_0DP_POS, "FIRE_RANGE"); stat_modifier(unit_type_effects.evasion, "evasion", FORMAT_x100_0DP_PC_POS, "EVASION"); } - stat_modifier( - unit_type_effects.supply_consumption, "supply_consumption", FORMAT_x100_0DP_PC_NEG, "SUPPLY_CONSUMPTION" - ); - if constexpr(std::same_as) { + stat_modifier(unit_type_effects.supply_consumption, "supply_consumption", FORMAT_x100_0DP_PC_NEG, "SUPPLY_CONSUMPTION"); + if constexpr (std::same_as) { stat_modifier( - unit_type_effects.supply_consumption_score, "supply_consumption_score", FORMAT_x1_0DP_NEG, "SUPPLY_LOAD" + unit_type_effects.supply_consumption_score, "supply_consumption_score", FORMAT_x1_0DP_NEG, "SUPPLY_LOAD" ); // Works but doesn't appear in tooltips in the base game stat_modifier(unit_type_effects.colonial_points, "colonial_points", FORMAT_x1_0DP_POS, "COLONIAL_POINTS_TECH"); @@ -389,13 +459,11 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons generate_stat_modifiers(modifier_manager.modifier_effect_cache.army_base_effects, "army_base"); memory::FixedVector& regiment_type_effects = - modifier_manager.modifier_effect_cache.regiment_type_effects; + modifier_manager.modifier_effect_cache.regiment_type_effects; regiment_type_effects = std::move( - decltype(ModifierEffectCache::regiment_type_effects) { - generate_values, - regiment_type_index_t(get_regiment_type_count()) - } + decltype(ModifierEffectCache::regiment_type_effects) { + generate_values, regiment_type_index_t(get_regiment_type_count()) } ); for (RegimentType const& regiment_type : get_regiment_types()) { @@ -405,13 +473,10 @@ bool UnitTypeManager::generate_modifiers(ModifierManager& modifier_manager) cons generate_stat_modifiers(modifier_manager.modifier_effect_cache.navy_base_effects, "navy_base"); memory::FixedVector& ship_type_effects = - modifier_manager.modifier_effect_cache.ship_type_effects; + modifier_manager.modifier_effect_cache.ship_type_effects; ship_type_effects = std::move( - decltype(ModifierEffectCache::ship_type_effects) { - generate_values, - ship_type_index_t(get_ship_type_count()) - } + decltype(ModifierEffectCache::ship_type_effects) { generate_values, ship_type_index_t(get_ship_type_count()) } ); for (ShipType const& ship_type : get_ship_types()) { diff --git a/src/openvic-simulation/military/UnitType.hpp b/src/openvic-simulation/military/UnitType.hpp index 62afbf556..d5fcdb1b1 100644 --- a/src/openvic-simulation/military/UnitType.hpp +++ b/src/openvic-simulation/military/UnitType.hpp @@ -27,7 +27,14 @@ namespace OpenVic { using terrain_modifiers_t = ordered_map; enum struct unit_category_t : uint8_t { - INVALID_UNIT_CATEGORY, INFANTRY, CAVALRY, SUPPORT, SPECIAL, BIG_SHIP, LIGHT_SHIP, TRANSPORT + INVALID_UNIT_CATEGORY, + INFANTRY, + CAVALRY, + SUPPORT, + SPECIAL, + BIG_SHIP, + LIGHT_SHIP, + TRANSPORT }; struct unit_type_args_t { @@ -40,7 +47,7 @@ namespace OpenVic { bool starts_unlocked = true, floating_flag = false; uint32_t priority = 0; fixed_point_t max_strength = 0, default_organisation = 0, maximum_speed = 0, weighted_value = 0, - supply_consumption = 0; + supply_consumption = 0; Timespan build_time; fixed_point_map_t build_cost, supply_cost; terrain_modifier_values_t terrain_modifier_values; @@ -62,8 +69,10 @@ namespace OpenVic { protected: /* Non-const reference unit_args so variables can be moved from it. */ UnitType( - std::string_view new_identifier, unit_type_index_t new_unit_type_index, unit_branch_t new_branch, - unit_type_args_t& unit_args + std::string_view new_identifier, + unit_type_index_t new_unit_type_index, + unit_branch_t new_branch, + unit_type_args_t& unit_args ); public: @@ -87,7 +96,7 @@ namespace OpenVic { template<> struct UnitTypeBranched : UnitType, HasIndex { static constexpr regiment_allowed_cultures_t allowed_cultures_get_most_permissive( - regiment_allowed_cultures_t lhs, regiment_allowed_cultures_t rhs + regiment_allowed_cultures_t lhs, regiment_allowed_cultures_t rhs ) { return std::min(lhs, rhs); } @@ -97,8 +106,7 @@ namespace OpenVic { std::string_view sprite_override, sprite_mount, sprite_mount_attach_node; // TODO - represent these as modifier effects, so that they can be combined with tech, inventions, // leader bonuses, etc. and applied to unit instances all in one go (same for ShipTypes below) - fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, - siege = 0; + fixed_point_t reconnaissance = 0, attack = 0, defence = 0, discipline = 0, support = 0, maneuver = 0, siege = 0; constexpr regiment_type_args_t() {}; regiment_type_args_t(regiment_type_args_t&&) = default; @@ -120,8 +128,11 @@ namespace OpenVic { const fixed_point_t siege; UnitTypeBranched( - index_t new_index, unit_type_index_t new_unit_type_index, std::string_view new_identifier, - unit_type_args_t& unit_args, regiment_type_args_t const& regiment_type_args + index_t new_index, + unit_type_index_t new_unit_type_index, + std::string_view new_identifier, + unit_type_args_t& unit_args, + regiment_type_args_t const& regiment_type_args ); UnitTypeBranched(UnitTypeBranched&&) = default; }; @@ -134,7 +145,7 @@ namespace OpenVic { uint32_t min_port_level = 0; int32_t limit_per_port = 0; fixed_point_t colonial_points = 0, supply_consumption_score = 0, hull = 0, gun_power = 0, fire_range = 0, - evasion = 0, torpedo_attack = 0; + evasion = 0, torpedo_attack = 0; constexpr ship_type_args_t() {}; ship_type_args_t(ship_type_args_t&&) = default; @@ -159,8 +170,11 @@ namespace OpenVic { const fixed_point_t torpedo_attack; UnitTypeBranched( - index_t new_index, unit_type_index_t new_unit_type_index, std::string_view new_identifier, - unit_type_args_t& unit_args, ship_type_args_t const& ship_type_args + index_t new_index, + unit_type_index_t new_unit_type_index, + std::string_view new_identifier, + unit_type_args_t& unit_args, + ship_type_args_t const& ship_type_args ); UnitTypeBranched(UnitTypeBranched&&) = default; }; @@ -176,21 +190,17 @@ namespace OpenVic { void lock_all_unit_types(); bool add_regiment_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, - RegimentType::regiment_type_args_t const& regiment_type_args + std::string_view identifier, + UnitType::unit_type_args_t& unit_args, + RegimentType::regiment_type_args_t const& regiment_type_args ); bool add_ship_type( - std::string_view identifier, UnitType::unit_type_args_t& unit_args, - ShipType::ship_type_args_t const& ship_type_args + std::string_view identifier, UnitType::unit_type_args_t& unit_args, ShipType::ship_type_args_t const& ship_type_args ); - static NodeTools::Callback auto expect_branch_str( - NodeTools::Callback auto callback - ) { + static NodeTools::Callback auto expect_branch_str(NodeTools::Callback auto callback) { using enum unit_branch_t; - static const string_map_t branch_map { - { "land", LAND }, { "naval", NAVAL }, { "sea", NAVAL } - }; + static const string_map_t branch_map { { "land", LAND }, { "naval", NAVAL }, { "sea", NAVAL } }; return NodeTools::expect_mapped_string(branch_map, callback); } static NodeTools::NodeCallback auto expect_branch_identifier(NodeTools::Callback auto callback) { @@ -198,29 +208,32 @@ namespace OpenVic { } constexpr NodeTools::NodeCallback auto expect_unit_type_index( - NodeTools::Callback auto callback, bool warn = false + NodeTools::Callback auto callback, bool warn = false ) const { return expect_unit_type_identifier( - [callback](UnitType const& unit_type) -> bool { - return callback(unit_type.unit_type_index); - }, - warn + [callback](UnitType const& unit_type) -> bool { + return callback(unit_type.unit_type_index); + }, + warn ); } constexpr NodeTools::Callback auto expect_unit_type_index_str( - NodeTools::Callback auto callback, bool allow_empty = false, bool warn = false + NodeTools::Callback auto callback, bool allow_empty = false, bool warn = false ) const { return expect_unit_type_str( - [callback](UnitType const& unit_type) -> bool { - return callback(unit_type.unit_type_index); - }, - allow_empty, warn + [callback](UnitType const& unit_type) -> bool { + return callback(unit_type.unit_type_index); + }, + allow_empty, + warn ); } bool load_unit_type_file( - GoodDefinitionManager const& good_definition_manager, TerrainTypeManager const& terrain_type_manager, - ModifierManager const& modifier_manager, ovdl::v2script::Parser const& parser + GoodDefinitionManager const& good_definition_manager, + TerrainTypeManager const& terrain_type_manager, + ModifierManager const& modifier_manager, + ovdl::v2script::Parser const& parser ); bool generate_modifiers(ModifierManager& modifier_manager) const; }; diff --git a/src/openvic-simulation/military/Wargoal.cpp b/src/openvic-simulation/military/Wargoal.cpp index 2ff37d140..62312550b 100644 --- a/src/openvic-simulation/military/Wargoal.cpp +++ b/src/openvic-simulation/military/Wargoal.cpp @@ -11,23 +11,40 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; WargoalType::WargoalType( - std::string_view new_identifier, std::string_view new_war_name, Timespan new_available_length, - Timespan new_truce_length, sprite_t new_sprite_index, bool new_triggered_only, bool new_civil_war, - bool new_constructing, bool new_crisis, bool new_great_war_obligatory, bool new_mutual, - bool new_all_allowed_states, bool new_always, peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, - ConditionScript&& new_can_use, ConditionScript&& new_is_valid, ConditionScript&& new_allowed_states, - ConditionScript&& new_allowed_substate_regions, ConditionScript&& new_allowed_states_in_crisis, - ConditionScript&& new_allowed_countries, EffectScript&& new_on_add, EffectScript&& new_on_po_accepted -) : HasIdentifier { new_identifier }, war_name { new_war_name }, available_length { new_available_length }, - truce_length { new_truce_length }, sprite_index { new_sprite_index }, is_triggered_only { new_triggered_only }, - is_civil_war { new_civil_war }, constructing { new_constructing }, crisis { new_crisis }, - is_great_war_obligatory { new_great_war_obligatory }, is_mutual { new_mutual }, all_allowed_states { new_all_allowed_states }, - always { new_always }, modifiers { std::move(new_modifiers) }, peace_options { new_peace_options }, - can_use { std::move(new_can_use) }, is_valid { std::move(new_is_valid) }, allowed_states { std::move(new_allowed_states) }, - allowed_substate_regions { std::move(new_allowed_substate_regions) }, - allowed_states_in_crisis { std::move(new_allowed_states_in_crisis) }, - allowed_countries { std::move(new_allowed_countries) }, on_add { std::move(new_on_add) }, - on_po_accepted { std::move(new_on_po_accepted) } {} + std::string_view new_identifier, + std::string_view new_war_name, + Timespan new_available_length, + Timespan new_truce_length, + sprite_t new_sprite_index, + bool new_triggered_only, + bool new_civil_war, + bool new_constructing, + bool new_crisis, + bool new_great_war_obligatory, + bool new_mutual, + bool new_all_allowed_states, + bool new_always, + peace_modifiers_t&& new_modifiers, + peace_options_t new_peace_options, + ConditionScript&& new_can_use, + ConditionScript&& new_is_valid, + ConditionScript&& new_allowed_states, + ConditionScript&& new_allowed_substate_regions, + ConditionScript&& new_allowed_states_in_crisis, + ConditionScript&& new_allowed_countries, + EffectScript&& new_on_add, + EffectScript&& new_on_po_accepted +) : + HasIdentifier { new_identifier }, war_name { new_war_name }, available_length { new_available_length }, + truce_length { new_truce_length }, sprite_index { new_sprite_index }, is_triggered_only { new_triggered_only }, + is_civil_war { new_civil_war }, constructing { new_constructing }, crisis { new_crisis }, + is_great_war_obligatory { new_great_war_obligatory }, is_mutual { new_mutual }, + all_allowed_states { new_all_allowed_states }, always { new_always }, modifiers { std::move(new_modifiers) }, + peace_options { new_peace_options }, can_use { std::move(new_can_use) }, is_valid { std::move(new_is_valid) }, + allowed_states { std::move(new_allowed_states) }, allowed_substate_regions { std::move(new_allowed_substate_regions) }, + allowed_states_in_crisis { std::move(new_allowed_states_in_crisis) }, + allowed_countries { std::move(new_allowed_countries) }, on_add { std::move(new_on_add) }, + on_po_accepted { std::move(new_on_po_accepted) } {} bool WargoalType::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -43,13 +60,29 @@ bool WargoalType::parse_scripts(DefinitionManager const& definition_manager) { } bool WargoalTypeManager::add_wargoal_type( - std::string_view identifier, std::string_view war_name, Timespan available_length, - Timespan truce_length, WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, - bool constructing, bool crisis, bool great_war_obligatory, bool mutual, bool all_allowed_states, - bool always, WargoalType::peace_modifiers_t&& modifiers, WargoalType::peace_options_t peace_options, - ConditionScript&& can_use, ConditionScript&& is_valid, ConditionScript&& allowed_states, - ConditionScript&& allowed_substate_regions, ConditionScript&& allowed_states_in_crisis, - ConditionScript&& allowed_countries, EffectScript&& on_add, EffectScript&& on_po_accepted + std::string_view identifier, + std::string_view war_name, + Timespan available_length, + Timespan truce_length, + WargoalType::sprite_t sprite_index, + bool triggered_only, + bool civil_war, + bool constructing, + bool crisis, + bool great_war_obligatory, + bool mutual, + bool all_allowed_states, + bool always, + WargoalType::peace_modifiers_t&& modifiers, + WargoalType::peace_options_t peace_options, + ConditionScript&& can_use, + ConditionScript&& is_valid, + ConditionScript&& allowed_states, + ConditionScript&& allowed_substate_regions, + ConditionScript&& allowed_states_in_crisis, + ConditionScript&& allowed_countries, + EffectScript&& on_add, + EffectScript&& on_po_accepted ) { if (identifier.empty()) { spdlog::error_s("Invalid wargoal identifier - empty!"); @@ -66,11 +99,30 @@ bool WargoalTypeManager::add_wargoal_type( } return wargoal_types.emplace_item( - identifier, - identifier, war_name, available_length, truce_length, sprite_index, triggered_only, civil_war, constructing, crisis, - great_war_obligatory, mutual, all_allowed_states, always, std::move(modifiers), peace_options, std::move(can_use), - std::move(is_valid), std::move(allowed_states), std::move(allowed_substate_regions), - std::move(allowed_states_in_crisis), std::move(allowed_countries), std::move(on_add), std::move(on_po_accepted) + identifier, + identifier, + war_name, + available_length, + truce_length, + sprite_index, + triggered_only, + civil_war, + constructing, + crisis, + great_war_obligatory, + mutual, + all_allowed_states, + always, + std::move(modifiers), + peace_options, + std::move(can_use), + std::move(is_valid), + std::move(allowed_states), + std::move(allowed_substate_regions), + std::move(allowed_states_in_crisis), + std::move(allowed_countries), + std::move(on_add), + std::move(on_po_accepted) ); } @@ -81,44 +133,43 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) spdlog::error_s("peace_order could not be interned."); } - bool ret = expect_dictionary_reserve_length( - wargoal_types, - [this, &peace_order_symbol](std::string_view identifier, ast::NodeCPtr value) -> bool { - // If peace_order_symbol is false, we know there is no peace_order string in the parser - if (peace_order_symbol && identifier == peace_order_symbol.c_str()) { - return true; - } - - using enum WargoalType::peace_options_t; - using enum scope_type_t; - - std::string_view war_name; - Timespan available {}, truce {}; - WargoalType::sprite_t sprite_index = 0; - bool triggered_only = false, civil_war = false, constructing = true, crisis = true, great_war_obligatory = false, - mutual = false, all_allowed_states = false, always = false; - WargoalType::peace_options_t peace_options = NO_PEACE_OPTIONS; - WargoalType::peace_modifiers_t modifiers; - ConditionScript can_use { COUNTRY, COUNTRY, COUNTRY }; - ConditionScript is_valid { COUNTRY, COUNTRY, COUNTRY }; - ConditionScript allowed_states { STATE, COUNTRY, COUNTRY }; - ConditionScript allowed_substate_regions { STATE, COUNTRY, COUNTRY }; - ConditionScript allowed_states_in_crisis { STATE, COUNTRY, COUNTRY }; - ConditionScript allowed_countries { COUNTRY, COUNTRY, COUNTRY }; - EffectScript on_add, on_po_accepted; //country as default scope for both - - const auto expect_peace_option = [&peace_options](WargoalType::peace_options_t peace_option) -> node_callback_t { - return expect_bool([&peace_options, peace_option](bool val) -> bool { - if (val) { - peace_options |= peace_option; - } else { - peace_options &= ~peace_option; - } - return true; - }); - }; + bool ret = + expect_dictionary_reserve_length(wargoal_types, [this, &peace_order_symbol](std::string_view identifier, ast::NodeCPtr value) -> bool { + // If peace_order_symbol is false, we know there is no peace_order string in the parser + if (peace_order_symbol && identifier == peace_order_symbol.c_str()) { + return true; + } + + using enum WargoalType::peace_options_t; + using enum scope_type_t; - bool ret = expect_dictionary_keys_and_default( + std::string_view war_name; + Timespan available {}, truce {}; + WargoalType::sprite_t sprite_index = 0; + bool triggered_only = false, civil_war = false, constructing = true, crisis = true, great_war_obligatory = false, + mutual = false, all_allowed_states = false, always = false; + WargoalType::peace_options_t peace_options = NO_PEACE_OPTIONS; + WargoalType::peace_modifiers_t modifiers; + ConditionScript can_use { COUNTRY, COUNTRY, COUNTRY }; + ConditionScript is_valid { COUNTRY, COUNTRY, COUNTRY }; + ConditionScript allowed_states { STATE, COUNTRY, COUNTRY }; + ConditionScript allowed_substate_regions { STATE, COUNTRY, COUNTRY }; + ConditionScript allowed_states_in_crisis { STATE, COUNTRY, COUNTRY }; + ConditionScript allowed_countries { COUNTRY, COUNTRY, COUNTRY }; + EffectScript on_add, on_po_accepted; // country as default scope for both + + const auto expect_peace_option = [&peace_options](WargoalType::peace_options_t peace_option) -> node_callback_t { + return expect_bool([&peace_options, peace_option](bool val) -> bool { + if (val) { + peace_options |= peace_option; + } else { + peace_options &= ~peace_option; + } + return true; + }); + }; + + bool ret = expect_dictionary_keys_and_default( [&modifiers, &identifier](std::string_view key, ast::NodeCPtr value) -> bool { using enum WargoalType::PEACE_MODIFIERS; static const string_map_t peace_modifier_map { @@ -196,15 +247,33 @@ bool WargoalTypeManager::load_wargoal_file(ovdl::v2script::Parser const& parser) "always", ZERO_OR_ONE, expect_bool(assign_variable_callback(always)) )(value); - add_wargoal_type( - identifier, war_name, available, truce, sprite_index, triggered_only, civil_war, constructing, crisis, - great_war_obligatory, mutual, all_allowed_states, always, std::move(modifiers), peace_options, - std::move(can_use), std::move(is_valid), std::move(allowed_states), std::move(allowed_substate_regions), - std::move(allowed_states_in_crisis), std::move(allowed_countries), std::move(on_add), std::move(on_po_accepted) - ); - return ret; - } - )(parser.get_file_node()); + add_wargoal_type( + identifier, + war_name, + available, + truce, + sprite_index, + triggered_only, + civil_war, + constructing, + crisis, + great_war_obligatory, + mutual, + all_allowed_states, + always, + std::move(modifiers), + peace_options, + std::move(can_use), + std::move(is_valid), + std::move(allowed_states), + std::move(allowed_substate_regions), + std::move(allowed_states_in_crisis), + std::move(allowed_countries), + std::move(on_add), + std::move(on_po_accepted) + ); + return ret; + })(parser.get_file_node()); /* load order in which CBs are prioritised by AI */ ret &= expect_key( diff --git a/src/openvic-simulation/military/Wargoal.hpp b/src/openvic-simulation/military/Wargoal.hpp index a02dd578d..982daa003 100644 --- a/src/openvic-simulation/military/Wargoal.hpp +++ b/src/openvic-simulation/military/Wargoal.hpp @@ -6,9 +6,9 @@ #include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/object/Timespan.hpp" +#include "openvic-simulation/core/template/EnumBitfield.hpp" #include "openvic-simulation/scripts/ConditionScript.hpp" #include "openvic-simulation/scripts/EffectScript.hpp" -#include "openvic-simulation/core/template/EnumBitfield.hpp" #include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/utility/Getters.hpp" @@ -38,23 +38,23 @@ namespace OpenVic { using peace_modifiers_t = fixed_point_map_t; enum class peace_options_t : uint32_t { - NO_PEACE_OPTIONS = 0, - PO_ANNEX = 1 << 0, - PO_DEMAND_STATE = 1 << 1, - PO_COLONY = 1 << 2, - PO_ADD_TO_SPHERE = 1 << 3, - PO_DISARMAMENT = 1 << 4, - PO_REMOVE_FORTS = 1 << 5, + NO_PEACE_OPTIONS = 0, + PO_ANNEX = 1 << 0, + PO_DEMAND_STATE = 1 << 1, + PO_COLONY = 1 << 2, + PO_ADD_TO_SPHERE = 1 << 3, + PO_DISARMAMENT = 1 << 4, + PO_REMOVE_FORTS = 1 << 5, PO_REMOVE_NAVAL_BASES = 1 << 6, - PO_REPARATIONS = 1 << 7, - PO_REPAY_DEBT = 1 << 8, - PO_REMOVE_PRESTIGE = 1 << 9, - PO_MAKE_PUPPET = 1 << 10, - PO_RELEASE_PUPPET = 1 << 11, - PO_STATUS_QUO = 1 << 12, - PO_INSTALL_COMMUNISM = 1 << 13, - PO_REMOVE_COMMUNISM = 1 << 14, - PO_REMOVE_CORES = 1 << 15, // only usable with ANNEX, DEMAND_STATE, or TRANSFER_PROVINCES + PO_REPARATIONS = 1 << 7, + PO_REPAY_DEBT = 1 << 8, + PO_REMOVE_PRESTIGE = 1 << 9, + PO_MAKE_PUPPET = 1 << 10, + PO_RELEASE_PUPPET = 1 << 11, + PO_STATUS_QUO = 1 << 12, + PO_INSTALL_COMMUNISM = 1 << 13, + PO_REMOVE_COMMUNISM = 1 << 14, + PO_REMOVE_CORES = 1 << 15, // only usable with ANNEX, DEMAND_STATE, or TRANSFER_PROVINCES PO_TRANSFER_PROVINCES = 1 << 16, PO_CLEAR_UNION_SPHERE = 1 << 17 }; @@ -88,18 +88,35 @@ namespace OpenVic { const bool is_mutual; // attacked and defender share wargoal WargoalType( - std::string_view new_identifier, std::string_view new_war_name, Timespan new_available_length, - Timespan new_truce_length, sprite_t new_sprite_index, bool new_triggered_only, bool new_civil_war, - bool new_constructing, bool new_crisis, bool new_great_war_obligatory, bool new_mutual, - bool new_all_allowed_states, bool new_always, peace_modifiers_t&& new_modifiers, peace_options_t new_peace_options, - ConditionScript&& new_can_use, ConditionScript&& new_is_valid, ConditionScript&& new_allowed_states, - ConditionScript&& new_allowed_substate_regions, ConditionScript&& new_allowed_states_in_crisis, - ConditionScript&& new_allowed_countries, EffectScript&& new_on_add, EffectScript&& new_on_po_accepted + std::string_view new_identifier, + std::string_view new_war_name, + Timespan new_available_length, + Timespan new_truce_length, + sprite_t new_sprite_index, + bool new_triggered_only, + bool new_civil_war, + bool new_constructing, + bool new_crisis, + bool new_great_war_obligatory, + bool new_mutual, + bool new_all_allowed_states, + bool new_always, + peace_modifiers_t&& new_modifiers, + peace_options_t new_peace_options, + ConditionScript&& new_can_use, + ConditionScript&& new_is_valid, + ConditionScript&& new_allowed_states, + ConditionScript&& new_allowed_substate_regions, + ConditionScript&& new_allowed_states_in_crisis, + ConditionScript&& new_allowed_countries, + EffectScript&& new_on_add, + EffectScript&& new_on_po_accepted ); WargoalType(WargoalType&&) = default; }; - template<> struct enable_bitfield : std::true_type{}; + template<> + struct enable_bitfield : std::true_type {}; struct WargoalTypeManager { private: @@ -108,13 +125,29 @@ namespace OpenVic { public: bool add_wargoal_type( - std::string_view identifier, std::string_view war_name, Timespan available_length, - Timespan truce_length, WargoalType::sprite_t sprite_index, bool triggered_only, bool civil_war, - bool constructing, bool crisis, bool great_war_obligatory, bool mutual, bool all_allowed_states, - bool always, WargoalType::peace_modifiers_t&& modifiers, WargoalType::peace_options_t peace_options, - ConditionScript&& can_use, ConditionScript&& is_valid, ConditionScript&& allowed_states, - ConditionScript&& allowed_substate_regions, ConditionScript&& allowed_states_in_crisis, - ConditionScript&& allowed_countries, EffectScript&& on_add, EffectScript&& on_po_accepted + std::string_view identifier, + std::string_view war_name, + Timespan available_length, + Timespan truce_length, + WargoalType::sprite_t sprite_index, + bool triggered_only, + bool civil_war, + bool constructing, + bool crisis, + bool great_war_obligatory, + bool mutual, + bool all_allowed_states, + bool always, + WargoalType::peace_modifiers_t&& modifiers, + WargoalType::peace_options_t peace_options, + ConditionScript&& can_use, + ConditionScript&& is_valid, + ConditionScript&& allowed_states, + ConditionScript&& allowed_substate_regions, + ConditionScript&& allowed_states_in_crisis, + ConditionScript&& allowed_countries, + EffectScript&& on_add, + EffectScript&& on_po_accepted ); bool load_wargoal_file(ovdl::v2script::Parser const& parser); diff --git a/src/openvic-simulation/misc/Decision.cpp b/src/openvic-simulation/misc/Decision.cpp index c09d994cf..d509fa02b 100644 --- a/src/openvic-simulation/misc/Decision.cpp +++ b/src/openvic-simulation/misc/Decision.cpp @@ -4,14 +4,23 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Decision::Decision( - std::string_view new_identifier, bool new_alert, bool new_news, std::string_view new_news_title, - std::string_view new_news_desc_long, std::string_view new_news_desc_medium, std::string_view new_news_desc_short, - std::string_view new_picture, ConditionScript&& new_potential, ConditionScript&& new_allow, - ConditionalWeightFactorMul&& new_ai_will_do, EffectScript&& new_effect -) : HasIdentifier { new_identifier }, has_alert { new_alert }, is_news { new_news }, news_title { new_news_title }, - news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, - news_desc_short { new_news_desc_short }, picture { new_picture }, potential { std::move(new_potential) }, - allow { std::move(new_allow) }, ai_will_do { std::move(new_ai_will_do) }, effect { std::move(new_effect) } {} + std::string_view new_identifier, + bool new_alert, + bool new_news, + std::string_view new_news_title, + std::string_view new_news_desc_long, + std::string_view new_news_desc_medium, + std::string_view new_news_desc_short, + std::string_view new_picture, + ConditionScript&& new_potential, + ConditionScript&& new_allow, + ConditionalWeightFactorMul&& new_ai_will_do, + EffectScript&& new_effect +) : + HasIdentifier { new_identifier }, has_alert { new_alert }, is_news { new_news }, news_title { new_news_title }, + news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, news_desc_short { new_news_desc_short }, + picture { new_picture }, potential { std::move(new_potential) }, allow { std::move(new_allow) }, + ai_will_do { std::move(new_ai_will_do) }, effect { std::move(new_effect) } {} bool Decision::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -23,9 +32,18 @@ bool Decision::parse_scripts(DefinitionManager const& definition_manager) { } bool DecisionManager::add_decision( - std::string_view identifier, bool alert, bool news, std::string_view news_title, std::string_view news_desc_long, - std::string_view news_desc_medium, std::string_view news_desc_short, std::string_view picture, ConditionScript&& potential, - ConditionScript&& allow, ConditionalWeightFactorMul&& ai_will_do, EffectScript&& effect + std::string_view identifier, + bool alert, + bool news, + std::string_view news_title, + std::string_view news_desc_long, + std::string_view news_desc_medium, + std::string_view news_desc_short, + std::string_view picture, + ConditionScript&& potential, + ConditionScript&& allow, + ConditionalWeightFactorMul&& ai_will_do, + EffectScript&& effect ) { if (identifier.empty()) { spdlog::error_s("Invalid decision identifier - empty!"); @@ -35,7 +53,7 @@ bool DecisionManager::add_decision( if (news) { if (news_desc_long.empty() || news_desc_medium.empty() || news_desc_short.empty()) { spdlog::warn_s( - "Decision with ID {} is a news decision but doesn't have long, medium and short descriptions!", identifier + "Decision with ID {} is a news decision but doesn't have long, medium and short descriptions!", identifier ); } } else { @@ -45,28 +63,35 @@ bool DecisionManager::add_decision( } return decisions.emplace_item( - identifier, - duplicate_warning_callback, - identifier, alert, news, news_title, news_desc_long, news_desc_medium, news_desc_short, picture, std::move(potential), - std::move(allow), std::move(ai_will_do), std::move(effect) + identifier, + duplicate_warning_callback, + identifier, + alert, + news, + news_title, + news_desc_long, + news_desc_medium, + news_desc_short, + picture, + std::move(potential), + std::move(allow), + std::move(ai_will_do), + std::move(effect) ); } bool DecisionManager::load_decision_file(ast::NodeCPtr root) { - return expect_dictionary_keys( - "political_decisions", ZERO_OR_ONE, expect_dictionary_reserve_length( - decisions, - [this](std::string_view identifier, ast::NodeCPtr node) -> bool { - using enum scope_type_t; + return expect_dictionary_keys("political_decisions", ZERO_OR_ONE, expect_dictionary_reserve_length(decisions, [this](std::string_view identifier, ast::NodeCPtr node) -> bool { + using enum scope_type_t; - bool alert = true, news = false; - std::string_view news_title, news_desc_long, news_desc_medium, news_desc_short, picture; - ConditionScript potential { COUNTRY, COUNTRY, NO_SCOPE }; - ConditionScript allow { COUNTRY, COUNTRY, NO_SCOPE }; - ConditionalWeightFactorMul ai_will_do { COUNTRY, COUNTRY, NO_SCOPE }; - EffectScript effect; + bool alert = true, news = false; + std::string_view news_title, news_desc_long, news_desc_medium, news_desc_short, picture; + ConditionScript potential { COUNTRY, COUNTRY, NO_SCOPE }; + ConditionScript allow { COUNTRY, COUNTRY, NO_SCOPE }; + ConditionalWeightFactorMul ai_will_do { COUNTRY, COUNTRY, NO_SCOPE }; + EffectScript effect; - bool ret = expect_dictionary_keys( + bool ret = expect_dictionary_keys( "alert", ZERO_OR_ONE, expect_bool(assign_variable_callback(alert)), "news", ZERO_OR_ONE, expect_bool(assign_variable_callback(news)), "news_title", ZERO_OR_ONE, expect_string(assign_variable_callback(news_title)), @@ -80,15 +105,23 @@ bool DecisionManager::load_decision_file(ast::NodeCPtr root) { "ai_will_do", ZERO_OR_ONE, ai_will_do.expect_conditional_weight() )(node); - ret &= add_decision( - identifier, alert, news, news_title, news_desc_long, news_desc_medium, news_desc_short, picture, - std::move(potential), std::move(allow), std::move(ai_will_do), std::move(effect) - ); + ret &= add_decision( + identifier, + alert, + news, + news_title, + news_desc_long, + news_desc_medium, + news_desc_short, + picture, + std::move(potential), + std::move(allow), + std::move(ai_will_do), + std::move(effect) + ); - return ret; - } - ) - )(root); + return ret; + }))(root); } bool DecisionManager::parse_scripts(DefinitionManager const& definition_manager) { diff --git a/src/openvic-simulation/misc/Decision.hpp b/src/openvic-simulation/misc/Decision.hpp index c545cf0a4..697b6c1b9 100644 --- a/src/openvic-simulation/misc/Decision.hpp +++ b/src/openvic-simulation/misc/Decision.hpp @@ -28,10 +28,18 @@ namespace OpenVic { const bool is_news; Decision( - std::string_view new_identifier, bool new_alert, bool new_news, std::string_view new_news_title, - std::string_view new_news_desc_long, std::string_view new_news_desc_medium, std::string_view new_news_desc_short, - std::string_view new_picture, ConditionScript&& new_potential, ConditionScript&& new_allow, - ConditionalWeightFactorMul&& new_ai_will_do, EffectScript&& new_effect + std::string_view new_identifier, + bool new_alert, + bool new_news, + std::string_view new_news_title, + std::string_view new_news_desc_long, + std::string_view new_news_desc_medium, + std::string_view new_news_desc_short, + std::string_view new_picture, + ConditionScript&& new_potential, + ConditionScript&& new_allow, + ConditionalWeightFactorMul&& new_ai_will_do, + EffectScript&& new_effect ); Decision(Decision&&) = default; }; @@ -42,10 +50,18 @@ namespace OpenVic { public: bool add_decision( - std::string_view identifier, bool alert, bool news, std::string_view news_title, std::string_view news_desc_long, - std::string_view news_desc_medium, std::string_view news_desc_short, std::string_view picture, - ConditionScript&& potential, ConditionScript&& allow, ConditionalWeightFactorMul&& ai_will_do, - EffectScript&& effect + std::string_view identifier, + bool alert, + bool news, + std::string_view news_title, + std::string_view news_desc_long, + std::string_view news_desc_medium, + std::string_view news_desc_short, + std::string_view picture, + ConditionScript&& potential, + ConditionScript&& allow, + ConditionalWeightFactorMul&& ai_will_do, + EffectScript&& effect ); bool load_decision_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/misc/Event.cpp b/src/openvic-simulation/misc/Event.cpp index d54f8b7aa..89dbd5bdd 100644 --- a/src/openvic-simulation/misc/Event.cpp +++ b/src/openvic-simulation/misc/Event.cpp @@ -12,7 +12,7 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Event::EventOption::EventOption( - std::string_view new_name, EffectScript&& new_effect, ConditionalWeightFactorMul&& new_ai_chance + std::string_view new_name, EffectScript&& new_effect, ConditionalWeightFactorMul&& new_ai_chance ) : name { new_name }, effect { std::move(new_effect) }, ai_chance { std::move(new_ai_chance) } {} bool Event::EventOption::parse_scripts(DefinitionManager const& definition_manager) { @@ -23,19 +23,34 @@ bool Event::EventOption::parse_scripts(DefinitionManager const& definition_manag } Event::Event( - std::string_view new_identifier, std::string_view new_title, std::string_view new_description, - std::string_view new_image, event_type_t new_type, bool new_triggered_only, bool new_major, bool new_fire_only_once, - bool new_allows_multiple_instances, bool new_news, std::string_view new_news_title, std::string_view new_news_desc_long, - std::string_view new_news_desc_medium, std::string_view new_news_desc_short, bool new_election, - const issue_group_t new_election_issue_group, ConditionScript&& new_trigger, ConditionalWeightTime&& new_mean_time_to_happen, - EffectScript&& new_immediate, memory::vector&& new_options -) : HasIdentifier { new_identifier }, title { new_title }, description { new_description }, image { new_image }, - type { new_type }, is_triggered_only { new_triggered_only }, is_major { new_major }, fire_only_once { new_fire_only_once }, - allows_multiple_instances { new_allows_multiple_instances }, is_news { new_news }, news_title { new_news_title }, - news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, news_desc_short { new_news_desc_short }, - election { new_election }, election_issue_group { new_election_issue_group }, trigger { std::move(new_trigger) }, - mean_time_to_happen { std::move(new_mean_time_to_happen) }, immediate { std::move(new_immediate) }, - options { std::move(new_options) } {} + std::string_view new_identifier, + std::string_view new_title, + std::string_view new_description, + std::string_view new_image, + event_type_t new_type, + bool new_triggered_only, + bool new_major, + bool new_fire_only_once, + bool new_allows_multiple_instances, + bool new_news, + std::string_view new_news_title, + std::string_view new_news_desc_long, + std::string_view new_news_desc_medium, + std::string_view new_news_desc_short, + bool new_election, + const issue_group_t new_election_issue_group, + ConditionScript&& new_trigger, + ConditionalWeightTime&& new_mean_time_to_happen, + EffectScript&& new_immediate, + memory::vector&& new_options +) : + HasIdentifier { new_identifier }, title { new_title }, description { new_description }, image { new_image }, + type { new_type }, is_triggered_only { new_triggered_only }, is_major { new_major }, fire_only_once { new_fire_only_once }, + allows_multiple_instances { new_allows_multiple_instances }, is_news { new_news }, news_title { new_news_title }, + news_desc_long { new_news_desc_long }, news_desc_medium { new_news_desc_medium }, news_desc_short { new_news_desc_short }, + election { new_election }, election_issue_group { new_election_issue_group }, trigger { std::move(new_trigger) }, + mean_time_to_happen { std::move(new_mean_time_to_happen) }, immediate { std::move(new_immediate) }, + options { std::move(new_options) } {} bool Event::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -48,8 +63,8 @@ bool Event::parse_scripts(DefinitionManager const& definition_manager) { return ret; } -OnAction::OnAction(std::string_view new_identifier, weight_map_t&& new_weighted_events) - : HasIdentifier { new_identifier }, weighted_events { std::move(new_weighted_events) } {} +OnAction::OnAction(std::string_view new_identifier, weight_map_t&& new_weighted_events) : + HasIdentifier { new_identifier }, weighted_events { std::move(new_weighted_events) } {} EventManager::EventManager() { // Default total vanilla events is 1064 @@ -57,11 +72,26 @@ EventManager::EventManager() { } bool EventManager::register_event( - std::string_view identifier, std::string_view title, std::string_view description, std::string_view image, - Event::event_type_t type, bool triggered_only, bool major, bool fire_only_once, bool allows_multiple_instances, bool news, - std::string_view news_title, std::string_view news_desc_long, std::string_view news_desc_medium, - std::string_view news_desc_short, bool election, const issue_group_t election_issue_group, ConditionScript&& trigger, - ConditionalWeightTime&& mean_time_to_happen, EffectScript&& immediate, memory::vector&& options + std::string_view identifier, + std::string_view title, + std::string_view description, + std::string_view image, + Event::event_type_t type, + bool triggered_only, + bool major, + bool fire_only_once, + bool allows_multiple_instances, + bool news, + std::string_view news_title, + std::string_view news_desc_long, + std::string_view news_desc_medium, + std::string_view news_desc_short, + bool election, + const issue_group_t election_issue_group, + ConditionScript&& trigger, + ConditionalWeightTime&& mean_time_to_happen, + EffectScript&& immediate, + memory::vector&& options ) { if (identifier.empty()) { spdlog::error_s("Invalid event ID - empty!"); @@ -80,31 +110,27 @@ bool EventManager::register_event( if (election && std::holds_alternative(election_issue_group)) { spdlog::warn_s("Event with ID {} is an election event but has no issue group!", identifier); } else if (!election) { - std::visit([identifier](auto&& arg) { - using T = std::decay_t; // Get the clean type - - if constexpr (std::is_same_v>) { - spdlog::warn_s( - "Event with ID {} is not an election event but has party policy group {}!", - identifier, arg - ); - } else if constexpr (std::is_same_v>) { - spdlog::warn_s( - "Event with ID {} is not an election event but has reform group {}!", - identifier, arg - ); - } else if constexpr (!std::is_same_v){ - spdlog::error_s( - "Event with ID {} is not an election event but has unknown issue group {}!", - identifier, arg - ); - } - }, election_issue_group); + std::visit( + [identifier](auto&& arg) { + using T = std::decay_t; // Get the clean type + + if constexpr (std::is_same_v>) { + spdlog::warn_s("Event with ID {} is not an election event but has party policy group {}!", identifier, arg); + } else if constexpr (std::is_same_v>) { + spdlog::warn_s("Event with ID {} is not an election event but has reform group {}!", identifier, arg); + } else if constexpr (!std::is_same_v) { + spdlog::error_s( + "Event with ID {} is not an election event but has unknown issue group {}!", identifier, arg + ); + } + }, + election_issue_group + ); } if (news) { if (news_desc_long.empty() || news_desc_medium.empty() || news_desc_short.empty()) { spdlog::warn_s( - "Event with ID {} is a news event but doesn't have long, medium and short descriptions!", identifier + "Event with ID {} is a news event but doesn't have long, medium and short descriptions!", identifier ); } } else { @@ -122,11 +148,28 @@ bool EventManager::register_event( // TODO - error if is_triggered_only with triggers or MTTH defined return events.emplace_item( - identifier, - duplicate_warning_callback, - identifier, title, description, image, type, triggered_only, major, fire_only_once, allows_multiple_instances, news, - news_title, news_desc_long, news_desc_medium, news_desc_short, election, election_issue_group, std::move(trigger), - std::move(mean_time_to_happen), std::move(immediate), std::move(options) + identifier, + duplicate_warning_callback, + identifier, + title, + description, + image, + type, + triggered_only, + major, + fire_only_once, + allows_multiple_instances, + news, + news_title, + news_desc_long, + news_desc_medium, + news_desc_short, + election, + election_issue_group, + std::move(trigger), + std::move(mean_time_to_happen), + std::move(immediate), + std::move(options) ); } @@ -136,48 +179,42 @@ bool EventManager::add_on_action(std::string_view identifier, OnAction::weight_m return false; } - return on_actions.emplace_item( - identifier, - identifier, std::move(weighted_events) - ); + return on_actions.emplace_item(identifier, identifier, std::move(weighted_events)); } bool EventManager::load_event_file(IssueManager const& issue_manager, ast::NodeCPtr root) { - return expect_dictionary_reserve_length( - events, - [this, &issue_manager](std::string_view key, ast::NodeCPtr value) -> bool { - using enum scope_type_t; - - Event::event_type_t type; - scope_type_t initial_scope; - - if (key == "country_event") { - type = Event::event_type_t::COUNTRY; - initial_scope = COUNTRY; - } else if (key == "province_event") { - type = Event::event_type_t::PROVINCE; - initial_scope = PROVINCE; - } else { - spdlog::error_s("Invalid event type: {}", key); - return false; - } - - std::string_view identifier, title, description, image, news_title, news_desc_long, news_desc_medium, - news_desc_short; - bool triggered_only = false, major = false, fire_only_once = false, allows_multiple_instances = false, - news = false, election = false; - issue_group_t election_issue_group; - ConditionScript trigger { initial_scope, COUNTRY, NO_SCOPE }; - ConditionalWeightTime mean_time_to_happen { initial_scope, COUNTRY, NO_SCOPE }; - EffectScript immediate; - - // Ensures that if ever multithreaded, only one vector is used per thread - // Else acts like static - thread_local memory::vector options; - // Default max vanilla options is 5 - options.reserve(2); - - bool ret = expect_dictionary_keys( + return expect_dictionary_reserve_length(events, [this, &issue_manager](std::string_view key, ast::NodeCPtr value) -> bool { + using enum scope_type_t; + + Event::event_type_t type; + scope_type_t initial_scope; + + if (key == "country_event") { + type = Event::event_type_t::COUNTRY; + initial_scope = COUNTRY; + } else if (key == "province_event") { + type = Event::event_type_t::PROVINCE; + initial_scope = PROVINCE; + } else { + spdlog::error_s("Invalid event type: {}", key); + return false; + } + + std::string_view identifier, title, description, image, news_title, news_desc_long, news_desc_medium, news_desc_short; + bool triggered_only = false, major = false, fire_only_once = false, allows_multiple_instances = false, news = false, + election = false; + issue_group_t election_issue_group; + ConditionScript trigger { initial_scope, COUNTRY, NO_SCOPE }; + ConditionalWeightTime mean_time_to_happen { initial_scope, COUNTRY, NO_SCOPE }; + EffectScript immediate; + + // Ensures that if ever multithreaded, only one vector is used per thread + // Else acts like static + thread_local memory::vector options; + // Default max vanilla options is 5 + options.reserve(2); + + bool ret = expect_dictionary_keys( "id", ONE_EXACTLY, expect_identifier(assign_variable_callback(identifier)), "title", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(title)), "desc", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(description)), @@ -218,46 +255,65 @@ bool EventManager::load_event_file(IssueManager const& issue_manager, ast::NodeC "immediate", ZERO_OR_MORE, immediate.expect_script() )(value); - ret &= register_event( - identifier, title, description, image, type, triggered_only, major, fire_only_once, allows_multiple_instances, - news, news_title, news_desc_long, news_desc_medium, news_desc_short, election, election_issue_group, - std::move(trigger), std::move(mean_time_to_happen), std::move(immediate), std::move(options) - ); - return ret; - } - )(root); + ret &= register_event( + identifier, + title, + description, + image, + type, + triggered_only, + major, + fire_only_once, + allows_multiple_instances, + news, + news_title, + news_desc_long, + news_desc_medium, + news_desc_short, + election, + election_issue_group, + std::move(trigger), + std::move(mean_time_to_happen), + std::move(immediate), + std::move(options) + ); + return ret; + })(root); } bool EventManager::load_on_action_file(ast::NodeCPtr root) { bool ret = expect_dictionary([this](std::string_view identifier, ast::NodeCPtr node) -> bool { OnAction::weight_map_t weighted_events; - bool ret = expect_dictionary_reserve_length( - weighted_events, - [this, &identifier, &weighted_events](std::string_view weight_str, ast::NodeCPtr event_node) -> bool { - bool ret = false; - uint64_t weight; - std::from_chars_result result = string_to_uint64(weight_str, weight); - ret = result.ec == std::errc{}; - if (!ret) { - spdlog::error_s("Invalid weight {} on action {}", weight_str, identifier); - return ret; - } - - Event const* event = nullptr; - ret &= expect_event_identifier(assign_variable_callback_pointer(event))(event_node); - - if (event != nullptr) { - ret &= map_callback(weighted_events, event)(weight); - } else if (ast::FlatValue const* event_name = dryad::node_try_cast(event_node); event_name && event_name->value()) { - spdlog::warn_s( - "Non-existing event {} loaded on action {} with weight {}!", - event_name->value().view(), identifier, weight - ); - } - - return ret; - } - )(node); + bool ret = + expect_dictionary_reserve_length(weighted_events, [this, &identifier, &weighted_events](std::string_view weight_str, ast::NodeCPtr event_node) -> bool { + bool ret = false; + uint64_t weight; + std::from_chars_result result = string_to_uint64(weight_str, weight); + ret = result.ec == std::errc {}; + if (!ret) { + spdlog::error_s("Invalid weight {} on action {}", weight_str, identifier); + return ret; + } + + Event const* event = nullptr; + ret &= expect_event_identifier(assign_variable_callback_pointer(event))(event_node); + + if (event != nullptr) { + ret &= map_callback(weighted_events, event)(weight); + } else if ( + ast::FlatValue const* event_name = dryad::node_try_cast(event_node); + event_name && event_name->value() + ) { + spdlog::warn_s( + "Non-existing event {} loaded on action {} with weight {}!", + event_name->value().view(), + identifier, + weight + ); + } + + return ret; + })(node); ret &= add_on_action(identifier, std::move(weighted_events)); return ret; })(root); diff --git a/src/openvic-simulation/misc/Event.hpp b/src/openvic-simulation/misc/Event.hpp index c909f8e54..f1da4b55a 100644 --- a/src/openvic-simulation/misc/Event.hpp +++ b/src/openvic-simulation/misc/Event.hpp @@ -15,7 +15,10 @@ namespace OpenVic { struct Event : HasIdentifier { friend struct EventManager; - enum struct event_type_t : uint8_t { COUNTRY, PROVINCE }; + enum struct event_type_t : uint8_t { + COUNTRY, + PROVINCE + }; struct EventOption { friend struct EventManager; @@ -65,13 +68,26 @@ namespace OpenVic { const bool is_news; Event( - std::string_view new_identifier, std::string_view new_title, std::string_view new_description, - std::string_view new_image, event_type_t new_type, bool new_triggered_only, bool new_major, - bool new_fire_only_once, bool new_allows_multiple_instances, bool new_news, std::string_view new_news_title, - std::string_view new_news_desc_long, std::string_view new_news_desc_medium, std::string_view new_news_desc_short, - bool new_election, const issue_group_t new_election_issue_group, ConditionScript&& new_trigger, - ConditionalWeightTime&& new_mean_time_to_happen, EffectScript&& new_immediate, - memory::vector&& new_options + std::string_view new_identifier, + std::string_view new_title, + std::string_view new_description, + std::string_view new_image, + event_type_t new_type, + bool new_triggered_only, + bool new_major, + bool new_fire_only_once, + bool new_allows_multiple_instances, + bool new_news, + std::string_view new_news_title, + std::string_view new_news_desc_long, + std::string_view new_news_desc_medium, + std::string_view new_news_desc_short, + bool new_election, + const issue_group_t new_election_issue_group, + ConditionScript&& new_trigger, + ConditionalWeightTime&& new_mean_time_to_happen, + EffectScript&& new_immediate, + memory::vector&& new_options ); Event(Event&&) = default; }; @@ -96,11 +112,26 @@ namespace OpenVic { EventManager(); bool register_event( - std::string_view identifier, std::string_view title, std::string_view description, std::string_view image, - Event::event_type_t type, bool triggered_only, bool major, bool fire_only_once, bool allows_multiple_instances, - bool news, std::string_view news_title, std::string_view news_desc_long, std::string_view news_desc_medium, - std::string_view news_desc_short, bool election, const issue_group_t election_issue_group, ConditionScript&& trigger, - ConditionalWeightTime&& mean_time_to_happen, EffectScript&& immediate, memory::vector&& options + std::string_view identifier, + std::string_view title, + std::string_view description, + std::string_view image, + Event::event_type_t type, + bool triggered_only, + bool major, + bool fire_only_once, + bool allows_multiple_instances, + bool news, + std::string_view news_title, + std::string_view news_desc_long, + std::string_view news_desc_medium, + std::string_view news_desc_short, + bool election, + const issue_group_t election_issue_group, + ConditionScript&& trigger, + ConditionalWeightTime&& mean_time_to_happen, + EffectScript&& immediate, + memory::vector&& options ); bool add_on_action(std::string_view identifier, OnAction::weight_map_t&& new_weighted_events); diff --git a/src/openvic-simulation/misc/GameAction.cpp b/src/openvic-simulation/misc/GameAction.cpp index dc7727b45..6284d923c 100644 --- a/src/openvic-simulation/misc/GameAction.cpp +++ b/src/openvic-simulation/misc/GameAction.cpp @@ -1,35 +1,35 @@ #include "GameAction.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/InstanceManager.hpp" +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" using namespace OpenVic; -bool GameActionManager::VariantVisitor::operator() (none_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(none_argument_t const& argument) const { return false; } // Core -bool GameActionManager::VariantVisitor::operator() (tick_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(tick_argument_t const& argument) const { instance_manager.tick(); return true; } -bool GameActionManager::VariantVisitor::operator() (set_pause_argument_t const& new_is_paused) const { +bool GameActionManager::VariantVisitor::operator()(set_pause_argument_t const& new_is_paused) const { const bool old_pause = instance_manager.get_simulation_clock().is_paused(); instance_manager.get_simulation_clock().set_paused(type_safe::get(new_is_paused)); return old_pause != instance_manager.get_simulation_clock().is_paused(); } -bool GameActionManager::VariantVisitor::operator() (set_speed_argument_t const& new_speed) const { +bool GameActionManager::VariantVisitor::operator()(set_speed_argument_t const& new_speed) const { const SimulationClock::speed_t old_speed = instance_manager.get_simulation_clock().get_simulation_speed(); instance_manager.get_simulation_clock().set_simulation_speed(type_safe::get(new_speed)); return old_speed != instance_manager.get_simulation_clock().get_simulation_speed(); } -bool GameActionManager::VariantVisitor::operator() (set_ai_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_ai_argument_t const& argument) const { const auto [country_index, new_is_ai] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -39,10 +39,10 @@ bool GameActionManager::VariantVisitor::operator() (set_ai_argument_t const& arg } // Production -bool GameActionManager::VariantVisitor::operator() (expand_province_building_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(expand_province_building_argument_t const& argument) const { const auto [country_index, province_index, province_building_index] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); - + ProvinceInstance* province = instance_manager.get_map_instance().get_province_instance_by_index(province_index); if (OV_unlikely(province == nullptr)) { @@ -51,14 +51,12 @@ bool GameActionManager::VariantVisitor::operator() (expand_province_building_arg } return province->expand_building( - instance_manager.definition_manager.get_modifier_manager().get_modifier_effect_cache(), - province_building_index, - country + instance_manager.definition_manager.get_modifier_manager().get_modifier_effect_cache(), province_building_index, country ); } // Budget -bool GameActionManager::VariantVisitor::operator() (set_strata_tax_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_strata_tax_argument_t const& argument) const { const auto [country_index, strata_index, tax_rate] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -73,7 +71,7 @@ bool GameActionManager::VariantVisitor::operator() (set_strata_tax_argument_t co return false; } -bool GameActionManager::VariantVisitor::operator() (set_army_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_army_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -81,7 +79,7 @@ bool GameActionManager::VariantVisitor::operator() (set_army_spending_argument_t return false; } -bool GameActionManager::VariantVisitor::operator() (set_navy_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_navy_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -89,7 +87,7 @@ bool GameActionManager::VariantVisitor::operator() (set_navy_spending_argument_t return false; } -bool GameActionManager::VariantVisitor::operator() (set_construction_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_construction_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -97,7 +95,7 @@ bool GameActionManager::VariantVisitor::operator() (set_construction_spending_ar return false; } -bool GameActionManager::VariantVisitor::operator() (set_education_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_education_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -105,7 +103,7 @@ bool GameActionManager::VariantVisitor::operator() (set_education_spending_argum return false; } -bool GameActionManager::VariantVisitor::operator() (set_administration_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_administration_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -113,7 +111,7 @@ bool GameActionManager::VariantVisitor::operator() (set_administration_spending_ return false; } -bool GameActionManager::VariantVisitor::operator() (set_social_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_social_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -121,7 +119,7 @@ bool GameActionManager::VariantVisitor::operator() (set_social_spending_argument return false; } -bool GameActionManager::VariantVisitor::operator() (set_military_spending_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_military_spending_argument_t const& argument) const { const auto [country_index, spending] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -129,7 +127,7 @@ bool GameActionManager::VariantVisitor::operator() (set_military_spending_argume return false; } -bool GameActionManager::VariantVisitor::operator() (set_tariff_rate_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_tariff_rate_argument_t const& argument) const { const auto [country_index, tariff_rate] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -138,14 +136,14 @@ bool GameActionManager::VariantVisitor::operator() (set_tariff_rate_argument_t c } // Technology -bool GameActionManager::VariantVisitor::operator() (start_research_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(start_research_argument_t const& argument) const { const auto [country_index, technology_index] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); - Technology const* technology = instance_manager.definition_manager - .get_research_manager() - .get_technology_manager() - .get_technology_by_index(technology_index); + Technology const* technology = + instance_manager.definition_manager.get_research_manager().get_technology_manager().get_technology_by_index( + technology_index + ); if (OV_unlikely(technology == nullptr)) { spdlog::error_s("GAME_ACTION_START_RESEARCH called with invalid technology index: {}", technology_index); @@ -164,7 +162,7 @@ bool GameActionManager::VariantVisitor::operator() (start_research_argument_t co // Population // Trade -bool GameActionManager::VariantVisitor::operator() (set_good_automated_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_good_automated_argument_t const& argument) const { const auto [country_index, good_index, new_is_automated] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -184,7 +182,7 @@ bool GameActionManager::VariantVisitor::operator() (set_good_automated_argument_ return old_automated != good_data.is_automated; } -bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_good_trade_order_argument_t const& argument) const { const auto [country_index, good_index, new_is_selling, new_cutoff] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -198,10 +196,7 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen CountryInstance::good_data_t& good_data = country.get_good_data(*good); if (OV_unlikely(good_data.is_automated)) { - spdlog::error_s( - "GAME_ACTION_SET_GOOD_TRADE_ORDER called for automated good! Country: {}, good: {}", - country, *good - ); + spdlog::error_s("GAME_ACTION_SET_GOOD_TRADE_ORDER called for automated good! Country: {}, good: {}", country, *good); return false; } @@ -213,11 +208,12 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen if (good_data.stockpile_cutoff.is_negative()) { spdlog::error_s( - "GAME_ACTION_SET_GOOD_TRADE_ORDER called with negative stockpile cutoff {} for {} good \"{}\" in country \"{}\". Setting to 0.", - good_data.stockpile_cutoff, - *good, - good_data.is_selling ? "selling" : "buying", - country + "GAME_ACTION_SET_GOOD_TRADE_ORDER called with negative stockpile cutoff {} for {} good \"{}\" in country \"{}\". " + "Setting to 0.", + good_data.stockpile_cutoff, + *good, + good_data.is_selling ? "selling" : "buying", + country ); good_data.stockpile_cutoff = 0; } @@ -228,26 +224,24 @@ bool GameActionManager::VariantVisitor::operator() (set_good_trade_order_argumen // Diplomacy // Military -bool GameActionManager::VariantVisitor::operator() (create_leader_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(create_leader_argument_t const& argument) const { const auto [country_index, unit_branch] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); if (country.get_create_leader_count() < 1) { spdlog::error_s( - "GAME_ACTION_CREATE_LEADER called for country \"{}\" without enough leadership points ({:.2}) to create any leaders!", - country, country.get_leadership_point_stockpile() + "GAME_ACTION_CREATE_LEADER called for country \"{}\" without enough leadership points ({:.2}) to create any " + "leaders!", + country, + country.get_leadership_point_stockpile() ); return false; } - return instance_manager.get_unit_instance_manager().create_leader( - country, - unit_branch, - instance_manager.get_today() - ); + return instance_manager.get_unit_instance_manager().create_leader(country, unit_branch, instance_manager.get_today()); } -bool GameActionManager::VariantVisitor::operator() (set_use_leader_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_use_leader_argument_t const& argument) const { const auto [unique_id, new_should_use] = argument; LeaderInstance* leader = instance_manager.get_unit_instance_manager().get_leader_instance_by_unique_id(unique_id); @@ -264,7 +258,7 @@ bool GameActionManager::VariantVisitor::operator() (set_use_leader_argument_t co return old_use != leader->get_can_be_used(); } -bool GameActionManager::VariantVisitor::operator() (set_auto_create_leaders_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_auto_create_leaders_argument_t const& argument) const { const auto [country_index, new_should_auto_create] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -273,7 +267,7 @@ bool GameActionManager::VariantVisitor::operator() (set_auto_create_leaders_argu return old_auto_create != country.get_auto_create_leaders(); } -bool GameActionManager::VariantVisitor::operator() (set_auto_assign_leaders_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_auto_assign_leaders_argument_t const& argument) const { const auto [country_index, new_should_auto_assign] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -282,7 +276,7 @@ bool GameActionManager::VariantVisitor::operator() (set_auto_assign_leaders_argu return old_auto_assign != country.get_auto_assign_leaders(); } -bool GameActionManager::VariantVisitor::operator() (set_mobilise_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(set_mobilise_argument_t const& argument) const { const auto [country_index, new_is_mobilised] = argument; CountryInstance& country = instance_manager.get_country_instance_manager().get_country_instance_by_index(country_index); @@ -291,21 +285,21 @@ bool GameActionManager::VariantVisitor::operator() (set_mobilise_argument_t cons return old_mobilise != country.is_mobilised(); } -bool GameActionManager::VariantVisitor::operator() (start_land_unit_recruitment_argument_t const& argument) const { +bool GameActionManager::VariantVisitor::operator()(start_land_unit_recruitment_argument_t const& argument) const { const auto [regiment_type_index, province_index, pop_id_in_province] = argument; - RegimentType const* const regiment_type = instance_manager.definition_manager - .get_military_manager() - .get_unit_type_manager() - .get_regiment_type_by_index(regiment_type_index); + RegimentType const* const regiment_type = + instance_manager.definition_manager.get_military_manager().get_unit_type_manager().get_regiment_type_by_index( + regiment_type_index + ); if (OV_unlikely(regiment_type == nullptr)) { - spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid regiment type index: {}", regiment_type_index); + spdlog::error_s( + "GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid regiment type index: {}", regiment_type_index + ); return false; } - ProvinceInstance* province = instance_manager - .get_map_instance() - .get_province_instance_by_index(province_index); + ProvinceInstance* province = instance_manager.get_map_instance().get_province_instance_by_index(province_index); if (OV_unlikely(province == nullptr)) { spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid province index: {}", province_index); return false; @@ -313,13 +307,15 @@ bool GameActionManager::VariantVisitor::operator() (start_land_unit_recruitment_ Pop* pop = province->find_pop_by_id(pop_id_in_province); if (OV_unlikely(pop == nullptr)) { - spdlog::error_s("GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid pop_id_in_province: {}", pop_id_in_province); + spdlog::error_s( + "GAME_ACTION_START_LAND_UNIT_RECRUITMENT called with invalid pop_id_in_province: {}", pop_id_in_province + ); return false; } - //these TODO's should be implemented in ProvinceInstance and/or some military type - //TODO verify pop's cultural status is acceptable for regiment type - //TODO verify pop is recruitable and has enough size (pop.try_recruit()) - //TODO actually instantiate a regiment in recruitment state + // these TODO's should be implemented in ProvinceInstance and/or some military type + // TODO verify pop's cultural status is acceptable for regiment type + // TODO verify pop is recruitable and has enough size (pop.try_recruit()) + // TODO actually instantiate a regiment in recruitment state return false; } diff --git a/src/openvic-simulation/misc/GameAction.hpp b/src/openvic-simulation/misc/GameAction.hpp index cb6ce2501..5ba9b7979 100644 --- a/src/openvic-simulation/misc/GameAction.hpp +++ b/src/openvic-simulation/misc/GameAction.hpp @@ -16,48 +16,48 @@ #include "openvic-simulation/types/UnitBranchType.hpp" namespace OpenVic { -namespace detail { - template - struct reduce_tuple { - using type = std::tuple; - static constexpr std::integral_constant size {}; - - template - static constexpr type construct(Args2&&... args) - requires requires { std::make_tuple(std::forward(args)...); } - { - return std::make_tuple(std::forward(args)...); - } - }; - - template - struct reduce_tuple { - using type = std::pair; - static constexpr std::integral_constant size {}; - - template - static constexpr type construct(InT1&& t1, InT2&& t2) - requires requires { std::make_pair(std::forward(t1), std::forward(t2)); } - { - return std::make_pair(std::forward(t1), std::forward(t2)); - } - }; + namespace detail { + template + struct reduce_tuple { + using type = std::tuple; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(Args2&&... args) + requires requires { std::make_tuple(std::forward(args)...); } + { + return std::make_tuple(std::forward(args)...); + } + }; - template - struct reduce_tuple { - using type = T; - static constexpr std::integral_constant size {}; + template + struct reduce_tuple { + using type = std::pair; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(InT1&& t1, InT2&& t2) + requires requires { std::make_pair(std::forward(t1), std::forward(t2)); } + { + return std::make_pair(std::forward(t1), std::forward(t2)); + } + }; - template - static constexpr type construct(InT&& t) - requires requires { std::forward(t); } - { - return std::forward(t); - } - }; + template + struct reduce_tuple { + using type = T; + static constexpr std::integral_constant size {}; + + template + static constexpr type construct(InT&& t) + requires requires { std::forward(t); } + { + return std::forward(t); + } + }; - struct ts_op_structured_binding_passthrough {}; -} + struct ts_op_structured_binding_passthrough {}; + } // To add a new game action: // 1. **Copy** an existing line. @@ -66,66 +66,62 @@ namespace detail { // The format for each action is: X(action_name, argument_type1, argument_type2, ...) // `none` is handled as example throughout the file #define FOR_EACH_GAME_ACTION(X) \ -X(tick, std::monostate) \ -X(set_pause, bool) \ -X(set_speed, int64_t) \ -X(set_ai, country_index_t, bool) \ -X(expand_province_building, country_index_t, province_index_t, province_building_index_t) \ -X(set_strata_tax, country_index_t, strata_index_t, fixed_point_t) \ -X(set_army_spending, country_index_t, fixed_point_t) \ -X(set_navy_spending, country_index_t, fixed_point_t) \ -X(set_construction_spending, country_index_t, fixed_point_t) \ -X(set_education_spending, country_index_t, fixed_point_t) \ -X(set_administration_spending, country_index_t, fixed_point_t) \ -X(set_social_spending, country_index_t, fixed_point_t) \ -X(set_military_spending, country_index_t, fixed_point_t) \ -X(set_tariff_rate, country_index_t, fixed_point_t) \ -X(start_research, country_index_t, technology_index_t) \ -X(set_good_automated, country_index_t, good_index_t, bool) \ -X(set_good_trade_order, country_index_t, good_index_t, bool, fixed_point_t) \ -X(create_leader, country_index_t, unit_branch_t) \ -X(set_use_leader, unique_id_t, bool) \ -X(set_auto_create_leaders, country_index_t, bool) \ -X(set_auto_assign_leaders, country_index_t, bool) \ -X(set_mobilise, country_index_t, bool) \ -X(start_land_unit_recruitment, regiment_type_index_t, province_index_t, pop_id_in_province_t) + X(tick, std::monostate) \ + X(set_pause, bool) \ + X(set_speed, int64_t) \ + X(set_ai, country_index_t, bool) \ + X(expand_province_building, country_index_t, province_index_t, province_building_index_t) \ + X(set_strata_tax, country_index_t, strata_index_t, fixed_point_t) \ + X(set_army_spending, country_index_t, fixed_point_t) \ + X(set_navy_spending, country_index_t, fixed_point_t) \ + X(set_construction_spending, country_index_t, fixed_point_t) \ + X(set_education_spending, country_index_t, fixed_point_t) \ + X(set_administration_spending, country_index_t, fixed_point_t) \ + X(set_social_spending, country_index_t, fixed_point_t) \ + X(set_military_spending, country_index_t, fixed_point_t) \ + X(set_tariff_rate, country_index_t, fixed_point_t) \ + X(start_research, country_index_t, technology_index_t) \ + X(set_good_automated, country_index_t, good_index_t, bool) \ + X(set_good_trade_order, country_index_t, good_index_t, bool, fixed_point_t) \ + X(create_leader, country_index_t, unit_branch_t) \ + X(set_use_leader, unique_id_t, bool) \ + X(set_auto_create_leaders, country_index_t, bool) \ + X(set_auto_assign_leaders, country_index_t, bool) \ + X(set_mobilise, country_index_t, bool) \ + X(start_land_unit_recruitment, regiment_type_index_t, province_index_t, pop_id_in_province_t) // <--- ADD NEW GAME ACTIONS HERE (copy/edit an X(...) line) -//the argument type alias for each game action +// the argument type alias for each game action #define ARG_TYPE(name) name##_argument_t -//define type aliases for game action arguments -//example: -struct none_argument_t : type_safe::strong_typedef { - using strong_typedef::strong_typedef; - constexpr none_argument_t(std::monostate const& value) : strong_typedef(value) {} - constexpr none_argument_t(std::monostate&& value) - : strong_typedef(static_cast(value)) {} -}; + // define type aliases for game action arguments + // example: + struct none_argument_t : type_safe::strong_typedef { + using strong_typedef::strong_typedef; + constexpr none_argument_t(std::monostate const& value) : strong_typedef(value) {} + constexpr none_argument_t(std::monostate&& value) : strong_typedef(static_cast(value)) {} + }; #define USING_ARG_TYPE(name, ...) \ -struct ARG_TYPE(name) \ - : type_safe::strong_typedef::type>, \ - detail::ts_op_structured_binding_passthrough { \ - using strong_typedef::strong_typedef; \ - using reduce_helper_t = detail::reduce_tuple<__VA_ARGS__>; \ - using underlying_type = reduce_helper_t::type; \ + struct ARG_TYPE(name) : \ + type_safe::strong_typedef::type>, \ + detail::ts_op_structured_binding_passthrough { \ + using strong_typedef::strong_typedef; \ + using reduce_helper_t = detail::reduce_tuple<__VA_ARGS__>; \ + using underlying_type = reduce_helper_t::type; \ \ - constexpr ARG_TYPE(name)(underlying_type const& value) : strong_typedef(value) {} \ - constexpr ARG_TYPE(name)(underlying_type && value) : strong_typedef(static_cast(value)) {} \ - template \ - constexpr ARG_TYPE(name)(Arg1 && arg1, Args&&... args) \ - : strong_typedef(reduce_helper_t::construct(std::forward(arg1), std::forward(args)...)) {} \ -}; - -FOR_EACH_GAME_ACTION(USING_ARG_TYPE) + constexpr ARG_TYPE(name)(underlying_type const& value) : strong_typedef(value) {} \ + constexpr ARG_TYPE(name)(underlying_type && value) : strong_typedef(static_cast(value)) {} \ + template \ + constexpr ARG_TYPE(name)(Arg1 && arg1, Args&&... args) : \ + strong_typedef(reduce_helper_t::construct(std::forward(arg1), std::forward(args)...)) {} \ + }; + + FOR_EACH_GAME_ACTION(USING_ARG_TYPE) #undef USING_ARG_TYPE -//define game_action_t as a variant of all possible game action arguments +// define game_action_t as a variant of all possible game action arguments #define COMMA_ARG_TYPE(name, ...) , ARG_TYPE(name) - using game_action_t = std::variant< - none_argument_t - FOR_EACH_GAME_ACTION(COMMA_ARG_TYPE) - >; + using game_action_t = std::variant; #undef COMMA_ARG_TYPE struct InstanceManager; @@ -135,17 +131,19 @@ FOR_EACH_GAME_ACTION(USING_ARG_TYPE) struct VariantVisitor { private: InstanceManager& instance_manager; + public: constexpr VariantVisitor(InstanceManager& new_instance_manager) : instance_manager { new_instance_manager } {} -//define a method for each game method +// define a method for each game method #define DEFINE_ARG_TYPE_AND_METHOD(name, ...) bool operator()(ARG_TYPE(name) const& argument) const; -//example: -bool operator()(none_argument_t const& argument) const; - FOR_EACH_GAME_ACTION(DEFINE_ARG_TYPE_AND_METHOD) + // example: + bool operator()(none_argument_t const& argument) const; + FOR_EACH_GAME_ACTION(DEFINE_ARG_TYPE_AND_METHOD) #undef DEFINE_ARG_TYPE_AND_METHOD }; VariantVisitor visitor; + public: constexpr GameActionManager(InstanceManager& new_instance_manager) : visitor { new_instance_manager } {} diff --git a/src/openvic-simulation/misc/GameRulesManager.cpp b/src/openvic-simulation/misc/GameRulesManager.cpp index 8b7dac0ce..4286d8fda 100644 --- a/src/openvic-simulation/misc/GameRulesManager.cpp +++ b/src/openvic-simulation/misc/GameRulesManager.cpp @@ -12,18 +12,16 @@ bool GameRulesManager::may_use_coastal_artisanal_production_types(ProvinceInstan const bool is_coastal_province = province.province_definition.is_coastal(); using enum artisan_coastal_restriction_t; switch (coastal_restriction_for_artisans) { - case Unrestricted: - return true; - case CountriesWithCoast: { - CountryInstance const* const country = province.get_country_to_report_economy(); - return is_coastal_province || (country != nullptr && country->is_coastal()); - } - case CoastalStates: { - State const* const state = province.get_state(); - return is_coastal_province || (state != nullptr && state->is_coastal()); - } - case CoastalProvinces: - return is_coastal_province; + case Unrestricted: return true; + case CountriesWithCoast: { + CountryInstance const* const country = province.get_country_to_report_economy(); + return is_coastal_province || (country != nullptr && country->is_coastal()); + } + case CoastalStates: { + State const* const state = province.get_state(); + return is_coastal_province || (state != nullptr && state->is_coastal()); + } + case CoastalProvinces: return is_coastal_province; } OpenVic::unreachable(); @@ -33,15 +31,14 @@ bool GameRulesManager::may_use_coastal_factory_production_types(State const& sta const bool is_coastal_state = state.is_coastal(); using enum factory_coastal_restriction_t; switch (coastal_restriction_for_factories) { - case Unrestricted: - return true; - case CountriesWithCoast: { - CountryInstance const* const country = state.get_owner(); - return is_coastal_state || (country != nullptr && country->is_coastal()); - } - case CoastalStates: { - return is_coastal_state; - } + case Unrestricted: return true; + case CountriesWithCoast: { + CountryInstance const* const country = state.get_owner(); + return is_coastal_state || (country != nullptr && country->is_coastal()); + } + case CoastalStates: { + return is_coastal_state; + } } OpenVic::unreachable(); diff --git a/src/openvic-simulation/misc/GameRulesManager.hpp b/src/openvic-simulation/misc/GameRulesManager.hpp index 76d1905f5..3d50639aa 100644 --- a/src/openvic-simulation/misc/GameRulesManager.hpp +++ b/src/openvic-simulation/misc/GameRulesManager.hpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { struct ProvinceInstance; @@ -80,4 +80,4 @@ namespace OpenVic { coastal_restriction_for_factories = factory_coastal_restriction_t::CoastalStates; } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/misc/SimulationClock.cpp b/src/openvic-simulation/misc/SimulationClock.cpp index bee19f013..c2d982d71 100644 --- a/src/openvic-simulation/misc/SimulationClock.cpp +++ b/src/openvic-simulation/misc/SimulationClock.cpp @@ -4,10 +4,9 @@ using namespace OpenVic; -SimulationClock::SimulationClock( - tick_function_t new_tick_function, update_function_t new_update_function -) : tick_function { new_tick_function ? std::move(new_tick_function) : []() {} }, - update_function { new_update_function ? std::move(new_update_function) : []() {} } { +SimulationClock::SimulationClock(tick_function_t new_tick_function, update_function_t new_update_function) : + tick_function { new_tick_function ? std::move(new_tick_function) : []() {} }, + update_function { new_update_function ? std::move(new_update_function) : []() {} } { reset(); } diff --git a/src/openvic-simulation/misc/SimulationClock.hpp b/src/openvic-simulation/misc/SimulationClock.hpp index f83d06d26..cdedbdaae 100644 --- a/src/openvic-simulation/misc/SimulationClock.hpp +++ b/src/openvic-simulation/misc/SimulationClock.hpp @@ -25,9 +25,7 @@ namespace OpenVic { * (in descending duration order, hence increasing speed order). */ static constexpr speed_rates_t GAME_SPEEDS = []() constexpr -> speed_rates_t { using namespace std::chrono_literals; - return { - 3s, 2s, 1s, 100ms, 1ms - }; + return { 3s, 2s, 1s, 100ms, 1ms }; }(); static constexpr speed_t MIN_SPEED = 0, MAX_SPEED = std::size(GAME_SPEEDS) - 1; @@ -42,10 +40,7 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(paused, is, true); public: - - SimulationClock( - tick_function_t new_tick_function, update_function_t new_update_function - ); + SimulationClock(tick_function_t new_tick_function, update_function_t new_update_function); time_point_t get_now() const; @@ -59,7 +54,7 @@ namespace OpenVic { bool can_decrease_simulation_speed() const; void conditionally_advance_game(); - void force_advance_game(); //for debug only + void force_advance_game(); // for debug only void reset(); }; } diff --git a/src/openvic-simulation/misc/SongChance.cpp b/src/openvic-simulation/misc/SongChance.cpp index 3ce39ee58..b956c90cc 100644 --- a/src/openvic-simulation/misc/SongChance.cpp +++ b/src/openvic-simulation/misc/SongChance.cpp @@ -3,9 +3,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -SongChance::SongChance( - size_t new_index, std::string_view new_filename, ConditionalWeightFactorMul&& new_chance -) : HasIdentifier { std::to_string(new_index) }, file_name { new_filename }, chance { std::move(new_chance) } {} +SongChance::SongChance(size_t new_index, std::string_view new_filename, ConditionalWeightFactorMul&& new_chance) : + HasIdentifier { std::to_string(new_index) }, file_name { new_filename }, chance { std::move(new_chance) } {} bool SongChance::parse_scripts(DefinitionManager const& definition_manager) { return chance.parse_scripts(definition_manager); @@ -14,30 +13,24 @@ bool SongChance::parse_scripts(DefinitionManager const& definition_manager) { bool SongChanceManager::load_songs_file(ast::NodeCPtr root) { bool ret = true; - ret &= expect_dictionary_reserve_length( - song_chances, - [this](std::string_view key, ast::NodeCPtr value) -> bool { - using enum scope_type_t; + ret &= expect_dictionary_reserve_length(song_chances, [this](std::string_view key, ast::NodeCPtr value) -> bool { + using enum scope_type_t; - if (key != "song") { - spdlog::error_s("Invalid song declaration {}", key); - return false; - } - std::string_view name {}; - ConditionalWeightFactorMul chance { COUNTRY, COUNTRY, NO_SCOPE }; + if (key != "song") { + spdlog::error_s("Invalid song declaration {}", key); + return false; + } + std::string_view name {}; + ConditionalWeightFactorMul chance { COUNTRY, COUNTRY, NO_SCOPE }; - bool ret = expect_dictionary_keys( + bool ret = expect_dictionary_keys( "name", ONE_EXACTLY, expect_string(assign_variable_callback(name)), "chance", ONE_EXACTLY, chance.expect_conditional_weight() )(value); - ret &= song_chances.emplace_item( - name, - song_chances.size(), name, std::move(chance) - ); - return ret; - } - )(root); + ret &= song_chances.emplace_item(name, song_chances.size(), name, std::move(chance)); + return ret; + })(root); if (song_chances.size() == 0) { spdlog::error_s("No songs found in Songs.txt"); diff --git a/src/openvic-simulation/misc/SongChance.hpp b/src/openvic-simulation/misc/SongChance.hpp index 818dc3244..6e19e0d2a 100644 --- a/src/openvic-simulation/misc/SongChance.hpp +++ b/src/openvic-simulation/misc/SongChance.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/scripts/ConditionalWeight.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" namespace OpenVic { /*For music/Songs.txt if it exists*/ @@ -24,10 +24,9 @@ namespace OpenVic { struct SongChanceManager { private: IdentifierRegistry IDENTIFIER_REGISTRY(song_chance); - //Songs.txt + // Songs.txt public: bool load_songs_file(ast::NodeCPtr root); bool parse_scripts(DefinitionManager const& definition_manager); }; } - diff --git a/src/openvic-simulation/misc/SoundEffect.cpp b/src/openvic-simulation/misc/SoundEffect.cpp index 968cc1319..b856f51fd 100644 --- a/src/openvic-simulation/misc/SoundEffect.cpp +++ b/src/openvic-simulation/misc/SoundEffect.cpp @@ -23,8 +23,12 @@ bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::s fixed_point_t volume = 1; bool ret = expect_dictionary_keys( - "file", ONE_EXACTLY, expect_string(file_callback), // - "volume", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(volume)) // + "file", + ONE_EXACTLY, + expect_string(file_callback), // + "volume", + ZERO_OR_ONE, + expect_fixed_point(assign_variable_callback(volume)) // )(root); if (sfx_identifier.empty()) { @@ -35,10 +39,7 @@ bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::s spdlog::warn_s("Sound filename {} was empty!", sfx_identifier); } - ret &= sound_effects.emplace_item( - sfx_identifier, - sfx_identifier, std::move(file), volume - ); + ret &= sound_effects.emplace_item(sfx_identifier, sfx_identifier, std::move(file), volume); return ret; } diff --git a/src/openvic-simulation/misc/SoundEffect.hpp b/src/openvic-simulation/misc/SoundEffect.hpp index ea698bba3..ae7ede37f 100644 --- a/src/openvic-simulation/misc/SoundEffect.hpp +++ b/src/openvic-simulation/misc/SoundEffect.hpp @@ -3,8 +3,8 @@ #include #include "openvic-simulation/core/object/FixedPoint.hpp" -#include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" namespace OpenVic { class Dataloader; diff --git a/src/openvic-simulation/modifier/Modifier.cpp b/src/openvic-simulation/modifier/Modifier.cpp index 6df23b270..99f66f084 100644 --- a/src/openvic-simulation/modifier/Modifier.cpp +++ b/src/openvic-simulation/modifier/Modifier.cpp @@ -6,44 +6,48 @@ std::string_view Modifier::modifier_type_to_string(modifier_type_t type) { using enum Modifier::modifier_type_t; switch (type) { -#define _CASE(X) case X: return #X; - _CASE(EVENT) - _CASE(STATIC) - _CASE(TRIGGERED) - _CASE(CRIME) - _CASE(TERRAIN) - _CASE(CLIMATE) - _CASE(CONTINENT) - _CASE(BUILDING) - _CASE(LEADER) - _CASE(UNIT_TERRAIN) - _CASE(NATIONAL_VALUE) - _CASE(NATIONAL_FOCUS) - _CASE(PARTY_POLICY) - _CASE(REFORM) - _CASE(TECHNOLOGY) - _CASE(INVENTION) - _CASE(TECH_SCHOOL) +#define _CASE(X) \ + case X: return #X; + _CASE(EVENT) + _CASE(STATIC) + _CASE(TRIGGERED) + _CASE(CRIME) + _CASE(TERRAIN) + _CASE(CLIMATE) + _CASE(CONTINENT) + _CASE(BUILDING) + _CASE(LEADER) + _CASE(UNIT_TERRAIN) + _CASE(NATIONAL_VALUE) + _CASE(NATIONAL_FOCUS) + _CASE(PARTY_POLICY) + _CASE(REFORM) + _CASE(TECHNOLOGY) + _CASE(INVENTION) + _CASE(TECH_SCHOOL) #undef _CASE default: return "INVALID MODIFIER TYPE"; } } -Modifier::Modifier(std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type) - : HasIdentifier { new_identifier }, ModifierValue { std::move(new_values) }, type { new_type } {} +Modifier::Modifier(std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type) : + HasIdentifier { new_identifier }, ModifierValue { std::move(new_values) }, type { new_type } {} IconModifier::IconModifier( - std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon + std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon ) : Modifier { new_identifier, std::move(new_values), new_type }, icon { new_icon } {} TriggeredModifier::TriggeredModifier( - std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon, - ConditionScript&& new_trigger + std::string_view new_identifier, + ModifierValue&& new_values, + modifier_type_t new_type, + icon_t new_icon, + ConditionScript&& new_trigger ) : IconModifier { new_identifier, std::move(new_values), new_type, new_icon }, trigger { std::move(new_trigger) } {} bool TriggeredModifier::parse_scripts(DefinitionManager const& definition_manager, bool can_be_null) { return trigger.parse_script(can_be_null, definition_manager); } -ModifierInstance::ModifierInstance(Modifier const& new_modifier, Date new_expiry_date) - : modifier { &new_modifier }, expiry_date { new_expiry_date } {} +ModifierInstance::ModifierInstance(Modifier const& new_modifier, Date new_expiry_date) : + modifier { &new_modifier }, expiry_date { new_expiry_date } {} diff --git a/src/openvic-simulation/modifier/Modifier.hpp b/src/openvic-simulation/modifier/Modifier.hpp index 61e194928..94cb3455a 100644 --- a/src/openvic-simulation/modifier/Modifier.hpp +++ b/src/openvic-simulation/modifier/Modifier.hpp @@ -18,8 +18,23 @@ namespace OpenVic { friend struct LeaderTraitManager; enum struct modifier_type_t : uint8_t { - EVENT, STATIC, TRIGGERED, CRIME, TERRAIN, CLIMATE, CONTINENT, BUILDING, LEADER, UNIT_TERRAIN, - NATIONAL_VALUE, NATIONAL_FOCUS, PARTY_POLICY, REFORM, TECHNOLOGY, INVENTION, TECH_SCHOOL + EVENT, + STATIC, + TRIGGERED, + CRIME, + TERRAIN, + CLIMATE, + CONTINENT, + BUILDING, + LEADER, + UNIT_TERRAIN, + NATIONAL_VALUE, + NATIONAL_FOCUS, + PARTY_POLICY, + REFORM, + TECHNOLOGY, + INVENTION, + TECH_SCHOOL }; static std::string_view modifier_type_to_string(modifier_type_t type); @@ -55,8 +70,11 @@ namespace OpenVic { public: TriggeredModifier( - std::string_view new_identifier, ModifierValue&& new_values, modifier_type_t new_type, icon_t new_icon, - ConditionScript&& new_trigger + std::string_view new_identifier, + ModifierValue&& new_values, + modifier_type_t new_type, + icon_t new_icon, + ConditionScript&& new_trigger ); TriggeredModifier(TriggeredModifier&&) = default; }; diff --git a/src/openvic-simulation/modifier/ModifierEffect.cpp b/src/openvic-simulation/modifier/ModifierEffect.cpp index 9fd072a69..a4a65385e 100644 --- a/src/openvic-simulation/modifier/ModifierEffect.cpp +++ b/src/openvic-simulation/modifier/ModifierEffect.cpp @@ -41,9 +41,14 @@ memory::string ModifierEffect::make_default_modifier_effect_localisation_key(std } ModifierEffect::ModifierEffect( - std::string_view new_identifier, format_t new_format, target_t new_targets, - std::string_view new_localisation_key, bool new_has_no_effect -) : HasIdentifier { new_identifier }, format { new_format }, targets { new_targets }, - localisation_key { - new_localisation_key.empty() ? make_default_modifier_effect_localisation_key(new_identifier) : new_localisation_key - }, has_no_effect { new_has_no_effect } {} + std::string_view new_identifier, + format_t new_format, + target_t new_targets, + std::string_view new_localisation_key, + bool new_has_no_effect +) : + HasIdentifier { new_identifier }, format { new_format }, targets { new_targets }, + localisation_key { + new_localisation_key.empty() ? make_default_modifier_effect_localisation_key(new_identifier) : new_localisation_key + }, + has_no_effect { new_has_no_effect } {} diff --git a/src/openvic-simulation/modifier/ModifierEffect.hpp b/src/openvic-simulation/modifier/ModifierEffect.hpp index 09bb5c284..771f01f39 100644 --- a/src/openvic-simulation/modifier/ModifierEffect.hpp +++ b/src/openvic-simulation/modifier/ModifierEffect.hpp @@ -21,15 +21,15 @@ namespace OpenVic { enum suffix_t : uint8_t { NO_SUFFIX = 0, - PERCENT = 1, - DAYS = 2, - SPEED = 3 + PERCENT = 1, + DAYS = 2, + SPEED = 3 }; enum class format_t : uint8_t { // 1 and 2 bits - FORMAT_PART_x1 = 0 << FORMAT_MULTIPLIER_BIT_OFFSET, - FORMAT_PART_x10 = 1 << FORMAT_MULTIPLIER_BIT_OFFSET, + FORMAT_PART_x1 = 0 << FORMAT_MULTIPLIER_BIT_OFFSET, + FORMAT_PART_x10 = 1 << FORMAT_MULTIPLIER_BIT_OFFSET, FORMAT_PART_x100 = 2 << FORMAT_MULTIPLIER_BIT_OFFSET, // 4 and 8 bits @@ -39,10 +39,10 @@ namespace OpenVic { FORMAT_PART_3DP = 3 << FORMAT_DECIMAL_PLACES_BIT_OFFSET, // 16 bit and 32 bit - FORMAT_PART_NO_SUFFIX = NO_SUFFIX << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_PERCENT_SUFFIX = PERCENT << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_DAYS_SUFFIX = DAYS << FORMAT_SUFFIX_BIT_OFFSET, - FORMAT_PART_SPEED_SUFFIX = SPEED << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_NO_SUFFIX = NO_SUFFIX << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_PERCENT_SUFFIX = PERCENT << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_DAYS_SUFFIX = DAYS << FORMAT_SUFFIX_BIT_OFFSET, + FORMAT_PART_SPEED_SUFFIX = SPEED << FORMAT_SUFFIX_BIT_OFFSET, // 64 bit FORMAT_PART_POS = 0 << FORMAT_POS_NEG_BIT_OFFSET, @@ -82,10 +82,10 @@ namespace OpenVic { }; enum class target_t : uint8_t { - NO_TARGETS = 0, - COUNTRY = 1 << 0, - PROVINCE = 1 << 1, - UNIT = 1 << 2, + NO_TARGETS = 0, + COUNTRY = 1 << 0, + PROVINCE = 1 << 1, + UNIT = 1 << 2, ALL_TARGETS = (1 << 3) - 1 }; @@ -95,7 +95,8 @@ namespace OpenVic { static memory::string make_default_modifier_effect_localisation_key(std::string_view identifier); - private:; + private: + ; memory::string PROPERTY(localisation_key); // TODO - format/precision, e.g. 80% vs 0.8 vs 0.800, 2 vs 2.0 vs 200% @@ -106,8 +107,11 @@ namespace OpenVic { const target_t targets; ModifierEffect( - std::string_view new_identifier, format_t new_format, target_t new_targets, - std::string_view new_localisation_key, bool new_has_no_effect + std::string_view new_identifier, + format_t new_format, + target_t new_targets, + std::string_view new_localisation_key, + bool new_has_no_effect ); ModifierEffect(ModifierEffect&&) = default; @@ -120,7 +124,8 @@ namespace OpenVic { } }; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; inline constexpr bool ModifierEffect::excludes_targets(target_t targets, target_t excluded_targets) { using enum target_t; diff --git a/src/openvic-simulation/modifier/ModifierEffectCache.cpp b/src/openvic-simulation/modifier/ModifierEffectCache.cpp index dd9655d2d..8ddd4973d 100644 --- a/src/openvic-simulation/modifier/ModifierEffectCache.cpp +++ b/src/openvic-simulation/modifier/ModifierEffectCache.cpp @@ -10,13 +10,17 @@ using namespace OpenVic; -ModifierEffectCache::building_type_effects_t const& ModifierEffectCache::get_building_type_effects(BuildingType const& key) const { +ModifierEffectCache::building_type_effects_t const& ModifierEffectCache::get_building_type_effects( + BuildingType const& key +) const { return building_type_effects[key.index]; } ModifierEffectCache::good_effects_t const& ModifierEffectCache::get_good_effects(GoodDefinition const& key) const { return good_effects[key.index]; } -ModifierEffectCache::regiment_type_effects_t const& ModifierEffectCache::get_regiment_type_effects(RegimentType const& key) const { +ModifierEffectCache::regiment_type_effects_t const& ModifierEffectCache::get_regiment_type_effects( + RegimentType const& key +) const { return regiment_type_effects[key.index]; } ModifierEffectCache::ship_type_effects_t const& ModifierEffectCache::get_ship_type_effects(ShipType const& key) const { @@ -33,4 +37,4 @@ ModifierEffectCache::strata_effects_t const& ModifierEffectCache::get_strata_eff } ModifierEffect const* ModifierEffectCache::get_research_bonus_effects(TechnologyFolder const& key) const { return research_bonus_effects[key.index]; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/modifier/ModifierEffectCache.hpp b/src/openvic-simulation/modifier/ModifierEffectCache.hpp index c055cf958..a6f124044 100644 --- a/src/openvic-simulation/modifier/ModifierEffectCache.hpp +++ b/src/openvic-simulation/modifier/ModifierEffectCache.hpp @@ -339,15 +339,15 @@ namespace OpenVic { constexpr strata_effects_t() {}; }; - - building_type_effects_t const& get_building_type_effects(BuildingType const& key) const; - good_effects_t const& get_good_effects(GoodDefinition const& key) const; - regiment_type_effects_t const& get_regiment_type_effects(RegimentType const& key) const; - ship_type_effects_t const& get_ship_type_effects(ShipType const& key) const; - unit_terrain_effects_t const& get_unit_terrain_effects(TerrainType const& key) const; - ModifierEffect const* get_rebel_org_gain_effects(RebelType const& key) const; - strata_effects_t const& get_strata_effects(Strata const& key) const; - ModifierEffect const* get_research_bonus_effects(TechnologyFolder const& key) const; + + building_type_effects_t const& get_building_type_effects(BuildingType const& key) const; + good_effects_t const& get_good_effects(GoodDefinition const& key) const; + regiment_type_effects_t const& get_regiment_type_effects(RegimentType const& key) const; + ship_type_effects_t const& get_ship_type_effects(ShipType const& key) const; + unit_terrain_effects_t const& get_unit_terrain_effects(TerrainType const& key) const; + ModifierEffect const* get_rebel_org_gain_effects(RebelType const& key) const; + strata_effects_t const& get_strata_effects(Strata const& key) const; + ModifierEffect const* get_research_bonus_effects(TechnologyFolder const& key) const; private: memory::FixedVector SPAN_PROPERTY(strata_effects); @@ -357,14 +357,8 @@ namespace OpenVic { // These values are replaced via moving during data loading. constexpr ModifierEffectCache() : - building_type_effects { create_empty }, - good_effects { create_empty }, - regiment_type_effects { create_empty }, - ship_type_effects { create_empty }, - unit_terrain_effects { create_empty }, - rebel_org_gain_effects { create_empty }, - strata_effects { create_empty }, - research_bonus_effects { create_empty } - {} + building_type_effects { create_empty }, good_effects { create_empty }, regiment_type_effects { create_empty }, + ship_type_effects { create_empty }, unit_terrain_effects { create_empty }, rebel_org_gain_effects { create_empty }, + strata_effects { create_empty }, research_bonus_effects { create_empty } {} }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/modifier/ModifierManager.cpp b/src/openvic-simulation/modifier/ModifierManager.cpp index 5a881cbe3..0a75b4243 100644 --- a/src/openvic-simulation/modifier/ModifierManager.cpp +++ b/src/openvic-simulation/modifier/ModifierManager.cpp @@ -20,13 +20,13 @@ void ModifierManager::lock_all_modifier_except_base_country_effects() { } bool ModifierManager::_register_modifier_effect( - modifier_effect_registry_t& registry, - ModifierEffect::target_t targets, - ModifierEffect const*& effect_cache, - const std::string_view identifier, - const ModifierEffect::format_t format, - const std::string_view localisation_key, - const bool has_no_effect + modifier_effect_registry_t& registry, + ModifierEffect::target_t targets, + ModifierEffect const*& effect_cache, + const std::string_view identifier, + const ModifierEffect::format_t format, + const std::string_view localisation_key, + const bool has_no_effect ) { using enum ModifierEffect::target_t; @@ -42,24 +42,21 @@ bool ModifierManager::_register_modifier_effect( if (!is_power_of_two(static_cast(targets))) { spdlog::error_s( - "Invalid targets for modifier effect \"{}\" - {} (can only contain one target)", - identifier, ModifierEffect::target_to_string(targets) + "Invalid targets for modifier effect \"{}\" - {} (can only contain one target)", + identifier, + ModifierEffect::target_to_string(targets) ); return false; } if (effect_cache != nullptr) { spdlog::error_s( - "Cache variable for modifier effect \"{}\" is already filled with modifier effect \"{}\"", - identifier, *effect_cache + "Cache variable for modifier effect \"{}\" is already filled with modifier effect \"{}\"", identifier, *effect_cache ); return false; } - const bool ret = registry.emplace_item( - identifier, - identifier, format, targets, localisation_key, has_no_effect - ); + const bool ret = registry.emplace_item(identifier, identifier, format, targets, localisation_key, has_no_effect); if (ret) { effect_cache = ®istry.back(); @@ -69,23 +66,23 @@ bool ModifierManager::_register_modifier_effect( } #define REGISTER_MODIFIER_EFFECT(MAPPING_TYPE, TARGETS) \ -bool ModifierManager::register_##MAPPING_TYPE##_modifier_effect( \ - ModifierEffect const*& effect_cache, \ - const std::string_view identifier, \ - const ModifierEffect::format_t format, \ - const std::string_view localisation_key, \ - const bool has_no_effect \ -) { \ - return _register_modifier_effect( \ - MAPPING_TYPE##_modifier_effects, \ - TARGETS, \ - effect_cache, \ - std::move(identifier), \ - format, \ - localisation_key, \ - has_no_effect \ - ); \ -} + bool ModifierManager::register_##MAPPING_TYPE##_modifier_effect( \ + ModifierEffect const*& effect_cache, \ + const std::string_view identifier, \ + const ModifierEffect::format_t format, \ + const std::string_view localisation_key, \ + const bool has_no_effect \ + ) { \ + return _register_modifier_effect( \ + MAPPING_TYPE##_modifier_effects, \ + TARGETS, \ + effect_cache, \ + std::move(identifier), \ + format, \ + localisation_key, \ + has_no_effect \ + ); \ + } REGISTER_MODIFIER_EFFECT(leader, UNIT) REGISTER_MODIFIER_EFFECT(unit_terrain, UNIT) @@ -105,538 +102,616 @@ bool ModifierManager::setup_modifier_effects() { /* Tech/inventions only */ ret &= register_technology_modifier_effect(modifier_effect_cache.tax_eff, "tax_eff", FORMAT_x1_2DP_PC_POS, "TECH_TAX_EFF"); ret &= register_technology_modifier_effect( - modifier_effect_cache.max_national_focus, "max_national_focus", FORMAT_x1_0DP_POS, "TECH_MAX_FOCUS" + modifier_effect_cache.max_national_focus, "max_national_focus", FORMAT_x1_0DP_POS, "TECH_MAX_FOCUS" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.dig_in_cap, "dig_in_cap", FORMAT_x1_0DP_POS, "DIGIN_FROM_TECH" + modifier_effect_cache.dig_in_cap, "dig_in_cap", FORMAT_x1_0DP_POS, "DIGIN_FROM_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.land_attrition, "land_attrition", FORMAT_x100_2DP_PC_NEG, "LAND_ATTRITION_TECH" + modifier_effect_cache.land_attrition, "land_attrition", FORMAT_x100_2DP_PC_NEG, "LAND_ATTRITION_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.naval_attrition, "naval_attrition", FORMAT_x100_2DP_PC_NEG, "NAVAL_ATTRITION_TECH" + modifier_effect_cache.naval_attrition, "naval_attrition", FORMAT_x100_2DP_PC_NEG, "NAVAL_ATTRITION_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.supply_range, "supply_range", FORMAT_x100_2DP_PC_POS, "SUPPLY_RANGE_TECH" + modifier_effect_cache.supply_range, "supply_range", FORMAT_x100_2DP_PC_POS, "SUPPLY_RANGE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.supply_limit_global_percentage_change, "supply_limit", FORMAT_x100_2DP_PC_POS, - "SUPPLY_LIMIT_TECH" + modifier_effect_cache.supply_limit_global_percentage_change, "supply_limit", FORMAT_x100_2DP_PC_POS, "SUPPLY_LIMIT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.morale_global, "morale", FORMAT_x100_2DP_PC_POS, "MORALE_TECH" + modifier_effect_cache.morale_global, "morale", FORMAT_x100_2DP_PC_POS, "MORALE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.reinforce_rate, "reinforce_rate", FORMAT_x100_2DP_PC_POS, "REINFORCE_TECH" + modifier_effect_cache.reinforce_rate, "reinforce_rate", FORMAT_x100_2DP_PC_POS, "REINFORCE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.soldier_to_pop_loss, "soldier_to_pop_loss", FORMAT_x100_2DP_PC_POS, "SOLDIER_TO_POP_LOSS_TECH" + modifier_effect_cache.soldier_to_pop_loss, "soldier_to_pop_loss", FORMAT_x100_2DP_PC_POS, "SOLDIER_TO_POP_LOSS_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.regular_experience_level, "regular_experience_level", FORMAT_x1_2DP_POS, "REGULAR_EXP_TECH" + modifier_effect_cache.regular_experience_level, "regular_experience_level", FORMAT_x1_2DP_POS, "REGULAR_EXP_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.mobilisation_size_tech, "mobilisation_size", FORMAT_x100_2DP_PC_POS, "MOB_SIZE_TECH" + modifier_effect_cache.mobilisation_size_tech, "mobilisation_size", FORMAT_x100_2DP_PC_POS, "MOB_SIZE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.mobilisation_economy_impact_tech, "mobilisation_economy_impact", FORMAT_x100_2DP_PC_NEG, - "MOB_IMPACT_TECH" + modifier_effect_cache.mobilisation_economy_impact_tech, + "mobilisation_economy_impact", + FORMAT_x100_2DP_PC_NEG, + "MOB_IMPACT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.colonial_life_rating, "colonial_life_rating", FORMAT_x1_2DP_PC_NEG, "COLONIAL_LIFE_TECH" + modifier_effect_cache.colonial_life_rating, "colonial_life_rating", FORMAT_x1_2DP_PC_NEG, "COLONIAL_LIFE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.cb_creation_speed, "cb_creation_speed", FORMAT_x1_2DP_PC_POS, "CB_MANUFACTURE_TECH" + modifier_effect_cache.cb_creation_speed, "cb_creation_speed", FORMAT_x1_2DP_PC_POS, "CB_MANUFACTURE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.colonial_points, "colonial_points", FORMAT_x1_0DP_POS, "COLONIAL_POINTS_TECH" + modifier_effect_cache.colonial_points, "colonial_points", FORMAT_x1_0DP_POS, "COLONIAL_POINTS_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.administrative_efficiency, "administrative_efficiency", FORMAT_x100_2DP_PC_POS, "ADM_EFF_TECH" + modifier_effect_cache.administrative_efficiency, "administrative_efficiency", FORMAT_x100_2DP_PC_POS, "ADM_EFF_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.education_efficiency, "education_efficiency", FORMAT_x100_2DP_PC_POS, "EDU_EFF_TECH" + modifier_effect_cache.education_efficiency, "education_efficiency", FORMAT_x100_2DP_PC_POS, "EDU_EFF_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.loan_interest_base, "loan_interest", FORMAT_x100_2DP_PC_NEG, "LOAN_INTEREST_TECH" + modifier_effect_cache.loan_interest_base, "loan_interest", FORMAT_x100_2DP_PC_NEG, "LOAN_INTEREST_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.war_exhaustion_from_battles, "war_exhaustion", FORMAT_x100_2DP_PC_NEG, "WAR_EXHAUST_BATTLES" + modifier_effect_cache.war_exhaustion_from_battles, "war_exhaustion", FORMAT_x100_2DP_PC_NEG, "WAR_EXHAUST_BATTLES" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.military_tactics, "military_tactics", FORMAT_x100_2DP_PC_POS, "MIL_TACTICS_TECH" + modifier_effect_cache.military_tactics, "military_tactics", FORMAT_x100_2DP_PC_POS, "MIL_TACTICS_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.prestige_gain_multiplier, "prestige", FORMAT_x100_1DP_PC_POS, "PRESTIGE_MODIFIER_TECH" + modifier_effect_cache.prestige_gain_multiplier, "prestige", FORMAT_x100_1DP_PC_POS, "PRESTIGE_MODIFIER_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.colonial_prestige, "colonial_prestige", FORMAT_x100_1DP_PC_POS, "COLONIAL_PRESTIGE_MODIFIER_TECH" + modifier_effect_cache.colonial_prestige, "colonial_prestige", FORMAT_x100_1DP_PC_POS, "COLONIAL_PRESTIGE_MODIFIER_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.permanent_prestige, "permanent_prestige", FORMAT_x1_1DP_POS, "PERMANENT_PRESTIGE_TECH" + modifier_effect_cache.permanent_prestige, "permanent_prestige", FORMAT_x1_1DP_POS, "PERMANENT_PRESTIGE_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.diplomatic_points, "diplomatic_points", FORMAT_x100_1DP_PC_POS, "DIPLOMATIC_POINTS_TECH" + modifier_effect_cache.diplomatic_points, "diplomatic_points", FORMAT_x100_1DP_PC_POS, "DIPLOMATIC_POINTS_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.influence, "influence", FORMAT_x100_1DP_PC_POS, "TECH_GP_INFLUENCE" + modifier_effect_cache.influence, "influence", FORMAT_x100_1DP_PC_POS, "TECH_GP_INFLUENCE" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.pop_growth, "pop_growth", FORMAT_x100_2DP_PC_POS, "TECH_POP_GROWTH" + modifier_effect_cache.pop_growth, "pop_growth", FORMAT_x100_2DP_PC_POS, "TECH_POP_GROWTH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.plurality, "plurality", FORMAT_x100_2DP_PC_POS, "TECH_PLURALITY" + modifier_effect_cache.plurality, "plurality", FORMAT_x100_2DP_PC_POS, "TECH_PLURALITY" ); // When applied to countries (army tech/inventions), combat_width is an additive integer value. ret &= register_technology_modifier_effect( - modifier_effect_cache.combat_width_additive, "combat_width", FORMAT_x1_1DP_NEG, "COMBAT_WIDTH_TECH" + modifier_effect_cache.combat_width_additive, "combat_width", FORMAT_x1_1DP_NEG, "COMBAT_WIDTH_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.colonial_migration, "colonial_migration", FORMAT_x100_1DP_PC_POS, "COLONIAL_MIGRATION_TECH" + modifier_effect_cache.colonial_migration, "colonial_migration", FORMAT_x100_1DP_PC_POS, "COLONIAL_MIGRATION_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.separatism, "seperatism", FORMAT_x100_1DP_PC_NEG, "SEPARATISM_TECH" // paradox typo + modifier_effect_cache.separatism, "seperatism", FORMAT_x100_1DP_PC_NEG, "SEPARATISM_TECH" // paradox typo ); ret &= register_technology_modifier_effect( - modifier_effect_cache.increase_research, "increase_research", FORMAT_x100_1DP_PC_POS, "INC_RES_TECH" + modifier_effect_cache.increase_research, "increase_research", FORMAT_x100_1DP_PC_POS, "INC_RES_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.suppression_points_modifier_tech, "suppression_points_modifier", FORMAT_x100_1DP_PC_POS, - "SUPPRESSION_TECH" + modifier_effect_cache.suppression_points_modifier_tech, + "suppression_points_modifier", + FORMAT_x100_1DP_PC_POS, + "SUPPRESSION_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.factory_cost_tech, "factory_cost", FORMAT_x100_2DP_PC_NEG, "TECH_FACTORY" + modifier_effect_cache.factory_cost_tech, "factory_cost", FORMAT_x100_2DP_PC_NEG, "TECH_FACTORY" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.rgo_output_tech, "rgo_output", FORMAT_x100_1DP_PC_POS, "RGO_OUTPUT_TECH" + modifier_effect_cache.rgo_output_tech, "rgo_output", FORMAT_x100_1DP_PC_POS, "RGO_OUTPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.rgo_throughput_tech, "rgo_throughput", FORMAT_x100_1DP_PC_POS, "RGO_THROUGHPUT_TECH" + modifier_effect_cache.rgo_throughput_tech, "rgo_throughput", FORMAT_x100_1DP_PC_POS, "RGO_THROUGHPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.factory_input_tech, "factory_input", FORMAT_x100_1DP_PC_NEG, "FACTORY_INPUT_TECH" + modifier_effect_cache.factory_input_tech, "factory_input", FORMAT_x100_1DP_PC_NEG, "FACTORY_INPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.factory_output_tech, "factory_output", FORMAT_x100_1DP_PC_POS, "FACTORY_OUTPUT_TECH" + modifier_effect_cache.factory_output_tech, "factory_output", FORMAT_x100_1DP_PC_POS, "FACTORY_OUTPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.factory_throughput_tech, "factory_throughput", FORMAT_x100_1DP_PC_POS, - "FACTORY_THROUGHPUT_TECH" + modifier_effect_cache.factory_throughput_tech, "factory_throughput", FORMAT_x100_1DP_PC_POS, "FACTORY_THROUGHPUT_TECH" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.artisan_input_tech, "artisan_input", FORMAT_x100_1DP_PC_NEG, "ARTISAN_INPUT_TECH", has_no_effect + modifier_effect_cache.artisan_input_tech, "artisan_input", FORMAT_x100_1DP_PC_NEG, "ARTISAN_INPUT_TECH", has_no_effect ); ret &= register_technology_modifier_effect( - modifier_effect_cache.artisan_output_tech, "artisan_output", FORMAT_x100_1DP_PC_POS, "ARTISAN_OUTPUT_TECH", - has_no_effect + modifier_effect_cache.artisan_output_tech, + "artisan_output", + FORMAT_x100_1DP_PC_POS, + "ARTISAN_OUTPUT_TECH", + has_no_effect ); ret &= register_technology_modifier_effect( - modifier_effect_cache.artisan_throughput_tech, "artisan_throughput", FORMAT_x100_1DP_PC_POS, "ARTISAN_THROUGHPUT_TECH", - has_no_effect + modifier_effect_cache.artisan_throughput_tech, + "artisan_throughput", + FORMAT_x100_1DP_PC_POS, + "ARTISAN_THROUGHPUT_TECH", + has_no_effect ); ret &= register_technology_modifier_effect( - modifier_effect_cache.mine_rgo_throughput_and_output, "mine_rgo_eff", FORMAT_x100_2DP_PC_POS, "TECH_MINE_OUTPUT" + modifier_effect_cache.mine_rgo_throughput_and_output, "mine_rgo_eff", FORMAT_x100_2DP_PC_POS, "TECH_MINE_OUTPUT" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.farm_rgo_throughput_and_output, "farm_rgo_eff", FORMAT_x100_2DP_PC_POS, "TECH_FARM_OUTPUT" + modifier_effect_cache.farm_rgo_throughput_and_output, "farm_rgo_eff", FORMAT_x100_2DP_PC_POS, "TECH_FARM_OUTPUT" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.mine_rgo_size_global, "mine_rgo_size", FORMAT_x100_2DP_PC_POS, "TECH_MINE_SIZE" + modifier_effect_cache.mine_rgo_size_global, "mine_rgo_size", FORMAT_x100_2DP_PC_POS, "TECH_MINE_SIZE" ); ret &= register_technology_modifier_effect( - modifier_effect_cache.farm_rgo_size_global, "farm_rgo_size", FORMAT_x100_2DP_PC_POS, "TECH_FARM_SIZE" + modifier_effect_cache.farm_rgo_size_global, "farm_rgo_size", FORMAT_x100_2DP_PC_POS, "TECH_FARM_SIZE" ); // Only for inventions, special tooltip (amount changes based on number of times discovered) ret &= register_technology_modifier_effect( - modifier_effect_cache.shared_prestige, "shared_prestige", FORMAT_x1_1DP_POS, "SHARED_PRESTIGE_TECH" + modifier_effect_cache.shared_prestige, "shared_prestige", FORMAT_x1_1DP_POS, "SHARED_PRESTIGE_TECH" ); /* Country Modifier Effects */ ret &= register_base_country_modifier_effect( - modifier_effect_cache.supply_limit_global_base, "supply_limit", FORMAT_x1_2DP_POS, "SUPPLY_LIMIT" + modifier_effect_cache.supply_limit_global_base, "supply_limit", FORMAT_x1_2DP_POS, "SUPPLY_LIMIT" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.war_exhaustion_monthly, "war_exhaustion", FORMAT_x1_2DP_NEG, "WAR_EXHAUSTION" + modifier_effect_cache.war_exhaustion_monthly, "war_exhaustion", FORMAT_x1_2DP_NEG, "WAR_EXHAUSTION" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.max_war_exhaustion, "max_war_exhaustion", FORMAT_x1_2DP_NEG, "MAX_WAR_EXHAUSTION" + modifier_effect_cache.max_war_exhaustion, "max_war_exhaustion", FORMAT_x1_2DP_NEG, "MAX_WAR_EXHAUSTION" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.leadership, "leadership", FORMAT_x1_2DP_POS, "LEADERSHIP" + modifier_effect_cache.leadership, "leadership", FORMAT_x1_2DP_POS, "LEADERSHIP" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.leadership_modifier, "leadership_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("global_leadership_modifier") + modifier_effect_cache.leadership_modifier, + "leadership_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("global_leadership_modifier") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.supply_consumption, "supply_consumption", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.supply_consumption, "supply_consumption", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.unit_recruitment_time, "unit_recruitment_time", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.unit_recruitment_time, "unit_recruitment_time", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect(modifier_effect_cache.org_regain, "org_regain", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.reinforce_speed, "reinforce_speed", FORMAT_x100_1DP_PC_POS - ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.land_organisation, "land_organisation", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.reinforce_speed, "reinforce_speed", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.naval_organisation, "naval_organisation", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.land_organisation, "land_organisation", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.research_points, "research_points", FORMAT_x1_2DP_POS + modifier_effect_cache.naval_organisation, "naval_organisation", FORMAT_x100_1DP_PC_POS ); + ret &= register_base_country_modifier_effect(modifier_effect_cache.research_points, "research_points", FORMAT_x1_2DP_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.research_points_modifier, "research_points_modifier", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.research_points_modifier, "research_points_modifier", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.research_points_on_conquer, "research_points_on_conquer", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.research_points_on_conquer, "research_points_on_conquer", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.import_cost, "import_cost", FORMAT_x100_1DP_PC_NEG, {}, has_no_effect + modifier_effect_cache.import_cost, "import_cost", FORMAT_x100_1DP_PC_NEG, {}, has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.loan_interest_foreign, "loan_interest", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.loan_interest_foreign, "loan_interest", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.tax_efficiency, "tax_efficiency", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.tax_efficiency, "tax_efficiency", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect(modifier_effect_cache.min_tax, "min_tax", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect(modifier_effect_cache.max_tax, "max_tax", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.min_military_spending, "min_military_spending", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.min_military_spending, "min_military_spending", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.max_military_spending, "max_military_spending", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.max_military_spending, "max_military_spending", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.min_social_spending, "min_social_spending", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.min_social_spending, "min_social_spending", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.max_social_spending, "max_social_spending", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.max_social_spending, "max_social_spending", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_owner_cost, "factory_owner_cost", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.factory_owner_cost, "factory_owner_cost", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect(modifier_effect_cache.min_tariff, "min_tariff", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect(modifier_effect_cache.max_tariff, "max_tariff", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.ruling_party_support, "ruling_party_support", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.ruling_party_support, "ruling_party_support", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.minimum_wage, "minimum_wage", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("minimun_wage") // paradox typo + modifier_effect_cache.minimum_wage, + "minimum_wage", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("minimun_wage") // paradox typo ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_maintenance, "factory_maintenance", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.factory_maintenance, "factory_maintenance", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.unemployment_benefit, "unemployment_benefit", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.unemployment_benefit, "unemployment_benefit", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect(modifier_effect_cache.pension_level, "pension_level", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.global_population_growth, "global_population_growth", FORMAT_x10_2DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("population_growth") + modifier_effect_cache.global_population_growth, + "global_population_growth", + FORMAT_x10_2DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("population_growth") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_input_country, "factory_input", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.factory_input_country, "factory_input", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_output_country, "factory_output", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.factory_output_country, "factory_output", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_throughput_country, "factory_throughput", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.factory_throughput_country, "factory_throughput", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.rgo_output_country, "rgo_output", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.rgo_output_country, "rgo_output", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.rgo_throughput_country, "rgo_throughput", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.rgo_throughput_country, "rgo_throughput", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.artisan_input_country, "artisan_input", FORMAT_x100_1DP_PC_POS, {}, has_no_effect + modifier_effect_cache.artisan_input_country, "artisan_input", FORMAT_x100_1DP_PC_POS, {}, has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.artisan_output_country, "artisan_output", FORMAT_x100_1DP_PC_POS, {}, has_no_effect + modifier_effect_cache.artisan_output_country, "artisan_output", FORMAT_x100_1DP_PC_POS, {}, has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.artisan_throughput_country, "artisan_throughput", FORMAT_x100_1DP_PC_POS, {}, has_no_effect + modifier_effect_cache.artisan_throughput_country, "artisan_throughput", FORMAT_x100_1DP_PC_POS, {}, has_no_effect ); ret &= register_base_country_modifier_effect(modifier_effect_cache.goods_demand, "goods_demand", FORMAT_x100_1DP_PC_POS); ret &= register_base_country_modifier_effect(modifier_effect_cache.badboy, "badboy", FORMAT_x1_2DP_NEG); ret &= register_base_country_modifier_effect( - modifier_effect_cache.global_assimilation_rate, "global_assimilation_rate", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("assimilation_rate") + modifier_effect_cache.global_assimilation_rate, + "global_assimilation_rate", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("assimilation_rate") ); + ret &= register_base_country_modifier_effect(modifier_effect_cache.prestige_monthly_gain, "prestige", FORMAT_x1_3DP_POS); ret &= register_base_country_modifier_effect( - modifier_effect_cache.prestige_monthly_gain, "prestige", FORMAT_x1_3DP_POS + modifier_effect_cache.factory_cost_country, "factory_cost", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.factory_cost_country, "factory_cost", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.farm_rgo_output_global, "farm_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_FARM_EFFICIENCY" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.farm_rgo_output_global, "farm_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_FARM_EFFICIENCY" + modifier_effect_cache.mine_rgo_output_global, + "mine_rgo_eff", + FORMAT_x100_1DP_PC_POS, + "MODIFIER_MINE_EFFICIENCY" // not sure about this one ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mine_rgo_output_global, "mine_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_MINE_EFFICIENCY" //not sure about this one + modifier_effect_cache.farm_rgo_size_fake, + "farm_rgo_size", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("farm_size"), + has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.farm_rgo_size_fake, "farm_rgo_size", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("farm_size"), has_no_effect + modifier_effect_cache.mine_rgo_size_fake, + "mine_rgo_size", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("mine_size"), + has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mine_rgo_size_fake, "mine_rgo_size", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("mine_size"), has_no_effect + modifier_effect_cache.issue_change_speed, "issue_change_speed", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.issue_change_speed, "issue_change_speed", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.social_reform_desire, "social_reform_desire", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.social_reform_desire, "social_reform_desire", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.political_reform_desire, "political_reform_desire", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.political_reform_desire, "political_reform_desire", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.literacy_con_impact, "literacy_con_impact", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.literacy_con_impact, "literacy_con_impact", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.global_immigrant_attract, + "global_immigrant_attract", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("immigant_attract") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.global_immigrant_attract, "global_immigrant_attract", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("immigant_attract") + modifier_effect_cache.poor_savings_modifier, "poor_savings_modifier", FORMAT_x100_1DP_PC_POS, {}, has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.poor_savings_modifier, "poor_savings_modifier", FORMAT_x100_1DP_PC_POS, {}, has_no_effect + modifier_effect_cache.influence_modifier, + "influence_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("greatpower_influence_gain") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.influence_modifier, "influence_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("greatpower_influence_gain") + modifier_effect_cache.diplomatic_points_modifier, + "diplomatic_points_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("diplopoints_gain") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.diplomatic_points_modifier, "diplomatic_points_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("diplopoints_gain") + modifier_effect_cache.mobilisation_size_country, "mobilisation_size", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mobilisation_size_country, "mobilisation_size", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.mobilisation_economy_impact_country, "mobilisation_economy_impact", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mobilisation_economy_impact_country, "mobilisation_economy_impact", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.global_pop_militancy_modifier, "global_pop_militancy_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.global_pop_militancy_modifier, "global_pop_militancy_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.global_pop_consciousness_modifier, "global_pop_consciousness_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.global_pop_consciousness_modifier, "global_pop_consciousness_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.core_pop_militancy_modifier, "core_pop_militancy_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.core_pop_militancy_modifier, "core_pop_militancy_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.core_pop_consciousness_modifier, "core_pop_consciousness_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.core_pop_consciousness_modifier, "core_pop_consciousness_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.non_accepted_pop_militancy_modifier, "non_accepted_pop_militancy_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.non_accepted_pop_militancy_modifier, "non_accepted_pop_militancy_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.non_accepted_pop_consciousness_modifier, + "non_accepted_pop_consciousness_modifier", + FORMAT_x1_2DP_NEG ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.non_accepted_pop_consciousness_modifier, "non_accepted_pop_consciousness_modifier", - FORMAT_x1_2DP_NEG + modifier_effect_cache.cb_generation_speed_modifier, "cb_generation_speed_modifier", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.cb_generation_speed_modifier, "cb_generation_speed_modifier", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.mobilization_impact, "mobilization_impact", FORMAT_x100_1DP_PC_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.mobilization_impact, "mobilization_impact", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.suppression_points_modifier_country, + "suppression_points_modifier", + FORMAT_x100_1DP_PC_POS, + "MODIFIER_SUPPRESSION_POINT_GAIN" ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.suppression_points_modifier_country, "suppression_points_modifier", FORMAT_x100_1DP_PC_POS, - "MODIFIER_SUPPRESSION_POINT_GAIN" + modifier_effect_cache.education_efficiency_modifier, + "education_efficiency_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("education_efficiency") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.education_efficiency_modifier, "education_efficiency_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("education_efficiency") + modifier_effect_cache.civilization_progress_modifier, + "civilization_progress_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("civilization_progress") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.civilization_progress_modifier, "civilization_progress_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("civilization_progress") + modifier_effect_cache.administrative_efficiency_modifier, + "administrative_efficiency_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("administrative_efficiency") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.administrative_efficiency_modifier, "administrative_efficiency_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("administrative_efficiency") + modifier_effect_cache.land_unit_start_experience, "land_unit_start_experience", FORMAT_x1_2DP_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.land_unit_start_experience, "land_unit_start_experience", FORMAT_x1_2DP_POS + modifier_effect_cache.naval_unit_start_experience, "naval_unit_start_experience", FORMAT_x1_2DP_POS ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.naval_unit_start_experience, "naval_unit_start_experience", FORMAT_x1_2DP_POS + modifier_effect_cache.naval_attack_modifier, + "naval_attack_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("naval_attack") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.naval_attack_modifier, "naval_attack_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("naval_attack") + modifier_effect_cache.naval_defense_modifier, + "naval_defense_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("naval_defense") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.naval_defense_modifier, "naval_defense_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("naval_defense") + modifier_effect_cache.land_attack_modifier, + "land_attack_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("land_attack") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.land_attack_modifier, "land_attack_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("land_attack") + modifier_effect_cache.land_defense_modifier, + "land_defense_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("land_defense") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.land_defense_modifier, "land_defense_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("land_defense") + modifier_effect_cache.tariff_efficiency_modifier, + "tariff_efficiency_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("tariff_efficiency") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.tariff_efficiency_modifier, "tariff_efficiency_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("tariff_efficiency") + modifier_effect_cache.max_loan_modifier, + "max_loan_modifier", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("max_loan_amount") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.max_loan_modifier, "max_loan_modifier", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("max_loan_amount") + modifier_effect_cache.unciv_economic_modifier, + "unciv_economic_modifier", + FORMAT_x100_1DP_PC_NEG, + ModifierEffect::make_default_modifier_effect_localisation_key("unciv_economic"), + has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.unciv_economic_modifier, "unciv_economic_modifier", FORMAT_x100_1DP_PC_NEG, - ModifierEffect::make_default_modifier_effect_localisation_key("unciv_economic"), has_no_effect + modifier_effect_cache.unciv_military_modifier, + "unciv_military_modifier", + FORMAT_x100_1DP_PC_NEG, + ModifierEffect::make_default_modifier_effect_localisation_key("unciv_military"), + has_no_effect ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.unciv_military_modifier, "unciv_military_modifier", FORMAT_x100_1DP_PC_NEG, - ModifierEffect::make_default_modifier_effect_localisation_key("unciv_military"), has_no_effect + modifier_effect_cache.self_unciv_economic_modifier, + "self_unciv_economic_modifier", + FORMAT_x100_1DP_PC_NEG, + ModifierEffect::make_default_modifier_effect_localisation_key("self_unciv_economic") ); ret &= register_base_country_modifier_effect( - modifier_effect_cache.self_unciv_economic_modifier, "self_unciv_economic_modifier", FORMAT_x100_1DP_PC_NEG, - ModifierEffect::make_default_modifier_effect_localisation_key("self_unciv_economic") - ); - ret &= register_base_country_modifier_effect( - modifier_effect_cache.self_unciv_military_modifier, "self_unciv_military_modifier", FORMAT_x100_1DP_PC_NEG, - ModifierEffect::make_default_modifier_effect_localisation_key("self_unciv_military") + modifier_effect_cache.self_unciv_military_modifier, + "self_unciv_military_modifier", + FORMAT_x100_1DP_PC_NEG, + ModifierEffect::make_default_modifier_effect_localisation_key("self_unciv_military") ); /* Province Modifier Effects */ // TODO - how to know when this is local province effect vs global country effect? (both can come from event modifiers) ret &= register_base_province_modifier_effect( - modifier_effect_cache.supply_limit_local_base, "supply_limit", FORMAT_x1_2DP_POS, "SUPPLY_LIMIT" + modifier_effect_cache.supply_limit_local_base, "supply_limit", FORMAT_x1_2DP_POS, "SUPPLY_LIMIT" ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.max_attrition, "max_attrition", FORMAT_x1_2DP_NEG, "MAX_ATTRITION" + modifier_effect_cache.max_attrition, "max_attrition", FORMAT_x1_2DP_NEG, "MAX_ATTRITION" ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_ruling_party_support, "local_ruling_party_support", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("ruling_party_support") + modifier_effect_cache.local_ruling_party_support, + "local_ruling_party_support", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("ruling_party_support") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.population_growth, "population_growth", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.population_growth, "population_growth", FORMAT_x100_1DP_PC_POS ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_factory_input, "local_factory_input", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("factory_input") + modifier_effect_cache.local_factory_input, + "local_factory_input", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("factory_input") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_factory_output, "local_factory_output", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("factory_output") + modifier_effect_cache.local_factory_output, + "local_factory_output", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("factory_output") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_factory_throughput, "local_factory_throughput", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("factory_throughput") + modifier_effect_cache.local_factory_throughput, + "local_factory_throughput", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("factory_throughput") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_rgo_output, "local_rgo_output", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("rgo_output") + modifier_effect_cache.local_rgo_output, + "local_rgo_output", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("rgo_output") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_rgo_throughput, "local_rgo_throughput", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("rgo_throughput") + modifier_effect_cache.local_rgo_throughput, + "local_rgo_throughput", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("rgo_throughput") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_artisan_input, "local_artisan_input", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_input"), - has_no_effect + modifier_effect_cache.local_artisan_input, + "local_artisan_input", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_input"), + has_no_effect ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_artisan_output, "local_artisan_output", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_output"), - has_no_effect + modifier_effect_cache.local_artisan_output, + "local_artisan_output", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_output"), + has_no_effect ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_artisan_throughput, "local_artisan_throughput", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("artisan_throughput"), - has_no_effect + modifier_effect_cache.local_artisan_throughput, + "local_artisan_throughput", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("artisan_throughput"), + has_no_effect ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.number_of_voters, "number_of_voters", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.number_of_voters, "number_of_voters", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.assimilation_rate, "assimilation_rate", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.assimilation_rate, "assimilation_rate", FORMAT_x100_1DP_PC_POS ); ret &= register_base_province_modifier_effect(modifier_effect_cache.life_rating, "life_rating", FORMAT_x100_1DP_PC_POS); ret &= register_base_province_modifier_effect( - modifier_effect_cache.farm_rgo_output_local, "farm_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_FARM_EFFICIENCY" + modifier_effect_cache.farm_rgo_output_local, "farm_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_FARM_EFFICIENCY" ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.mine_rgo_output_local, "mine_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_MINE_EFFICIENCY" + modifier_effect_cache.mine_rgo_output_local, "mine_rgo_eff", FORMAT_x100_1DP_PC_POS, "MODIFIER_MINE_EFFICIENCY" ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.farm_rgo_size_local, "farm_rgo_size", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("farm_size") + modifier_effect_cache.farm_rgo_size_local, + "farm_rgo_size", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("farm_size") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.mine_rgo_size_local, "mine_rgo_size", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("mine_size") + modifier_effect_cache.mine_rgo_size_local, + "mine_rgo_size", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("mine_size") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.pop_militancy_modifier, "pop_militancy_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.pop_militancy_modifier, "pop_militancy_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.pop_consciousness_modifier, "pop_consciousness_modifier", FORMAT_x1_2DP_NEG + modifier_effect_cache.pop_consciousness_modifier, "pop_consciousness_modifier", FORMAT_x1_2DP_NEG ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.boost_strongest_party, "boost_strongest_party", FORMAT_x100_1DP_PC_NEG, {}, has_no_effect + modifier_effect_cache.boost_strongest_party, "boost_strongest_party", FORMAT_x100_1DP_PC_NEG, {}, has_no_effect ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.immigrant_attract, "immigrant_attract", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("immigant_attract") + modifier_effect_cache.immigrant_attract, + "immigrant_attract", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("immigant_attract") ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.immigrant_push, "immigrant_push", FORMAT_x100_1DP_PC_POS, - ModifierEffect::make_default_modifier_effect_localisation_key("immigant_push") + modifier_effect_cache.immigrant_push, + "immigrant_push", + FORMAT_x100_1DP_PC_POS, + ModifierEffect::make_default_modifier_effect_localisation_key("immigant_push") ); + ret &= register_base_province_modifier_effect(modifier_effect_cache.local_repair, "local_repair", FORMAT_x100_1DP_PC_POS); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_repair, "local_repair", FORMAT_x100_1DP_PC_POS + modifier_effect_cache.local_ship_build, "local_ship_build", FORMAT_x100_1DP_PC_NEG ); ret &= register_base_province_modifier_effect( - modifier_effect_cache.local_ship_build, "local_ship_build", FORMAT_x100_1DP_PC_NEG - ); - ret &= register_base_province_modifier_effect( - modifier_effect_cache.movement_cost_percentage_change, "movement_cost", FORMAT_x100_1DP_PC_NEG + modifier_effect_cache.movement_cost_percentage_change, "movement_cost", FORMAT_x100_1DP_PC_NEG ); /* Terrain Modifier Effects */ - ret &= register_terrain_modifier_effect( - modifier_effect_cache.attrition_local, "attrition", FORMAT_x1_2DP_NEG, "ATTRITION" - ); + ret &= register_terrain_modifier_effect(modifier_effect_cache.attrition_local, "attrition", FORMAT_x1_2DP_NEG, "ATTRITION"); /* Military Modifier Effects */ ret &= register_leader_modifier_effect(modifier_effect_cache.attack_leader, "attack", FORMAT_x1_2DP_POS, "TRAIT_ATTACK"); + ret &= register_leader_modifier_effect(modifier_effect_cache.defence_leader, "defence", FORMAT_x1_2DP_POS, "TRAIT_DEFEND"); ret &= register_leader_modifier_effect( - modifier_effect_cache.defence_leader, "defence", FORMAT_x1_2DP_POS, "TRAIT_DEFEND" + modifier_effect_cache.morale_leader, "morale", FORMAT_x100_1DP_PC_POS, "TRAIT_MORALE" ); ret &= register_leader_modifier_effect( - modifier_effect_cache.morale_leader, "morale", FORMAT_x100_1DP_PC_POS, "TRAIT_MORALE" + modifier_effect_cache.organisation, "organisation", FORMAT_x100_1DP_PC_POS, "TRAIT_ORGANISATION" ); ret &= register_leader_modifier_effect( - modifier_effect_cache.organisation, "organisation", FORMAT_x100_1DP_PC_POS, "TRAIT_ORGANISATION" - ); - ret &= register_leader_modifier_effect( - modifier_effect_cache.reconnaissance, "reconnaissance", FORMAT_x100_1DP_PC_POS, "TRAIT_RECONAISSANCE" // paradox typo + modifier_effect_cache.reconnaissance, "reconnaissance", FORMAT_x100_1DP_PC_POS, "TRAIT_RECONAISSANCE" // paradox typo ); ret &= register_leader_modifier_effect(modifier_effect_cache.speed, "speed", FORMAT_x100_1DP_PC_POS, "TRAIT_SPEED"); ret &= register_leader_modifier_effect( - modifier_effect_cache.attrition_leader, "attrition", FORMAT_x100_1DP_PC_NEG, "TRAIT_ATTRITION" + modifier_effect_cache.attrition_leader, "attrition", FORMAT_x100_1DP_PC_NEG, "TRAIT_ATTRITION" ); ret &= register_leader_modifier_effect( - modifier_effect_cache.experience, "experience", FORMAT_x100_1DP_PC_POS, "TRAIT_EXPERIENCE" + modifier_effect_cache.experience, "experience", FORMAT_x100_1DP_PC_POS, "TRAIT_EXPERIENCE" ); ret &= register_leader_modifier_effect( - modifier_effect_cache.reliability, "reliability", FORMAT_x100_1DP_PC_POS, "TRAIT_RELIABILITY" + modifier_effect_cache.reliability, "reliability", FORMAT_x100_1DP_PC_POS, "TRAIT_RELIABILITY" ); return ret; @@ -652,17 +727,16 @@ bool ModifierManager::register_complex_modifier(const std::string_view identifie } memory::string ModifierManager::get_flat_identifier( - const std::string_view complex_modifier_identifier, - const std::string_view variant_identifier + const std::string_view complex_modifier_identifier, const std::string_view variant_identifier ) { return memory::fmt::format("{} {}", complex_modifier_identifier, variant_identifier); } bool ModifierManager::add_event_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, - const Modifier::modifier_type_t type + const std::string_view identifier, + ModifierValue&& values, + const IconModifier::icon_t icon, + const Modifier::modifier_type_t type ) { if (identifier.empty()) { @@ -670,30 +744,23 @@ bool ModifierManager::add_event_modifier( return false; } - return event_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - identifier, std::move(values), type, icon - ); + return event_modifiers.emplace_item(identifier, duplicate_warning_callback, identifier, std::move(values), type, icon); } bool ModifierManager::load_event_modifiers(const ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - event_modifiers, - [this](std::string_view key, ast::NodeCPtr value) -> bool { - ModifierValue modifier_value; - IconModifier::icon_t icon = 0; - - bool ret = expect_dictionary_keys_and_default( - expect_base_province_modifier(modifier_value), - "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)) - )(value); + const bool ret = expect_dictionary_reserve_length(event_modifiers, [this](std::string_view key, ast::NodeCPtr value) -> bool { + ModifierValue modifier_value; + IconModifier::icon_t icon = 0; - ret &= add_event_modifier(key, std::move(modifier_value), icon); + bool ret = + expect_dictionary_keys_and_default(expect_base_province_modifier(modifier_value), "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)))( + value + ); - return ret; - } - )(root); + ret &= add_event_modifier(key, std::move(modifier_value), icon); + + return ret; + })(root); return ret; } @@ -703,10 +770,7 @@ bool ModifierManager::load_static_modifiers(const ast::NodeCPtr root) { } bool ModifierManager::add_triggered_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, - ConditionScript&& trigger + const std::string_view identifier, ModifierValue&& values, const IconModifier::icon_t icon, ConditionScript&& trigger ) { using enum Modifier::modifier_type_t; @@ -716,33 +780,29 @@ bool ModifierManager::add_triggered_modifier( } return triggered_modifiers.emplace_item( - identifier, - duplicate_warning_callback, - identifier, std::move(values), TRIGGERED, icon, std::move(trigger) + identifier, duplicate_warning_callback, identifier, std::move(values), TRIGGERED, icon, std::move(trigger) ); } bool ModifierManager::load_triggered_modifiers(const ast::NodeCPtr root) { - const bool ret = expect_dictionary_reserve_length( - triggered_modifiers, - [this](const std::string_view key, const ast::NodeCPtr value) -> bool { - using enum scope_type_t; + const bool ret = + expect_dictionary_reserve_length(triggered_modifiers, [this](const std::string_view key, const ast::NodeCPtr value) -> bool { + using enum scope_type_t; - ModifierValue modifier_value {}; - IconModifier::icon_t icon = 0; - ConditionScript trigger { COUNTRY, COUNTRY, NO_SCOPE }; + ModifierValue modifier_value {}; + IconModifier::icon_t icon = 0; + ConditionScript trigger { COUNTRY, COUNTRY, NO_SCOPE }; - bool ret = expect_dictionary_keys_and_default( + bool ret = expect_dictionary_keys_and_default( expect_base_country_modifier(modifier_value), "icon", ZERO_OR_ONE, expect_uint(assign_variable_callback(icon)), "trigger", ONE_EXACTLY, trigger.expect_script() )(value); - ret &= add_triggered_modifier(key, std::move(modifier_value), icon, std::move(trigger)); + ret &= add_triggered_modifier(key, std::move(modifier_value), icon, std::move(trigger)); - return ret; - } - )(root); + return ret; + })(root); lock_triggered_modifiers(); @@ -760,10 +820,7 @@ bool ModifierManager::parse_scripts(DefinitionManager const& definition_manager) } bool ModifierManager::_add_flattened_modifier_cb( - ModifierValue& modifier_value, - const std::string_view prefix, - const std::string_view key, - const ast::NodeCPtr value + ModifierValue& modifier_value, const std::string_view prefix, const std::string_view key, const ast::NodeCPtr value ) const { const memory::string flat_identifier = get_flat_identifier(prefix, key); ModifierEffect const* effect = technology_modifier_effects.get_item_by_identifier(flat_identifier); @@ -776,9 +833,7 @@ bool ModifierManager::_add_flattened_modifier_cb( }; bool ModifierManager::_add_modifier_cb( - ModifierValue& modifier_value, - ModifierEffect const* const effect, - const ast::NodeCPtr value + ModifierValue& modifier_value, ModifierEffect const* const effect, const ast::NodeCPtr value ) const { if (effect->has_no_effect) { spdlog::warn_s("This modifier does nothing: {}", *effect); @@ -787,22 +842,17 @@ bool ModifierManager::_add_modifier_cb( } key_value_callback_t ModifierManager::_expect_modifier_effect( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value + modifier_effect_registry_t const& registry, ModifierValue& modifier_value ) const { return _expect_modifier_effect_with_fallback(registry, modifier_value, key_value_warn_callback); } key_value_callback_t ModifierManager::_expect_modifier_effect_with_fallback( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value, - key_value_callback_t fallback + modifier_effect_registry_t const& registry, ModifierValue& modifier_value, key_value_callback_t fallback ) const { return [this, ®istry, &modifier_value, fallback](const std::string_view key, const ast::NodeCPtr value) mutable -> bool { if (dryad::node_has_kind(value) && complex_modifiers.contains(key)) { - return expect_dictionary([this, &modifier_value, key]( - const std::string_view inner_key, const ast::NodeCPtr inner_value - ) -> bool { + return expect_dictionary([this, &modifier_value, key](const std::string_view inner_key, const ast::NodeCPtr inner_value) -> bool { return _add_flattened_modifier_cb(modifier_value, key, inner_key, inner_value); })(value); } @@ -825,26 +875,22 @@ key_value_callback_t ModifierManager::expect_technology_modifier(ModifierValue& std::string_view faction_identifier; ast::NodeCPtr value_node = nullptr; - bool ret = expect_dictionary_keys( - "faction", ONE_EXACTLY, expect_identifier(assign_variable_callback(faction_identifier)), - "value", ONE_EXACTLY, assign_variable_callback(value_node) - )(value); + bool ret = + expect_dictionary_keys("faction", ONE_EXACTLY, expect_identifier(assign_variable_callback(faction_identifier)), "value", ONE_EXACTLY, assign_variable_callback(value_node))( + value + ); ret &= _add_flattened_modifier_cb(modifier_value, key, faction_identifier, value_node); return ret; } - return _expect_modifier_effect( - technology_modifier_effects, - modifier_value - )(key, value); + return _expect_modifier_effect(technology_modifier_effects, modifier_value)(key, value); }; } key_value_callback_t ModifierManager::expect_unit_terrain_modifier( - ModifierValue& modifier_value, - const std::string_view terrain_type_identifier + ModifierValue& modifier_value, const std::string_view terrain_type_identifier ) const { return [this, &modifier_value, terrain_type_identifier](const std::string_view key, const ast::NodeCPtr value) -> bool { const memory::string flat_identifier = get_flat_identifier(key, terrain_type_identifier); @@ -862,16 +908,12 @@ key_value_callback_t ModifierManager::expect_base_country_modifier(ModifierValue key_value_callback_t ModifierManager::expect_base_province_modifier(ModifierValue& modifier_value) const { return _expect_modifier_effect_with_fallback( - base_province_modifier_effects, - modifier_value, - expect_base_country_modifier(modifier_value) + base_province_modifier_effects, modifier_value, expect_base_country_modifier(modifier_value) ); } key_value_callback_t ModifierManager::expect_terrain_modifier(ModifierValue& modifier_value) const { return _expect_modifier_effect_with_fallback( - terrain_modifier_effects, - modifier_value, - expect_base_province_modifier(modifier_value) + terrain_modifier_effects, modifier_value, expect_base_province_modifier(modifier_value) ); } diff --git a/src/openvic-simulation/modifier/ModifierManager.hpp b/src/openvic-simulation/modifier/ModifierManager.hpp index d712ad464..096f8b84c 100644 --- a/src/openvic-simulation/modifier/ModifierManager.hpp +++ b/src/openvic-simulation/modifier/ModifierManager.hpp @@ -40,23 +40,23 @@ namespace OpenVic { StaticModifierCache PROPERTY(static_modifier_cache); bool _register_modifier_effect( - modifier_effect_registry_t& registry, - ModifierEffect::target_t targets, - ModifierEffect const*& effect_cache, - const std::string_view identifier, - const ModifierEffect::format_t format, - const std::string_view localisation_key, - const bool has_no_effect + modifier_effect_registry_t& registry, + ModifierEffect::target_t targets, + ModifierEffect const*& effect_cache, + const std::string_view identifier, + const ModifierEffect::format_t format, + const std::string_view localisation_key, + const bool has_no_effect ); #define REGISTER_MODIFIER_EFFECT_DEFINITION(MAPPING_TYPE) \ - bool register_##MAPPING_TYPE##_modifier_effect( \ - ModifierEffect const*& effect_cache, \ - std::string_view identifier, \ - ModifierEffect::format_t format, \ - std::string_view localisation_key = {}, \ - bool has_no_effect = false \ - ); + bool register_##MAPPING_TYPE##_modifier_effect( \ + ModifierEffect const*& effect_cache, \ + std::string_view identifier, \ + ModifierEffect::format_t format, \ + std::string_view localisation_key = {}, \ + bool has_no_effect = false \ + ); REGISTER_MODIFIER_EFFECT_DEFINITION(leader) REGISTER_MODIFIER_EFFECT_DEFINITION(unit_terrain) @@ -67,50 +67,44 @@ namespace OpenVic { #undef REGISTER_MODIFIER_EFFECT_DEFINITION bool _add_flattened_modifier_cb( - ModifierValue& modifier_value, - const std::string_view prefix, - const std::string_view key, - const ast::NodeCPtr value + ModifierValue& modifier_value, const std::string_view prefix, const std::string_view key, const ast::NodeCPtr value ) const; bool _add_modifier_cb( - ModifierValue& modifier_value, - ModifierEffect const* const effect, - const ast::NodeCPtr value + ModifierValue& modifier_value, ModifierEffect const* const effect, const ast::NodeCPtr value ) const; NodeTools::key_value_callback_t _expect_modifier_effect( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value + modifier_effect_registry_t const& registry, ModifierValue& modifier_value ) const; NodeTools::key_value_callback_t _expect_modifier_effect_with_fallback( - modifier_effect_registry_t const& registry, - ModifierValue& modifier_value, - NodeTools::key_value_callback_t fallback + modifier_effect_registry_t const& registry, ModifierValue& modifier_value, NodeTools::key_value_callback_t fallback ) const; public: bool register_complex_modifier(const std::string_view identifier); - static memory::string get_flat_identifier(const std::string_view complex_modifier_identifier, const std::string_view variant_identifier); + static memory::string get_flat_identifier( + const std::string_view complex_modifier_identifier, const std::string_view variant_identifier + ); bool setup_modifier_effects(); bool add_event_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, - const Modifier::modifier_type_t type = Modifier::modifier_type_t::EVENT + const std::string_view identifier, + ModifierValue&& values, + const IconModifier::icon_t icon, + const Modifier::modifier_type_t type = Modifier::modifier_type_t::EVENT ); bool load_event_modifiers(const ast::NodeCPtr root); bool load_static_modifiers(const ast::NodeCPtr root); bool add_triggered_modifier( - const std::string_view identifier, - ModifierValue&& values, - const IconModifier::icon_t icon, - ConditionScript&& trigger + const std::string_view identifier, + ModifierValue&& values, + const IconModifier::icon_t icon, + ConditionScript&& trigger ); bool load_triggered_modifiers(const ast::NodeCPtr root); @@ -120,8 +114,7 @@ namespace OpenVic { NodeTools::key_value_callback_t expect_leader_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_technology_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_unit_terrain_modifier( - ModifierValue& modifier_value, - const std::string_view terrain_type_identifier + ModifierValue& modifier_value, const std::string_view terrain_type_identifier ) const; NodeTools::key_value_callback_t expect_base_country_modifier(ModifierValue& modifier_value) const; NodeTools::key_value_callback_t expect_base_province_modifier(ModifierValue& modifier_value) const; diff --git a/src/openvic-simulation/modifier/ModifierSum.cpp b/src/openvic-simulation/modifier/ModifierSum.cpp index 442a4e8e7..592bc2bc1 100644 --- a/src/openvic-simulation/modifier/ModifierSum.cpp +++ b/src/openvic-simulation/modifier/ModifierSum.cpp @@ -11,22 +11,20 @@ using namespace OpenVic; std::string_view modifier_entry_t::source_to_string(modifier_source_t const& source) { return std::visit( - [](has_get_identifier auto const* has_identifier) -> std::string_view { - return has_identifier == nullptr - ? "" - : has_identifier->get_identifier(); - }, - source + [](has_get_identifier auto const* has_identifier) -> std::string_view { + return has_identifier == nullptr ? "" : has_identifier->get_identifier(); + }, + source ); } memory::string modifier_entry_t::to_string() const { return memory::fmt::format( - "[{}, {}, {}, {}]", - ovfmt::validate(modifier), - multiplier, - source_to_string(source), - ModifierEffect::target_to_string(excluded_targets) + "[{}, {}, {}, {}]", + ovfmt::validate(modifier), + multiplier, + source_to_string(source), + ModifierEffect::target_to_string(excluded_targets) ); } @@ -44,22 +42,20 @@ bool ModifierSum::has_modifier_effect(ModifierEffect const& effect) const { } void ModifierSum::add_modifier( - Modifier const& modifier, fixed_point_t multiplier, modifier_entry_t::modifier_source_t const& source, - ModifierEffect::target_t excluded_targets + Modifier const& modifier, + fixed_point_t multiplier, + modifier_entry_t::modifier_source_t const& source, + ModifierEffect::target_t excluded_targets ) { // We could test that excluded_targets != ALL_TARGETS, but in practice it's always // called with an explcit/hardcoded value and so won't ever exclude everything. if (multiplier != 0) { modifier_entry_t const& new_entry = modifiers.emplace_back( - modifier, - multiplier, - modifier_entry_t::source_or_null_fallback(source, this_source), - excluded_targets | this_excluded_targets - ); - value_sum.multiply_add_exclude_targets( - *new_entry.modifier, - new_entry.multiplier, - new_entry.excluded_targets + modifier, + multiplier, + modifier_entry_t::source_or_null_fallback(source, this_source), + excluded_targets | this_excluded_targets ); + value_sum.multiply_add_exclude_targets(*new_entry.modifier, new_entry.multiplier, new_entry.excluded_targets); } } diff --git a/src/openvic-simulation/modifier/ModifierSum.hpp b/src/openvic-simulation/modifier/ModifierSum.hpp index a8474b83f..474c82bf6 100644 --- a/src/openvic-simulation/modifier/ModifierSum.hpp +++ b/src/openvic-simulation/modifier/ModifierSum.hpp @@ -3,13 +3,13 @@ #include #include -#include "openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/portable/ForwardableSpan.hpp" +#include "openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/modifier/ModifierValue.hpp" #include "openvic-simulation/modifier/Modifier.hpp" +#include "openvic-simulation/modifier/ModifierValue.hpp" namespace OpenVic { struct CountryInstance; @@ -21,16 +21,21 @@ namespace OpenVic { static std::string_view source_to_string(modifier_source_t const& source); static constexpr bool source_is_null(modifier_source_t const& source) { - return std::visit([](auto const* source) -> bool { return source == nullptr; }, source); + return std::visit( + [](auto const* source) -> bool { + return source == nullptr; + }, + source + ); } static constexpr modifier_source_t const& source_or_null_fallback( - modifier_source_t const& source, modifier_source_t const& fallback + modifier_source_t const& source, modifier_source_t const& fallback ) { return std::visit( - [&source, &fallback](auto const* source_ptr) -> modifier_source_t const& { - return source_ptr == nullptr ? fallback : source; - }, - source + [&source, &fallback](auto const* source_ptr) -> modifier_source_t const& { + return source_ptr == nullptr ? fallback : source; + }, + source ); } @@ -39,38 +44,29 @@ namespace OpenVic { modifier_source_t source; ModifierEffect::target_t excluded_targets; - //invalid but required fore resizing to work - constexpr modifier_entry_t() - : modifier {nullptr}, - multiplier {fixed_point_t::_0}, - source {static_cast>(nullptr)}, - excluded_targets {} {} + // invalid but required fore resizing to work + constexpr modifier_entry_t() : + modifier { nullptr }, multiplier { fixed_point_t::_0 }, + source { static_cast>(nullptr) }, excluded_targets {} {} // constexpr modifier_entry_t( - Modifier const& new_modifier, - fixed_point_t new_multiplier, - modifier_source_t const& new_source, - ModifierEffect::target_t new_excluded_targets - ) : modifier { &new_modifier }, - multiplier { new_multiplier }, - source { new_source }, - excluded_targets { new_excluded_targets } {} + Modifier const& new_modifier, + fixed_point_t new_multiplier, + modifier_source_t const& new_source, + ModifierEffect::target_t new_excluded_targets + ) : + modifier { &new_modifier }, multiplier { new_multiplier }, source { new_source }, + excluded_targets { new_excluded_targets } {} constexpr bool is_valid() const { - return multiplier != fixed_point_t::_0 - && modifier != nullptr - && ( - get_source_country() != nullptr - || get_source_province() != nullptr - ); + return multiplier != fixed_point_t::_0 && modifier != nullptr && + (get_source_country() != nullptr || get_source_province() != nullptr); } constexpr bool operator==(modifier_entry_t const& other) const { - return modifier == other.modifier - && multiplier == other.multiplier - && source == other.source - && excluded_targets == other.excluded_targets; + return modifier == other.modifier && multiplier == other.multiplier && source == other.source && + excluded_targets == other.excluded_targets; } constexpr CountryInstance const* get_source_country() const { @@ -84,9 +80,7 @@ namespace OpenVic { memory::string to_string() const; - constexpr fixed_point_t get_modifier_effect_value( - ModifierEffect const& effect, bool* effect_found = nullptr - ) const { + constexpr fixed_point_t get_modifier_effect_value(ModifierEffect const& effect, bool* effect_found = nullptr) const { if (!is_valid()) { return fixed_point_t::_0; } @@ -118,9 +112,7 @@ namespace OpenVic { // Targets to be excluded from all modifiers added to the sum, combined with any explicit exclusions. ModifierEffect::target_t PROPERTY_RW(this_excluded_targets, ModifierEffect::target_t::NO_TARGETS); - bulk_insert_wrapper< - memory::vector - > SPAN_PROPERTY(modifiers); + bulk_insert_wrapper> SPAN_PROPERTY(modifiers); ModifierValue PROPERTY(value_sum); public: @@ -139,10 +131,10 @@ namespace OpenVic { bool has_modifier_effect(ModifierEffect const& effect) const; void add_modifier( - Modifier const& modifier, - fixed_point_t multiplier = 1, - modifier_entry_t::modifier_source_t const& source = {}, - ModifierEffect::target_t excluded_targets = ModifierEffect::target_t::NO_TARGETS + Modifier const& modifier, + fixed_point_t multiplier = 1, + modifier_entry_t::modifier_source_t const& source = {}, + ModifierEffect::target_t excluded_targets = ModifierEffect::target_t::NO_TARGETS ); constexpr void make_room_for(ModifierSum const& modifier_sum) { @@ -159,17 +151,13 @@ namespace OpenVic { modifiers.append_range(modifier_sum.modifiers); for (modifier_entry_t const& m : modifier_sum.get_modifiers()) { - value_sum.multiply_add_exclude_targets( - *m.modifier, - m.multiplier, - m.excluded_targets - ); + value_sum.multiply_add_exclude_targets(*m.modifier, m.multiplier, m.excluded_targets); } } // TODO - help calculate value_sum[effect]? Early return if lookup in value_sum fails? constexpr void for_each_contributing_modifier( - ModifierEffect const& effect, ContributingModifierCallback auto callback + ModifierEffect const& effect, ContributingModifierCallback auto callback ) const { for (modifier_entry_t const& modifier_entry : get_modifiers()) { const fixed_point_t contribution = modifier_entry.get_modifier_effect_value(effect); diff --git a/src/openvic-simulation/modifier/ModifierValue.cpp b/src/openvic-simulation/modifier/ModifierValue.cpp index 2882edd41..b502e2040 100644 --- a/src/openvic-simulation/modifier/ModifierValue.cpp +++ b/src/openvic-simulation/modifier/ModifierValue.cpp @@ -94,16 +94,13 @@ void ModifierValue::apply_exclude_targets(ModifierEffect::target_t excluded_targ // We could test if excluded_targets is NO_TARGETS (and so we do nothing) or ALL_TARGETS (and so we clear everything), // but so long as this is always called with an explicit/hardcoded value then we'll never have either of those cases. - erase_if( - values, - [excluded_targets](effect_map_t::value_type const& value) -> bool { - return !ModifierEffect::excludes_targets(value.first->targets, excluded_targets); - } - ); + erase_if(values, [excluded_targets](effect_map_t::value_type const& value) -> bool { + return !ModifierEffect::excludes_targets(value.first->targets, excluded_targets); + }); } void ModifierValue::multiply_add_exclude_targets( - ModifierValue const& other, fixed_point_t multiplier, ModifierEffect::target_t excluded_targets + ModifierValue const& other, fixed_point_t multiplier, ModifierEffect::target_t excluded_targets ) { using enum ModifierEffect::target_t; diff --git a/src/openvic-simulation/modifier/ModifierValue.hpp b/src/openvic-simulation/modifier/ModifierValue.hpp index 104d71084..1bde30e3b 100644 --- a/src/openvic-simulation/modifier/ModifierValue.hpp +++ b/src/openvic-simulation/modifier/ModifierValue.hpp @@ -41,7 +41,7 @@ namespace OpenVic { void apply_exclude_targets(ModifierEffect::target_t excluded_targets); void multiply_add_exclude_targets( - ModifierValue const& other, fixed_point_t multiplier, ModifierEffect::target_t excluded_targets + ModifierValue const& other, fixed_point_t multiplier, ModifierEffect::target_t excluded_targets ); friend std::ostream& operator<<(std::ostream& stream, ModifierValue const& value); diff --git a/src/openvic-simulation/modifier/StaticModifierCache.cpp b/src/openvic-simulation/modifier/StaticModifierCache.cpp index bcd017804..504426cee 100644 --- a/src/openvic-simulation/modifier/StaticModifierCache.cpp +++ b/src/openvic-simulation/modifier/StaticModifierCache.cpp @@ -16,64 +16,66 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage bool ret = true; key_map_t key_map {}; - const auto set_static_country_modifier = [&key_map, &modifier_manager, &ret]( - Modifier& modifier - ) -> void { + const auto set_static_country_modifier = [&key_map, &modifier_manager, &ret](Modifier& modifier) -> void { ret &= add_key_map_entry( - key_map, modifier.get_identifier(), ONE_EXACTLY, - expect_dictionary(modifier_manager.expect_base_country_modifier(modifier)) + key_map, + modifier.get_identifier(), + ONE_EXACTLY, + expect_dictionary(modifier_manager.expect_base_country_modifier(modifier)) ); }; - const auto set_country_event_modifier = [&key_map, &modifier_manager, &ret]( - const std::string_view identifier, const IconModifier::icon_t icon - ) -> void { + const auto set_country_event_modifier = + [&key_map, &modifier_manager, &ret](const std::string_view identifier, const IconModifier::icon_t icon) -> void { ret &= add_key_map_entry( - key_map, identifier, ONE_EXACTLY, - [&modifier_manager, identifier, icon](const ast::NodeCPtr value) -> bool { - if (modifier_manager.get_event_modifier_by_identifier(identifier) != nullptr) { - return true; //an event modifier overrides a static modifier with the same identifier. - } - - ModifierValue modifier_value {}; - bool has_parsed_modifier = expect_dictionary(modifier_manager.expect_base_country_modifier(modifier_value))(value); - has_parsed_modifier &= modifier_manager.add_event_modifier(identifier, std::move(modifier_value), icon, STATIC); - return has_parsed_modifier; - } + key_map, identifier, ONE_EXACTLY, [&modifier_manager, identifier, icon](const ast::NodeCPtr value) -> bool { + if (modifier_manager.get_event_modifier_by_identifier(identifier) != nullptr) { + return true; // an event modifier overrides a static modifier with the same identifier. + } + + ModifierValue modifier_value {}; + bool has_parsed_modifier = expect_dictionary(modifier_manager.expect_base_country_modifier(modifier_value))( + value + ); + has_parsed_modifier &= modifier_manager.add_event_modifier(identifier, std::move(modifier_value), icon, STATIC); + return has_parsed_modifier; + } ); }; - const auto set_static_province_modifier = [&key_map, &modifier_manager, &ret]( - Modifier& modifier - ) -> void { + const auto set_static_province_modifier = [&key_map, &modifier_manager, &ret](Modifier& modifier) -> void { ret &= add_key_map_entry( - key_map, modifier.get_identifier(), ONE_EXACTLY, - expect_dictionary(modifier_manager.expect_base_province_modifier(modifier)) + key_map, + modifier.get_identifier(), + ONE_EXACTLY, + expect_dictionary(modifier_manager.expect_base_province_modifier(modifier)) ); }; - #define SET_COUNTRY_MODIFIER(PROP, ...) set_static_country_modifier(PROP); +#define SET_COUNTRY_MODIFIER(PROP, ...) set_static_country_modifier(PROP); // Country modifiers COUNTRY_DIFFICULTY_MODIFIER_LIST(SET_COUNTRY_MODIFIER, SET_COUNTRY_MODIFIER) ret &= add_key_map_entry( - key_map, base_modifier.get_identifier(), ONE_EXACTLY, - expect_dictionary_keys_and_default( - modifier_manager.expect_base_country_modifier(base_modifier), - "supply_limit", ZERO_OR_ONE, [this, &modifier_manager](const ast::NodeCPtr value) -> bool { - return modifier_manager._add_modifier_cb( - base_modifier, - modifier_manager.get_modifier_effect_cache().get_supply_limit_global_base(), - value - ); - } - ) + key_map, + base_modifier.get_identifier(), + ONE_EXACTLY, + expect_dictionary_keys_and_default( + modifier_manager.expect_base_country_modifier(base_modifier), + "supply_limit", + ZERO_OR_ONE, + [this, &modifier_manager](const ast::NodeCPtr value) -> bool { + return modifier_manager._add_modifier_cb( + base_modifier, modifier_manager.get_modifier_effect_cache().get_supply_limit_global_base(), value + ); + } + ) ); COUNTRY_MODIFIER_LIST(SET_COUNTRY_MODIFIER, SET_COUNTRY_MODIFIER) - #undef SET_COUNTRY_MODIFIER +#undef SET_COUNTRY_MODIFIER // Country Event modifiers static constexpr IconModifier::icon_t default_icon = 0; @@ -84,12 +86,12 @@ bool StaticModifierCache::load_static_modifiers(ModifierManager& modifier_manage set_country_event_modifier(in_bankruptcy_id, default_icon); set_country_event_modifier(generalised_debt_default_id, default_icon); - #define SET_PROVINCE_MODIFIER(PROP, ...) set_static_province_modifier(PROP); +#define SET_PROVINCE_MODIFIER(PROP, ...) set_static_province_modifier(PROP); // Province modifiers PROVINCE_MODIFIER_LIST(SET_PROVINCE_MODIFIER, SET_PROVINCE_MODIFIER) - #undef SET_PROVINCE_MODIFIER +#undef SET_PROVINCE_MODIFIER ret &= expect_dictionary_key_map_and_default(key_map, key_value_invalid_callback)(root); diff --git a/src/openvic-simulation/modifier/StaticModifierCache.hpp b/src/openvic-simulation/modifier/StaticModifierCache.hpp index b30ac50eb..74e9f83ef 100644 --- a/src/openvic-simulation/modifier/StaticModifierCache.hpp +++ b/src/openvic-simulation/modifier/StaticModifierCache.hpp @@ -12,7 +12,7 @@ F(very_easy_ai) \ F(easy_ai) \ F(hard_ai) \ - F(very_hard_ai) \ + F(very_hard_ai) #define COUNTRY_MODIFIER_LIST(F, ID_F) \ F(war) \ @@ -53,22 +53,22 @@ namespace OpenVic { friend struct ModifierManager; private: - #define DEFINE_PROPERTY_ID(PROP, ID) Modifier PROPERTY(PROP, { #ID, {}, Modifier::modifier_type_t::STATIC }); - #define DEFINE_PROPERTY(PROP) DEFINE_PROPERTY_ID(PROP, PROP) +#define DEFINE_PROPERTY_ID(PROP, ID) Modifier PROPERTY(PROP, { #ID, {}, Modifier::modifier_type_t::STATIC }); +#define DEFINE_PROPERTY(PROP) DEFINE_PROPERTY_ID(PROP, PROP) COUNTRY_DIFFICULTY_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) COUNTRY_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) PROVINCE_MODIFIER_LIST(DEFINE_PROPERTY, DEFINE_PROPERTY_ID) - #undef DEFINE_PROPERTY - #undef DEFINE_PROPERTY_NAME +#undef DEFINE_PROPERTY +#undef DEFINE_PROPERTY_NAME Modifier PROPERTY(base_modifier, { "base_values", {}, Modifier::modifier_type_t::STATIC }); // Country event modifiers Modifier const* PROPERTY(in_bankruptcy, nullptr); Modifier const* PROPERTY(bad_debtor, nullptr); - Modifier const* PROPERTY(generalised_debt_default, nullptr); //possibly, as it's used to trigger gunboat CB + Modifier const* PROPERTY(generalised_debt_default, nullptr); // possibly, as it's used to trigger gunboat CB StaticModifierCache(); diff --git a/src/openvic-simulation/pathfinding/AStarPathing.cpp b/src/openvic-simulation/pathfinding/AStarPathing.cpp index 42de33dea..2df8f1544 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.cpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.cpp @@ -8,8 +8,8 @@ #include -#include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/map/MapDefinition.hpp" #include "openvic-simulation/map/MapInstance.hpp" @@ -41,8 +41,8 @@ bool AStarPathing::_solve(search_iterator begin_point, search_iterator end_point // Find point closer to end_point, or same distance to end_point but closer to begin_point. if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // - last_closest_point.value().g_score > p.value().g_score)) { + (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // + last_closest_point.value().g_score > p.value().g_score)) { last_closest_point = p; } @@ -98,12 +98,8 @@ bool AStarPathing::_solve(search_iterator begin_point, search_iterator end_point return found_route; } -ArmyAStarPathing::ArmyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance -) : map_instance { new_map_instance }, - AStarPathing(&new_map_definition.get_path_map_land()) - {} +ArmyAStarPathing::ArmyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance) : + map_instance { new_map_instance }, AStarPathing(&new_map_definition.get_path_map_land()) {} bool ArmyAStarPathing::_is_point_enabled(search_const_iterator it) const { if (!AStarPathing::_is_point_enabled(it)) { @@ -133,12 +129,8 @@ bool ArmyAStarPathing::_is_point_enabled(search_const_iterator it) const { return army_instance->get_country().can_army_units_enter(*province_owner); } -NavyAStarPathing::NavyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance -) : map_instance {new_map_instance}, - AStarPathing(&new_map_definition.get_path_map_land()) - {} +NavyAStarPathing::NavyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance) : + map_instance { new_map_instance }, AStarPathing(&new_map_definition.get_path_map_land()) {} bool NavyAStarPathing::_is_point_enabled(search_const_iterator it) const { if (!AStarPathing::_is_point_enabled(it)) { diff --git a/src/openvic-simulation/pathfinding/AStarPathing.hpp b/src/openvic-simulation/pathfinding/AStarPathing.hpp index 4ee8889c3..0c27fec2c 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.hpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.hpp @@ -59,10 +59,7 @@ namespace OpenVic { }; struct ArmyAStarPathing final : public AStarPathing { - ArmyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance - ); + ArmyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance); protected: UnitInstanceGroupBranched const* PROPERTY_RW_ACCESS(army_instance, protected, nullptr); @@ -72,10 +69,7 @@ namespace OpenVic { }; struct NavyAStarPathing final : public AStarPathing { - NavyAStarPathing( - MapDefinition const& new_map_definition, - MapInstance const& new_map_instance - ); + NavyAStarPathing(MapDefinition const& new_map_definition, MapInstance const& new_map_instance); protected: UnitInstanceGroupBranched const* PROPERTY_RW_ACCESS(navy_instance, protected, nullptr); diff --git a/src/openvic-simulation/pathfinding/FringePathing.cpp b/src/openvic-simulation/pathfinding/FringePathing.cpp index b1d2a77a5..93b212448 100644 --- a/src/openvic-simulation/pathfinding/FringePathing.cpp +++ b/src/openvic-simulation/pathfinding/FringePathing.cpp @@ -57,8 +57,8 @@ bool FringePathing::_solve(search_iterator begin_point, search_iterator end_poin // Find point closer to end_point, or same distance to end_point but closer to begin_point. if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // - last_closest_point.value().g_score > p.value().g_score)) { + (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // + last_closest_point.value().g_score > p.value().g_score)) { last_closest_point = p; } diff --git a/src/openvic-simulation/pathfinding/PathingBase.hpp b/src/openvic-simulation/pathfinding/PathingBase.hpp index fa0b6ebbf..50d29c7d0 100644 --- a/src/openvic-simulation/pathfinding/PathingBase.hpp +++ b/src/openvic-simulation/pathfinding/PathingBase.hpp @@ -22,11 +22,15 @@ namespace OpenVic { using search_value_type = ValueT; using search_pair_type = std::pair; using search_allocator_type = - foonathan::memory::std_allocator>; + foonathan::memory::std_allocator>; using search_container_type = std::vector; using search_map_type = tsl::ordered_map< - search_key_type, search_value_type, // - std::hash, std::equal_to, search_allocator_type, search_container_type>; + search_key_type, + search_value_type, // + std::hash, + std::equal_to, + search_allocator_type, + search_container_type>; using search_iterator = search_map_type::iterator; using search_const_iterator = search_map_type::const_iterator; @@ -66,15 +70,11 @@ namespace OpenVic { } virtual fixed_point_t _estimate_cost(search_const_iterator from_it, search_const_iterator end_it) { - return fp::sqrt( - fixed_point_t { from_it.value().point->position.distance_squared(end_it.value().point->position) } - ); + return fp::sqrt(fixed_point_t { from_it.value().point->position.distance_squared(end_it.value().point->position) }); } virtual fixed_point_t _compute_cost(search_const_iterator from_it, search_const_iterator end_it) { - return fp::sqrt( - fixed_point_t { from_it.value().point->position.distance_squared(end_it.value().point->position) } - ); + return fp::sqrt(fixed_point_t { from_it.value().point->position.distance_squared(end_it.value().point->position) }); } virtual bool _solve( // @@ -145,7 +145,9 @@ namespace OpenVic { } template - inline memory::vector generate_path_result(search_iterator from_it, search_iterator to_it, Projection projection = {}) { + inline memory::vector generate_path_result( + search_iterator from_it, search_iterator to_it, Projection projection = {} + ) { search_iterator p = to_it; int64_t pc = 1; // Begin point while (p != from_it) { diff --git a/src/openvic-simulation/pathfinding/PointMap.cpp b/src/openvic-simulation/pathfinding/PointMap.cpp index dabab048e..815cd163c 100644 --- a/src/openvic-simulation/pathfinding/PointMap.cpp +++ b/src/openvic-simulation/pathfinding/PointMap.cpp @@ -10,11 +10,11 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/memory/Formatting.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/Vector.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; @@ -35,13 +35,13 @@ int64_t PointMap::get_available_points() const { } bool PointMap::try_add_point( - points_key_type id, ivec2_t const& position, fixed_point_t weight_scale, std::span adjacent_points + points_key_type id, ivec2_t const& position, fixed_point_t weight_scale, std::span adjacent_points ) { if constexpr (!std::is_unsigned_v) { OV_ERR_FAIL_COND_V_MSG(id < 0, false, memory::fmt::format("Can't add a point with negative id: {}.", id)); } OV_ERR_FAIL_COND_V_MSG( - weight_scale < 0, false, memory::fmt::format("Can't add a point with weight scale less than 0.0: {}.", weight_scale) + weight_scale < 0, false, memory::fmt::format("Can't add a point with weight scale less than 0.0: {}.", weight_scale) ); if (OV_unlikely(points.contains(id))) { @@ -62,13 +62,13 @@ bool PointMap::try_add_point( } void PointMap::add_point( - points_key_type id, ivec2_t const& position, fixed_point_t weight_scale, std::span adjacent_points + points_key_type id, ivec2_t const& position, fixed_point_t weight_scale, std::span adjacent_points ) { if constexpr (!std::is_unsigned_v) { OV_ERR_FAIL_COND_MSG(id < 0, memory::fmt::format("Can't add a point with negative id: {}.", id)); } OV_ERR_FAIL_COND_MSG( - weight_scale < 0, memory::fmt::format("Can't add a point with weight scale less than 0.0: {}.", weight_scale) + weight_scale < 0, memory::fmt::format("Can't add a point with weight scale less than 0.0: {}.", weight_scale) ); points_iterator found_pt = points.find(id); @@ -91,7 +91,9 @@ void PointMap::add_point( PointMap::Point const* PointMap::get_point(points_key_type id) const { points_const_iterator it = points.find(id); - OV_ERR_FAIL_COND_V_MSG(it == points.end(), nullptr, memory::fmt::format("Can't get a point. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_V_MSG( + it == points.end(), nullptr, memory::fmt::format("Can't get a point. Point with id: {} doesn't exist.", id) + ); return &it.value(); } @@ -108,7 +110,7 @@ PointMap::Point const* PointMap::try_get_point(points_key_type id) const { ivec2_t PointMap::get_point_position(points_key_type id) const { points_const_iterator it = points.find(id); OV_ERR_FAIL_COND_V_MSG( - it == points.end(), ivec2_t(), memory::fmt::format("Can't get point's position. Point with id: {} doesn't exist.", id) + it == points.end(), ivec2_t(), memory::fmt::format("Can't get point's position. Point with id: {} doesn't exist.", id) ); return it.value().position; @@ -116,7 +118,9 @@ ivec2_t PointMap::get_point_position(points_key_type id) const { void PointMap::set_point_position(points_key_type id, ivec2_t const& position) { points_iterator it = points.find(id); - OV_ERR_FAIL_COND_MSG(it == points.end(), memory::fmt::format("Can't set point's position. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + it == points.end(), memory::fmt::format("Can't set point's position. Point with id: {} doesn't exist.", id) + ); it.value().position = position; } @@ -124,7 +128,7 @@ void PointMap::set_point_position(points_key_type id, ivec2_t const& position) { fixed_point_t PointMap::get_point_weight_scale(points_key_type id) const { points_const_iterator it = points.find(id); OV_ERR_FAIL_COND_V_MSG( - it == points.end(), 0, memory::fmt::format("Can't get point's weight scale. Point with id: {} doesn't exist.", id) + it == points.end(), 0, memory::fmt::format("Can't get point's weight scale. Point with id: {} doesn't exist.", id) ); return it.value().weight_scale; @@ -133,10 +137,10 @@ fixed_point_t PointMap::get_point_weight_scale(points_key_type id) const { void PointMap::set_point_weight_scale(points_key_type id, fixed_point_t weight_scale) { points_iterator it = points.find(id); OV_ERR_FAIL_COND_MSG( - it == points.end(), memory::fmt::format("Can't set point's weight scale. Point with id: {} doesn't exist.", id) + it == points.end(), memory::fmt::format("Can't set point's weight scale. Point with id: {} doesn't exist.", id) ); OV_ERR_FAIL_COND_MSG( - weight_scale < 0, memory::fmt::format("Can't set point's weight scale less than 0.0: {}.", weight_scale) + weight_scale < 0, memory::fmt::format("Can't set point's weight scale less than 0.0: {}.", weight_scale) ); it.value().weight_scale = weight_scale; @@ -178,8 +182,9 @@ bool PointMap::has_point(points_key_type id) const { std::span PointMap::get_point_connections(points_key_type id) const { points_const_iterator it = points.find(id); OV_ERR_FAIL_COND_V_MSG( - it == points.end(), std::span(), - memory::fmt::format("Can't get point's connections. Point with id: {} doesn't exist.", id) + it == points.end(), + std::span(), + memory::fmt::format("Can't get point's connections. Point with id: {} doesn't exist.", id) ); return std::span { it.value().neighbors.values_container() }; @@ -199,7 +204,7 @@ memory::vector PointMap::get_point_ids() { void PointMap::set_point_disabled(points_key_type id, bool disabled) { points_iterator it = points.find(id); OV_ERR_FAIL_COND_MSG( - it == points.end(), memory::fmt::format("Can't set if point is disabled. Point with id: {} doesn't exist.", id) + it == points.end(), memory::fmt::format("Can't set if point is disabled. Point with id: {} doesn't exist.", id) ); it.value().enabled = !disabled; @@ -208,7 +213,7 @@ void PointMap::set_point_disabled(points_key_type id, bool disabled) { bool PointMap::is_point_disabled(points_key_type id) const { points_const_iterator it = points.find(id); OV_ERR_FAIL_COND_V_MSG( - it == points.end(), false, memory::fmt::format("Can't get if point is disabled. Point with id: {} doesn't exist.", id) + it == points.end(), false, memory::fmt::format("Can't get if point is disabled. Point with id: {} doesn't exist.", id) ); return !it.value().enabled; @@ -218,10 +223,14 @@ void PointMap::connect_points(points_key_type id, points_key_type with_id, bool OV_ERR_FAIL_COND_MSG(id == with_id, memory::fmt::format("Can't connect point with id: {} to itself.", id)); points_iterator from_it = points.find(id); - OV_ERR_FAIL_COND_MSG(from_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + from_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", id) + ); points_iterator to_it = points.find(with_id); - OV_ERR_FAIL_COND_MSG(to_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", with_id)); + OV_ERR_FAIL_COND_MSG( + to_it == points.end(), memory::fmt::format("Can't connect points. Point with id: {} doesn't exist.", with_id) + ); from_it.value().neighbors.insert(to_it.key()); @@ -252,11 +261,13 @@ void PointMap::connect_points(points_key_type id, points_key_type with_id, bool void PointMap::disconnect_points(points_key_type id, points_key_type with_id, bool bidirectional) { points_iterator from_it = points.find(id); - OV_ERR_FAIL_COND_MSG(from_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", id)); + OV_ERR_FAIL_COND_MSG( + from_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", id) + ); points_iterator to_it = points.find(with_id); OV_ERR_FAIL_COND_MSG( - to_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", with_id) + to_it == points.end(), memory::fmt::format("Can't disconnect points. Point with id: {} doesn't exist.", with_id) ); Segment s { id, with_id }; @@ -308,8 +319,10 @@ size_t PointMap::get_point_capacity() const { void PointMap::reserve_space(size_t num_nodes) { OV_ERR_FAIL_COND_MSG(num_nodes <= 0, memory::fmt::format("New capacity must be greater than 0, new was: {}.", num_nodes)); OV_ERR_FAIL_COND_MSG( - num_nodes <= points.capacity(), - memory::fmt::format("New capacity must be greater than current capacity: {}, new was: {}.", points.capacity(), num_nodes) + num_nodes <= points.capacity(), + memory::fmt::format( + "New capacity must be greater than current capacity: {}, new was: {}.", points.capacity(), num_nodes + ) ); points.reserve(num_nodes); points_pointers_invalidated(); diff --git a/src/openvic-simulation/pathfinding/PointMap.hpp b/src/openvic-simulation/pathfinding/PointMap.hpp index 4a642b3f1..ff32cc5c9 100644 --- a/src/openvic-simulation/pathfinding/PointMap.hpp +++ b/src/openvic-simulation/pathfinding/PointMap.hpp @@ -23,11 +23,15 @@ namespace OpenVic { using points_value_type = Point; using points_pair_type = std::pair; using points_allocator_type = - foonathan::memory::std_allocator>; + foonathan::memory::std_allocator>; using points_container_type = std::vector; using points_map_type = tsl::ordered_map< - points_key_type, points_value_type, // - std::hash, std::equal_to, points_allocator_type, points_container_type>; + points_key_type, + points_value_type, // + std::hash, + std::equal_to, + points_allocator_type, + points_container_type>; using points_iterator = points_map_type::iterator; using points_const_iterator = points_map_type::const_iterator; @@ -63,30 +67,35 @@ namespace OpenVic { struct SegmentHash { inline constexpr std::size_t operator()(Segment const& segment) const { - return hash_murmur3(hash_murmur3(segment.key.first) << 32) | - hash_murmur3(segment.key.second); + return hash_murmur3(hash_murmur3(segment.key.first) << 32) | hash_murmur3(segment.key.second); } }; using segments_type = Segment; using segments_hash_type = SegmentHash; using segments_allocator_type = - foonathan::memory::std_allocator>; + foonathan::memory::std_allocator>; using segments_container_type = std::vector; using segments_set_type = tsl::ordered_set< - segments_type, segments_hash_type, std::equal_to, segments_allocator_type, segments_container_type>; + segments_type, + segments_hash_type, + std::equal_to, + segments_allocator_type, + segments_container_type>; using segments_iterator = segments_set_type::iterator; using segments_const_iterator = segments_set_type::const_iterator; struct Point { using neighbor_point_id_type = points_key_type; using neighbors_allocator_type = - foonathan::memory::std_allocator>; + foonathan::memory::std_allocator>; using neighbors_container_type = std::vector; using neighbors_type = tsl::ordered_set< - neighbor_point_id_type, // - std::hash, std::equal_to, neighbors_allocator_type, - neighbors_container_type>; + neighbor_point_id_type, // + std::hash, + std::equal_to, + neighbors_allocator_type, + neighbors_container_type>; using neighbors_iterator = neighbors_type::iterator; using neighbors_const_iterator = neighbors_type::const_iterator; @@ -146,13 +155,17 @@ namespace OpenVic { int64_t get_available_points() const; bool try_add_point( - points_key_type id, ivec2_t const& position, fixed_point_t weight_scale = 1, - std::span adjacent_points = {} + points_key_type id, + ivec2_t const& position, + fixed_point_t weight_scale = 1, + std::span adjacent_points = {} ); void add_point( - points_key_type id, ivec2_t const& position, fixed_point_t weight_scale = 1, - std::span adjacent_points = {} + points_key_type id, + ivec2_t const& position, + fixed_point_t weight_scale = 1, + std::span adjacent_points = {} ); Point const* get_point(points_key_type id) const; diff --git a/src/openvic-simulation/politics/BaseIssue.cpp b/src/openvic-simulation/politics/BaseIssue.cpp index 1fa3ba1f9..f0acc2593 100644 --- a/src/openvic-simulation/politics/BaseIssue.cpp +++ b/src/openvic-simulation/politics/BaseIssue.cpp @@ -3,13 +3,12 @@ using namespace OpenVic; BaseIssue::BaseIssue( - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - RuleSet&& new_rules, - bool new_is_jingoism, - modifier_type_t new_type -) : Modifier { new_identifier, std::move(new_values), new_type }, - HasColour { new_colour, false }, - rules { std::move(new_rules) }, - is_jingoism { new_is_jingoism } {} \ No newline at end of file + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_values, + RuleSet&& new_rules, + bool new_is_jingoism, + modifier_type_t new_type +) : + Modifier { new_identifier, std::move(new_values), new_type }, HasColour { new_colour, false }, + rules { std::move(new_rules) }, is_jingoism { new_is_jingoism } {} diff --git a/src/openvic-simulation/politics/BaseIssue.hpp b/src/openvic-simulation/politics/BaseIssue.hpp index 6aae4b6ea..04b7fd9d5 100644 --- a/src/openvic-simulation/politics/BaseIssue.hpp +++ b/src/openvic-simulation/politics/BaseIssue.hpp @@ -8,16 +8,17 @@ namespace OpenVic { struct BaseIssue : Modifier, public HasColour { protected: BaseIssue( - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - RuleSet&& new_rules, - bool new_is_jingoism, - modifier_type_t new_type + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_values, + RuleSet&& new_rules, + bool new_is_jingoism, + modifier_type_t new_type ); BaseIssue(BaseIssue&&) = default; + public: const bool is_jingoism; const RuleSet rules; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Government.cpp b/src/openvic-simulation/politics/Government.cpp index 7ff15c5ae..64bb19b62 100644 --- a/src/openvic-simulation/politics/Government.cpp +++ b/src/openvic-simulation/politics/Government.cpp @@ -9,31 +9,29 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; GovernmentType::GovernmentType( - index_t new_index, - std::string_view new_identifier, - memory::vector>&& new_ideologies, - bool new_holds_elections, - bool new_can_appoint_ruling_party, - Timespan new_term_duration, - std::string_view new_flag_type_identifier -) : HasIndex { new_index }, - HasIdentifier { new_identifier }, - ideologies { std::move(new_ideologies) }, - holds_elections { new_holds_elections }, - can_appoint_ruling_party { new_can_appoint_ruling_party }, - term_duration { new_term_duration }, - flag_type_identifier { new_flag_type_identifier } {} + index_t new_index, + std::string_view new_identifier, + memory::vector>&& new_ideologies, + bool new_holds_elections, + bool new_can_appoint_ruling_party, + Timespan new_term_duration, + std::string_view new_flag_type_identifier +) : + HasIndex { new_index }, HasIdentifier { new_identifier }, ideologies { std::move(new_ideologies) }, + holds_elections { new_holds_elections }, can_appoint_ruling_party { new_can_appoint_ruling_party }, + term_duration { new_term_duration }, flag_type_identifier { new_flag_type_identifier } {} bool GovernmentType::is_ideology_compatible(Ideology const& ideology) const { - return ranges::contains( - ideologies, - ideology - ); + return ranges::contains(ideologies, ideology); } bool GovernmentTypeManager::add_government_type( - std::string_view identifier, memory::vector>&& ideologies, bool elections, bool appoint_ruling_party, - Timespan term_duration, std::string_view flag_type + std::string_view identifier, + memory::vector>&& ideologies, + bool elections, + bool appoint_ruling_party, + Timespan term_duration, + std::string_view flag_type ) { spdlog::scope scope { fmt::format("government type {}", identifier) }; if (identifier.empty()) { @@ -52,8 +50,14 @@ bool GovernmentTypeManager::add_government_type( } const bool ret = government_types.emplace_item( - identifier, - index_from_count(get_government_type_count()), identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, flag_type + identifier, + index_from_count(get_government_type_count()), + identifier, + std::move(ideologies), + elections, + appoint_ruling_party, + term_duration, + flag_type ); /* flag_type can be empty here for default/non-ideological flag */ @@ -67,71 +71,63 @@ bool GovernmentTypeManager::add_government_type( /* REQUIREMENTS: FS-525, SIM-27 */ bool GovernmentTypeManager::load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/governments.txt" }; - bool ret = expect_dictionary_reserve_length( - government_types, - [this, &ideology_manager](std::string_view government_type_identifier, ast::NodeCPtr government_type_value) -> bool { - memory::vector> ideologies; - bool elections = false, appoint_ruling_party = false; - Timespan term_duration = 0; - std::string_view flag_type_identifier; - - size_t total_expected_ideologies = 0; - bool ret = expect_dictionary_keys_and_default( - increment_callback(total_expected_ideologies), - "election", ZERO_OR_ONE, expect_bool(assign_variable_callback(elections)), - "duration", ZERO_OR_ONE, expect_months(assign_variable_callback(term_duration)), - "appoint_ruling_party", ONE_EXACTLY, expect_bool(assign_variable_callback(appoint_ruling_party)), - "flagType", ZERO_OR_ONE, expect_identifier(assign_variable_callback(flag_type_identifier)) - )(government_type_value); - ideologies.reserve(total_expected_ideologies); - - ret &= expect_dictionary( - [this, &ideology_manager, &ideologies, government_type_identifier]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - static const string_set_t reserved_keys = { "election", "duration", "appoint_ruling_party", "flagType" }; - if (reserved_keys.contains(key)) { - return true; - } - Ideology const* ideology_ptr = ideology_manager.get_ideology_by_identifier(key); - if (ideology_ptr == nullptr) { - spdlog::error_s( - "When loading government type {}, specified ideology {} is invalid!", - government_type_identifier, key - ); - return false; - } - return expect_bool([&ideologies, &ideology = *ideology_ptr, government_type_identifier](bool val) -> bool { - if (val) { - if (!ranges::contains( - ideologies, - ideology - )) { - ideologies.emplace_back(ideology); - return true; - } - spdlog::error_s( - "Government type {} marked as supporting ideology {}", - government_type_identifier, ideology - ); - return false; - } - spdlog::error_s( - "Government type {} redundantly marked as not supporting ideology {} multiple times", - government_type_identifier, ideology - ); - return false; - })(value); - } - )(government_type_value); - - ret &= add_government_type( - government_type_identifier, std::move(ideologies), elections, appoint_ruling_party, term_duration, - flag_type_identifier - ); - return ret; - } - )(root); + bool ret = expect_dictionary_reserve_length(government_types, [this, &ideology_manager](std::string_view government_type_identifier, ast::NodeCPtr government_type_value) -> bool { + memory::vector> ideologies; + bool elections = false, appoint_ruling_party = false; + Timespan term_duration = 0; + std::string_view flag_type_identifier; + + size_t total_expected_ideologies = 0; + bool + ret = + expect_dictionary_keys_and_default(increment_callback(total_expected_ideologies), "election", ZERO_OR_ONE, expect_bool(assign_variable_callback(elections)), "duration", ZERO_OR_ONE, expect_months(assign_variable_callback(term_duration)), "appoint_ruling_party", ONE_EXACTLY, expect_bool(assign_variable_callback(appoint_ruling_party)), "flagType", ZERO_OR_ONE, expect_identifier(assign_variable_callback(flag_type_identifier)))( + government_type_value + ); + ideologies.reserve(total_expected_ideologies); + + ret &= + expect_dictionary([this, &ideology_manager, &ideologies, government_type_identifier](std::string_view key, ast::NodeCPtr value) -> bool { + static const string_set_t reserved_keys = { "election", "duration", "appoint_ruling_party", "flagType" }; + if (reserved_keys.contains(key)) { + return true; + } + Ideology const* ideology_ptr = ideology_manager.get_ideology_by_identifier(key); + if (ideology_ptr == nullptr) { + spdlog::error_s( + "When loading government type {}, specified ideology {} is invalid!", government_type_identifier, key + ); + return false; + } + return expect_bool([&ideologies, &ideology = *ideology_ptr, government_type_identifier](bool val) -> bool { + if (val) { + if (!ranges::contains(ideologies, ideology)) { + ideologies.emplace_back(ideology); + return true; + } + spdlog::error_s( + "Government type {} marked as supporting ideology {}", government_type_identifier, ideology + ); + return false; + } + spdlog::error_s( + "Government type {} redundantly marked as not supporting ideology {} multiple times", + government_type_identifier, + ideology + ); + return false; + })(value); + })(government_type_value); + + ret &= add_government_type( + government_type_identifier, + std::move(ideologies), + elections, + appoint_ruling_party, + term_duration, + flag_type_identifier + ); + return ret; + })(root); lock_government_types(); return ret; diff --git a/src/openvic-simulation/politics/Government.hpp b/src/openvic-simulation/politics/Government.hpp index a829c387e..91f60b077 100644 --- a/src/openvic-simulation/politics/Government.hpp +++ b/src/openvic-simulation/politics/Government.hpp @@ -25,13 +25,13 @@ namespace OpenVic { const Timespan term_duration; GovernmentType( - index_t new_index, - std::string_view new_identifier, - memory::vector>&& new_ideologies, - bool new_holds_elections, - bool new_can_appoint_ruling_party, - Timespan new_term_duration, - std::string_view new_flag_type_identifier + index_t new_index, + std::string_view new_identifier, + memory::vector>&& new_ideologies, + bool new_holds_elections, + bool new_can_appoint_ruling_party, + Timespan new_term_duration, + std::string_view new_flag_type_identifier ); GovernmentType(GovernmentType&&) = default; @@ -45,8 +45,12 @@ namespace OpenVic { public: bool add_government_type( - std::string_view identifier, memory::vector>&& ideologies, bool elections, bool appoint_ruling_party, - Timespan term_duration, std::string_view flag_type + std::string_view identifier, + memory::vector>&& ideologies, + bool elections, + bool appoint_ruling_party, + Timespan term_duration, + std::string_view flag_type ); bool load_government_types_file(IdeologyManager const& ideology_manager, ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/Ideology.cpp b/src/openvic-simulation/politics/Ideology.cpp index 881f9a141..358874cfa 100644 --- a/src/openvic-simulation/politics/Ideology.cpp +++ b/src/openvic-simulation/politics/Ideology.cpp @@ -8,33 +8,28 @@ using namespace OpenVic::NodeTools; IdeologyGroup::IdeologyGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} Ideology::Ideology( - std::string_view new_identifier, - index_t new_index, - colour_t new_colour, - IdeologyGroup const& new_group, - bool new_is_allowed_for_uncivilised, - bool new_can_reduce_consciousness, - bool new_can_reduce_militancy, - std::optional new_spawn_date, - ConditionalWeightBase&& new_add_political_reform, - ConditionalWeightBase&& new_remove_political_reform, - ConditionalWeightBase&& new_add_social_reform, - ConditionalWeightBase&& new_remove_social_reform, - ConditionalWeightBase&& new_add_military_reform, - ConditionalWeightBase&& new_add_economic_reform -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - group { new_group }, - is_allowed_for_uncivilised { new_is_allowed_for_uncivilised }, - can_reduce_consciousness { new_can_reduce_consciousness }, - can_reduce_militancy { new_can_reduce_militancy }, - spawn_date { new_spawn_date }, - add_political_reform { std::move(new_add_political_reform) }, - remove_political_reform { std::move(new_remove_political_reform) }, - add_social_reform { std::move(new_add_social_reform) }, - remove_social_reform { std::move(new_remove_social_reform) }, - add_military_reform { std::move(new_add_military_reform) }, - add_economic_reform { std::move(new_add_economic_reform) } {} + std::string_view new_identifier, + index_t new_index, + colour_t new_colour, + IdeologyGroup const& new_group, + bool new_is_allowed_for_uncivilised, + bool new_can_reduce_consciousness, + bool new_can_reduce_militancy, + std::optional new_spawn_date, + ConditionalWeightBase&& new_add_political_reform, + ConditionalWeightBase&& new_remove_political_reform, + ConditionalWeightBase&& new_add_social_reform, + ConditionalWeightBase&& new_remove_social_reform, + ConditionalWeightBase&& new_add_military_reform, + ConditionalWeightBase&& new_add_economic_reform +) : + HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, group { new_group }, + is_allowed_for_uncivilised { new_is_allowed_for_uncivilised }, can_reduce_consciousness { new_can_reduce_consciousness }, + can_reduce_militancy { new_can_reduce_militancy }, spawn_date { new_spawn_date }, + add_political_reform { std::move(new_add_political_reform) }, + remove_political_reform { std::move(new_remove_political_reform) }, add_social_reform { std::move(new_add_social_reform) }, + remove_social_reform { std::move(new_remove_social_reform) }, add_military_reform { std::move(new_add_military_reform) }, + add_economic_reform { std::move(new_add_economic_reform) } {} bool Ideology::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -58,19 +53,19 @@ bool IdeologyManager::add_ideology_group(std::string_view identifier) { } bool IdeologyManager::add_ideology( - std::string_view identifier, - colour_t colour, - IdeologyGroup const* group, - bool uncivilised, - bool can_reduce_consciousness, - bool can_reduce_militancy, - std::optional spawn_date, - ConditionalWeightBase&& add_political_reform, - ConditionalWeightBase&& remove_political_reform, - ConditionalWeightBase&& add_social_reform, - ConditionalWeightBase&& remove_social_reform, - ConditionalWeightBase&& add_military_reform, - ConditionalWeightBase&& add_economic_reform + std::string_view identifier, + colour_t colour, + IdeologyGroup const* group, + bool uncivilised, + bool can_reduce_consciousness, + bool can_reduce_militancy, + std::optional spawn_date, + ConditionalWeightBase&& add_political_reform, + ConditionalWeightBase&& remove_political_reform, + ConditionalWeightBase&& add_social_reform, + ConditionalWeightBase&& remove_social_reform, + ConditionalWeightBase&& add_military_reform, + ConditionalWeightBase&& add_economic_reform ) { spdlog::scope scope { fmt::format("ideology {}", identifier) }; if (identifier.empty()) { @@ -85,21 +80,21 @@ bool IdeologyManager::add_ideology( const Ideology::index_t new_index = index_from_count(ideologies.size()); return ideologies.emplace_item( - identifier, - identifier, - new_index, - colour, - *group, - uncivilised, - can_reduce_consciousness, - can_reduce_militancy, - spawn_date, - std::move(add_political_reform), - std::move(remove_political_reform), - std::move(add_social_reform), - std::move(remove_social_reform), - std::move(add_military_reform), - std::move(add_economic_reform) + identifier, + identifier, + new_index, + colour, + *group, + uncivilised, + can_reduce_consciousness, + can_reduce_militancy, + spawn_date, + std::move(add_political_reform), + std::move(remove_political_reform), + std::move(add_social_reform), + std::move(remove_social_reform), + std::move(add_military_reform), + std::move(add_economic_reform) ); } @@ -109,14 +104,12 @@ bool IdeologyManager::add_ideology( bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { spdlog::scope scope { "common/ideologies.txt" }; size_t expected_ideologies = 0; - bool ret = expect_dictionary_reserve_length( - ideology_groups, - [this, &expected_ideologies](std::string_view key, ast::NodeCPtr value) -> bool { - bool ret = expect_length(add_variable_callback(expected_ideologies))(value); - ret &= add_ideology_group(key); - return ret; - } - )(root); + bool ret = + expect_dictionary_reserve_length(ideology_groups, [this, &expected_ideologies](std::string_view key, ast::NodeCPtr value) -> bool { + bool ret = expect_length(add_variable_callback(expected_ideologies))(value); + ret &= add_ideology_group(key); + return ret; + })(root); lock_ideology_groups(); reserve_more_ideologies(expected_ideologies); @@ -152,19 +145,19 @@ bool IdeologyManager::load_ideology_file(ast::NodeCPtr root) { )(value); ret &= add_ideology( - key, - colour, - ideology_group, - uncivilised, - can_reduce_consciousness, - can_reduce_militancy, - spawn_date, - std::move(add_political_reform), - std::move(remove_political_reform), - std::move(add_social_reform), - std::move(remove_social_reform), - std::move(add_military_reform), - std::move(add_economic_reform) + key, + colour, + ideology_group, + uncivilised, + can_reduce_consciousness, + can_reduce_militancy, + spawn_date, + std::move(add_political_reform), + std::move(remove_political_reform), + std::move(add_social_reform), + std::move(remove_social_reform), + std::move(add_military_reform), + std::move(add_economic_reform) ); return ret; diff --git a/src/openvic-simulation/politics/Ideology.hpp b/src/openvic-simulation/politics/Ideology.hpp index 1b4e98ffe..2b1219dbf 100644 --- a/src/openvic-simulation/politics/Ideology.hpp +++ b/src/openvic-simulation/politics/Ideology.hpp @@ -41,20 +41,20 @@ namespace OpenVic { IdeologyGroup const& group; Ideology( - std::string_view new_identifier, - index_t new_index, - colour_t new_colour, - IdeologyGroup const& new_group, - bool new_is_allowed_for_uncivilised, - bool new_can_reduce_consciousness, - bool new_can_reduce_militancy, - std::optional new_spawn_date, - ConditionalWeightBase&& new_add_political_reform, - ConditionalWeightBase&& new_remove_political_reform, - ConditionalWeightBase&& new_add_social_reform, - ConditionalWeightBase&& new_remove_social_reform, - ConditionalWeightBase&& new_add_military_reform, - ConditionalWeightBase&& new_add_economic_reform + std::string_view new_identifier, + index_t new_index, + colour_t new_colour, + IdeologyGroup const& new_group, + bool new_is_allowed_for_uncivilised, + bool new_can_reduce_consciousness, + bool new_can_reduce_militancy, + std::optional new_spawn_date, + ConditionalWeightBase&& new_add_political_reform, + ConditionalWeightBase&& new_remove_political_reform, + ConditionalWeightBase&& new_add_social_reform, + ConditionalWeightBase&& new_remove_social_reform, + ConditionalWeightBase&& new_add_military_reform, + ConditionalWeightBase&& new_add_economic_reform ); Ideology(Ideology&&) = default; }; @@ -68,19 +68,19 @@ namespace OpenVic { bool add_ideology_group(std::string_view identifier); bool add_ideology( - std::string_view identifier, - colour_t colour, - IdeologyGroup const* group, - bool uncivilised, - bool can_reduce_consciousness, - bool can_reduce_militancy, - std::optional spawn_date, - ConditionalWeightBase&& add_political_reform, - ConditionalWeightBase&& remove_political_reform, - ConditionalWeightBase&& add_social_reform, - ConditionalWeightBase&& remove_social_reform, - ConditionalWeightBase&& add_military_reform, - ConditionalWeightBase&& add_economic_reform + std::string_view identifier, + colour_t colour, + IdeologyGroup const* group, + bool uncivilised, + bool can_reduce_consciousness, + bool can_reduce_militancy, + std::optional spawn_date, + ConditionalWeightBase&& add_political_reform, + ConditionalWeightBase&& remove_political_reform, + ConditionalWeightBase&& add_social_reform, + ConditionalWeightBase&& remove_social_reform, + ConditionalWeightBase&& add_military_reform, + ConditionalWeightBase&& add_economic_reform ); bool load_ideology_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/politics/IssueGroup.hpp b/src/openvic-simulation/politics/IssueGroup.hpp index 1b14d9cc1..014171aee 100644 --- a/src/openvic-simulation/politics/IssueGroup.hpp +++ b/src/openvic-simulation/politics/IssueGroup.hpp @@ -6,9 +6,6 @@ namespace OpenVic { struct PartyPolicyGroup; struct ReformGroup; - using issue_group_t = std::variant< - std::monostate, - std::reference_wrapper, - std::reference_wrapper - >; -} \ No newline at end of file + using issue_group_t = + std::variant, std::reference_wrapper>; +} diff --git a/src/openvic-simulation/politics/IssueManager.cpp b/src/openvic-simulation/politics/IssueManager.cpp index b219cdce8..d25ecf537 100644 --- a/src/openvic-simulation/politics/IssueManager.cpp +++ b/src/openvic-simulation/politics/IssueManager.cpp @@ -1,7 +1,7 @@ #include "IssueManager.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/core/Typedefs.hpp" +#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -13,14 +13,17 @@ bool IssueManager::add_party_policy_group(std::string_view identifier) { } return party_policy_groups.emplace_item( - identifier, - identifier, index_from_count(get_party_policy_group_count()) + identifier, identifier, index_from_count(get_party_policy_group_count()) ); } bool IssueManager::add_party_policy( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, RuleSet&& rules, - bool jingoism + std::string_view identifier, + colour_t new_colour, + ModifierValue&& values, + PartyPolicyGroup& party_policy_group, + RuleSet&& rules, + bool jingoism ) { if (identifier.empty()) { spdlog::error_s("Invalid party policy identifier - empty!"); @@ -28,10 +31,15 @@ bool IssueManager::add_party_policy( } if (!party_policies.emplace_item( - identifier, - index_from_count(get_party_policy_count()), identifier, - new_colour, std::move(values), party_policy_group, std::move(rules), jingoism - )) { + identifier, + index_from_count(get_party_policy_count()), + identifier, + new_colour, + std::move(values), + party_policy_group, + std::move(rules), + jingoism + )) { return false; } @@ -45,24 +53,23 @@ bool IssueManager::add_reform_type(std::string_view identifier, bool uncivilised return false; } - return reform_types.emplace_item( - identifier, - identifier, uncivilised - ); + return reform_types.emplace_item(identifier, identifier, uncivilised); } -bool IssueManager::add_reform_group( - std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative -) { +bool IssueManager::add_reform_group(std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative) { if (identifier.empty()) { spdlog::error_s("Invalid issue group identifier - empty!"); return false; } if (!reform_groups.emplace_item( - identifier, - identifier, index_from_count(get_reform_group_count()), reform_type, ordered, administrative - )) { + identifier, + identifier, + index_from_count(get_reform_group_count()), + reform_type, + ordered, + administrative + )) { return false; } @@ -71,9 +78,17 @@ bool IssueManager::add_reform_group( } bool IssueManager::add_reform( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, ReformGroup& reform_group, size_t ordinal, - fixed_point_t administrative_multiplier, RuleSet&& rules, Reform::tech_cost_t technology_cost, ConditionScript&& allow, - ConditionScript&& on_execute_trigger, EffectScript&& on_execute_effect + std::string_view identifier, + colour_t new_colour, + ModifierValue&& values, + ReformGroup& reform_group, + size_t ordinal, + fixed_point_t administrative_multiplier, + RuleSet&& rules, + Reform::tech_cost_t technology_cost, + ConditionScript&& allow, + ConditionScript&& on_execute_trigger, + EffectScript&& on_execute_effect ) { if (identifier.empty()) { spdlog::error_s("Invalid issue identifier - empty!"); @@ -84,38 +99,47 @@ bool IssueManager::add_reform( if (ordinal == 0) { if (technology_cost != 0) { spdlog::warn_s( - "Non-zero technology cost {} found in ordinal 0 uncivilised reform {}!", - technology_cost, identifier + "Non-zero technology cost {} found in ordinal 0 uncivilised reform {}!", technology_cost, identifier ); } } else { if (technology_cost <= 0) { spdlog::warn_s( - "Non-positive technology cost {} found in ordinal {} uncivilised reform {}!", - technology_cost, ordinal, identifier + "Non-positive technology cost {} found in ordinal {} uncivilised reform {}!", + technology_cost, + ordinal, + identifier ); } } } else if (technology_cost != 0) { - spdlog::warn_s( - "Non-zero technology cost {} found in civilised reform {}!", - technology_cost, identifier - ); + spdlog::warn_s("Non-zero technology cost {} found in civilised reform {}!", technology_cost, identifier); } if (administrative_multiplier != 0 && !reform_group.is_administrative) { spdlog::warn_s( - "Non-zero administrative multiplier {} found in reform {} belonging to non-administrative group {}!", - administrative_multiplier, identifier, reform_group + "Non-zero administrative multiplier {} found in reform {} belonging to non-administrative group {}!", + administrative_multiplier, + identifier, + reform_group ); } if (!reforms.emplace_item( - identifier, - index_from_count(get_reform_count()), identifier, - new_colour, std::move(values), reform_group, ordinal, administrative_multiplier, std::move(rules), - technology_cost, std::move(allow), std::move(on_execute_trigger), std::move(on_execute_effect) - )) { + identifier, + index_from_count(get_reform_count()), + identifier, + new_colour, + std::move(values), + reform_group, + ordinal, + administrative_multiplier, + std::move(rules), + technology_cost, + std::move(allow), + std::move(on_execute_trigger), + std::move(on_execute_effect) + )) { return false; } @@ -125,8 +149,7 @@ bool IssueManager::add_reform( bool IssueManager::_load_party_policy_group(size_t& expected_party_policies, std::string_view identifier, ast::NodeCPtr node) { spdlog::scope scope { fmt::format("party policy group {}", identifier) }; - return expect_length(add_variable_callback(expected_party_policies))(node) - & add_party_policy_group(identifier); + return expect_length(add_variable_callback(expected_party_policies))(node) & add_party_policy_group(identifier); } /* Each colour is made up of these components in some order: @@ -144,8 +167,8 @@ static constexpr size_t varying_colour_denominator = 60; /* 3! = 3 (choices for 0) * 2 (choices for 252) * 1 (choices for 4.25 * i) */ static constexpr size_t colour_pattern_period = 6; -static constexpr std::array dim_colour_indices { 0, 1, 2, 0, 1, 2 }; -static constexpr std::array bright_colour_indices { 1, 2, 0, 2, 0, 1 }; +static constexpr std::array dim_colour_indices { 0, 1, 2, 0, 1, 2 }; +static constexpr std::array bright_colour_indices { 1, 2, 0, 2, 0, 1 }; static constexpr std::array varying_colour_indices { 2, 0, 1, 1, 2, 0 }; static constexpr colour_t create_issue_reform_colour(size_t index) { @@ -157,15 +180,18 @@ static constexpr colour_t create_issue_reform_colour(size_t index) { ret[bright_colour_indices[periodic_index]] = bright_colour_component; - ret[varying_colour_indices[periodic_index]] = static_cast(colour_t::max_value) - * ((index * scattering_prime) % varying_colour_denominator) / varying_colour_denominator; + ret[varying_colour_indices[periodic_index]] = + static_cast(colour_t::max_value) * ((index * scattering_prime) % varying_colour_denominator) / + varying_colour_denominator; return ret; } bool IssueManager::_load_party_policy( - ModifierManager const& modifier_manager, std::string_view identifier, - PartyPolicyGroup& party_policy_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, + std::string_view identifier, + PartyPolicyGroup& party_policy_group, + ast::NodeCPtr node ) { spdlog::scope scope { fmt::format("party policy {}", identifier) }; @@ -173,35 +199,34 @@ bool IssueManager::_load_party_policy( RuleSet rules; bool is_jingoism = false; - bool ret = NodeTools::expect_dictionary_keys_and_default( - modifier_manager.expect_base_country_modifier(values), - "is_jingoism", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_jingoism)), - "rules", ZERO_OR_ONE, RuleSet::expect_rule_set(move_variable_callback(rules)), - "war_exhaustion_effect", ZERO_OR_ONE, [](const ast::NodeCPtr _) -> bool { - spdlog::warn_s("war_exhaustion_effect does nothing (vanilla issues have it)."); - return true; - } - )(node); + bool + ret = NodeTools::expect_dictionary_keys_and_default(modifier_manager.expect_base_country_modifier(values), "is_jingoism", ZERO_OR_ONE, expect_bool(assign_variable_callback(is_jingoism)), "rules", ZERO_OR_ONE, RuleSet::expect_rule_set(move_variable_callback(rules)), "war_exhaustion_effect", ZERO_OR_ONE, [](const ast::NodeCPtr _) -> bool { + spdlog::warn_s("war_exhaustion_effect does nothing (vanilla issues have it)."); + return true; + })(node); ret &= add_party_policy( - identifier, create_issue_reform_colour(get_party_policy_count() + get_reform_count()), std::move(values), party_policy_group, - std::move(rules), is_jingoism + identifier, + create_issue_reform_colour(get_party_policy_count() + get_reform_count()), + std::move(values), + party_policy_group, + std::move(rules), + is_jingoism ); return ret; } bool IssueManager::_load_reform_group( - size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node + size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node ) { spdlog::scope scope { fmt::format("reform group {}", identifier) }; bool ordered = false, administrative = false; - bool ret = expect_dictionary_keys_and_default( - increment_callback(expected_reforms), - "next_step_only", ZERO_OR_ONE, expect_bool(assign_variable_callback(ordered)), - "administrative", ZERO_OR_ONE, expect_bool(assign_variable_callback(administrative)) - )(node); + bool ret = + expect_dictionary_keys_and_default(increment_callback(expected_reforms), "next_step_only", ZERO_OR_ONE, expect_bool(assign_variable_callback(ordered)), "administrative", ZERO_OR_ONE, expect_bool(assign_variable_callback(administrative)))( + node + ); ret &= add_reform_group(identifier, reform_type, ordered, administrative); @@ -209,8 +234,11 @@ bool IssueManager::_load_reform_group( } bool IssueManager::_load_reform( - ModifierManager const& modifier_manager, size_t ordinal, std::string_view identifier, - ReformGroup& reform_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, + size_t ordinal, + std::string_view identifier, + ReformGroup& reform_group, + ast::NodeCPtr node ) { spdlog::scope scope { fmt::format("reform {}", identifier) }; using enum scope_type_t; @@ -236,9 +264,17 @@ bool IssueManager::_load_reform( )(node); ret &= add_reform( - identifier, create_issue_reform_colour(get_party_policy_count() + get_reform_count()), std::move(values), reform_group, - ordinal, administrative_multiplier, std::move(rules), technology_cost, std::move(allow), std::move(on_execute_trigger), - std::move(on_execute_effect) + identifier, + create_issue_reform_colour(get_party_policy_count() + get_reform_count()), + std::move(values), + reform_group, + ordinal, + administrative_multiplier, + std::move(rules), + technology_cost, + std::move(allow), + std::move(on_execute_trigger), + std::move(on_execute_effect) ); return ret; @@ -253,39 +289,33 @@ bool IssueManager::_load_reform( * POL-99, POL-101, POL-102, POL-103, POL-104, POL-105, POL-107, POL-108, POL-109, POL-110, POL-111, POL-113, * POL-113, POL-114, POL-115, POL-116 */ -bool IssueManager::load_issues_file( - ModifierManager const& modifier_manager, ast::NodeCPtr root -) { +bool IssueManager::load_issues_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/issues.txt" }; bool party_issues_found = false; size_t expected_party_policy_groups = 0; size_t expected_reform_groups = 0; /* Reserve space for issue and reform groups and reserve space for and load reform types. */ - bool ret = expect_dictionary_reserve_length( - reform_types, - [this, &party_issues_found, &expected_party_policy_groups, &expected_reform_groups]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - if (key == "party_issues") { - if (party_issues_found) { - /* Error emitted here allowing later passes to return true with no error message. */ - spdlog::error_s("Duplicate party issues found!"); - return false; - } - party_issues_found = true; - - return expect_length(add_variable_callback(expected_party_policy_groups))(value); - } else { - static const string_set_t uncivilised_reform_groups { - "economic_reforms", "education_reforms", "military_reforms" - }; - - return expect_length(add_variable_callback(expected_reform_groups))(value) - & add_reform_type(key, uncivilised_reform_groups.contains(key)); - } - } - )(root); + bool ret = + expect_dictionary_reserve_length(reform_types, [this, &party_issues_found, &expected_party_policy_groups, &expected_reform_groups](std::string_view key, ast::NodeCPtr value) -> bool { + if (key == "party_issues") { + if (party_issues_found) { + /* Error emitted here allowing later passes to return true with no error message. */ + spdlog::error_s("Duplicate party issues found!"); + return false; + } + party_issues_found = true; + + return expect_length(add_variable_callback(expected_party_policy_groups))(value); + } else { + static const string_set_t uncivilised_reform_groups { + "economic_reforms", "education_reforms", "military_reforms" + }; + + return expect_length(add_variable_callback(expected_reform_groups))(value) & + add_reform_type(key, uncivilised_reform_groups.contains(key)); + } + })(root); lock_reform_types(); @@ -297,35 +327,30 @@ bool IssueManager::load_issues_file( size_t expected_reforms = 0; /* Load issue and reform groups. */ - ret &= expect_dictionary( - [this, &party_issues_found, &expected_party_policies, &expected_reforms]( - std::string_view type_key, ast::NodeCPtr type_value - ) -> bool { - if (type_key == "party_issues") { - if (party_issues_found) { - return true; /* Error will have been emitted in first pass. */ - } - party_issues_found = true; - - return expect_dictionary([this, &expected_party_policies](std::string_view key, ast::NodeCPtr value) -> bool { - return _load_party_policy_group(expected_party_policies, key, value); - })(type_value); - } else { - ReformType* reform_type = reform_types.get_item_by_identifier(type_key); - - if (OV_unlikely(reform_type == nullptr)) { - spdlog::error_s("Reform type \"{}\" not found!", type_key); - return false; - } - - return expect_dictionary( - [this, reform_type, &expected_reforms](std::string_view key, ast::NodeCPtr value) -> bool { - return _load_reform_group(expected_reforms, key, *reform_type, value); - } - )(type_value); - } - } - )(root); + ret &= + expect_dictionary([this, &party_issues_found, &expected_party_policies, &expected_reforms](std::string_view type_key, ast::NodeCPtr type_value) -> bool { + if (type_key == "party_issues") { + if (party_issues_found) { + return true; /* Error will have been emitted in first pass. */ + } + party_issues_found = true; + + return expect_dictionary([this, &expected_party_policies](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_party_policy_group(expected_party_policies, key, value); + })(type_value); + } else { + ReformType* reform_type = reform_types.get_item_by_identifier(type_key); + + if (OV_unlikely(reform_type == nullptr)) { + spdlog::error_s("Reform type \"{}\" not found!", type_key); + return false; + } + + return expect_dictionary([this, reform_type, &expected_reforms](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_reform_group(expected_reforms, key, *reform_type, value); + })(type_value); + } + })(root); lock_party_policy_groups(); lock_reform_groups(); @@ -336,58 +361,46 @@ bool IssueManager::load_issues_file( party_issues_found = false; /* Load issues and reforms. */ - ret &= expect_dictionary( - [this, &party_issues_found, &modifier_manager]( - std::string_view type_key, ast::NodeCPtr type_value - ) -> bool { - if (type_key == "party_issues") { - if (party_issues_found) { - return true; - } - party_issues_found = true; + ret &= expect_dictionary([this, &party_issues_found, &modifier_manager](std::string_view type_key, ast::NodeCPtr type_value) -> bool { + if (type_key == "party_issues") { + if (party_issues_found) { + return true; + } + party_issues_found = true; - return expect_dictionary([this, &modifier_manager]( - std::string_view group_key, ast::NodeCPtr group_value - ) -> bool { - PartyPolicyGroup* party_policy_group = party_policy_groups.get_item_by_identifier(group_key); + return expect_dictionary([this, &modifier_manager](std::string_view group_key, ast::NodeCPtr group_value) -> bool { + PartyPolicyGroup* party_policy_group = party_policy_groups.get_item_by_identifier(group_key); - if (OV_unlikely(party_policy_group == nullptr)) { - spdlog::error_s("Party policy group \"{}\" not found!", group_key); - return false; - } + if (OV_unlikely(party_policy_group == nullptr)) { + spdlog::error_s("Party policy group \"{}\" not found!", group_key); + return false; + } - return expect_dictionary([this, &modifier_manager, party_policy_group]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - return _load_party_policy(modifier_manager, key, *party_policy_group, value); - })(group_value); - })(type_value); - } else { - return expect_dictionary([this, &party_issues_found, &modifier_manager]( - std::string_view group_key, ast::NodeCPtr group_value - ) -> bool { - ReformGroup* reform_group = reform_groups.get_item_by_identifier(group_key); - - if (OV_unlikely(reform_group == nullptr)) { - spdlog::error_s("Reform group \"{}\" not found!", group_key); - return false; - } + return expect_dictionary([this, &modifier_manager, party_policy_group](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_party_policy(modifier_manager, key, *party_policy_group, value); + })(group_value); + })(type_value); + } else { + return expect_dictionary([this, &party_issues_found, &modifier_manager](std::string_view group_key, ast::NodeCPtr group_value) -> bool { + ReformGroup* reform_group = reform_groups.get_item_by_identifier(group_key); - size_t ordinal = 0; + if (OV_unlikely(reform_group == nullptr)) { + spdlog::error_s("Reform group \"{}\" not found!", group_key); + return false; + } - return expect_dictionary([this, &modifier_manager, reform_group, &ordinal]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - if (key == "next_step_only" || key == "administrative") { - return true; - } + size_t ordinal = 0; - return _load_reform(modifier_manager, ordinal++, key, *reform_group, value); - })(group_value); - })(type_value); - } + return expect_dictionary([this, &modifier_manager, reform_group, &ordinal](std::string_view key, ast::NodeCPtr value) -> bool { + if (key == "next_step_only" || key == "administrative") { + return true; + } + + return _load_reform(modifier_manager, ordinal++, key, *reform_group, value); + })(group_value); + })(type_value); } - )(root); + })(root); lock_party_policies(); lock_reforms(); diff --git a/src/openvic-simulation/politics/IssueManager.hpp b/src/openvic-simulation/politics/IssueManager.hpp index 8f4e0dea2..6ac22b424 100644 --- a/src/openvic-simulation/politics/IssueManager.hpp +++ b/src/openvic-simulation/politics/IssueManager.hpp @@ -21,15 +21,20 @@ namespace OpenVic { bool _load_party_policy_group(size_t& expected_party_policies, std::string_view identifier, ast::NodeCPtr node); bool _load_party_policy( - ModifierManager const& modifier_manager, std::string_view identifier, - PartyPolicyGroup& party_policy_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, + std::string_view identifier, + PartyPolicyGroup& party_policy_group, + ast::NodeCPtr node ); bool _load_reform_group( - size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node + size_t& expected_reforms, std::string_view identifier, ReformType& reform_type, ast::NodeCPtr node ); bool _load_reform( - ModifierManager const& modifier_manager, size_t ordinal, - std::string_view identifier, ReformGroup& reform_group, ast::NodeCPtr node + ModifierManager const& modifier_manager, + size_t ordinal, + std::string_view identifier, + ReformGroup& reform_group, + ast::NodeCPtr node ); public: @@ -54,45 +59,53 @@ namespace OpenVic { return {}; } constexpr NodeTools::NodeCallback auto expect_base_issue_group_identifier( - NodeTools::Callback auto callback, bool warn = false + NodeTools::Callback auto callback, bool warn = false ) const { - return NodeTools::expect_identifier( - [this, callback, warn](std::string_view identifier) -> bool { - if (identifier.empty()) { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Invalid base issue group identifier: empty!" - ); - return warn; - } - issue_group_t issue_group = get_base_issue_group_by_identifier(identifier); - if (std::holds_alternative(issue_group)) { - spdlog::log_s( - warn ? spdlog::level::warn : spdlog::level::err, - "Invalid base issue group identifier: {}", identifier - ); - return warn; - } - - return callback(issue_group); + return NodeTools::expect_identifier([this, callback, warn](std::string_view identifier) -> bool { + if (identifier.empty()) { + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Invalid base issue group identifier: empty!" + ); + return warn; } - ); + issue_group_t issue_group = get_base_issue_group_by_identifier(identifier); + if (std::holds_alternative(issue_group)) { + spdlog::log_s( + warn ? spdlog::level::warn : spdlog::level::err, "Invalid base issue group identifier: {}", identifier + ); + return warn; + } + + return callback(issue_group); + }); } bool add_party_policy_group(std::string_view identifier); bool add_party_policy( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, PartyPolicyGroup& party_policy_group, RuleSet&& rules, - bool jingoism + std::string_view identifier, + colour_t new_colour, + ModifierValue&& values, + PartyPolicyGroup& party_policy_group, + RuleSet&& rules, + bool jingoism ); bool add_reform_type(std::string_view identifier, bool uncivilised); bool add_reform_group(std::string_view identifier, ReformType& reform_type, bool ordered, bool administrative); bool add_reform( - std::string_view identifier, colour_t new_colour, ModifierValue&& values, ReformGroup& reform_group, - size_t ordinal, fixed_point_t administrative_multiplier, RuleSet&& rules, Reform::tech_cost_t technology_cost, - ConditionScript&& allow, ConditionScript&& on_execute_trigger, EffectScript&& on_execute_effect + std::string_view identifier, + colour_t new_colour, + ModifierValue&& values, + ReformGroup& reform_group, + size_t ordinal, + fixed_point_t administrative_multiplier, + RuleSet&& rules, + Reform::tech_cost_t technology_cost, + ConditionScript&& allow, + ConditionScript&& on_execute_trigger, + EffectScript&& on_execute_effect ); bool load_issues_file(ModifierManager const& modifier_manager, ast::NodeCPtr root); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/NationalFocus.cpp b/src/openvic-simulation/politics/NationalFocus.cpp index f62bd07d1..0b26cca80 100644 --- a/src/openvic-simulation/politics/NationalFocus.cpp +++ b/src/openvic-simulation/politics/NationalFocus.cpp @@ -1,10 +1,10 @@ #include "NationalFocus.hpp" +#include "openvic-simulation/core/FormatValidate.hpp" #include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/politics/Ideology.hpp" #include "openvic-simulation/population/PopManager.hpp" -#include "openvic-simulation/core/FormatValidate.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -12,33 +12,27 @@ using namespace OpenVic::NodeTools; NationalFocusGroup::NationalFocusGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} NationalFocus::NationalFocus( - std::string_view new_identifier, - NationalFocusGroup const& new_group, - uint8_t new_icon, - bool new_has_flashpoint, - fixed_point_t new_flashpoint_tension, - bool new_own_provinces, - bool new_outliner_show_as_percent, - ModifierValue&& new_modifiers, - Ideology const* new_loyalty_ideology, - fixed_point_t new_loyalty_value, - fixed_point_t new_encourage_railroads, - fixed_point_map_t&& new_encourage_goods, - fixed_point_map_t&& new_encourage_pop_types, - ConditionScript&& new_limit -) : Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_FOCUS }, - group { new_group }, - icon { new_icon }, - has_flashpoint { new_has_flashpoint }, - flashpoint_tension { new_flashpoint_tension }, - own_provinces { new_own_provinces }, - outliner_show_as_percent { new_outliner_show_as_percent }, - loyalty_ideology { new_loyalty_ideology }, - loyalty_value { new_loyalty_value }, - encourage_railroads { new_encourage_railroads }, - encourage_goods { std::move(new_encourage_goods) }, - encourage_pop_types { std::move(new_encourage_pop_types) }, - limit { std::move(new_limit) } {} + std::string_view new_identifier, + NationalFocusGroup const& new_group, + uint8_t new_icon, + bool new_has_flashpoint, + fixed_point_t new_flashpoint_tension, + bool new_own_provinces, + bool new_outliner_show_as_percent, + ModifierValue&& new_modifiers, + Ideology const* new_loyalty_ideology, + fixed_point_t new_loyalty_value, + fixed_point_t new_encourage_railroads, + fixed_point_map_t&& new_encourage_goods, + fixed_point_map_t&& new_encourage_pop_types, + ConditionScript&& new_limit +) : + Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_FOCUS }, group { new_group }, + icon { new_icon }, has_flashpoint { new_has_flashpoint }, flashpoint_tension { new_flashpoint_tension }, + own_provinces { new_own_provinces }, outliner_show_as_percent { new_outliner_show_as_percent }, + loyalty_ideology { new_loyalty_ideology }, loyalty_value { new_loyalty_value }, + encourage_railroads { new_encourage_railroads }, encourage_goods { std::move(new_encourage_goods) }, + encourage_pop_types { std::move(new_encourage_pop_types) }, limit { std::move(new_limit) } {} bool NationalFocus::parse_scripts(DefinitionManager const& definition_manager) { spdlog::scope scope { fmt::format("national focus {}", get_identifier()) }; @@ -55,20 +49,20 @@ inline bool NationalFocusManager::add_national_focus_group(std::string_view iden } inline bool NationalFocusManager::add_national_focus( - std::string_view identifier, - NationalFocusGroup const& group, - uint8_t icon, - bool has_flashpoint, - fixed_point_t flashpoint_tension, - bool own_provinces, - bool outliner_show_as_percent, - ModifierValue&& modifiers, - Ideology const* loyalty_ideology, - fixed_point_t loyalty_value, - fixed_point_t encourage_railroads, - fixed_point_map_t&& encourage_goods, - fixed_point_map_t&& encourage_pop_types, - ConditionScript&& limit + std::string_view identifier, + NationalFocusGroup const& group, + uint8_t icon, + bool has_flashpoint, + fixed_point_t flashpoint_tension, + bool own_provinces, + bool outliner_show_as_percent, + ModifierValue&& modifiers, + Ideology const* loyalty_ideology, + fixed_point_t loyalty_value, + fixed_point_t encourage_railroads, + fixed_point_map_t&& encourage_goods, + fixed_point_map_t&& encourage_pop_types, + ConditionScript&& limit ) { spdlog::scope scope { fmt::format("national focus {}", identifier) }; if (identifier.empty()) { @@ -83,63 +77,69 @@ inline bool NationalFocusManager::add_national_focus( if ((loyalty_ideology == nullptr) != (loyalty_value == 0)) { spdlog::warn_s( - "Party loyalty incorrectly defined for national focus {}: ideology = {}, value = {}", - identifier, ovfmt::validate(loyalty_ideology), loyalty_value + "Party loyalty incorrectly defined for national focus {}: ideology = {}, value = {}", + identifier, + ovfmt::validate(loyalty_ideology), + loyalty_value ); } return national_foci.emplace_item( - identifier, - identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, - std::move(modifiers), loyalty_ideology, loyalty_value, encourage_railroads, std::move(encourage_goods), - std::move(encourage_pop_types), std::move(limit) + identifier, + identifier, + group, + icon, + has_flashpoint, + flashpoint_tension, + own_provinces, + outliner_show_as_percent, + std::move(modifiers), + loyalty_ideology, + loyalty_value, + encourage_railroads, + std::move(encourage_goods), + std::move(encourage_pop_types), + std::move(limit) ); } bool NationalFocusManager::load_national_foci_file( - PopManager const& pop_manager, IdeologyManager const& ideology_manager, - GoodDefinitionManager const& good_definition_manager, ModifierManager const& modifier_manager, ast::NodeCPtr root + PopManager const& pop_manager, + IdeologyManager const& ideology_manager, + GoodDefinitionManager const& good_definition_manager, + ModifierManager const& modifier_manager, + ast::NodeCPtr root ) { spdlog::scope scope { "common/national_focus.txt" }; size_t expected_national_foci = 0; - bool ret = expect_dictionary_reserve_length( - national_focus_groups, - [this, &expected_national_foci](std::string_view identifier, ast::NodeCPtr node) -> bool { - return expect_length(add_variable_callback(expected_national_foci))(node) & add_national_focus_group(identifier); - } - )(root); + bool ret = + expect_dictionary_reserve_length(national_focus_groups, [this, &expected_national_foci](std::string_view identifier, ast::NodeCPtr node) -> bool { + return expect_length(add_variable_callback(expected_national_foci))(node) & add_national_focus_group(identifier); + })(root); lock_national_focus_groups(); reserve_more_national_foci(expected_national_foci); - ret &= expect_national_focus_group_dictionary( - [this, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager]( - NationalFocusGroup const& group, ast::NodeCPtr group_node - ) -> bool { - return expect_dictionary( - [this, &group, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager]( - std::string_view identifier, ast::NodeCPtr node - ) -> bool { - spdlog::scope scope { fmt::format("national focus {}", identifier) }; - using enum scope_type_t; - - uint8_t icon = 0; - bool has_flashpoint = false, own_provinces = true, outliner_show_as_percent = false; - fixed_point_t flashpoint_tension = 0; - ModifierValue modifiers; - Ideology const* loyalty_ideology = nullptr; - fixed_point_t loyalty_value = 0; - fixed_point_t encourage_railroads = 0; - fixed_point_map_t encourage_goods; - fixed_point_map_t encourage_pop_types; - ConditionScript limit { - PROVINCE | COUNTRY, PROVINCE | COUNTRY, NO_SCOPE - }; - - auto expect_base_province_modifier_cb = modifier_manager.expect_base_province_modifier(modifiers); - bool ret = NodeTools::expect_dictionary_keys_and_default( + ret &= expect_national_focus_group_dictionary([this, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager](NationalFocusGroup const& group, ast::NodeCPtr group_node) -> bool { + return expect_dictionary([this, &group, &pop_manager, &ideology_manager, &good_definition_manager, &modifier_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + spdlog::scope scope { fmt::format("national focus {}", identifier) }; + using enum scope_type_t; + + uint8_t icon = 0; + bool has_flashpoint = false, own_provinces = true, outliner_show_as_percent = false; + fixed_point_t flashpoint_tension = 0; + ModifierValue modifiers; + Ideology const* loyalty_ideology = nullptr; + fixed_point_t loyalty_value = 0; + fixed_point_t encourage_railroads = 0; + fixed_point_map_t encourage_goods; + fixed_point_map_t encourage_pop_types; + ConditionScript limit { PROVINCE | COUNTRY, PROVINCE | COUNTRY, NO_SCOPE }; + + auto expect_base_province_modifier_cb = modifier_manager.expect_base_province_modifier(modifiers); + bool ret = NodeTools::expect_dictionary_keys_and_default( [&good_definition_manager, &encourage_goods, &pop_manager, &encourage_pop_types, &expect_base_province_modifier_cb]( std::string_view key, ast::NodeCPtr value ) mutable -> bool { @@ -168,17 +168,26 @@ bool NationalFocusManager::load_national_foci_file( "railroads", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(encourage_railroads)) )(node); - ret &= add_national_focus( - identifier, group, icon, has_flashpoint, flashpoint_tension, own_provinces, outliner_show_as_percent, - std::move(modifiers), loyalty_ideology, loyalty_value, encourage_railroads, - std::move(encourage_goods), std::move(encourage_pop_types), std::move(limit) - ); - - return ret; - } - )(group_node); - } - )(root); + ret &= add_national_focus( + identifier, + group, + icon, + has_flashpoint, + flashpoint_tension, + own_provinces, + outliner_show_as_percent, + std::move(modifiers), + loyalty_ideology, + loyalty_value, + encourage_railroads, + std::move(encourage_goods), + std::move(encourage_pop_types), + std::move(limit) + ); + + return ret; + })(group_node); + })(root); lock_national_foci(); diff --git a/src/openvic-simulation/politics/NationalFocus.hpp b/src/openvic-simulation/politics/NationalFocus.hpp index 4fccee361..99a1a401e 100644 --- a/src/openvic-simulation/politics/NationalFocus.hpp +++ b/src/openvic-simulation/politics/NationalFocus.hpp @@ -40,20 +40,20 @@ namespace OpenVic { const fixed_point_map_t encourage_pop_types; NationalFocus( - std::string_view new_identifier, - NationalFocusGroup const& new_group, - uint8_t new_icon, - bool new_has_flashpoint, - fixed_point_t new_flashpoint_tension, - bool new_own_provinces, - bool new_outliner_show_as_percent, - ModifierValue&& new_modifiers, - Ideology const* new_loyalty_ideology, - fixed_point_t new_loyalty_value, - fixed_point_t new_encourage_railroads, - fixed_point_map_t&& new_encourage_goods, - fixed_point_map_t&& new_encourage_pop_types, - ConditionScript&& new_limit + std::string_view new_identifier, + NationalFocusGroup const& new_group, + uint8_t new_icon, + bool new_has_flashpoint, + fixed_point_t new_flashpoint_tension, + bool new_own_provinces, + bool new_outliner_show_as_percent, + ModifierValue&& new_modifiers, + Ideology const* new_loyalty_ideology, + fixed_point_t new_loyalty_value, + fixed_point_t new_encourage_railroads, + fixed_point_map_t&& new_encourage_goods, + fixed_point_map_t&& new_encourage_pop_types, + ConditionScript&& new_limit ); NationalFocus(NationalFocus&&) = default; }; @@ -71,25 +71,28 @@ namespace OpenVic { inline bool add_national_focus_group(std::string_view identifier); inline bool add_national_focus( - std::string_view identifier, - NationalFocusGroup const& group, - uint8_t icon, - bool has_flashpoint, - fixed_point_t flashpoint_tension, - bool own_provinces, - bool outliner_show_as_percent, - ModifierValue&& modifiers, - Ideology const* loyalty_ideology, - fixed_point_t loyalty_value, - fixed_point_t encourage_railroads, - fixed_point_map_t&& encourage_goods, - fixed_point_map_t&& encourage_pop_types, - ConditionScript&& limit + std::string_view identifier, + NationalFocusGroup const& group, + uint8_t icon, + bool has_flashpoint, + fixed_point_t flashpoint_tension, + bool own_provinces, + bool outliner_show_as_percent, + ModifierValue&& modifiers, + Ideology const* loyalty_ideology, + fixed_point_t loyalty_value, + fixed_point_t encourage_railroads, + fixed_point_map_t&& encourage_goods, + fixed_point_map_t&& encourage_pop_types, + ConditionScript&& limit ); bool load_national_foci_file( - PopManager const& pop_manager, IdeologyManager const& ideology_manager, - GoodDefinitionManager const& good_definition_manager, ModifierManager const& modifier_manager, ast::NodeCPtr root + PopManager const& pop_manager, + IdeologyManager const& ideology_manager, + GoodDefinitionManager const& good_definition_manager, + ModifierManager const& modifier_manager, + ast::NodeCPtr root ); bool parse_scripts(DefinitionManager const& definition_manager); diff --git a/src/openvic-simulation/politics/NationalValue.cpp b/src/openvic-simulation/politics/NationalValue.cpp index ef9bbee86..e1e199f9a 100644 --- a/src/openvic-simulation/politics/NationalValue.cpp +++ b/src/openvic-simulation/politics/NationalValue.cpp @@ -5,8 +5,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -NationalValue::NationalValue(std::string_view new_identifier, ModifierValue&& new_modifiers) - : Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_VALUE } {} +NationalValue::NationalValue(std::string_view new_identifier, ModifierValue&& new_modifiers) : + Modifier { new_identifier, std::move(new_modifiers), modifier_type_t::NATIONAL_VALUE } {} bool NationalValueManager::add_national_value(std::string_view identifier, ModifierValue&& modifiers) { if (identifier.empty()) { @@ -14,28 +14,21 @@ bool NationalValueManager::add_national_value(std::string_view identifier, Modif return false; } - return national_values.emplace_item( - identifier, - identifier, std::move(modifiers) - ); + return national_values.emplace_item(identifier, identifier, std::move(modifiers)); } bool NationalValueManager::load_national_values_file(ModifierManager const& modifier_manager, ast::NodeCPtr root) { spdlog::scope scope { "common/nationalvalues.txt" }; - bool ret = expect_dictionary_reserve_length( - national_values, - [this, &modifier_manager](std::string_view national_value_identifier, ast::NodeCPtr value) -> bool { - spdlog::scope scope { fmt::format("national value {}", national_value_identifier) }; - ModifierValue modifiers; - bool ret = NodeTools::expect_dictionary( - modifier_manager.expect_base_country_modifier(modifiers) - )(value); - - ret &= add_national_value(national_value_identifier, std::move(modifiers)); - - return ret; - } - )(root); + bool ret = + expect_dictionary_reserve_length(national_values, [this, &modifier_manager](std::string_view national_value_identifier, ast::NodeCPtr value) -> bool { + spdlog::scope scope { fmt::format("national value {}", national_value_identifier) }; + ModifierValue modifiers; + bool ret = NodeTools::expect_dictionary(modifier_manager.expect_base_country_modifier(modifiers))(value); + + ret &= add_national_value(national_value_identifier, std::move(modifiers)); + + return ret; + })(root); lock_national_values(); diff --git a/src/openvic-simulation/politics/PartyPolicy.hpp b/src/openvic-simulation/politics/PartyPolicy.hpp index f4c57a65f..6195fb07f 100644 --- a/src/openvic-simulation/politics/PartyPolicy.hpp +++ b/src/openvic-simulation/politics/PartyPolicy.hpp @@ -12,14 +12,13 @@ namespace OpenVic { // PartyPolicy group (i.e. trade_policy) struct PartyPolicyGroup : HasIndex, HasIdentifier { friend struct IssueManager; + private: memory::vector> SPAN_PROPERTY(party_policies); public: - PartyPolicyGroup( - std::string_view new_identifier, - index_t new_index - ) : HasIndex { new_index }, HasIdentifier { new_identifier } {} + PartyPolicyGroup(std::string_view new_identifier, index_t new_index) : + HasIndex { new_index }, HasIdentifier { new_identifier } {} PartyPolicyGroup(PartyPolicyGroup&&) = default; }; @@ -29,23 +28,18 @@ namespace OpenVic { PartyPolicyGroup const& group; PartyPolicy( - index_t new_index, - std::string_view new_identifier, - colour_t new_colour, - ModifierValue&& new_values, - PartyPolicyGroup const& new_issue_group, - RuleSet&& new_rules, - bool new_is_jingoism - ) : HasIndex { new_index }, - BaseIssue { - new_identifier, - new_colour, - std::move(new_values), - std::move(new_rules), - new_is_jingoism, - modifier_type_t::PARTY_POLICY - }, - group { new_issue_group } {} + index_t new_index, + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_values, + PartyPolicyGroup const& new_issue_group, + RuleSet&& new_rules, + bool new_is_jingoism + ) : + HasIndex { new_index }, + BaseIssue { new_identifier, new_colour, std::move(new_values), + std::move(new_rules), new_is_jingoism, modifier_type_t::PARTY_POLICY }, + group { new_issue_group } {} PartyPolicy(PartyPolicy&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/PoliticsInstanceManager.cpp b/src/openvic-simulation/politics/PoliticsInstanceManager.cpp index eea1305c2..dfe1f746f 100644 --- a/src/openvic-simulation/politics/PoliticsInstanceManager.cpp +++ b/src/openvic-simulation/politics/PoliticsInstanceManager.cpp @@ -6,11 +6,8 @@ using namespace OpenVic; PoliticsInstanceManager::PoliticsInstanceManager( - InstanceManager const& new_instance_manager, - forwardable_span ideologies -) - : instance_manager { new_instance_manager }, - ideology_spawn_date { ideologies } {} + InstanceManager const& new_instance_manager, forwardable_span ideologies +) : instance_manager { new_instance_manager }, ideology_spawn_date { ideologies } {} void PoliticsInstanceManager::setup_starting_ideologies() { const Date today = instance_manager.get_today(); @@ -39,16 +36,13 @@ void PoliticsInstanceManager::unlock_ideology(Ideology const& ideology) { if (!spawn_date.has_value()) { spawn_date = instance_manager.get_today(); } else { - spdlog::warn_s( - "Cannot unlock ideology \"{}\" - it was already unlocked on: {}", - ideology, *spawn_date - ); + spdlog::warn_s("Cannot unlock ideology \"{}\" - it was already unlocked on: {}", ideology, *spawn_date); } } void PoliticsInstanceManager::set_great_wars_enabled(bool enabled) { // if (enabled && !great_wars_enabled) { - // TODO - trigger "Great Wars discovered!" popup + // TODO - trigger "Great Wars discovered!" popup // } great_wars_enabled = enabled; diff --git a/src/openvic-simulation/politics/PoliticsInstanceManager.hpp b/src/openvic-simulation/politics/PoliticsInstanceManager.hpp index 06a7d4731..9ac87afb7 100644 --- a/src/openvic-simulation/politics/PoliticsInstanceManager.hpp +++ b/src/openvic-simulation/politics/PoliticsInstanceManager.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/core/object/Date.hpp" +#include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" #include "openvic-simulation/utility/Getters.hpp" -#include "openvic-simulation/core/portable/ForwardableSpan.hpp" namespace OpenVic { struct InstanceManager; @@ -22,10 +22,7 @@ namespace OpenVic { bool PROPERTY(world_wars_enabled, false); public: - PoliticsInstanceManager( - InstanceManager const& new_instance_manager, - forwardable_span ideologies - ); + PoliticsInstanceManager(InstanceManager const& new_instance_manager, forwardable_span ideologies); PoliticsInstanceManager(PoliticsInstanceManager&&) = default; void setup_starting_ideologies(); @@ -37,4 +34,4 @@ namespace OpenVic { void set_great_wars_enabled(bool enabled); void set_world_wars_enabled(bool enabled); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/PoliticsManager.hpp b/src/openvic-simulation/politics/PoliticsManager.hpp index 1c9b750bb..efca548fa 100644 --- a/src/openvic-simulation/politics/PoliticsManager.hpp +++ b/src/openvic-simulation/politics/PoliticsManager.hpp @@ -22,11 +22,13 @@ namespace OpenVic { return government_type_manager.load_government_types_file(ideology_manager, root); } inline bool load_national_foci_file( - PopManager const& pop_manager, GoodDefinitionManager const& good_definition_manager, - ModifierManager const& modifier_manager, ast::NodeCPtr root + PopManager const& pop_manager, + GoodDefinitionManager const& good_definition_manager, + ModifierManager const& modifier_manager, + ast::NodeCPtr root ) { return national_focus_manager.load_national_foci_file( - pop_manager, ideology_manager, good_definition_manager, modifier_manager, root + pop_manager, ideology_manager, good_definition_manager, modifier_manager, root ); } inline bool load_rebels_file(ast::NodeCPtr root) { diff --git a/src/openvic-simulation/politics/Rebel.cpp b/src/openvic-simulation/politics/Rebel.cpp index a6a8a33fe..51c59efab 100644 --- a/src/openvic-simulation/politics/Rebel.cpp +++ b/src/openvic-simulation/politics/Rebel.cpp @@ -2,35 +2,52 @@ #include +#include "openvic-simulation/modifier/ModifierManager.hpp" #include "openvic-simulation/politics/Government.hpp" #include "openvic-simulation/politics/Ideology.hpp" -#include "openvic-simulation/modifier/ModifierManager.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; RebelType::RebelType( - index_t new_index, std::string_view new_identifier, - RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, - RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, - bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, - bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, ConditionalWeightFactorMul&& new_will_rise, - ConditionalWeightFactorMul&& new_spawn_chance, ConditionalWeightFactorMul&& new_movement_evaluation, - ConditionScript&& new_siege_won_trigger, EffectScript&& new_siege_won_effect, - ConditionScript&& new_demands_enforced_trigger, EffectScript&& new_demands_enforced_effect -) : HasIndex { new_index }, - HasIdentifier { new_identifier }, - icon { icon }, area { area }, will_break_alliance_on_win { break_alliance_on_win }, - desired_governments { std::move(desired_governments) }, defection_type { defection }, independence_type { independence }, - defect_delay { defect_delay }, ideology { ideology }, allows_all_cultures { allow_all_cultures }, - allows_all_culture_groups { allow_all_culture_groups }, allows_all_religions { allow_all_religions }, - allows_all_ideologies { allow_all_ideologies }, is_resilient { resilient }, is_reinforcing { reinforcing }, has_generals { general }, - is_smart { smart }, will_transfer_units { unit_transfer }, occupation_mult { occupation_mult }, - will_rise { std::move(new_will_rise) }, spawn_chance { std::move(new_spawn_chance) }, - movement_evaluation { std::move(new_movement_evaluation) }, siege_won_trigger { std::move(new_siege_won_trigger) }, - siege_won_effect { std::move(new_siege_won_effect) }, demands_enforced_trigger { std::move(new_demands_enforced_trigger) }, - demands_enforced_effect { std::move(new_demands_enforced_effect) } {} + index_t new_index, + std::string_view new_identifier, + RebelType::icon_t icon, + RebelType::area_t area, + bool break_alliance_on_win, + RebelType::government_map_t&& desired_governments, + RebelType::defection_t defection, + RebelType::independence_t independence, + uint16_t defect_delay, + Ideology const* ideology, + bool allow_all_cultures, + bool allow_all_culture_groups, + bool allow_all_religions, + bool allow_all_ideologies, + bool resilient, + bool reinforcing, + bool general, + bool smart, + bool unit_transfer, + fixed_point_t occupation_mult, + ConditionalWeightFactorMul&& new_will_rise, + ConditionalWeightFactorMul&& new_spawn_chance, + ConditionalWeightFactorMul&& new_movement_evaluation, + ConditionScript&& new_siege_won_trigger, + EffectScript&& new_siege_won_effect, + ConditionScript&& new_demands_enforced_trigger, + EffectScript&& new_demands_enforced_effect +) : + HasIndex { new_index }, HasIdentifier { new_identifier }, icon { icon }, area { area }, + will_break_alliance_on_win { break_alliance_on_win }, desired_governments { std::move(desired_governments) }, + defection_type { defection }, independence_type { independence }, defect_delay { defect_delay }, ideology { ideology }, + allows_all_cultures { allow_all_cultures }, allows_all_culture_groups { allow_all_culture_groups }, + allows_all_religions { allow_all_religions }, allows_all_ideologies { allow_all_ideologies }, is_resilient { resilient }, + is_reinforcing { reinforcing }, has_generals { general }, is_smart { smart }, will_transfer_units { unit_transfer }, + occupation_mult { occupation_mult }, will_rise { std::move(new_will_rise) }, spawn_chance { std::move(new_spawn_chance) }, + movement_evaluation { std::move(new_movement_evaluation) }, siege_won_trigger { std::move(new_siege_won_trigger) }, + siege_won_effect { std::move(new_siege_won_effect) }, demands_enforced_trigger { std::move(new_demands_enforced_trigger) }, + demands_enforced_effect { std::move(new_demands_enforced_effect) } {} bool RebelType::parse_scripts(DefinitionManager const& definition_manager) { spdlog::scope scope { fmt::format("rebel type {}", get_identifier()) }; @@ -46,14 +63,32 @@ bool RebelType::parse_scripts(DefinitionManager const& definition_manager) { } bool RebelManager::add_rebel_type( - std::string_view new_identifier, RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, - RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, - bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, bool reinforcing, - bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, ConditionalWeightFactorMul&& will_rise, - ConditionalWeightFactorMul&& spawn_chance, ConditionalWeightFactorMul&& movement_evaluation, - ConditionScript&& siege_won_trigger, EffectScript&& siege_won_effect, ConditionScript&& demands_enforced_trigger, - EffectScript&& demands_enforced_effect + std::string_view new_identifier, + RebelType::icon_t icon, + RebelType::area_t area, + bool break_alliance_on_win, + RebelType::government_map_t&& desired_governments, + RebelType::defection_t defection, + RebelType::independence_t independence, + uint16_t defect_delay, + Ideology const* ideology, + bool allow_all_cultures, + bool allow_all_culture_groups, + bool allow_all_religions, + bool allow_all_ideologies, + bool resilient, + bool reinforcing, + bool general, + bool smart, + bool unit_transfer, + fixed_point_t occupation_mult, + ConditionalWeightFactorMul&& will_rise, + ConditionalWeightFactorMul&& spawn_chance, + ConditionalWeightFactorMul&& movement_evaluation, + ConditionScript&& siege_won_trigger, + EffectScript&& siege_won_effect, + ConditionScript&& demands_enforced_trigger, + EffectScript&& demands_enforced_effect ) { if (new_identifier.empty()) { spdlog::error_s("Invalid rebel type identifier - empty!"); @@ -61,18 +96,39 @@ bool RebelManager::add_rebel_type( } return rebel_types.emplace_item( - new_identifier, - index_from_count(get_rebel_type_count()), new_identifier, - icon, area, break_alliance_on_win, std::move(desired_governments), defection, independence, - defect_delay, ideology, allow_all_cultures, allow_all_culture_groups, allow_all_religions, allow_all_ideologies, - resilient, reinforcing, general, smart, unit_transfer, occupation_mult, std::move(will_rise), std::move(spawn_chance), - std::move(movement_evaluation), std::move(siege_won_trigger), std::move(siege_won_effect), - std::move(demands_enforced_trigger), std::move(demands_enforced_effect) + new_identifier, + index_from_count(get_rebel_type_count()), + new_identifier, + icon, + area, + break_alliance_on_win, + std::move(desired_governments), + defection, + independence, + defect_delay, + ideology, + allow_all_cultures, + allow_all_culture_groups, + allow_all_religions, + allow_all_ideologies, + resilient, + reinforcing, + general, + smart, + unit_transfer, + occupation_mult, + std::move(will_rise), + std::move(spawn_chance), + std::move(movement_evaluation), + std::move(siege_won_trigger), + std::move(siege_won_effect), + std::move(demands_enforced_trigger), + std::move(demands_enforced_effect) ); } bool RebelManager::load_rebels_file( - IdeologyManager const& ideology_manager, GovernmentTypeManager const& government_type_manager, ast::NodeCPtr root + IdeologyManager const& ideology_manager, GovernmentTypeManager const& government_type_manager, ast::NodeCPtr root ) { spdlog::scope scope { "common/rebel_types.txt" }; @@ -106,32 +162,31 @@ bool RebelManager::load_rebels_file( { "any", RebelType::independence_t::ANY } }; - bool ret = expect_dictionary_reserve_length( - rebel_types, - [this, &ideology_manager, &government_type_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { - using enum scope_type_t; - - spdlog::scope scope { fmt::format("rebel type {}", identifier) }; - - RebelType::icon_t icon = 0; - RebelType::area_t area = RebelType::area_t::ALL; - RebelType::government_map_t desired_governments; - RebelType::defection_t defection = RebelType::defection_t::NONE; - RebelType::independence_t independence = RebelType::independence_t::NONE; - uint16_t defect_delay = 0; - Ideology const* ideology = nullptr; - bool break_alliance_on_win = false, allow_all_cultures = true, allow_all_culture_groups = true, - allow_all_religions = true, allow_all_ideologies = true, resilient = true, reinforcing = true, general = true, - smart = true, unit_transfer = false; - fixed_point_t occupation_mult = 0; - ConditionalWeightFactorMul will_rise { POP, COUNTRY, NO_SCOPE }; - ConditionalWeightFactorMul spawn_chance { POP, POP, NO_SCOPE }; - ConditionalWeightFactorMul movement_evaluation { PROVINCE, PROVINCE, NO_SCOPE }; - ConditionScript siege_won_trigger { PROVINCE, PROVINCE, NO_SCOPE }; - ConditionScript demands_enforced_trigger { COUNTRY, COUNTRY, NO_SCOPE }; - EffectScript siege_won_effect, demands_enforced_effect; - - bool ret = expect_dictionary_keys( + bool ret = + expect_dictionary_reserve_length(rebel_types, [this, &ideology_manager, &government_type_manager](std::string_view identifier, ast::NodeCPtr node) -> bool { + using enum scope_type_t; + + spdlog::scope scope { fmt::format("rebel type {}", identifier) }; + + RebelType::icon_t icon = 0; + RebelType::area_t area = RebelType::area_t::ALL; + RebelType::government_map_t desired_governments; + RebelType::defection_t defection = RebelType::defection_t::NONE; + RebelType::independence_t independence = RebelType::independence_t::NONE; + uint16_t defect_delay = 0; + Ideology const* ideology = nullptr; + bool break_alliance_on_win = false, allow_all_cultures = true, allow_all_culture_groups = true, + allow_all_religions = true, allow_all_ideologies = true, resilient = true, reinforcing = true, general = true, + smart = true, unit_transfer = false; + fixed_point_t occupation_mult = 0; + ConditionalWeightFactorMul will_rise { POP, COUNTRY, NO_SCOPE }; + ConditionalWeightFactorMul spawn_chance { POP, POP, NO_SCOPE }; + ConditionalWeightFactorMul movement_evaluation { PROVINCE, PROVINCE, NO_SCOPE }; + ConditionScript siege_won_trigger { PROVINCE, PROVINCE, NO_SCOPE }; + ConditionScript demands_enforced_trigger { COUNTRY, COUNTRY, NO_SCOPE }; + EffectScript siege_won_effect, demands_enforced_effect; + + bool ret = expect_dictionary_keys( "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), "area", ONE_EXACTLY, expect_identifier(expect_mapped_string(area_map, assign_variable_callback(area))), "break_alliance_on_win", ZERO_OR_ONE, expect_bool(assign_variable_callback(break_alliance_on_win)), @@ -173,17 +228,37 @@ bool RebelManager::load_rebels_file( "demands_enforced_effect", ZERO_OR_ONE, demands_enforced_effect.expect_script() )(node); - ret &= add_rebel_type( - identifier, icon, area, break_alliance_on_win, std::move(desired_governments), defection, independence, - defect_delay, ideology, allow_all_cultures, allow_all_culture_groups, allow_all_religions, - allow_all_ideologies, resilient, reinforcing, general, smart, unit_transfer, occupation_mult, - std::move(will_rise), std::move(spawn_chance), std::move(movement_evaluation), std::move(siege_won_trigger), - std::move(siege_won_effect), std::move(demands_enforced_trigger), std::move(demands_enforced_effect) - ); + ret &= add_rebel_type( + identifier, + icon, + area, + break_alliance_on_win, + std::move(desired_governments), + defection, + independence, + defect_delay, + ideology, + allow_all_cultures, + allow_all_culture_groups, + allow_all_religions, + allow_all_ideologies, + resilient, + reinforcing, + general, + smart, + unit_transfer, + occupation_mult, + std::move(will_rise), + std::move(spawn_chance), + std::move(movement_evaluation), + std::move(siege_won_trigger), + std::move(siege_won_effect), + std::move(demands_enforced_trigger), + std::move(demands_enforced_effect) + ); - return ret; - } - )(root); + return ret; + })(root); lock_rebel_types(); @@ -201,24 +276,23 @@ bool RebelManager::generate_modifiers(ModifierManager& modifier_manager) const { ret &= modifier_manager.register_complex_modifier(identifier); ret &= modifier_manager.register_technology_modifier_effect( - modifier_manager.modifier_effect_cache.rebel_org_gain_all, ModifierManager::get_flat_identifier(identifier, "all"), - FORMAT_x100_2DP_PC_NEG, "TECH_REBEL_ORG_GAIN" + modifier_manager.modifier_effect_cache.rebel_org_gain_all, + ModifierManager::get_flat_identifier(identifier, "all"), + FORMAT_x100_2DP_PC_NEG, + "TECH_REBEL_ORG_GAIN" ); auto& rebel_org_gain_effects = modifier_manager.modifier_effect_cache.rebel_org_gain_effects; rebel_org_gain_effects = std::move( - decltype(ModifierEffectCache::rebel_org_gain_effects) { - generate_values, - rebel_type_index_t(get_rebel_type_count()) - } + decltype(ModifierEffectCache::rebel_org_gain_effects) { generate_values, rebel_type_index_t(get_rebel_type_count()) } ); for (RebelType const& rebel_type : get_rebel_types()) { ret &= modifier_manager.register_technology_modifier_effect( - rebel_org_gain_effects[rebel_type.index], - ModifierManager::get_flat_identifier(identifier, rebel_type.get_identifier()), - FORMAT_x100_2DP_PC_NEG, - memory::fmt::format("${}_title$ $TECH_REBEL_ORG_GAIN$", rebel_type) + rebel_org_gain_effects[rebel_type.index], + ModifierManager::get_flat_identifier(identifier, rebel_type.get_identifier()), + FORMAT_x100_2DP_PC_NEG, + memory::fmt::format("${}_title$ $TECH_REBEL_ORG_GAIN$", rebel_type) ); } return ret; diff --git a/src/openvic-simulation/politics/Rebel.hpp b/src/openvic-simulation/politics/Rebel.hpp index efccb83f7..b02ec3315 100644 --- a/src/openvic-simulation/politics/Rebel.hpp +++ b/src/openvic-simulation/politics/Rebel.hpp @@ -25,18 +25,33 @@ namespace OpenVic { using icon_t = uint16_t; enum class area_t { - NATION, NATION_RELIGION, NATION_CULTURE, - CULTURE, CULTURE_GROUP, RELIGION, ALL + NATION, + NATION_RELIGION, + NATION_CULTURE, + CULTURE, + CULTURE_GROUP, + RELIGION, + ALL }; enum class defection_t { - NONE, CULTURE, CULTURE_GROUP, RELIGION, - IDEOLOGY, PAN_NATIONALIST, ANY + NONE, + CULTURE, + CULTURE_GROUP, + RELIGION, + IDEOLOGY, + PAN_NATIONALIST, + ANY }; enum class independence_t { - NONE, CULTURE, CULTURE_GROUP, RELIGION, - COLONIAL, PAN_NATIONALIST, ANY + NONE, + CULTURE, + CULTURE_GROUP, + RELIGION, + COLONIAL, + PAN_NATIONALIST, + ANY }; private: @@ -71,16 +86,33 @@ namespace OpenVic { const fixed_point_t occupation_mult; RebelType( - index_t new_index, std::string_view new_identifier, - RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, - RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, - bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, - bool reinforcing, bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, - ConditionalWeightFactorMul&& new_will_rise, ConditionalWeightFactorMul&& new_spawn_chance, - ConditionalWeightFactorMul&& new_movement_evaluation, ConditionScript&& new_siege_won_trigger, - EffectScript&& new_siege_won_effect, ConditionScript&& new_demands_enforced_trigger, - EffectScript&& new_demands_enforced_effect + index_t new_index, + std::string_view new_identifier, + RebelType::icon_t icon, + RebelType::area_t area, + bool break_alliance_on_win, + RebelType::government_map_t&& desired_governments, + RebelType::defection_t defection, + RebelType::independence_t independence, + uint16_t defect_delay, + Ideology const* ideology, + bool allow_all_cultures, + bool allow_all_culture_groups, + bool allow_all_religions, + bool allow_all_ideologies, + bool resilient, + bool reinforcing, + bool general, + bool smart, + bool unit_transfer, + fixed_point_t occupation_mult, + ConditionalWeightFactorMul&& new_will_rise, + ConditionalWeightFactorMul&& new_spawn_chance, + ConditionalWeightFactorMul&& new_movement_evaluation, + ConditionScript&& new_siege_won_trigger, + EffectScript&& new_siege_won_effect, + ConditionScript&& new_demands_enforced_trigger, + EffectScript&& new_demands_enforced_effect ); RebelType(RebelType&&) = default; }; @@ -91,21 +123,39 @@ namespace OpenVic { public: bool add_rebel_type( - std::string_view new_identifier, RebelType::icon_t icon, RebelType::area_t area, bool break_alliance_on_win, - RebelType::government_map_t&& desired_governments, RebelType::defection_t defection, - RebelType::independence_t independence, uint16_t defect_delay, Ideology const* ideology, bool allow_all_cultures, - bool allow_all_culture_groups, bool allow_all_religions, bool allow_all_ideologies, bool resilient, - bool reinforcing, bool general, bool smart, bool unit_transfer, fixed_point_t occupation_mult, - ConditionalWeightFactorMul&& will_rise, ConditionalWeightFactorMul&& spawn_chance, - ConditionalWeightFactorMul&& movement_evaluation, ConditionScript&& siege_won_trigger, - EffectScript&& siege_won_effect, ConditionScript&& demands_enforced_trigger, EffectScript&& demands_enforced_effect + std::string_view new_identifier, + RebelType::icon_t icon, + RebelType::area_t area, + bool break_alliance_on_win, + RebelType::government_map_t&& desired_governments, + RebelType::defection_t defection, + RebelType::independence_t independence, + uint16_t defect_delay, + Ideology const* ideology, + bool allow_all_cultures, + bool allow_all_culture_groups, + bool allow_all_religions, + bool allow_all_ideologies, + bool resilient, + bool reinforcing, + bool general, + bool smart, + bool unit_transfer, + fixed_point_t occupation_mult, + ConditionalWeightFactorMul&& will_rise, + ConditionalWeightFactorMul&& spawn_chance, + ConditionalWeightFactorMul&& movement_evaluation, + ConditionScript&& siege_won_trigger, + EffectScript&& siege_won_effect, + ConditionScript&& demands_enforced_trigger, + EffectScript&& demands_enforced_effect ); bool load_rebels_file( - IdeologyManager const& ideology_manager, GovernmentTypeManager const& government_type_manager, ast::NodeCPtr root + IdeologyManager const& ideology_manager, GovernmentTypeManager const& government_type_manager, ast::NodeCPtr root ); bool generate_modifiers(ModifierManager& modifier_manager) const; bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Reform.cpp b/src/openvic-simulation/politics/Reform.cpp index 378d268ed..823b58227 100644 --- a/src/openvic-simulation/politics/Reform.cpp +++ b/src/openvic-simulation/politics/Reform.cpp @@ -2,38 +2,37 @@ using namespace OpenVic; -ReformType::ReformType(std::string_view new_identifier, bool new_is_civilizing) - : HasIdentifier { new_identifier }, is_civilizing { new_is_civilizing } {} +ReformType::ReformType(std::string_view new_identifier, bool new_is_civilizing) : + HasIdentifier { new_identifier }, is_civilizing { new_is_civilizing } {} ReformGroup::ReformGroup( - std::string_view new_identifier, - index_t new_index, - ReformType const& new_reform_type, - bool new_is_ordered, - bool new_is_administrative -) : HasIdentifier { new_identifier }, - HasIndex { new_index }, - reform_type { new_reform_type }, - is_ordered { new_is_ordered }, - is_administrative { new_is_administrative } {} + std::string_view new_identifier, + index_t new_index, + ReformType const& new_reform_type, + bool new_is_ordered, + bool new_is_administrative +) : + HasIdentifier { new_identifier }, HasIndex { new_index }, reform_type { new_reform_type }, is_ordered { new_is_ordered }, + is_administrative { new_is_administrative } {} Reform::Reform( - index_t new_index, std::string_view new_identifier, - colour_t new_colour, ModifierValue&& new_values, ReformGroup const& new_reform_group, - size_t new_ordinal, fixed_point_t new_administrative_multiplier, RuleSet&& new_rules, tech_cost_t new_technology_cost, - ConditionScript&& new_allow, ConditionScript&& new_on_execute_trigger, EffectScript&& new_on_execute_effect -) : BaseIssue { - new_identifier, new_colour, std::move(new_values), std::move(new_rules), false, - modifier_type_t::REFORM - }, - HasIndex { new_index }, - ordinal { new_ordinal }, - administrative_multiplier { new_administrative_multiplier }, - technology_cost { new_technology_cost }, - group { new_reform_group }, - allow { std::move(new_allow) }, - on_execute_trigger { std::move(new_on_execute_trigger) }, - on_execute_effect { std::move(new_on_execute_effect) } {} + index_t new_index, + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_values, + ReformGroup const& new_reform_group, + size_t new_ordinal, + fixed_point_t new_administrative_multiplier, + RuleSet&& new_rules, + tech_cost_t new_technology_cost, + ConditionScript&& new_allow, + ConditionScript&& new_on_execute_trigger, + EffectScript&& new_on_execute_effect +) : + BaseIssue { new_identifier, new_colour, std::move(new_values), std::move(new_rules), false, modifier_type_t::REFORM }, + HasIndex { new_index }, ordinal { new_ordinal }, administrative_multiplier { new_administrative_multiplier }, + technology_cost { new_technology_cost }, group { new_reform_group }, allow { std::move(new_allow) }, + on_execute_trigger { std::move(new_on_execute_trigger) }, on_execute_effect { std::move(new_on_execute_effect) } {} bool Reform::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -43,4 +42,4 @@ bool Reform::parse_scripts(DefinitionManager const& definition_manager) { ret &= on_execute_effect.parse_script(true, definition_manager); return ret; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/Reform.hpp b/src/openvic-simulation/politics/Reform.hpp index b67c9de06..e9eb8c066 100644 --- a/src/openvic-simulation/politics/Reform.hpp +++ b/src/openvic-simulation/politics/Reform.hpp @@ -9,7 +9,7 @@ #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/TypedIndices.hpp" -namespace OpenVic { +namespace OpenVic { struct ReformGroup; // Reform type (i.e. political_issues) @@ -42,11 +42,11 @@ namespace OpenVic { const bool is_administrative; ReformGroup( - std::string_view new_identifier, - index_t new_index, - ReformType const& new_reform_type, - bool new_is_ordered, - bool new_is_administrative + std::string_view new_identifier, + index_t new_index, + ReformType const& new_reform_type, + bool new_is_ordered, + bool new_is_administrative ); ReformGroup(ReformGroup&&) = default; @@ -75,12 +75,19 @@ namespace OpenVic { ReformGroup const& group; Reform( - index_t new_index, std::string_view new_identifier, - colour_t new_colour, ModifierValue&& new_values, ReformGroup const& new_reform_group, - size_t new_ordinal, fixed_point_t new_administrative_multiplier, - RuleSet&& new_rules, tech_cost_t new_technology_cost, ConditionScript&& new_allow, - ConditionScript&& new_on_execute_trigger, EffectScript&& new_on_execute_effect + index_t new_index, + std::string_view new_identifier, + colour_t new_colour, + ModifierValue&& new_values, + ReformGroup const& new_reform_group, + size_t new_ordinal, + fixed_point_t new_administrative_multiplier, + RuleSet&& new_rules, + tech_cost_t new_technology_cost, + ConditionScript&& new_allow, + ConditionScript&& new_on_execute_trigger, + EffectScript&& new_on_execute_effect ); Reform(Reform&&) = default; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/politics/RuleSet.hpp b/src/openvic-simulation/politics/RuleSet.hpp index b27d50eaf..3c65a06bc 100644 --- a/src/openvic-simulation/politics/RuleSet.hpp +++ b/src/openvic-simulation/politics/RuleSet.hpp @@ -3,16 +3,16 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/string/StringLiteral.hpp" #include "openvic-simulation/core/string/Utility.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/OptionalBool.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/utility/Logger.hpp" namespace OpenVic { - //TODO replace with strategy pattern? + // TODO replace with strategy pattern? enum struct ApportionmentMethod : std::uint8_t { largest_share, dhont, @@ -42,47 +42,45 @@ namespace OpenVic { } }; - //in the order of Vic2 tooltip - #define DO_FOR_ALL_RULES_SEP(F, SEP) \ - F(build_factory) SEP \ - F(expand_factory) SEP \ - F(open_factory) SEP \ - F(destroy_factory) SEP \ - F(build_railway) SEP \ - F(factory_priority) SEP \ - F(can_subsidise) SEP \ - F(pop_build_factory) SEP \ - F(pop_expand_factory) SEP \ - F(pop_open_factory) SEP \ - F(delete_factory_if_no_input) SEP \ - F(build_factory_invest) SEP \ - F(expand_factory_invest) SEP \ - F(open_factory_invest) SEP \ - F(build_railway_invest) SEP \ - F(can_invest_in_pop_projects) SEP \ - F(pop_build_factory_invest) SEP \ - F(pop_expand_factory_invest) SEP \ - F(pop_open_factory_invest) SEP \ - F(allow_foreign_investment) SEP \ - F(primary_culture_voting) SEP \ - F(culture_voting) SEP \ - F(all_voting) SEP \ - F(largest_share) SEP \ - F(dhont) SEP \ - F(sainte_laque) SEP \ - F(rich_only) SEP \ - F(same_as_ruling_party) SEP \ - F(state_vote) SEP \ - F(population_vote) SEP \ - F(slavery_allowed) - - #define RULE_FIELDS(RULE) \ - OptionalBool RULE : 2 = OptionalBool::UNSPECIFIED; - - DO_FOR_ALL_RULES_SEP(RULE_FIELDS,) - #undef RULE_FIELDS - - template +// in the order of Vic2 tooltip +#define DO_FOR_ALL_RULES_SEP(F, SEP) \ + F(build_factory) SEP F(expand_factory) \ + SEP F(open_factory) \ + SEP F(destroy_factory) \ + SEP F(build_railway) \ + SEP F(factory_priority) \ + SEP F(can_subsidise) \ + SEP F(pop_build_factory) \ + SEP F(pop_expand_factory) \ + SEP F(pop_open_factory) \ + SEP F(delete_factory_if_no_input) \ + SEP F(build_factory_invest) \ + SEP F(expand_factory_invest) \ + SEP F(open_factory_invest) \ + SEP F(build_railway_invest) \ + SEP F(can_invest_in_pop_projects) \ + SEP F(pop_build_factory_invest) \ + SEP F(pop_expand_factory_invest) \ + SEP F(pop_open_factory_invest) \ + SEP F(allow_foreign_investment) \ + SEP F(primary_culture_voting) \ + SEP F(culture_voting) \ + SEP F(all_voting) \ + SEP F(largest_share) \ + SEP F(dhont) \ + SEP F(sainte_laque) \ + SEP F(rich_only) \ + SEP F(same_as_ruling_party) \ + SEP F(state_vote) \ + SEP F(population_vote) \ + SEP F(slavery_allowed) + +#define RULE_FIELDS(RULE) OptionalBool RULE : 2 = OptionalBool::UNSPECIFIED; + + DO_FOR_ALL_RULES_SEP(RULE_FIELDS, ) +#undef RULE_FIELDS + + template EnumType select_with_priority(const RuleDefinition (&rules)[N]) const { const std::string_view context_name = type_name(); @@ -93,11 +91,11 @@ namespace OpenVic { for (size_t j = i + 1; j < N; ++j) { if (OV_unlikely(rules[j].value == OptionalBool::TRUE)) { spdlog::warn_s( - "Both {} and {} are enabled for {}. {} is picked.", - rules[i].name, - rules[j].name, - context_name, - rules[i].name + "Both {} and {} are enabled for {}. {} is picked.", + rules[i].name, + rules[j].name, + context_name, + rules[i].name ); } } @@ -118,9 +116,9 @@ namespace OpenVic { return EnumType(0); } - #define DEF(VALUE) RuleDefinition::Define<#VALUE>(VALUE) +#define DEF(VALUE) RuleDefinition::Define<#VALUE>(VALUE) - #define RESOLVE_DEFAULT_FALSE(METHOD_NAME, FIELD) \ +#define RESOLVE_DEFAULT_FALSE(METHOD_NAME, FIELD) \ bool METHOD_NAME() const { \ const bool is_true = FIELD == OptionalBool::TRUE; \ if (FIELD == OptionalBool::UNSPECIFIED) { \ @@ -129,95 +127,78 @@ namespace OpenVic { return is_true; \ } - [[nodiscard]] OptionalBool merge_rule(OptionalBool current, OptionalBool other, std::string_view name) { - // If they are the same or 'other' provides no new info, stay as we are. - if (current == other || other == OptionalBool::UNSPECIFIED) { - return current; - } + [[nodiscard]] OptionalBool merge_rule(OptionalBool current, OptionalBool other, std::string_view name) { + // If they are the same or 'other' provides no new info, stay as we are. + if (current == other || other == OptionalBool::UNSPECIFIED) { + return current; + } + + // If we were unspecified, take whatever 'other' has. + if (current == OptionalBool::UNSPECIFIED) { + return other; + } - // If we were unspecified, take whatever 'other' has. - if (current == OptionalBool::UNSPECIFIED) { - return other; + // Conflict: One is TRUE and the other is FALSE. + // Since 'other' isn't UNSPECIFIED and isn't the same as 'current', + // and we know 'current' isn't UNSPECIFIED, they must be TRUE/FALSE opposites. + spdlog::warn_s("{} is both false and true, true wins.", name); + return OptionalBool::TRUE; } - // Conflict: One is TRUE and the other is FALSE. - // Since 'other' isn't UNSPECIFIED and isn't the same as 'current', - // and we know 'current' isn't UNSPECIFIED, they must be TRUE/FALSE opposites. - spdlog::warn_s("{} is both false and true, true wins.", name); - return OptionalBool::TRUE; - } - - static memory::string make_rule_localisation_key(std::string_view identifier) { - return "RULE_" + ascii_toupper(identifier); - } + static memory::string make_rule_localisation_key(std::string_view identifier) { + return "RULE_" + ascii_toupper(identifier); + } public: - #define MAP_FROM_BOOL(RULE) \ - #RULE, ZERO_OR_ONE, NodeTools::expect_bool( \ - [&ruleset](const bool value) mutable -> bool { \ - const bool ret = ruleset.RULE == OptionalBool::UNSPECIFIED; \ - ruleset.RULE = value ? OptionalBool::TRUE : OptionalBool::FALSE; \ - return ret; \ - } \ - ) - #define COMMA , +#define MAP_FROM_BOOL(RULE) \ + #RULE, ZERO_OR_ONE, NodeTools::expect_bool([&ruleset](const bool value) mutable -> bool { \ + const bool ret = ruleset.RULE == OptionalBool::UNSPECIFIED; \ + ruleset.RULE = value ? OptionalBool::TRUE : OptionalBool::FALSE; \ + return ret; \ + }) +#define COMMA , static NodeTools::node_callback_t expect_rule_set(NodeTools::callback_t ruleset_callback) { return [ruleset_callback](ast::NodeCPtr root) mutable -> bool { RuleSet ruleset; using enum NodeTools::dictionary_entry_t::expected_count_t; - bool outer_result = NodeTools::expect_dictionary_keys( - DO_FOR_ALL_RULES_SEP(MAP_FROM_BOOL, COMMA) - )(root); + bool outer_result = NodeTools::expect_dictionary_keys(DO_FOR_ALL_RULES_SEP(MAP_FROM_BOOL, COMMA))(root); outer_result &= ruleset_callback(std::move(ruleset)); return outer_result; }; } - #undef COMMA - #undef MAP_FROM_BOOL +#undef COMMA +#undef MAP_FROM_BOOL - #define ADD_IF_NOT_UNSPECIFIED(RULE) \ - if (RULE != OptionalBool::UNSPECIFIED) { \ - result.emplace(make_rule_localisation_key(#RULE), RULE == OptionalBool::TRUE); \ - } +#define ADD_IF_NOT_UNSPECIFIED(RULE) \ + if (RULE != OptionalBool::UNSPECIFIED) { \ + result.emplace(make_rule_localisation_key(#RULE), RULE == OptionalBool::TRUE); \ + } ordered_map get_localisation_keys_and_values() const { ordered_map result {}; - DO_FOR_ALL_RULES_SEP(ADD_IF_NOT_UNSPECIFIED,) + DO_FOR_ALL_RULES_SEP(ADD_IF_NOT_UNSPECIFIED, ) return result; } - #undef ADD_IF_NOT_UNSPECIFIED +#undef ADD_IF_NOT_UNSPECIFIED - //political + // political ApportionmentMethod get_apportionment_method() const { - const RuleDefinition rules[] { - DEF(largest_share), - DEF(dhont), - DEF(sainte_laque) - }; + const RuleDefinition rules[] { DEF(largest_share), DEF(dhont), DEF(sainte_laque) }; return select_with_priority(rules); } UpperHouseComposition get_upper_house_composition() const { - const RuleDefinition rules[] { - DEF(same_as_ruling_party), - DEF(rich_only), - DEF(state_vote), - DEF(population_vote) - }; + const RuleDefinition rules[] { DEF(same_as_ruling_party), DEF(rich_only), DEF(state_vote), DEF(population_vote) }; return select_with_priority(rules); } CulturalVotingRight get_cultural_voting_rights() const { - const RuleDefinition rules[] { - DEF(primary_culture_voting), - DEF(culture_voting), - DEF(all_voting) - }; + const RuleDefinition rules[] { DEF(primary_culture_voting), DEF(culture_voting), DEF(all_voting) }; return select_with_priority(rules); } - #undef DEF +#undef DEF RESOLVE_DEFAULT_FALSE(is_slavery_legal, slavery_allowed) - //economic + // economic RESOLVE_DEFAULT_FALSE(may_expand_infrastructure_domestically, build_railway) RESOLVE_DEFAULT_FALSE(may_build_factory_domestically, build_factory) RESOLVE_DEFAULT_FALSE(may_expand_factory_domestically, expand_factory) @@ -244,13 +225,13 @@ namespace OpenVic { RESOLVE_DEFAULT_FALSE(may_invest_in_expanding_infrastructure_abroad, build_railway_invest) RESOLVE_DEFAULT_FALSE(foreigners_may_invest, allow_foreign_investment) - #undef RESOLVE_DEFAULT_FALSE +#undef RESOLVE_DEFAULT_FALSE - #define ASSIGN_MERGED_RULE(RULE) RULE = merge_rule(RULE, other.RULE, #RULE); +#define ASSIGN_MERGED_RULE(RULE) RULE = merge_rule(RULE, other.RULE, #RULE); void add_ruleset(RuleSet const& other) { - DO_FOR_ALL_RULES_SEP(ASSIGN_MERGED_RULE,) + DO_FOR_ALL_RULES_SEP(ASSIGN_MERGED_RULE, ) } - #undef ASSIGN_MERGED_RULE - #undef DO_FOR_ALL_RULES +#undef ASSIGN_MERGED_RULE +#undef DO_FOR_ALL_RULES }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/Culture.cpp b/src/openvic-simulation/population/Culture.cpp index 3de5de71d..e0a677287 100644 --- a/src/openvic-simulation/population/Culture.cpp +++ b/src/openvic-simulation/population/Culture.cpp @@ -2,31 +2,41 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/object/Colour.hpp" +#include "openvic-simulation/core/string/Utility.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/dataloader/Dataloader.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" -#include "openvic-simulation/core/string/Utility.hpp" -#include "openvic-simulation/core/Typedefs.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; -GraphicalCultureType::GraphicalCultureType(std::string_view new_identifier, index_t new_index) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} +GraphicalCultureType::GraphicalCultureType(std::string_view new_identifier, index_t new_index) : + HasIdentifier { new_identifier }, HasIndex { new_index } {} CultureGroup::CultureGroup( - std::string_view new_identifier, std::string_view new_leader, GraphicalCultureType const& new_unit_graphical_culture_type, - bool new_is_overseas, CountryDefinition const* new_union_country -) : HasIdentifier { new_identifier }, leader { new_leader }, unit_graphical_culture_type { new_unit_graphical_culture_type }, - is_overseas { new_is_overseas }, union_country { new_union_country } {} + std::string_view new_identifier, + std::string_view new_leader, + GraphicalCultureType const& new_unit_graphical_culture_type, + bool new_is_overseas, + CountryDefinition const* new_union_country +) : + HasIdentifier { new_identifier }, leader { new_leader }, unit_graphical_culture_type { new_unit_graphical_culture_type }, + is_overseas { new_is_overseas }, union_country { new_union_country } {} Culture::Culture( - std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, name_list_t&& new_first_names, - name_list_t&& new_last_names, fixed_point_t new_radicalism, CountryDefinition const* new_primary_country -) : HasIdentifierAndColour { new_identifier, new_colour, false }, group { new_group }, - first_names { std::move(new_first_names) }, last_names { std::move(new_last_names) }, radicalism { new_radicalism }, - primary_country { new_primary_country } {} + std::string_view new_identifier, + colour_t new_colour, + CultureGroup const& new_group, + name_list_t&& new_first_names, + name_list_t&& new_last_names, + fixed_point_t new_radicalism, + CountryDefinition const* new_primary_country +) : + HasIdentifierAndColour { new_identifier, new_colour, false }, group { new_group }, + first_names { std::move(new_first_names) }, last_names { std::move(new_last_names) }, radicalism { new_radicalism }, + primary_country { new_primary_country } {} CultureManager::CultureManager() : default_graphical_culture_type { nullptr } {} @@ -36,14 +46,16 @@ bool CultureManager::add_graphical_culture_type(std::string_view identifier) { return false; } return graphical_culture_types.emplace_item( - identifier, - identifier, index_from_count(get_graphical_culture_type_count()) + identifier, identifier, index_from_count(get_graphical_culture_type_count()) ); } bool CultureManager::add_culture_group( - std::string_view identifier, std::string_view leader, GraphicalCultureType const* graphical_culture_type, bool is_overseas, - CountryDefinition const* union_country + std::string_view identifier, + std::string_view leader, + GraphicalCultureType const* graphical_culture_type, + bool is_overseas, + CountryDefinition const* union_country ) { if (!graphical_culture_types.is_locked()) { spdlog::error_s("Cannot register culture groups until graphical culture types are locked!"); @@ -67,24 +79,25 @@ bool CultureManager::add_culture_group( } leader = default_leader; spdlog::warn_s( - "In culture group \"{}\" - group leader is undefined, set to default of: \"{}\".", - identifier, default_leader + "In culture group \"{}\" - group leader is undefined, set to default of: \"{}\".", identifier, default_leader ); } - if (!culture_groups.emplace_item( - identifier, - identifier, leader, *graphical_culture_type, is_overseas, union_country - )) { + if (!culture_groups.emplace_item(identifier, identifier, leader, *graphical_culture_type, is_overseas, union_country)) { return false; } - + leader_picture_counts.emplace(leader, general_admiral_picture_count_t { 0, 0 }); return true; } bool CultureManager::add_culture( - std::string_view identifier, colour_t colour, CultureGroup const& group, name_list_t&& first_names, - name_list_t&& last_names, fixed_point_t radicalism, CountryDefinition const* primary_country + std::string_view identifier, + colour_t colour, + CultureGroup const& group, + name_list_t&& first_names, + name_list_t&& last_names, + fixed_point_t radicalism, + CountryDefinition const* primary_country ) { if (!culture_groups.is_locked()) { spdlog::error_s("Cannot register cultures until culture groups are locked!"); @@ -98,16 +111,15 @@ bool CultureManager::add_culture( // TODO - check radicalism range return cultures.emplace_item( - identifier, - identifier, colour, group, std::move(first_names), std::move(last_names), radicalism, primary_country + identifier, identifier, colour, group, std::move(first_names), std::move(last_names), radicalism, primary_country ); } bool CultureManager::load_graphical_culture_type_file(ast::NodeCPtr root) { - const bool ret = expect_list_reserve_length( - graphical_culture_types, - expect_identifier(std::bind_front(&CultureManager::add_graphical_culture_type, this)) - )(root); + const bool ret = + expect_list_reserve_length(graphical_culture_types, expect_identifier(std::bind_front(&CultureManager::add_graphical_culture_type, this)))( + root + ); lock_graphical_culture_types(); @@ -123,8 +135,10 @@ bool CultureManager::load_graphical_culture_type_file(ast::NodeCPtr root) { } bool CultureManager::_load_culture_group( - CountryDefinitionManager const& country_definition_manager, size_t& total_expected_cultures, - std::string_view culture_group_key, ast::NodeCPtr culture_group_node + CountryDefinitionManager const& country_definition_manager, + size_t& total_expected_cultures, + std::string_view culture_group_key, + ast::NodeCPtr culture_group_node ) { std::string_view leader {}; GraphicalCultureType const* unit_graphical_culture_type = default_graphical_culture_type; @@ -145,8 +159,10 @@ bool CultureManager::_load_culture_group( } bool CultureManager::_load_culture( - CountryDefinitionManager const& country_definition_manager, CultureGroup const& culture_group, std::string_view culture_key, - ast::NodeCPtr culture_node + CountryDefinitionManager const& country_definition_manager, + CultureGroup const& culture_group, + std::string_view culture_key, + ast::NodeCPtr culture_node ) { colour_t colour = colour_t::null(); name_list_t first_names {}, last_names {}; @@ -162,7 +178,7 @@ bool CultureManager::_load_culture( country_definition_manager.expect_country_definition_identifier(assign_variable_callback_pointer(primary_country)) )(culture_node); ret &= add_culture( - culture_key, colour, culture_group, std::move(first_names), std::move(last_names), radicalism, primary_country + culture_key, colour, culture_group, std::move(first_names), std::move(last_names), radicalism, primary_country ); return ret; } @@ -194,35 +210,28 @@ bool CultureManager::load_culture_file(CountryDefinitionManager const& country_d } size_t total_expected_cultures = 0; - bool ret = expect_dictionary_reserve_length(culture_groups, - [this, &country_definition_manager, &total_expected_cultures]( - std::string_view key, ast::NodeCPtr value - ) -> bool { - return _load_culture_group(country_definition_manager, total_expected_cultures, key, value); - } - )(root); + bool ret = + expect_dictionary_reserve_length(culture_groups, [this, &country_definition_manager, &total_expected_cultures](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_culture_group(country_definition_manager, total_expected_cultures, key, value); + })(root); lock_culture_groups(); reserve_more_cultures(total_expected_cultures); - ret &= expect_culture_group_dictionary( - [this, &country_definition_manager](CultureGroup const& culture_group, ast::NodeCPtr culture_group_value) -> bool { - return expect_dictionary( - [this, &country_definition_manager, &culture_group](std::string_view key, ast::NodeCPtr value) -> bool { - static const string_set_t reserved_keys = { "leader", "unit", "union", "is_overseas" }; - if (reserved_keys.contains(key)) { - return true; - } - return _load_culture(country_definition_manager, culture_group, key, value); - } - )(culture_group_value); - } - )(root); + ret &= expect_culture_group_dictionary([this, &country_definition_manager](CultureGroup const& culture_group, ast::NodeCPtr culture_group_value) -> bool { + return expect_dictionary([this, &country_definition_manager, &culture_group](std::string_view key, ast::NodeCPtr value) -> bool { + static const string_set_t reserved_keys = { "leader", "unit", "union", "is_overseas" }; + if (reserved_keys.contains(key)) { + return true; + } + return _load_culture(country_definition_manager, culture_group, key, value); + })(culture_group_value); + })(root); lock_cultures(); return ret; } memory::string CultureManager::make_leader_picture_name( - std::string_view cultural_type, unit_branch_t branch, leader_count_t count + std::string_view cultural_type, unit_branch_t branch, leader_count_t count ) { if (cultural_type.empty()) { spdlog::error_s("Cannot construct leader picture name - empty cultural type!"); @@ -237,15 +246,11 @@ memory::string CultureManager::make_leader_picture_name( using enum unit_branch_t; switch (branch) { - case LAND: - branch_text = &GENERAL_TEXT; - break; - case NAVAL: - branch_text = &ADMIRAL_TEXT; - break; - default: - spdlog::error_s("Cannot construct leader picture name - invalid branch type: {}", static_cast(branch)); - return {}; + case LAND: branch_text = &GENERAL_TEXT; break; + case NAVAL: branch_text = &ADMIRAL_TEXT; break; + default: + spdlog::error_s("Cannot construct leader picture name - invalid branch type: {}", static_cast(branch)); + return {}; } return append_string_views(cultural_type, *branch_text, std::to_string(count)); @@ -269,22 +274,19 @@ bool CultureManager::find_cultural_leader_pictures(Dataloader const& dataloader) bool ret = true; for (auto [cultural_type, general_and_admiral_count] : mutable_iterator(leader_picture_counts)) { - const auto search = [&dataloader, &cultural_type, &ret]( - unit_branch_t branch, leader_count_t& leader_count - ) -> void { - while ( - leader_count < std::numeric_limits::max() && - !dataloader.lookup_file( - make_leader_picture_path(make_leader_picture_name(cultural_type, branch, leader_count)), false - ).empty() - ) { + const auto search = [&dataloader, &cultural_type, &ret](unit_branch_t branch, leader_count_t& leader_count) -> void { + while (leader_count < std::numeric_limits::max() && + !dataloader + .lookup_file( + make_leader_picture_path(make_leader_picture_name(cultural_type, branch, leader_count)), false + ) + .empty()) { leader_count++; } if (leader_count < 1) { spdlog::error_s( - "No {} pictures found for cultural type \"{}\"!", - get_branched_leader_name(branch), cultural_type + "No {} pictures found for cultural type \"{}\"!", get_branched_leader_name(branch), cultural_type ); ret = false; } @@ -311,24 +313,20 @@ memory::string CultureManager::get_leader_picture_name(std::string_view cultural using enum unit_branch_t; switch (branch) { - case LAND: - desired_picture_count = it->second.first; - break; - case NAVAL: - desired_picture_count = it->second.second; - break; + case LAND: desired_picture_count = it->second.first; break; + case NAVAL: desired_picture_count = it->second.second; break; default: spdlog::error_s( - "Cannot get \"{}\" leader picture name - invalid branch type: {}", - cultural_type, static_cast(branch) + "Cannot get \"{}\" leader picture name - invalid branch type: {}", cultural_type, static_cast(branch) ); return {}; } if (desired_picture_count < 1) { spdlog::error_s( - "Cannot get \"{}\" {} picture name - no pictures of this type were found during game loading!", - cultural_type, get_branched_leader_name(branch) + "Cannot get \"{}\" {} picture name - no pictures of this type were found during game loading!", + cultural_type, + get_branched_leader_name(branch) ); return {}; } diff --git a/src/openvic-simulation/population/Culture.hpp b/src/openvic-simulation/population/Culture.hpp index 28c55cfeb..45dc3ba60 100644 --- a/src/openvic-simulation/population/Culture.hpp +++ b/src/openvic-simulation/population/Culture.hpp @@ -1,10 +1,10 @@ #pragma once -#include "openvic-simulation/types/IdentifierRegistry.hpp" -#include "openvic-simulation/types/UnitBranchType.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" +#include "openvic-simulation/types/IdentifierRegistry.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/UnitBranchType.hpp" namespace OpenVic { struct CultureManager; @@ -32,9 +32,11 @@ namespace OpenVic { CountryDefinition const* const union_country; CultureGroup( - std::string_view new_identifier, std::string_view new_leader, - GraphicalCultureType const& new_unit_graphical_culture_type, bool new_is_overseas, - CountryDefinition const* new_union_country + std::string_view new_identifier, + std::string_view new_leader, + GraphicalCultureType const& new_unit_graphical_culture_type, + bool new_is_overseas, + CountryDefinition const* new_union_country ); CultureGroup(CultureGroup&&) = default; @@ -54,8 +56,13 @@ namespace OpenVic { CountryDefinition const* const primary_country; Culture( - std::string_view new_identifier, colour_t new_colour, CultureGroup const& new_group, name_list_t&& new_first_names, - name_list_t&& new_last_names, fixed_point_t new_radicalism, CountryDefinition const* new_primary_country + std::string_view new_identifier, + colour_t new_colour, + CultureGroup const& new_group, + name_list_t&& new_first_names, + name_list_t&& new_last_names, + fixed_point_t new_radicalism, + CountryDefinition const* new_primary_country ); Culture(Culture&&) = default; @@ -79,12 +86,16 @@ namespace OpenVic { string_map_t leader_picture_counts; bool _load_culture_group( - CountryDefinitionManager const& country_definition_manager, size_t& total_expected_cultures, - std::string_view culture_group_key, ast::NodeCPtr culture_group_node + CountryDefinitionManager const& country_definition_manager, + size_t& total_expected_cultures, + std::string_view culture_group_key, + ast::NodeCPtr culture_group_node ); bool _load_culture( - CountryDefinitionManager const& country_definition_manager, CultureGroup const& culture_group, - std::string_view culture_key, ast::NodeCPtr node + CountryDefinitionManager const& country_definition_manager, + CultureGroup const& culture_group, + std::string_view culture_key, + ast::NodeCPtr node ); public: @@ -93,20 +104,28 @@ namespace OpenVic { bool add_graphical_culture_type(std::string_view identifier); bool add_culture_group( - std::string_view identifier, std::string_view leader, GraphicalCultureType const* graphical_culture_type, - bool is_overseas, CountryDefinition const* union_country + std::string_view identifier, + std::string_view leader, + GraphicalCultureType const* graphical_culture_type, + bool is_overseas, + CountryDefinition const* union_country ); bool add_culture( - std::string_view identifier, colour_t colour, CultureGroup const& group, name_list_t&& first_names, - name_list_t&& last_names, fixed_point_t radicalism, CountryDefinition const* primary_country + std::string_view identifier, + colour_t colour, + CultureGroup const& group, + name_list_t&& first_names, + name_list_t&& last_names, + fixed_point_t radicalism, + CountryDefinition const* primary_country ); bool load_graphical_culture_type_file(ast::NodeCPtr root); bool load_culture_file(CountryDefinitionManager const& country_definition_manager, ast::NodeCPtr root); static memory::string make_leader_picture_name( - std::string_view cultural_type, unit_branch_t branch, leader_count_t count + std::string_view cultural_type, unit_branch_t branch, leader_count_t count ); static memory::string make_leader_picture_path(std::string_view leader_picture_name); diff --git a/src/openvic-simulation/population/Pop.cpp b/src/openvic-simulation/population/Pop.cpp index ef887fe2e..5007f3239 100644 --- a/src/openvic-simulation/population/Pop.cpp +++ b/src/openvic-simulation/population/Pop.cpp @@ -10,11 +10,11 @@ #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/error/ErrorMacros.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" -#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/country/CountryParty.hpp" @@ -39,9 +39,9 @@ #include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/population/Religion.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Logger.hpp" #include "PopDeps.hpp" @@ -51,32 +51,35 @@ using namespace OpenVic; constexpr pop_size_t TRUNCATION_ACCEPTABLE_BELOW_SIZE = 16; PopBase::PopBase( - PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size, - fixed_point_t new_militancy, fixed_point_t new_consciousness, RebelType const* new_rebel_type -) : type { new_type }, culture { new_culture }, religion { new_religion }, size { new_size }, militancy { new_militancy }, - consciousness { new_consciousness }, rebel_type { new_rebel_type } {} + PopType const& new_type, + Culture const& new_culture, + Religion const& new_religion, + pop_size_t new_size, + fixed_point_t new_militancy, + fixed_point_t new_consciousness, + RebelType const* new_rebel_type +) : + type { new_type }, culture { new_culture }, religion { new_religion }, size { new_size }, militancy { new_militancy }, + consciousness { new_consciousness }, rebel_type { new_rebel_type } {} Pop::Pop( - ProvinceInstance& new_location, - PopBase const& pop_base, - PopDeps const& pop_deps, - const pop_id_in_province_t new_id_in_province -) : PopBase { pop_base }, - location { new_location }, - id_in_province { new_id_in_province }, - market_instance { pop_deps.market_instance }, - artisanal_producer_optional { - pop_base.get_type().is_artisan - ? std::optional { - pop_deps.artisanal_producer_deps - } - : std::optional {} - }, - supporter_equivalents_by_ideology { generate_values, pop_deps.pops_aggregate_deps.ideology_count }, - supporter_equivalents_by_party_policy { generate_values, pop_deps.pops_aggregate_deps.party_policy_count }, - supporter_equivalents_by_reform { generate_values, pop_deps.pops_aggregate_deps.reform_count } { - reserve_needs_fulfilled_goods(); - } + ProvinceInstance& new_location, + PopBase const& pop_base, + PopDeps const& pop_deps, + const pop_id_in_province_t new_id_in_province +) : + PopBase { pop_base }, location { new_location }, id_in_province { new_id_in_province }, + market_instance { pop_deps.market_instance }, + artisanal_producer_optional { + pop_base.get_type().is_artisan + ? std::optional { pop_deps.artisanal_producer_deps } + : std::optional {} + }, + supporter_equivalents_by_ideology { generate_values, pop_deps.pops_aggregate_deps.ideology_count }, + supporter_equivalents_by_party_policy { generate_values, pop_deps.pops_aggregate_deps.party_policy_count }, + supporter_equivalents_by_reform { generate_values, pop_deps.pops_aggregate_deps.reform_count } { + reserve_needs_fulfilled_goods(); +} fixed_point_t Pop::get_unemployment_fraction() const { if (!get_type().can_be_unemployed) { @@ -98,8 +101,8 @@ void Pop::setup_pop_test_values(TypedSpan reforms) num_migrated_external = test_size(1); num_migrated_colonial = test_size(2); - total_change = - num_grown + num_promoted + num_demoted + num_migrated_internal + num_migrated_external + num_migrated_colonial; + total_change = num_grown + num_promoted + num_demoted + num_migrated_internal + num_migrated_external + + num_migrated_colonial; /* Generates a number between 0 and max (inclusive) and sets map[&key] to it if it's at least min. */ static auto fill_span_with_test_weights = [](std::span span, int32_t min, int32_t max) -> void { @@ -114,17 +117,16 @@ void Pop::setup_pop_test_values(TypedSpan reforms) old_total += item; } - if (old_total == 0) { return; } + if (old_total == 0) { + return; + } for (fixed_point_t& item : span) { item = fp::mul_div(item, new_total, old_total); } }; - static auto rescale_spans = []( - std::span span_a, - std::span span_b, - const fixed_point_t new_total - ) -> void { + static auto rescale_spans = + [](std::span span_a, std::span span_b, const fixed_point_t new_total) -> void { fixed_point_t old_total = 0; for (const fixed_point_t item : span_a) { old_total += item; @@ -133,7 +135,9 @@ void Pop::setup_pop_test_values(TypedSpan reforms) old_total += item; } - if (old_total == 0) { return; } + if (old_total == 0) { + return; + } for (fixed_point_t& item : span_a) { item = fp::mul_div(item, new_total, old_total); @@ -142,7 +146,8 @@ void Pop::setup_pop_test_values(TypedSpan reforms) item = fp::mul_div(item, new_total, old_total); } }; - static auto test_weight_ordered = [](ordered_map& map, U const& key, int32_t min, int32_t max) -> void { + static auto test_weight_ordered = + [](ordered_map& map, U const& key, int32_t min, int32_t max) -> void { if constexpr (std::is_convertible_v || std::is_convertible_v) { const int32_t value = rand() % (max + 1); if (value >= min) { @@ -154,7 +159,10 @@ void Pop::setup_pop_test_values(TypedSpan reforms) } } else { // Optional: Handle the case where the conversion is not possible, perhaps with a static_assert. - static_assert(std::is_convertible_v || std::is_convertible_v, "Type U is not convertible to T const*."); + static_assert( + std::is_convertible_v || std::is_convertible_v, + "Type U is not convertible to T const*." + ); } }; @@ -162,18 +170,14 @@ void Pop::setup_pop_test_values(TypedSpan reforms) fill_span_with_test_weights(supporter_equivalents_by_ideology, 1, 5); rescale_span(supporter_equivalents_by_ideology, type_safe::get(size)); - fill_span_with_test_weights(supporter_equivalents_by_party_policy, 3, 6); + fill_span_with_test_weights(supporter_equivalents_by_party_policy, 3, 6); fill_span_with_test_weights(supporter_equivalents_by_reform, 3, 6); for (Reform const& reform : reforms) { if (reform.group.is_civilizing()) { supporter_equivalents_by_reform[reform.index] = 0; } } - rescale_spans( - supporter_equivalents_by_party_policy, - supporter_equivalents_by_reform, - type_safe::get(size) - ); + rescale_spans(supporter_equivalents_by_party_policy, supporter_equivalents_by_reform, type_safe::get(size)); if (!vote_equivalents_by_party.empty()) { for (auto& [party, value] : vote_equivalents_by_party) { @@ -219,11 +223,9 @@ void Pop::update_location_based_attributes() { } CountryDefinition const& country_definition = owner->country_definition; - auto view = country_definition.get_parties() | std::views::transform( - [](CountryParty const& key) { - return std::make_pair(&key, fixed_point_t::_0); - } - ); + auto view = country_definition.get_parties() | std::views::transform([](CountryParty const& key) { + return std::make_pair(&key, fixed_point_t::_0); + }); vote_equivalents_by_party.insert(view.begin(), view.end()); // TODO - calculate vote distribution } @@ -237,9 +239,7 @@ fixed_point_t Pop::get_vote_equivalents_by_party(CountryParty const& party) cons } void Pop::update_gamestate( - MilitaryDefines const& military_defines, - CountryInstance const* owner, - const fixed_point_t pop_size_per_regiment_multiplier + MilitaryDefines const& military_defines, CountryInstance const* owner, const fixed_point_t pop_size_per_regiment_multiplier ) { using enum culture_status_t; @@ -266,10 +266,8 @@ void Pop::update_gamestate( consciousness = std::clamp(consciousness, MIN_CONSCIOUSNESS, MAX_CONSCIOUSNESS); literacy = std::clamp(literacy, MIN_LITERACY, MAX_LITERACY); - if ( - size < military_defines.get_min_pop_size_for_regiment() || owner == nullptr || - !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status) - ) { + if (size < military_defines.get_min_pop_size_for_regiment() || owner == nullptr || + !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status)) { max_supported_regiments = 0; } else { max_supported_regiments = ( @@ -280,30 +278,29 @@ void Pop::update_gamestate( memory::string Pop::get_pop_context_text() const { return memory::fmt::format( - "location: {} type: {} culture: {} religion: {} size: {}", - location, type, culture, religion, size + "location: {} type: {} culture: {} religion: {} size: {}", location, type, culture, religion, size ); } void Pop::reserve_needs_fulfilled_goods() { PopType const& pop_type = type.get(); - #define RESERVE_NEEDS(need_category) \ - need_category##_needs_fulfilled_goods.reserve(pop_type.get_##need_category##_needs().size()); +#define RESERVE_NEEDS(need_category) \ + need_category##_needs_fulfilled_goods.reserve(pop_type.get_##need_category##_needs().size()); OV_DO_FOR_ALL_NEED_CATEGORIES(RESERVE_NEEDS) - #undef RESERVE_NEEDS +#undef RESERVE_NEEDS } void Pop::fill_needs_fulfilled_goods_with_false() { PopType const& pop_type = type.get(); - #define FILL_WITH_FALSE(need_category) \ - need_category##_needs_fulfilled_goods.clear(); \ - for (auto [good, base_demand] : pop_type.get_##need_category##_needs()) { \ - need_category##_needs_fulfilled_goods.emplace(good, false); \ - } +#define FILL_WITH_FALSE(need_category) \ + need_category##_needs_fulfilled_goods.clear(); \ + for (auto [good, base_demand] : pop_type.get_##need_category##_needs()) { \ + need_category##_needs_fulfilled_goods.emplace(good, false); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(FILL_WITH_FALSE) - #undef FILL_WITH_FALSE +#undef FILL_WITH_FALSE } void Pop::pay_income_tax(fixed_point_t& income) { @@ -311,7 +308,8 @@ void Pop::pay_income_tax(fixed_point_t& income) { if (tax_collector_nullable == nullptr) { return; } - const fixed_point_t effective_tax_rate = tax_collector_nullable->get_effective_tax_rate_by_strata(get_type().strata).get_untracked(); + const fixed_point_t effective_tax_rate = + tax_collector_nullable->get_effective_tax_rate_by_strata(get_type().strata).get_untracked(); const fixed_point_t tax = effective_tax_rate * income; tax_collector_nullable->report_pop_income_tax(type, income, tax); income -= tax; @@ -336,10 +334,7 @@ void Pop::add_artisanal_revenue(const fixed_point_t revenue) { if (OV_unlikely(!artisanal_producer_optional.has_value())) { income = revenue; } else { - income = std::max( - fixed_point_t::_0, - revenue - artisanal_producer_optional->get_costs_of_production() - ); + income = std::max(fixed_point_t::_0, revenue - artisanal_producer_optional->get_costs_of_production()); } pay_income_tax(income); @@ -355,7 +350,7 @@ template void Pop::add_artisanal_revenue(const fixed_point_t revenue); template void Pop::add_artisanal_revenue(const fixed_point_t revenue); #define DEFINE_ADD_INCOME_FUNCTIONS(name) \ - void Pop::add_##name(fixed_point_t amount){ \ + void Pop::add_##name(fixed_point_t amount) { \ if (OV_unlikely(amount == 0)) { \ if (size >= TRUNCATION_ACCEPTABLE_BELOW_SIZE) { \ spdlog::warn_s("Adding " #name " of 0 to pop. Context{}", get_pop_context_text()); \ @@ -376,7 +371,7 @@ OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DEFINE_ADD_INCOME_FUNCTIONS) #undef DEFINE_ADD_INCOME_FUNCTIONS #define DEFINE_ADD_EXPENSE_FUNCTIONS(name) \ - void Pop::add_##name(const fixed_point_t amount){ \ + void Pop::add_##name(const fixed_point_t amount) { \ if (OV_unlikely(amount == 0)) { \ if (size >= TRUNCATION_ACCEPTABLE_BELOW_SIZE) { \ spdlog::warn_s("Adding " #name " of 0 to pop. Context:{}", get_pop_context_text()); \ @@ -387,15 +382,19 @@ OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DEFINE_ADD_INCOME_FUNCTIONS) const fixed_point_t expenses_copy = expenses += amount; \ if (OV_unlikely(expenses_copy < 0)) { \ spdlog::error_s( \ - "Total expenses became negative ({}) after adding " #name " of {} to pop. Context:{}", \ - expenses_copy, amount, get_pop_context_text() \ + "Total expenses became negative ({}) after adding " #name " of {} to pop. Context:{}", \ + expenses_copy, \ + amount, \ + get_pop_context_text() \ ); \ } \ const fixed_point_t cash_copy = cash -= amount; \ if (OV_unlikely(cash_copy < 0)) { \ spdlog::error_s( \ - "Total cash became negative ({}) after adding " #name " of {} to pop. Context:{}", \ - cash_copy, amount, get_pop_context_text() \ + "Total cash became negative ({}) after adding " #name " of {} to pop. Context:{}", \ + cash_copy, \ + amount, \ + get_pop_context_text() \ ); \ } \ } @@ -404,8 +403,8 @@ OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DEFINE_ADD_EXPENSE_FUNCTIONS) #undef DEFINE_ADD_EXPENSE_FUNCTIONS void Pop::add_import_subsidies(const fixed_point_t amount) { - //It's not income, otherwise we'd pay income tax. - //It's not a negative expense, otherwise total expense might go negative. + // It's not income, otherwise we'd pay income tax. + // It's not a negative expense, otherwise total expense might go negative. cash += amount; } @@ -421,11 +420,11 @@ OV_DO_FOR_ALL_NEED_CATEGORIES(DEFINE_NEEDS_FULFILLED) #undef DEFINE_NEEDS_FULFILLED void Pop::allocate_for_needs( - fixed_point_map_t const& scaled_needs, - forwardable_span money_to_spend_per_good, - memory::vector& reusable_vector, - fixed_point_t& weights_sum, - fixed_point_t& cash_left_to_spend + fixed_point_map_t const& scaled_needs, + forwardable_span money_to_spend_per_good, + memory::vector& reusable_vector, + fixed_point_t& weights_sum, + fixed_point_t& cash_left_to_spend ) { if (weights_sum <= 0) { return; @@ -443,19 +442,14 @@ void Pop::allocate_for_needs( const fixed_point_t max_quantity_to_buy = it.value(); const ptrdiff_t i = it - scaled_needs.begin(); const fixed_point_t max_money_to_spend = market_instance.get_max_money_to_allocate_to_buy_quantity( - good_index, - max_quantity_to_buy + good_index, max_quantity_to_buy ); if (money_to_spend_per_good_draft[i] >= max_money_to_spend) { continue; } fixed_point_t weight = market_instance.get_good_instance(good_index).get_price_inverse(); - fixed_point_t cash_available_for_good = fp::mul_div( - cash_left_to_spend_draft, - weight, - weights_sum - ); + fixed_point_t cash_available_for_good = fp::mul_div(cash_left_to_spend_draft, weight, weights_sum); if (cash_available_for_good >= max_money_to_spend) { cash_left_to_spend_draft -= max_money_to_spend; @@ -465,7 +459,8 @@ void Pop::allocate_for_needs( break; } - const fixed_point_t max_possible_quantity_bought = cash_available_for_good / market_instance.get_min_next_price(good_index); + const fixed_point_t max_possible_quantity_bought = + cash_available_for_good / market_instance.get_min_next_price(good_index); if (max_possible_quantity_bought < fixed_point_t::epsilon) { money_to_spend_per_good_draft[i] = 0; } else { @@ -485,33 +480,22 @@ void Pop::allocate_for_needs( } void Pop::pop_tick( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + PopValuesFromProvince const& shared_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ) { - pop_tick_without_cleanup( - shared_values, - random_number_generator, - reusable_goods_mask, - reusable_vectors - ); + pop_tick_without_cleanup(shared_values, random_number_generator, reusable_goods_mask, reusable_vectors); for (auto& reusable_vector : reusable_vectors) { reusable_vector.clear(); } } void Pop::pop_tick_without_cleanup( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + PopValuesFromProvince const& shared_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ) { const std::size_t good_count = type_safe::get(reusable_goods_mask.size()); memory::vector& reusable_vector_0 = reusable_vectors[0]; @@ -522,32 +506,31 @@ void Pop::pop_tick_without_cleanup( money_to_spend_per_good.resize(good_count, 0); cash_allocated_for_artisanal_spending = 0; fill_needs_fulfilled_goods_with_false(); - + fixed_point_map_t goods_to_sell {}; if (artisanal_producer_optional.has_value()) { - //execute artisan_tick before needs + // execute artisan_tick before needs ArtisanalProducer& artisanal_producer = artisanal_producer_optional.value(); artisanal_producer.artisan_tick( - market_instance, - *this, - shared_values, - random_number_generator, - reusable_goods_mask, - max_quantity_to_buy_per_good, - money_to_spend_per_good, - reusable_vector_0, - reusable_vector_1, - goods_to_sell + market_instance, + *this, + shared_values, + random_number_generator, + reusable_goods_mask, + max_quantity_to_buy_per_good, + money_to_spend_per_good, + reusable_vector_0, + reusable_vector_1, + goods_to_sell ); } - //after artisan_tick as it uses income & expenses - #define SET_TO_ZERO(name) \ - name = 0; +// after artisan_tick as it uses income & expenses +#define SET_TO_ZERO(name) name = 0; OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(SET_TO_ZERO) OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(SET_TO_ZERO) - #undef SET_TO_ZERO +#undef SET_TO_ZERO income = expenses = 0; CountryInstance* const country_to_report_economy_nullable = get_location().get_country_to_report_economy(); @@ -556,78 +539,80 @@ void Pop::pop_tick_without_cleanup( country_to_report_economy_nullable->request_salaries_and_welfare_and_import_subsidies(*this); } - //unemployment subsidies are based on yesterdays unemployment + // unemployment subsidies are based on yesterdays unemployment employed = 0; - //import subsidies are based on yesterday + // import subsidies are based on yesterday yesterdays_import_value = 0; PopType const& pop_type = type; PopStrataValuesFromProvince const& shared_strata_values = shared_values.get_effects_by_strata()[pop_type.strata.index]; PopsDefines const& defines = shared_values.defines; - const fixed_point_t base_needs_scalar = ( - fixed_point_t::_1 + 2 * consciousness / defines.get_pdef_base_con() - ) * size; - - #define FILL_NEEDS(need_category) \ - need_category##_needs.clear(); \ - const fixed_point_t need_category##_needs_scalar = base_needs_scalar * shared_strata_values.get_shared_##need_category##_needs_scalar(); \ - fixed_point_t need_category##_needs_price_inverse_sum = 0; \ - if (OV_likely(need_category##_needs_scalar > 0)) { \ - need_category##_needs_acquired_quantity = need_category##_needs_desired_quantity = 0; \ - for (auto [good_index, quantity] : pop_type.get_##need_category##_needs()) { \ - if (!market_instance.get_is_available(good_index)) { \ - continue; \ - } \ - fixed_point_t max_quantity_to_buy = quantity * need_category##_needs_scalar / size_denominator; \ - if (max_quantity_to_buy == 0) { \ - continue; \ - } \ + const fixed_point_t base_needs_scalar = (fixed_point_t::_1 + 2 * consciousness / defines.get_pdef_base_con()) * size; + +#define FILL_NEEDS(need_category) \ + need_category##_needs.clear(); \ + const fixed_point_t need_category##_needs_scalar = \ + base_needs_scalar * shared_strata_values.get_shared_##need_category##_needs_scalar(); \ + fixed_point_t need_category##_needs_price_inverse_sum = 0; \ + if (OV_likely(need_category##_needs_scalar > 0)) { \ + need_category##_needs_acquired_quantity = need_category##_needs_desired_quantity = 0; \ + for (auto [good_index, quantity] : pop_type.get_##need_category##_needs()) { \ + if (!market_instance.get_is_available(good_index)) { \ + continue; \ + } \ + fixed_point_t max_quantity_to_buy = quantity * need_category##_needs_scalar / size_denominator; \ + if (max_quantity_to_buy == 0) { \ + continue; \ + } \ + if (country_to_report_economy_nullable != nullptr) { \ + country_to_report_economy_nullable->report_pop_need_demand(pop_type, good_index, max_quantity_to_buy); \ + } \ + need_category##_needs_desired_quantity += max_quantity_to_buy; \ + auto goods_to_sell_iterator = goods_to_sell.find(good_index); \ + if (goods_to_sell_iterator != goods_to_sell.end() && goods_to_sell_iterator.value() > 0) { \ + const fixed_point_t own_produce_consumed = std::min(goods_to_sell_iterator.value(), max_quantity_to_buy); \ + goods_to_sell_iterator.value() -= own_produce_consumed; \ + max_quantity_to_buy -= own_produce_consumed; \ + need_category##_needs_acquired_quantity += own_produce_consumed; \ if (country_to_report_economy_nullable != nullptr) { \ - country_to_report_economy_nullable->report_pop_need_demand(pop_type, good_index, max_quantity_to_buy); \ - } \ - need_category##_needs_desired_quantity += max_quantity_to_buy; \ - auto goods_to_sell_iterator = goods_to_sell.find(good_index); \ - if (goods_to_sell_iterator != goods_to_sell.end() && goods_to_sell_iterator.value() > 0) { \ - const fixed_point_t own_produce_consumed = std::min(goods_to_sell_iterator.value(), max_quantity_to_buy); \ - goods_to_sell_iterator.value() -= own_produce_consumed; \ - max_quantity_to_buy -= own_produce_consumed; \ - need_category##_needs_acquired_quantity += own_produce_consumed; \ - if (country_to_report_economy_nullable != nullptr) { \ - country_to_report_economy_nullable->report_pop_need_consumption(pop_type, good_index, own_produce_consumed); \ - } \ - } \ - if (OV_likely(max_quantity_to_buy > 0)) { \ - need_category##_needs_price_inverse_sum += market_instance.get_good_instance(good_index).get_price_inverse(); \ - need_category##_needs[good_index] += max_quantity_to_buy; \ - max_quantity_to_buy_per_good[type_safe::get(good_index)] += max_quantity_to_buy; \ + country_to_report_economy_nullable->report_pop_need_consumption( \ + pop_type, good_index, own_produce_consumed \ + ); \ } \ } \ - } + if (OV_likely(max_quantity_to_buy > 0)) { \ + need_category##_needs_price_inverse_sum += market_instance.get_good_instance(good_index).get_price_inverse(); \ + need_category##_needs[good_index] += max_quantity_to_buy; \ + max_quantity_to_buy_per_good[type_safe::get(good_index)] += max_quantity_to_buy; \ + } \ + } \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(FILL_NEEDS) - #undef FILL_NEEDS - - //It's safe to use cash as this happens before cash is updated via spending - fixed_point_t cash_left_to_spend = cash.get_copy_of_value() / shared_values.get_max_cost_multiplier() - - cash_allocated_for_artisanal_spending; - - #define ALLOCATE_FOR_NEEDS(need_category) \ - if (cash_left_to_spend > 0) { \ - allocate_for_needs( \ - need_category##_needs, \ - money_to_spend_per_good, \ - reusable_vector_0, \ - need_category##_needs_price_inverse_sum, \ - cash_left_to_spend \ - ); \ - } +#undef FILL_NEEDS + + // It's safe to use cash as this happens before cash is updated via spending + fixed_point_t cash_left_to_spend = + cash.get_copy_of_value() / shared_values.get_max_cost_multiplier() - cash_allocated_for_artisanal_spending; + +#define ALLOCATE_FOR_NEEDS(need_category) \ + if (cash_left_to_spend > 0) { \ + allocate_for_needs( \ + need_category##_needs, \ + money_to_spend_per_good, \ + reusable_vector_0, \ + need_category##_needs_price_inverse_sum, \ + cash_left_to_spend \ + ); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(ALLOCATE_FOR_NEEDS) - #undef ALLOCATE_FOR_NEEDS +#undef ALLOCATE_FOR_NEEDS - const std::optional country_index_optional = country_to_report_economy_nullable == nullptr - ? std::nullopt - : std::optional{country_to_report_economy_nullable->index}; + const std::optional country_index_optional = + country_to_report_economy_nullable == nullptr + ? std::nullopt + : std::optional { country_to_report_economy_nullable->index }; for (std::size_t i = 0; i < good_count; ++i) { const fixed_point_t max_quantity_to_buy = max_quantity_to_buy_per_good[i]; @@ -635,17 +620,12 @@ void Pop::pop_tick_without_cleanup( if (max_quantity_to_buy <= 0) { continue; } - + const fixed_point_t money_to_spend = money_to_spend_per_good[i]; - market_instance.place_buy_up_to_order({ - good_index_t(i), - country_index_optional, - max_quantity_to_buy, - money_to_spend, - this, - after_buy - }); + market_instance.place_buy_up_to_order( + { good_index_t(i), country_index_optional, max_quantity_to_buy, money_to_spend, this, after_buy } + ); } for (const auto [good_index, quantity_to_sell] : goods_to_sell) { @@ -657,14 +637,7 @@ void Pop::pop_tick_without_cleanup( } market_instance.place_market_sell_order( - { - good_index, - country_index_optional, - quantity_to_sell, - this, - after_sell - }, - reusable_vectors[4] + { good_index, country_index_optional, quantity_to_sell, this, after_sell }, reusable_vectors[4] ); } } @@ -693,58 +666,51 @@ void Pop::after_buy(void* actor, BuyResult const& buy_result) { return; } const fixed_point_t quantity_added_to_stockpile = pop.artisanal_producer_optional.value().add_to_stockpile( - good_index, - quantity_left_to_consume + good_index, quantity_left_to_consume ); if (quantity_added_to_stockpile > 0) { quantity_left_to_consume -= quantity_added_to_stockpile; - const fixed_point_t expense = fp::mul_div( - money_spent, - quantity_added_to_stockpile, - quantity_bought - ); + const fixed_point_t expense = fp::mul_div(money_spent, quantity_added_to_stockpile, quantity_bought); pop.add_artisan_inputs_expense(expense); } } CountryInstance* get_country_to_report_economy_nullable = pop.get_location().get_country_to_report_economy(); - - #define CONSUME_NEED(need_category) \ - if (quantity_left_to_consume <= 0) { \ - return; \ + +#define CONSUME_NEED(need_category) \ + if (quantity_left_to_consume <= 0) { \ + return; \ + } \ + const fixed_point_map_t::const_iterator need_category##it = pop.need_category##_needs.find(good_index); \ + if (need_category##it != pop.need_category##_needs.end()) { \ + const fixed_point_t desired_quantity = need_category##it->second; \ + fixed_point_t consumed_quantity; \ + if (quantity_left_to_consume >= desired_quantity) { \ + consumed_quantity = desired_quantity; \ + pop.need_category##_needs_fulfilled_goods.at(good_index) = true; \ + } else { \ + consumed_quantity = quantity_left_to_consume; \ } \ - const fixed_point_map_t::const_iterator need_category##it = pop.need_category##_needs.find(good_index); \ - if (need_category##it != pop.need_category##_needs.end()) { \ - const fixed_point_t desired_quantity = need_category##it->second; \ - fixed_point_t consumed_quantity; \ - if (quantity_left_to_consume >= desired_quantity) { \ - consumed_quantity = desired_quantity; \ - pop.need_category##_needs_fulfilled_goods.at(good_index) = true; \ - } else { \ - consumed_quantity = quantity_left_to_consume; \ - } \ - pop.need_category##_needs_acquired_quantity += consumed_quantity; \ - quantity_left_to_consume -= consumed_quantity; \ - if (get_country_to_report_economy_nullable != nullptr) { \ - get_country_to_report_economy_nullable->report_pop_need_consumption(pop.type, good_index, consumed_quantity); \ - } \ - const fixed_point_t expense = fp::mul_div( \ - money_spent, \ - consumed_quantity, \ - quantity_bought \ - ); \ - pop.add_##need_category##_needs_expense(expense); \ - } + pop.need_category##_needs_acquired_quantity += consumed_quantity; \ + quantity_left_to_consume -= consumed_quantity; \ + if (get_country_to_report_economy_nullable != nullptr) { \ + get_country_to_report_economy_nullable->report_pop_need_consumption(pop.type, good_index, consumed_quantity); \ + } \ + const fixed_point_t expense = fp::mul_div(money_spent, consumed_quantity, quantity_bought); \ + pop.add_##need_category##_needs_expense(expense); \ + } OV_DO_FOR_ALL_NEED_CATEGORIES(CONSUME_NEED) - #undef CONSUME_NEED +#undef CONSUME_NEED } void Pop::after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { Pop& pop = *static_cast(actor); if (sell_result.money_gained > 0) { - OV_ERR_FAIL_COND_MSG(!pop.artisanal_producer_optional.has_value(), "Pop is selling artisanal goods but has no artisan."); + OV_ERR_FAIL_COND_MSG( + !pop.artisanal_producer_optional.has_value(), "Pop is selling artisanal goods but has no artisan." + ); ArtisanalProducer& artisan = pop.artisanal_producer_optional.value(); if (artisan.get_last_produced_good() != nullptr && artisan.get_last_produced_good()->index == sell_result.good_index) { pop.add_artisanal_revenue(sell_result.money_gained); @@ -761,22 +727,13 @@ void Pop::allocate_cash_for_artisanal_spending(fixed_point_t money_to_spend) { void Pop::hire(pop_size_t count) { if (OV_unlikely(count <= 0)) { - spdlog::warn_s( - "Tried employing non-positive number of pops. {} Context{}", - count, get_pop_context_text() - ); + spdlog::warn_s("Tried employing non-positive number of pops. {} Context{}", count, get_pop_context_text()); } employed += count; if (OV_unlikely(employed > size)) { - spdlog::error_s( - "Employed count became greater than pop size. {} Context{}", - employed, get_pop_context_text() - ); + spdlog::error_s("Employed count became greater than pop size. {} Context{}", employed, get_pop_context_text()); } else if (OV_unlikely(employed < 0)) { - spdlog::error_s( - "Employed count became negative. {} Context{}", - employed, get_pop_context_text() - ); + spdlog::error_s("Employed count became negative. {} Context{}", employed, get_pop_context_text()); } } diff --git a/src/openvic-simulation/population/Pop.hpp b/src/openvic-simulation/population/Pop.hpp index 475412719..eb421afd5 100644 --- a/src/openvic-simulation/population/Pop.hpp +++ b/src/openvic-simulation/population/Pop.hpp @@ -13,8 +13,8 @@ #include "openvic-simulation/population/PopIdInProvince.hpp" #include "openvic-simulation/population/PopNeedsMacro.hpp" #include "openvic-simulation/population/PopSize.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/UnitBranchType.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" namespace OpenVic { struct BuyResult; @@ -44,39 +44,47 @@ namespace OpenVic { RebelType const* PROPERTY_ACCESS(rebel_type, protected); PopBase( - PopType const& new_type, Culture const& new_culture, Religion const& new_religion, pop_size_t new_size, - fixed_point_t new_militancy, fixed_point_t new_consciousness, RebelType const* new_rebel_type + PopType const& new_type, + Culture const& new_culture, + Religion const& new_religion, + pop_size_t new_size, + fixed_point_t new_militancy, + fixed_point_t new_consciousness, + RebelType const* new_rebel_type ); + public: Culture const& culture; Religion const& religion; }; - #define OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(F) \ - F(rgo_owner_income) \ - F(rgo_worker_income) \ - F(factory_worker_income) \ - F(factory_owner_income) \ - F(unemployment_subsidies) \ - F(pensions) \ - F(government_salary_administration) \ - F(government_salary_education) \ - F(government_salary_military) \ - F(event_and_decision_income) \ - F(loan_interest_payments) - - #define OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(F) \ - F(life_needs_expense) \ - F(everyday_needs_expense) \ - F(luxury_needs_expense) \ - F(artisan_inputs_expense) +#define OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(F) \ + F(rgo_owner_income) \ + F(rgo_worker_income) \ + F(factory_worker_income) \ + F(factory_owner_income) \ + F(unemployment_subsidies) \ + F(pensions) \ + F(government_salary_administration) \ + F(government_salary_education) \ + F(government_salary_military) \ + F(event_and_decision_income) \ + F(loan_interest_payments) + +#define OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(F) \ + F(life_needs_expense) \ + F(everyday_needs_expense) \ + F(luxury_needs_expense) \ + F(artisan_inputs_expense) /* REQUIREMENTS: * POP-18, POP-19, POP-20, POP-21, POP-34, POP-35, POP-36, POP-37 */ struct Pop : PopBase { enum struct culture_status_t : uint8_t { - UNACCEPTED, ACCEPTED, PRIMARY + UNACCEPTED, + ACCEPTED, + PRIMARY }; static constexpr bool is_culture_status_allowed(regiment_allowed_cultures_t allowed, culture_status_t status) { @@ -102,7 +110,6 @@ namespace OpenVic { } private: - /* Last day's size change by source. */ pop_size_t PROPERTY(total_change, 0); pop_size_t PROPERTY(num_grown, 0); @@ -137,31 +144,35 @@ namespace OpenVic { return size - employed; } fixed_point_t get_unemployment_fraction() const; + private: fixed_point_t PROPERTY(income); fixed_point_t PROPERTY(savings); moveable_atomic_fixed_point_t PROPERTY(cash); - moveable_atomic_fixed_point_t PROPERTY(expenses); //positive value means POP paid for goods. This is displayed * -1 in UI. + moveable_atomic_fixed_point_t PROPERTY( + expenses + ); // positive value means POP paid for goods. This is displayed * -1 in UI. moveable_atomic_fixed_point_t PROPERTY(yesterdays_import_value); - #define NEED_MEMBERS(need_category) \ - moveable_atomic_fixed_point_t need_category##_needs_acquired_quantity, need_category##_needs_desired_quantity; \ - public: \ - fixed_point_t get_##need_category##_needs_fulfilled() const; \ - private: \ - fixed_point_map_t PROPERTY(need_category##_needs); /* TODO pool? (if recalculating in UI is acceptable) */ \ - ordered_map PROPERTY(need_category##_needs_fulfilled_goods); +#define NEED_MEMBERS(need_category) \ + moveable_atomic_fixed_point_t need_category##_needs_acquired_quantity, need_category##_needs_desired_quantity; \ +\ +public: \ + fixed_point_t get_##need_category##_needs_fulfilled() const; \ +\ +private: \ + fixed_point_map_t PROPERTY(need_category##_needs); /* TODO pool? (if recalculating in UI is acceptable) */ \ + ordered_map PROPERTY(need_category##_needs_fulfilled_goods); OV_DO_FOR_ALL_NEED_CATEGORIES(NEED_MEMBERS) - #undef NEED_MEMBERS +#undef NEED_MEMBERS fixed_point_t PROPERTY(artisanal_revenue); - #define DECLARE_POP_MONEY_STORES(money_type) \ - fixed_point_t PROPERTY(money_type); +#define DECLARE_POP_MONEY_STORES(money_type) fixed_point_t PROPERTY(money_type); OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DECLARE_POP_MONEY_STORES); OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DECLARE_POP_MONEY_STORES); - #undef DECLARE_POP_MONEY_STORES +#undef DECLARE_POP_MONEY_STORES std::size_t PROPERTY(regiment_count, 0); std::size_t PROPERTY(max_supported_regiments, 0); @@ -170,20 +181,17 @@ namespace OpenVic { void reserve_needs_fulfilled_goods(); void fill_needs_fulfilled_goods_with_false(); void allocate_for_needs( - fixed_point_map_t const& scaled_needs, - forwardable_span money_to_spend_per_good, - memory::vector& reusable_vector, - fixed_point_t& price_inverse_sum, - fixed_point_t& cash_left_to_spend + fixed_point_map_t const& scaled_needs, + forwardable_span money_to_spend_per_good, + memory::vector& reusable_vector, + fixed_point_t& price_inverse_sum, + fixed_point_t& cash_left_to_spend ); void pop_tick_without_cleanup( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + PopValuesFromProvince const& shared_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ); void pay_income_tax(fixed_point_t& income); @@ -191,16 +199,14 @@ namespace OpenVic { void add_artisanal_revenue(const fixed_point_t revenue); static void after_buy(void* actor, BuyResult const& buy_result); - //matching GoodMarketSellOrder::callback_t + // matching GoodMarketSellOrder::callback_t static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector); public: - Pop( - ProvinceInstance& new_location, - PopBase const& pop_base, - PopDeps const& pop_deps, - const pop_id_in_province_t new_id_in_province - ); + Pop(ProvinceInstance& new_location, + PopBase const& pop_base, + PopDeps const& pop_deps, + const pop_id_in_province_t new_id_in_province); Pop(Pop const&) = delete; Pop(Pop&&) = default; Pop& operator=(Pop const&) = delete; @@ -211,31 +217,27 @@ namespace OpenVic { void update_location_based_attributes(); void update_gamestate( - MilitaryDefines const& military_defines, - CountryInstance const* owner, - const fixed_point_t pop_size_per_regiment_multiplier + MilitaryDefines const& military_defines, + CountryInstance const* owner, + const fixed_point_t pop_size_per_regiment_multiplier ); - #define DECLARE_POP_MONEY_STORE_FUNCTIONS(name) \ - void add_##name(fixed_point_t amount); +#define DECLARE_POP_MONEY_STORE_FUNCTIONS(name) void add_##name(fixed_point_t amount); OV_DO_FOR_ALL_TYPES_OF_POP_INCOME(DECLARE_POP_MONEY_STORE_FUNCTIONS) OV_DO_FOR_ALL_TYPES_OF_POP_EXPENSES(DECLARE_POP_MONEY_STORE_FUNCTIONS) DECLARE_POP_MONEY_STORE_FUNCTIONS(import_subsidies) - #undef DECLARE_POP_MONEY_STORE_FUNCTIONS +#undef DECLARE_POP_MONEY_STORE_FUNCTIONS void pop_tick( - PopValuesFromProvince const& shared_values, - RandomU32& random_number_generator, - TypedSpan reusable_goods_mask, - forwardable_span< - memory::vector, - VECTORS_FOR_POP_TICK - > reusable_vectors + PopValuesFromProvince const& shared_values, + RandomU32& random_number_generator, + TypedSpan reusable_goods_mask, + forwardable_span, VECTORS_FOR_POP_TICK> reusable_vectors ); void allocate_cash_for_artisanal_spending(const fixed_point_t money_to_spend); void hire(pop_size_t count); - //recruit or conscript + // recruit or conscript bool try_recruit(); bool try_recruit_understrength(); }; diff --git a/src/openvic-simulation/population/PopDeps.hpp b/src/openvic-simulation/population/PopDeps.hpp index c610ed914..252718b96 100644 --- a/src/openvic-simulation/population/PopDeps.hpp +++ b/src/openvic-simulation/population/PopDeps.hpp @@ -10,4 +10,4 @@ namespace OpenVic { MarketInstance& market_instance; PopsAggregateDeps const& pops_aggregate_deps; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopIdInProvince.hpp b/src/openvic-simulation/population/PopIdInProvince.hpp index c9b02ed0d..e32962e1a 100644 --- a/src/openvic-simulation/population/PopIdInProvince.hpp +++ b/src/openvic-simulation/population/PopIdInProvince.hpp @@ -8,18 +8,23 @@ #include namespace OpenVic { - struct pop_id_in_province_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic { + struct pop_id_in_province_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic { using strong_typedef::strong_typedef; - constexpr bool is_null() const { return type_safe::get(*this) == 0; } - constexpr bool operator!() const { return is_null(); } + constexpr bool is_null() const { + return type_safe::get(*this) == 0; + } + constexpr bool operator!() const { + return is_null(); + } }; } namespace std { - template <> + template<> struct hash : type_safe::hashable {}; } template<> @@ -27,4 +32,4 @@ struct fmt::formatter : fmt::formatter::format(type_safe::get(value), ctx); } -}; \ No newline at end of file +}; diff --git a/src/openvic-simulation/population/PopManager.cpp b/src/openvic-simulation/population/PopManager.cpp index 0d1d86957..f7480b743 100644 --- a/src/openvic-simulation/population/PopManager.cpp +++ b/src/openvic-simulation/population/PopManager.cpp @@ -18,15 +18,15 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -PopManager::PopManager() - : slave_sprite { 0 }, administrative_sprite { 0 }, - promotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - demotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - migration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - colonialmigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - emigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - assimilation_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, - conversion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE } {} +PopManager::PopManager() : + slave_sprite { 0 }, administrative_sprite { 0 }, + promotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + demotion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + migration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + colonialmigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + emigration_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + assimilation_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE }, + conversion_chance { scope_type_t::POP, scope_type_t::POP, scope_type_t::NO_SCOPE } {} bool PopManager::setup_stratas() { if (stratas_are_locked()) { @@ -34,9 +34,7 @@ bool PopManager::setup_stratas() { return false; } - static constexpr std::array STRATA_IDENTIFIERS { - "poor", "middle", "rich" - }; + static constexpr std::array STRATA_IDENTIFIERS { "poor", "middle", "rich" }; reserve_more_stratas(STRATA_IDENTIFIERS.size()); @@ -64,48 +62,45 @@ bool PopManager::add_strata(std::string_view identifier) { spdlog::error_s("Invalid strata identifier - empty!"); return false; } - return stratas.emplace_item( - identifier, - identifier, index_from_count(get_strata_count()) - ); + return stratas.emplace_item(identifier, identifier, index_from_count(get_strata_count())); } bool PopManager::add_pop_type( - std::string_view identifier, - colour_t colour, - Strata* strata, - pop_sprite_t sprite, - fixed_point_map_t&& life_needs, - fixed_point_map_t&& everyday_needs, - fixed_point_map_t&& luxury_needs, - PopType::income_type_t life_needs_income_types, - PopType::income_type_t everyday_needs_income_types, - PopType::income_type_t luxury_needs_income_types, - ast::NodeCPtr rebel_units, - pop_size_t max_size, - pop_size_t merge_max_size, - bool state_capital_only, - bool demote_migrant, - bool is_artisan, - bool allowed_to_vote, - bool is_slave, - bool can_be_recruited, - bool can_reduce_consciousness, - bool administrative_efficiency, - bool can_invest, - bool factory, - bool can_work_factory, - bool unemployment, - fixed_point_t research_points, - fixed_point_t leadership_points, - fixed_point_t research_leadership_optimum, - fixed_point_t state_administration_multiplier, - ast::NodeCPtr equivalent, - ConditionalWeightFactorMul&& country_migration_target, - ConditionalWeightFactorMul&& migration_target, - ast::NodeCPtr promote_to_node, - PopType::ideology_weight_map_t&& ideologies, - ast::NodeCPtr issues_node + std::string_view identifier, + colour_t colour, + Strata* strata, + pop_sprite_t sprite, + fixed_point_map_t&& life_needs, + fixed_point_map_t&& everyday_needs, + fixed_point_map_t&& luxury_needs, + PopType::income_type_t life_needs_income_types, + PopType::income_type_t everyday_needs_income_types, + PopType::income_type_t luxury_needs_income_types, + ast::NodeCPtr rebel_units, + pop_size_t max_size, + pop_size_t merge_max_size, + bool state_capital_only, + bool demote_migrant, + bool is_artisan, + bool allowed_to_vote, + bool is_slave, + bool can_be_recruited, + bool can_reduce_consciousness, + bool administrative_efficiency, + bool can_invest, + bool factory, + bool can_work_factory, + bool unemployment, + fixed_point_t research_points, + fixed_point_t leadership_points, + fixed_point_t research_leadership_optimum, + fixed_point_t state_administration_multiplier, + ast::NodeCPtr equivalent, + ConditionalWeightFactorMul&& country_migration_target, + ConditionalWeightFactorMul&& migration_target, + ast::NodeCPtr promote_to_node, + PopType::ideology_weight_map_t&& ideologies, + ast::NodeCPtr issues_node ) { if (identifier.empty()) { spdlog::error_s("Invalid pop type identifier - empty!"); @@ -116,82 +111,77 @@ bool PopManager::add_pop_type( return false; } if (sprite <= 0) { - spdlog::error_s( - "Invalid pop type sprite index for {}: {} (must be positive)", - identifier, sprite - ); + spdlog::error_s("Invalid pop type sprite index for {}: {} (must be positive)", identifier, sprite); return false; } if (max_size <= 0) { - spdlog::error_s( - "Invalid pop type max size for {}: {} (must be positive)", - identifier, max_size - ); + spdlog::error_s("Invalid pop type max size for {}: {} (must be positive)", identifier, max_size); return false; } if (merge_max_size <= 0) { - spdlog::error_s( - "Invalid pop type merge max size for {}: {} (must be positive)", - identifier, merge_max_size - ); + spdlog::error_s("Invalid pop type merge max size for {}: {} (must be positive)", identifier, merge_max_size); return false; } if (research_leadership_optimum < 0) { spdlog::error_s( - "Invalid pop type research/leadership optimum for {}: {} (cannot be negative)", - identifier, research_leadership_optimum + "Invalid pop type research/leadership optimum for {}: {} (cannot be negative)", + identifier, + research_leadership_optimum ); return false; } if ((research_points != 0 || leadership_points != 0) != (research_leadership_optimum > 0)) { spdlog::error_s( - "Invalid pop type research/leadership points and optimum for {}: research = {}, leadership = {}, optimum = {} " - "(optimum is positive if and only if at least one of research and leadership is non-zero)", - identifier, research_points, leadership_points, research_leadership_optimum + "Invalid pop type research/leadership points and optimum for {}: research = {}, leadership = {}, optimum = {} " + "(optimum is positive if and only if at least one of research and leadership is non-zero)", + identifier, + research_points, + leadership_points, + research_leadership_optimum ); return false; } if (OV_unlikely(!pop_types.emplace_item( - identifier, - identifier, - colour, - index_from_count(get_pop_type_count()), - *strata, - sprite, - std::move(life_needs), - std::move(everyday_needs), - std::move(luxury_needs), - life_needs_income_types, - everyday_needs_income_types, - luxury_needs_income_types, - PopType::rebel_units_t{}, - max_size, - merge_max_size, - state_capital_only, - demote_migrant, - is_artisan, - allowed_to_vote, - is_slave, - can_be_recruited, - can_reduce_consciousness, - administrative_efficiency, - can_invest, - factory, - can_work_factory, - unemployment, - research_points, - leadership_points, - research_leadership_optimum, - state_administration_multiplier, - static_cast(nullptr), - std::move(country_migration_target), - std::move(migration_target), - PopType::poptype_weight_map_t { PopType::poptype_weight_map_t{ create_empty } }, - std::move(ideologies), - PopType::issue_weight_map_t{} - ))) { + identifier, + identifier, + colour, + index_from_count(get_pop_type_count()), + *strata, + sprite, + std::move(life_needs), + std::move(everyday_needs), + std::move(luxury_needs), + life_needs_income_types, + everyday_needs_income_types, + luxury_needs_income_types, + PopType::rebel_units_t {}, + max_size, + merge_max_size, + state_capital_only, + demote_migrant, + is_artisan, + allowed_to_vote, + is_slave, + can_be_recruited, + can_reduce_consciousness, + administrative_efficiency, + can_invest, + factory, + can_work_factory, + unemployment, + research_points, + leadership_points, + research_leadership_optimum, + state_administration_multiplier, + static_cast(nullptr), + std::move(country_migration_target), + std::move(migration_target), + PopType::poptype_weight_map_t { PopType::poptype_weight_map_t { create_empty } }, + std::move(ideologies), + PopType::issue_weight_map_t {} + ))) { return false; } @@ -224,26 +214,26 @@ void PopManager::reserve_pop_types_and_delayed_nodes(size_t size) { static NodeCallback auto expect_needs_income(PopType::income_type_t& types) { using enum PopType::income_type_t; static const string_map_t income_type_map { - { "administration", ADMINISTRATION }, - { "education", EDUCATION }, - { "military", MILITARY } + { "administration", ADMINISTRATION }, { "education", EDUCATION }, { "military", MILITARY } }; constexpr bool is_warning = true; return expect_dictionary_keys_and_default_map( - map_key_value_ignore_invalid_callback>, - "type", ONE_OR_MORE, expect_identifier(expect_mapped_string( - income_type_map, - [&types](PopType::income_type_t type) -> bool { - if (OV_unlikely(share_income_type(types, type))) { - spdlog::warn_s("Duplicate pop income type {} is treated as single income.", fmt::underlying(type)); - } else { - types |= type; - } - return true; - }, - is_warning - )) + map_key_value_ignore_invalid_callback>, + "type", + ONE_OR_MORE, + expect_identifier(expect_mapped_string( + income_type_map, + [&types](PopType::income_type_t type) -> bool { + if (OV_unlikely(share_income_type(types, type))) { + spdlog::warn_s("Duplicate pop income type {} is treated as single income.", fmt::underlying(type)); + } else { + types |= type; + } + return true; + }, + is_warning + )) ); } @@ -251,8 +241,10 @@ static NodeCallback auto expect_needs_income(PopType::income_type_t& types) { * POP-3, POP-4, POP-5, POP-6, POP-7, POP-8, POP-9, POP-10, POP-11, POP-12, POP-13, POP-14 */ bool PopManager::load_pop_type_file( - std::string_view filestem, GoodDefinitionManager const& good_definition_manager, IdeologyManager const& ideology_manager, - ast::NodeCPtr root + std::string_view filestem, + GoodDefinitionManager const& good_definition_manager, + IdeologyManager const& ideology_manager, + ast::NodeCPtr root ) { spdlog::scope scope { fmt::format("poptypes/{}.txt", filestem) }; using enum scope_type_t; @@ -263,14 +255,14 @@ bool PopManager::load_pop_type_file( pop_sprite_t sprite = 0; fixed_point_map_t life_needs, everyday_needs, luxury_needs; PopType::income_type_t life_needs_income_types = NO_INCOME_TYPE, everyday_needs_income_types = NO_INCOME_TYPE, - luxury_needs_income_types = NO_INCOME_TYPE; + luxury_needs_income_types = NO_INCOME_TYPE; ast::NodeCPtr rebel_units = nullptr; pop_size_t max_size = Pop::MAX_SIZE, merge_max_size = Pop::MAX_SIZE; bool state_capital_only = false, demote_migrant = false, is_artisan = false, allowed_to_vote = true, is_slave = false, - can_be_recruited = false, can_reduce_consciousness = false, administrative_efficiency = false, can_invest = false, - factory = false, can_work_factory = false, unemployment = false; + can_be_recruited = false, can_reduce_consciousness = false, administrative_efficiency = false, can_invest = false, + factory = false, can_work_factory = false, unemployment = false; fixed_point_t research_points = 0, leadership_points = 0, research_leadership_optimum = 0, - state_administration_multiplier = 0; + state_administration_multiplier = 0; ast::NodeCPtr equivalent = nullptr; ConditionalWeightFactorMul country_migration_target { COUNTRY, POP, NO_SCOPE }; ConditionalWeightFactorMul migration_target { PROVINCE, POP, NO_SCOPE }; @@ -347,48 +339,46 @@ bool PopManager::load_pop_type_file( } ret &= add_pop_type( - filestem, - colour, - strata, - sprite, - std::move(life_needs_index_based), - std::move(everyday_needs_index_based), - std::move(luxury_needs_index_based), - life_needs_income_types, - everyday_needs_income_types, - luxury_needs_income_types, - rebel_units, - max_size, - merge_max_size, - state_capital_only, - demote_migrant, - is_artisan, - allowed_to_vote, - is_slave, - can_be_recruited, - can_reduce_consciousness, - administrative_efficiency, - can_invest, - factory, - can_work_factory, - unemployment, - research_points, - leadership_points, - research_leadership_optimum, - state_administration_multiplier, - equivalent, - std::move(country_migration_target), - std::move(migration_target), - promote_to_node, - std::move(ideologies), - issues_node + filestem, + colour, + strata, + sprite, + std::move(life_needs_index_based), + std::move(everyday_needs_index_based), + std::move(luxury_needs_index_based), + life_needs_income_types, + everyday_needs_income_types, + luxury_needs_income_types, + rebel_units, + max_size, + merge_max_size, + state_capital_only, + demote_migrant, + is_artisan, + allowed_to_vote, + is_slave, + can_be_recruited, + can_reduce_consciousness, + administrative_efficiency, + can_invest, + factory, + can_work_factory, + unemployment, + research_points, + leadership_points, + research_leadership_optimum, + state_administration_multiplier, + equivalent, + std::move(country_migration_target), + std::move(migration_target), + promote_to_node, + std::move(ideologies), + issues_node ); return ret; } -bool PopManager::load_delayed_parse_pop_type_data( - UnitTypeManager const& unit_type_manager, IssueManager const& issue_manager -) { +bool PopManager::load_delayed_parse_pop_type_data(UnitTypeManager const& unit_type_manager, IssueManager const& issue_manager) { using enum scope_type_t; bool ret = true; @@ -396,52 +386,47 @@ bool PopManager::load_delayed_parse_pop_type_data( const auto [rebel_units, equivalent, promote_to_node, issues_node] = delayed_parse_nodes[index]; PopType* pop_type = pop_types.get_item_by_index(pop_type_index_t(index)); - pop_type->promote_to = std::move(decltype(PopType::promote_to){get_pop_types()}); + pop_type->promote_to = std::move(decltype(PopType::promote_to) { get_pop_types() }); - if (rebel_units != nullptr && !unit_type_manager.expect_unit_type_decimal_map( - move_variable_callback(pop_type->rebel_units) - )(rebel_units)) { + if (rebel_units != nullptr && + !unit_type_manager.expect_unit_type_decimal_map(move_variable_callback(pop_type->rebel_units))(rebel_units)) { spdlog::error_s("Errors parsing rebel unit distribution for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (equivalent != nullptr && !expect_pop_type_identifier( - assign_variable_callback_pointer(pop_type->equivalent) - )(equivalent)) { + if (equivalent != nullptr && + !expect_pop_type_identifier(assign_variable_callback_pointer(pop_type->equivalent))(equivalent)) { spdlog::error_s("Errors parsing equivalent pop type for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (promote_to_node != nullptr && !expect_pop_type_dictionary( - [pop_type](PopType const& type, ast::NodeCPtr node) -> bool { - if (pop_type && type == *pop_type) { - spdlog::error_s("Pop type {} cannot have promotion weight to itself!", type); - return false; - } - ConditionalWeightFactorAdd weight { POP, POP, NO_SCOPE }; - bool ret = weight.expect_conditional_weight()(node); - ret &= map_callback(pop_type->promote_to, &type)(std::move(weight)); - return ret; - } - )(promote_to_node)) { + if (promote_to_node != nullptr && + !expect_pop_type_dictionary([pop_type](PopType const& type, ast::NodeCPtr node) -> bool { + if (pop_type && type == *pop_type) { + spdlog::error_s("Pop type {} cannot have promotion weight to itself!", type); + return false; + } + ConditionalWeightFactorAdd weight { POP, POP, NO_SCOPE }; + bool ret = weight.expect_conditional_weight()(node); + ret &= map_callback(pop_type->promote_to, &type)(std::move(weight)); + return ret; + })(promote_to_node)) { spdlog::error_s("Errors parsing promotion weights for pop type {}!", ovfmt::validate(pop_type)); ret = false; } - if (issues_node != nullptr && !expect_dictionary_reserve_length( - pop_type->issues, - [pop_type, &issue_manager](std::string_view key, ast::NodeCPtr node) -> bool { - BaseIssue const* issue = issue_manager.get_base_issue_by_identifier(key); - if (issue == nullptr) { - spdlog::error_s("Invalid issue in pop type {} issue weights: {}", ovfmt::validate(pop_type), key); - return false; - } - ConditionalWeightFactorMul weight { POP, POP, NO_SCOPE }; - bool ret = weight.expect_conditional_weight()(node); - ret &= map_callback(pop_type->issues, issue)(std::move(weight)); - return ret; - } - )(issues_node)) { + if (issues_node != nullptr && + !expect_dictionary_reserve_length(pop_type->issues, [pop_type, &issue_manager](std::string_view key, ast::NodeCPtr node) -> bool { + BaseIssue const* issue = issue_manager.get_base_issue_by_identifier(key); + if (issue == nullptr) { + spdlog::error_s("Invalid issue in pop type {} issue weights: {}", ovfmt::validate(pop_type), key); + return false; + } + ConditionalWeightFactorMul weight { POP, POP, NO_SCOPE }; + bool ret = weight.expect_conditional_weight()(node); + ret &= map_callback(pop_type->issues, issue)(std::move(weight)); + return ret; + })(issues_node)) { spdlog::error_s("Errors parsing issue weights for pop type {}!", ovfmt::validate(pop_type)); ret = false; } @@ -463,8 +448,11 @@ bool PopManager::load_pop_type_chances_file(ast::NodeCPtr root) { } bool PopManager::load_pop_bases_into_vector( - RebelManager const& rebel_manager, memory::vector& vec, PopType const& type, ast::NodeCPtr pop_node, - bool *non_integer_size + RebelManager const& rebel_manager, + memory::vector& vec, + PopType const& type, + ast::NodeCPtr pop_node, + bool* non_integer_size ) const { Culture const* culture = nullptr; Religion const* religion = nullptr; @@ -490,12 +478,15 @@ bool PopManager::load_pop_bases_into_vector( return true; } - if (culture != nullptr && religion != nullptr && size >= 1 && size <= std::numeric_limits>::max()) { + if (culture != nullptr && religion != nullptr && size >= 1 && + size <= std::numeric_limits>::max()) { vec.emplace_back(PopBase { type, *culture, *religion, size.floor(), militancy, consciousness, rebel_type }); } else { spdlog::warn_s( - "Some pop arguments are invalid: culture = {}, religion = {}, size = {}", - ovfmt::validate(culture), ovfmt::validate(religion), size + "Some pop arguments are invalid: culture = {}, religion = {}, size = {}", + ovfmt::validate(culture), + ovfmt::validate(religion), + size ); } return ret; @@ -508,24 +499,24 @@ bool PopManager::generate_modifiers(ModifierManager& modifier_manager) const { static constexpr bool HAS_NO_EFFECT = true; memory::FixedVector& strata_effects = - modifier_manager.modifier_effect_cache.strata_effects; + modifier_manager.modifier_effect_cache.strata_effects; strata_effects = std::move( - decltype(ModifierEffectCache::strata_effects) { - generate_values, - strata_index_t(get_strata_count()) - } + decltype(ModifierEffectCache::strata_effects) { generate_values, strata_index_t(get_strata_count()) } ); bool ret = true; for (Strata const& strata : get_stratas()) { - const auto strata_modifier = [&modifier_manager, &ret, &strata]( - ModifierEffect const*& effect_cache, std::string_view suffix, ModifierEffect::format_t format, - bool has_no_effect = false - ) -> void { + const auto strata_modifier = + [&modifier_manager, &ret, &strata]( + ModifierEffect const*& effect_cache, + std::string_view suffix, + ModifierEffect::format_t format, + bool has_no_effect = false + ) -> void { ret &= modifier_manager.register_base_country_modifier_effect( - effect_cache, append_string_views(strata.get_identifier(), suffix), format, {}, has_no_effect + effect_cache, append_string_views(strata.get_identifier(), suffix), format, {}, has_no_effect ); }; diff --git a/src/openvic-simulation/population/PopManager.hpp b/src/openvic-simulation/population/PopManager.hpp index 5e3d77f31..cc02d1a18 100644 --- a/src/openvic-simulation/population/PopManager.hpp +++ b/src/openvic-simulation/population/PopManager.hpp @@ -3,8 +3,8 @@ #include #include "openvic-simulation/population/Culture.hpp" -#include "openvic-simulation/population/Religion.hpp" #include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/Religion.hpp" namespace OpenVic { struct GoodDefinitionManager; @@ -53,41 +53,41 @@ namespace OpenVic { bool add_strata(std::string_view identifier); bool add_pop_type( - std::string_view identifier, - colour_t new_colour, - Strata* strata, - pop_sprite_t sprite, - fixed_point_map_t&& life_needs, - fixed_point_map_t&& everyday_needs, - fixed_point_map_t&& luxury_needs, - PopType::income_type_t life_needs_income_types, - PopType::income_type_t everyday_needs_income_types, - PopType::income_type_t luxury_needs_income_types, - ast::NodeCPtr rebel_units, - pop_size_t max_size, - pop_size_t merge_max_size, - bool state_capital_only, - bool demote_migrant, - bool is_artisan, - bool allowed_to_vote, - bool is_slave, - bool can_be_recruited, - bool can_reduce_consciousness, - bool administrative_efficiency, - bool can_invest, - bool factory, - bool can_work_factory, - bool unemployment, - fixed_point_t research_points, - fixed_point_t leadership_points, - fixed_point_t research_leadership_optimum, - fixed_point_t state_administration_multiplier, - ast::NodeCPtr equivalent, - ConditionalWeightFactorMul&& country_migration_target, - ConditionalWeightFactorMul&& migration_target, - ast::NodeCPtr promote_to_node, - PopType::ideology_weight_map_t&& ideologies, - ast::NodeCPtr issues_node + std::string_view identifier, + colour_t new_colour, + Strata* strata, + pop_sprite_t sprite, + fixed_point_map_t&& life_needs, + fixed_point_map_t&& everyday_needs, + fixed_point_map_t&& luxury_needs, + PopType::income_type_t life_needs_income_types, + PopType::income_type_t everyday_needs_income_types, + PopType::income_type_t luxury_needs_income_types, + ast::NodeCPtr rebel_units, + pop_size_t max_size, + pop_size_t merge_max_size, + bool state_capital_only, + bool demote_migrant, + bool is_artisan, + bool allowed_to_vote, + bool is_slave, + bool can_be_recruited, + bool can_reduce_consciousness, + bool administrative_efficiency, + bool can_invest, + bool factory, + bool can_work_factory, + bool unemployment, + fixed_point_t research_points, + fixed_point_t leadership_points, + fixed_point_t research_leadership_optimum, + fixed_point_t state_administration_multiplier, + ast::NodeCPtr equivalent, + ConditionalWeightFactorMul&& country_migration_target, + ConditionalWeightFactorMul&& migration_target, + ast::NodeCPtr promote_to_node, + PopType::ideology_weight_map_t&& ideologies, + ast::NodeCPtr issues_node ); bool setup_stratas(); @@ -95,20 +95,25 @@ namespace OpenVic { void reserve_pop_types_and_delayed_nodes(size_t size); bool load_pop_type_file( - std::string_view filestem, GoodDefinitionManager const& good_definition_manager, - IdeologyManager const& ideology_manager, ast::NodeCPtr root + std::string_view filestem, + GoodDefinitionManager const& good_definition_manager, + IdeologyManager const& ideology_manager, + ast::NodeCPtr root ); bool load_delayed_parse_pop_type_data(UnitTypeManager const& unit_type_manager, IssueManager const& issue_manager); bool load_pop_type_chances_file(ast::NodeCPtr root); bool load_pop_bases_into_vector( - RebelManager const& rebel_manager, memory::vector& vec, PopType const& type, ast::NodeCPtr pop_node, - bool *non_integer_size + RebelManager const& rebel_manager, + memory::vector& vec, + PopType const& type, + ast::NodeCPtr pop_node, + bool* non_integer_size ) const; bool generate_modifiers(ModifierManager& modifier_manager) const; bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopSize.hpp b/src/openvic-simulation/population/PopSize.hpp index 94cafd06d..d5769595c 100644 --- a/src/openvic-simulation/population/PopSize.hpp +++ b/src/openvic-simulation/population/PopSize.hpp @@ -10,12 +10,13 @@ #include "openvic-simulation/core/object/FixedPoint.hpp" namespace OpenVic { - struct pop_size_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_relational_comparison, - type_safe::strong_typedef_op::mixed_equality_comparison { + struct pop_size_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_relational_comparison, + type_safe::strong_typedef_op::mixed_equality_comparison { using strong_typedef::strong_typedef; constexpr pop_size_t(std::same_as auto value) : strong_typedef(value) {} diff --git a/src/openvic-simulation/population/PopSum.hpp b/src/openvic-simulation/population/PopSum.hpp index 6b89f3749..8bfe0aba8 100644 --- a/src/openvic-simulation/population/PopSum.hpp +++ b/src/openvic-simulation/population/PopSum.hpp @@ -14,20 +14,21 @@ namespace OpenVic { namespace detail { template - struct basic_pop_sum_t : type_safe::strong_typedef, T>, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_relational_comparison>, - type_safe::strong_typedef_op::mixed_equality_comparison, - type_safe::strong_typedef_op::mixed_equality_comparison { + struct basic_pop_sum_t + : type_safe::strong_typedef, T>, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_relational_comparison>, + type_safe::strong_typedef_op::mixed_equality_comparison, + type_safe::strong_typedef_op::mixed_equality_comparison { using type_safe::strong_typedef, T>::strong_typedef; - constexpr basic_pop_sum_t(std::same_as auto value) - : type_safe::strong_typedef, T>(value) {} + constexpr basic_pop_sum_t(std::same_as auto value) : + type_safe::strong_typedef, T>(value) {} - constexpr basic_pop_sum_t(pop_size_t value) - : type_safe::strong_typedef, T>(type_safe::get(value)) {} + constexpr basic_pop_sum_t(pop_size_t value) : + type_safe::strong_typedef, T>(type_safe::get(value)) {} using ov_return_by_value = void; diff --git a/src/openvic-simulation/population/PopType.cpp b/src/openvic-simulation/population/PopType.cpp index f15e663d2..61551fe9e 100644 --- a/src/openvic-simulation/population/PopType.cpp +++ b/src/openvic-simulation/population/PopType.cpp @@ -8,81 +8,61 @@ using namespace OpenVic; -Strata::Strata(std::string_view new_identifier, index_t new_index) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} +Strata::Strata(std::string_view new_identifier, index_t new_index) : HasIdentifier { new_identifier }, HasIndex { new_index } {} PopType::PopType( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - Strata const& new_strata, - pop_sprite_t new_sprite, - fixed_point_map_t&& new_life_needs, - fixed_point_map_t&& new_everyday_needs, - fixed_point_map_t&& new_luxury_needs, - income_type_t new_life_needs_income_types, - income_type_t new_everyday_needs_income_types, - income_type_t new_luxury_needs_income_types, - rebel_units_t&& new_rebel_units, - pop_size_t new_max_size, - pop_size_t new_merge_max_size, - bool new_state_capital_only, - bool new_demote_migrant, - bool new_is_artisan, - bool new_allowed_to_vote, - bool new_is_slave, - bool new_can_be_recruited, - bool new_can_reduce_consciousness, - bool new_is_administrator, - bool new_can_invest, - bool new_factory, - bool new_can_work_factory, - bool new_can_be_unemployed, - fixed_point_t new_research_points, - fixed_point_t new_leadership_points, - fixed_point_t new_research_leadership_optimum, - fixed_point_t new_state_administration_multiplier, - PopType const* new_equivalent, - ConditionalWeightFactorMul&& new_country_migration_target, - ConditionalWeightFactorMul&& new_migration_target, - poptype_weight_map_t&& new_promote_to, - ideology_weight_map_t&& new_ideologies, - issue_weight_map_t&& new_issues -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - HasIndex { new_index }, - strata { new_strata }, - sprite { new_sprite }, - life_needs { std::move(new_life_needs) }, - everyday_needs { std::move(new_everyday_needs) }, - luxury_needs { std::move(new_luxury_needs) }, - life_needs_income_types { new_life_needs_income_types }, - everyday_needs_income_types { new_everyday_needs_income_types }, - luxury_needs_income_types { new_luxury_needs_income_types }, - rebel_units { std::move(new_rebel_units) }, - max_size { new_max_size }, - merge_max_size { new_merge_max_size }, - state_capital_only { new_state_capital_only }, - demote_migrant { new_demote_migrant }, - is_artisan { new_is_artisan }, - allowed_to_vote { new_allowed_to_vote }, - is_slave { new_is_slave }, - can_be_recruited { new_can_be_recruited }, - can_reduce_consciousness { new_can_reduce_consciousness }, - is_administrator { new_is_administrator }, - can_invest { new_can_invest }, - factory { new_factory }, - can_work_factory { new_can_work_factory }, - can_be_unemployed { new_can_be_unemployed }, - research_points { new_research_points }, - leadership_points { new_leadership_points }, - research_leadership_optimum { new_research_leadership_optimum }, - state_administration_multiplier { new_state_administration_multiplier }, - equivalent { new_equivalent }, - country_migration_target { std::move(new_country_migration_target) }, - migration_target { std::move(new_migration_target) }, - promote_to { std::move(new_promote_to) }, - ideologies { std::move(new_ideologies) }, - issues { std::move(new_issues) } {} + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + Strata const& new_strata, + pop_sprite_t new_sprite, + fixed_point_map_t&& new_life_needs, + fixed_point_map_t&& new_everyday_needs, + fixed_point_map_t&& new_luxury_needs, + income_type_t new_life_needs_income_types, + income_type_t new_everyday_needs_income_types, + income_type_t new_luxury_needs_income_types, + rebel_units_t&& new_rebel_units, + pop_size_t new_max_size, + pop_size_t new_merge_max_size, + bool new_state_capital_only, + bool new_demote_migrant, + bool new_is_artisan, + bool new_allowed_to_vote, + bool new_is_slave, + bool new_can_be_recruited, + bool new_can_reduce_consciousness, + bool new_is_administrator, + bool new_can_invest, + bool new_factory, + bool new_can_work_factory, + bool new_can_be_unemployed, + fixed_point_t new_research_points, + fixed_point_t new_leadership_points, + fixed_point_t new_research_leadership_optimum, + fixed_point_t new_state_administration_multiplier, + PopType const* new_equivalent, + ConditionalWeightFactorMul&& new_country_migration_target, + ConditionalWeightFactorMul&& new_migration_target, + poptype_weight_map_t&& new_promote_to, + ideology_weight_map_t&& new_ideologies, + issue_weight_map_t&& new_issues +) : + HasIdentifierAndColour { new_identifier, new_colour, false }, HasIndex { new_index }, strata { new_strata }, + sprite { new_sprite }, life_needs { std::move(new_life_needs) }, everyday_needs { std::move(new_everyday_needs) }, + luxury_needs { std::move(new_luxury_needs) }, life_needs_income_types { new_life_needs_income_types }, + everyday_needs_income_types { new_everyday_needs_income_types }, + luxury_needs_income_types { new_luxury_needs_income_types }, rebel_units { std::move(new_rebel_units) }, + max_size { new_max_size }, merge_max_size { new_merge_max_size }, state_capital_only { new_state_capital_only }, + demote_migrant { new_demote_migrant }, is_artisan { new_is_artisan }, allowed_to_vote { new_allowed_to_vote }, + is_slave { new_is_slave }, can_be_recruited { new_can_be_recruited }, + can_reduce_consciousness { new_can_reduce_consciousness }, is_administrator { new_is_administrator }, + can_invest { new_can_invest }, factory { new_factory }, can_work_factory { new_can_work_factory }, + can_be_unemployed { new_can_be_unemployed }, research_points { new_research_points }, + leadership_points { new_leadership_points }, research_leadership_optimum { new_research_leadership_optimum }, + state_administration_multiplier { new_state_administration_multiplier }, equivalent { new_equivalent }, + country_migration_target { std::move(new_country_migration_target) }, migration_target { std::move(new_migration_target) }, + promote_to { std::move(new_promote_to) }, ideologies { std::move(new_ideologies) }, issues { std::move(new_issues) } {} bool PopType::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; diff --git a/src/openvic-simulation/population/PopType.hpp b/src/openvic-simulation/population/PopType.hpp index 4d7621b8f..a91d3d2d0 100644 --- a/src/openvic-simulation/population/PopType.hpp +++ b/src/openvic-simulation/population/PopType.hpp @@ -4,14 +4,14 @@ #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" +#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/scripts/ConditionalWeight.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/types/HasIdentifier.hpp" #include "openvic-simulation/types/HasIndex.hpp" #include "openvic-simulation/types/IndexedFlatMap.hpp" -#include "openvic-simulation/population/PopSize.hpp" #include "openvic-simulation/types/PopSprite.hpp" #include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" namespace OpenVic { struct BaseIssue; @@ -40,10 +40,10 @@ namespace OpenVic { /* This is a bitfield - PopTypes can have up to one of each income source for each need category. */ enum struct income_type_t : uint8_t { - NO_INCOME_TYPE = 0, - ADMINISTRATION = 1 << 0, - EDUCATION = 1 << 1, - MILITARY = 1 << 2 + NO_INCOME_TYPE = 0, + ADMINISTRATION = 1 << 0, + EDUCATION = 1 << 1, + MILITARY = 1 << 2 }; using rebel_units_t = fixed_point_map_t; @@ -92,54 +92,55 @@ namespace OpenVic { const fixed_point_t state_administration_multiplier; PopType( - std::string_view new_identifier, - colour_t new_colour, - index_t new_index, - Strata const& new_strata, - pop_sprite_t new_sprite, - fixed_point_map_t&& new_life_needs, - fixed_point_map_t&& new_everyday_needs, - fixed_point_map_t&& new_luxury_needs, - income_type_t new_life_needs_income_types, - income_type_t new_everyday_needs_income_types, - income_type_t new_luxury_needs_income_types, - rebel_units_t&& new_rebel_units, - pop_size_t new_max_size, - pop_size_t new_merge_max_size, - bool new_state_capital_only, - bool new_demote_migrant, - bool new_is_artisan, - bool new_allowed_to_vote, - bool new_is_slave, - bool new_can_be_recruited, - bool new_can_reduce_consciousness, - bool new_is_administrator, - bool new_can_invest, - bool new_factory, - bool new_can_work_factory, - bool new_can_be_unemployed, - fixed_point_t new_research_points, - fixed_point_t new_leadership_points, - fixed_point_t new_research_leadership_optimum, - fixed_point_t new_state_administration_multiplier, - PopType const* new_equivalent, - ConditionalWeightFactorMul&& new_country_migration_target, - ConditionalWeightFactorMul&& new_migration_target, - poptype_weight_map_t&& new_promote_to, - ideology_weight_map_t&& new_ideologies, - issue_weight_map_t&& new_issues + std::string_view new_identifier, + colour_t new_colour, + index_t new_index, + Strata const& new_strata, + pop_sprite_t new_sprite, + fixed_point_map_t&& new_life_needs, + fixed_point_map_t&& new_everyday_needs, + fixed_point_map_t&& new_luxury_needs, + income_type_t new_life_needs_income_types, + income_type_t new_everyday_needs_income_types, + income_type_t new_luxury_needs_income_types, + rebel_units_t&& new_rebel_units, + pop_size_t new_max_size, + pop_size_t new_merge_max_size, + bool new_state_capital_only, + bool new_demote_migrant, + bool new_is_artisan, + bool new_allowed_to_vote, + bool new_is_slave, + bool new_can_be_recruited, + bool new_can_reduce_consciousness, + bool new_is_administrator, + bool new_can_invest, + bool new_factory, + bool new_can_work_factory, + bool new_can_be_unemployed, + fixed_point_t new_research_points, + fixed_point_t new_leadership_points, + fixed_point_t new_research_leadership_optimum, + fixed_point_t new_state_administration_multiplier, + PopType const* new_equivalent, + ConditionalWeightFactorMul&& new_country_migration_target, + ConditionalWeightFactorMul&& new_migration_target, + poptype_weight_map_t&& new_promote_to, + ideology_weight_map_t&& new_ideologies, + issue_weight_map_t&& new_issues ); PopType(PopType&&) = default; constexpr bool has_income_type(income_type_t income_type) const; }; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; constexpr bool PopType::has_income_type(income_type_t income_type) const { - return (life_needs_income_types & income_type) == income_type - || (everyday_needs_income_types & income_type) == income_type - || (luxury_needs_income_types & income_type) == income_type; + return (life_needs_income_types & income_type) == income_type || + (everyday_needs_income_types & income_type) == income_type || + (luxury_needs_income_types & income_type) == income_type; } /* This returns true if at least one income type is shared by both arguments. */ @@ -172,4 +173,4 @@ namespace OpenVic { } return stream << ']'; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopValuesFromProvince.cpp b/src/openvic-simulation/population/PopValuesFromProvince.cpp index 95919e8b2..451feeb15 100644 --- a/src/openvic-simulation/population/PopValuesFromProvince.cpp +++ b/src/openvic-simulation/population/PopValuesFromProvince.cpp @@ -1,4 +1,5 @@ #include "PopValuesFromProvince.hpp" + #include #include "openvic-simulation/core/object/FixedPoint.hpp" @@ -7,20 +8,19 @@ #include "openvic-simulation/economy/GoodInstance.hpp" #include "openvic-simulation/economy/production/ArtisanalProducer.hpp" #include "openvic-simulation/economy/production/ProductionType.hpp" -#include "openvic-simulation/modifier/ModifierEffectCache.hpp" #include "openvic-simulation/map/ProvinceInstance.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" +#include "openvic-simulation/modifier/ModifierEffectCache.hpp" using namespace OpenVic; void PopStrataValuesFromProvince::update_pop_strata_values_from_province( - PopsDefines const& defines, - ModifierEffectCache const& modifier_effect_cache, - ProvinceInstance const& province + PopsDefines const& defines, ModifierEffectCache const& modifier_effect_cache, ProvinceInstance const& province ) { ModifierEffectCache::strata_effects_t const& strata_effects = modifier_effect_cache.get_strata_effects()[strata_index]; - fixed_point_t shared_base_needs_scalar = defines.get_base_goods_demand() - * (fixed_point_t::_1 + province.get_modifier_effect_value(*modifier_effect_cache.get_goods_demand())); + fixed_point_t shared_base_needs_scalar = + defines.get_base_goods_demand() * + (fixed_point_t::_1 + province.get_modifier_effect_value(*modifier_effect_cache.get_goods_demand())); fixed_point_t invention_needs_scalar = 1; CountryInstance const* const owner_nullable = province.get_owner(); @@ -30,67 +30,60 @@ void PopStrataValuesFromProvince::update_pop_strata_values_from_province( invention_needs_scalar += owner.get_inventions_count_untracked() * defines.get_invention_impact_on_demand(); } - shared_life_needs_scalar = shared_base_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_life_needs())); - shared_everyday_needs_scalar = shared_base_needs_scalar - * invention_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_everyday_needs())); - shared_luxury_needs_scalar = shared_base_needs_scalar - * invention_needs_scalar - * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_luxury_needs())); + shared_life_needs_scalar = + shared_base_needs_scalar * (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_life_needs())); + shared_everyday_needs_scalar = + shared_base_needs_scalar * invention_needs_scalar * + (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_everyday_needs())); + shared_luxury_needs_scalar = shared_base_needs_scalar * invention_needs_scalar * + (fixed_point_t::_1 + province.get_modifier_effect_value(*strata_effects.get_luxury_needs())); } PopValuesFromProvince::PopValuesFromProvince( - GameRulesManager const& new_game_rules_manager, - GoodInstanceManager const& new_good_instance_manager, - ModifierEffectCache const& new_modifier_effect_cache, - ProductionTypeManager const& new_production_type_manager, - PopsDefines const& new_defines, - const strata_index_t strata_size -) : game_rules_manager { new_game_rules_manager }, - good_instance_manager { new_good_instance_manager }, - modifier_effect_cache { new_modifier_effect_cache }, - production_type_manager { new_production_type_manager }, - defines { new_defines }, - effects_by_strata { - generate_values, - strata_size - } {} + GameRulesManager const& new_game_rules_manager, + GoodInstanceManager const& new_good_instance_manager, + ModifierEffectCache const& new_modifier_effect_cache, + ProductionTypeManager const& new_production_type_manager, + PopsDefines const& new_defines, + const strata_index_t strata_size +) : + game_rules_manager { new_game_rules_manager }, good_instance_manager { new_good_instance_manager }, + modifier_effect_cache { new_modifier_effect_cache }, production_type_manager { new_production_type_manager }, + defines { new_defines }, effects_by_strata { generate_values, strata_size } {} void PopValuesFromProvince::update_pop_values_from_province(ProvinceInstance& province) { for (auto& values : effects_by_strata) { values.update_pop_strata_values_from_province(defines, modifier_effect_cache, province); } - max_cost_multiplier = 1; + max_cost_multiplier = 1; CountryInstance* const country_to_report_economy_nullable = province.get_country_to_report_economy(); if (country_to_report_economy_nullable != nullptr) { const fixed_point_t tariff_rate = country_to_report_economy_nullable->effective_tariff_rate.get_untracked(); if (tariff_rate > fixed_point_t::_0) { - max_cost_multiplier += tariff_rate; //max (domestic cost, imported cost) + max_cost_multiplier += tariff_rate; // max (domestic cost, imported cost) } } - + ranked_artisanal_production_types.clear(); ranked_artisanal_production_types.reserve(production_type_manager.get_production_type_count()); for (auto const& production_type : production_type_manager.get_production_types()) { const std::optional estimated_score = ArtisanalProducer::estimate_production_type_score( - good_instance_manager, - production_type, - province, - max_cost_multiplier + good_instance_manager, production_type, province, max_cost_multiplier ); if (estimated_score.has_value() && estimated_score.value() > 0) { - ranked_artisanal_production_types.push_back({&production_type, estimated_score.value()}); + ranked_artisanal_production_types.push_back({ &production_type, estimated_score.value() }); } } if (!ranked_artisanal_production_types.empty()) { - std::stable_sort(ranked_artisanal_production_types.begin(), ranked_artisanal_production_types.end(), - [](const auto& a, const auto& b) { - return a.second > b.second; - } + std::stable_sort( + ranked_artisanal_production_types.begin(), + ranked_artisanal_production_types.end(), + [](const auto& a, const auto& b) { + return a.second > b.second; + } ); } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopValuesFromProvince.hpp b/src/openvic-simulation/population/PopValuesFromProvince.hpp index c072a948d..007ad5cc2 100644 --- a/src/openvic-simulation/population/PopValuesFromProvince.hpp +++ b/src/openvic-simulation/population/PopValuesFromProvince.hpp @@ -23,14 +23,12 @@ namespace OpenVic { fixed_point_t PROPERTY(shared_life_needs_scalar); fixed_point_t PROPERTY(shared_everyday_needs_scalar); fixed_point_t PROPERTY(shared_luxury_needs_scalar); + public: - constexpr PopStrataValuesFromProvince(const strata_index_t new_strata_index) - : strata_index { new_strata_index } {} + constexpr PopStrataValuesFromProvince(const strata_index_t new_strata_index) : strata_index { new_strata_index } {} void update_pop_strata_values_from_province( - PopsDefines const& defines, - ModifierEffectCache const& modifier_effect_cache, - ProvinceInstance const& province + PopsDefines const& defines, ModifierEffectCache const& modifier_effect_cache, ProvinceInstance const& province ); }; @@ -41,21 +39,22 @@ namespace OpenVic { ProductionTypeManager const& production_type_manager; fixed_point_t PROPERTY(max_cost_multiplier); memory::FixedVector PROPERTY(effects_by_strata); - //excludes availability of goods on market + // excludes availability of goods on market memory::vector> SPAN_PROPERTY(ranked_artisanal_production_types); + public: PopsDefines const& defines; GameRulesManager const& game_rules_manager; PopValuesFromProvince( - GameRulesManager const& new_game_rules_manager, - GoodInstanceManager const& new_good_instance_manager, - ModifierEffectCache const& new_modifier_effect_cache, - ProductionTypeManager const& new_production_type_manager, - PopsDefines const& new_defines, - const strata_index_t strata_size + GameRulesManager const& new_game_rules_manager, + GoodInstanceManager const& new_good_instance_manager, + ModifierEffectCache const& new_modifier_effect_cache, + ProductionTypeManager const& new_production_type_manager, + PopsDefines const& new_defines, + const strata_index_t strata_size ); void update_pop_values_from_province(ProvinceInstance& province); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/PopsAggregate.cpp b/src/openvic-simulation/population/PopsAggregate.cpp index 9014451fe..672c8edbb 100644 --- a/src/openvic-simulation/population/PopsAggregate.cpp +++ b/src/openvic-simulation/population/PopsAggregate.cpp @@ -9,27 +9,27 @@ #include "openvic-simulation/country/CountryDefinition.hpp" #include "openvic-simulation/country/CountryInstance.hpp" #include "openvic-simulation/population/Pop.hpp" -#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/population/PopType.hpp" +#include "openvic-simulation/population/PopsAggregateDeps.hpp" #include "openvic-simulation/types/ConstructorTags.hpp" #include "openvic-simulation/types/OrderedContainersMath.hpp" using namespace OpenVic; -PopsAggregate::PopsAggregate(PopsAggregateDeps const& deps) - : population_by_strata { generate_values, deps.strata_count }, - militancy_by_strata_running_total_raw { generate_values, deps.strata_count }, - life_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, - everyday_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, - luxury_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, - militancy_by_strata { generate_values, deps.strata_count }, - life_needs_fulfilled_by_strata { generate_values, deps.strata_count }, - everyday_needs_fulfilled_by_strata { generate_values, deps.strata_count }, - luxury_needs_fulfilled_by_strata { generate_values, deps.strata_count }, - population_by_type { generate_values, deps.pop_type_count }, - unemployed_pops_by_type { generate_values, deps.pop_type_count }, - supporter_equivalents_by_ideology { generate_values, deps.ideology_count }, - supporter_equivalents_by_party_policy { generate_values, deps.party_policy_count }, - supporter_equivalents_by_reform { generate_values, deps.reform_count } {} +PopsAggregate::PopsAggregate(PopsAggregateDeps const& deps) : + population_by_strata { generate_values, deps.strata_count }, + militancy_by_strata_running_total_raw { generate_values, deps.strata_count }, + life_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, + everyday_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, + luxury_needs_fulfilled_by_strata_running_total_raw { generate_values, deps.strata_count }, + militancy_by_strata { generate_values, deps.strata_count }, + life_needs_fulfilled_by_strata { generate_values, deps.strata_count }, + everyday_needs_fulfilled_by_strata { generate_values, deps.strata_count }, + luxury_needs_fulfilled_by_strata { generate_values, deps.strata_count }, + population_by_type { generate_values, deps.pop_type_count }, + unemployed_pops_by_type { generate_values, deps.pop_type_count }, + supporter_equivalents_by_ideology { generate_values, deps.ideology_count }, + supporter_equivalents_by_party_policy { generate_values, deps.party_policy_count }, + supporter_equivalents_by_reform { generate_values, deps.reform_count } {} fixed_point_t PopsAggregate::get_vote_equivalents_by_party(CountryParty const& party) const { const decltype(vote_equivalents_by_party)::const_iterator it = vote_equivalents_by_party.find(&party); @@ -57,9 +57,9 @@ pop_sum_t PopsAggregate::get_population_by_religion(Religion const& religion) co } } -template +template constexpr void bulk_fill_default(Vectors&... vecs) { - (std::fill(vecs.begin(), vecs.end(), typename Vectors::value_type{}), ...); + (std::fill(vecs.begin(), vecs.end(), typename Vectors::value_type {}), ...); } void PopsAggregate::clear_pops_aggregate() { @@ -75,20 +75,20 @@ void PopsAggregate::clear_pops_aggregate() { average_militancy = fixed_point_t::_0; bulk_fill_default( - militancy_by_strata_running_total_raw, - life_needs_fulfilled_by_strata_running_total_raw, - everyday_needs_fulfilled_by_strata_running_total_raw, - luxury_needs_fulfilled_by_strata_running_total_raw, - militancy_by_strata, - life_needs_fulfilled_by_strata, - everyday_needs_fulfilled_by_strata, - luxury_needs_fulfilled_by_strata, - population_by_strata, - population_by_type, - unemployed_pops_by_type, - supporter_equivalents_by_ideology, - supporter_equivalents_by_party_policy, - supporter_equivalents_by_reform + militancy_by_strata_running_total_raw, + life_needs_fulfilled_by_strata_running_total_raw, + everyday_needs_fulfilled_by_strata_running_total_raw, + luxury_needs_fulfilled_by_strata_running_total_raw, + militancy_by_strata, + life_needs_fulfilled_by_strata, + everyday_needs_fulfilled_by_strata, + luxury_needs_fulfilled_by_strata, + population_by_strata, + population_by_type, + unemployed_pops_by_type, + supporter_equivalents_by_ideology, + supporter_equivalents_by_party_policy, + supporter_equivalents_by_reform ); vote_equivalents_by_party.clear(); @@ -96,10 +96,8 @@ void PopsAggregate::clear_pops_aggregate() { population_by_religion.clear(); } -constexpr void update_running_total_raw_128 ( - boost::int128::int128_t& running_total_raw, - const pop_sum_t part_population, - const fixed_point_t average +constexpr void update_running_total_raw_128( + boost::int128::int128_t& running_total_raw, const pop_sum_t part_population, const fixed_point_t average ) { running_total_raw += type_safe::get(part_population) * static_cast(average.get_raw_value()); }; @@ -126,24 +124,22 @@ void PopsAggregate::add_pops_aggregate(PopsAggregate& part) { for (const pop_sum_t strata_population : part.get_population_by_strata()) { population_by_strata[strata_index] += strata_population; update_running_total_raw_128( - militancy_by_strata_running_total_raw[strata_index], - strata_population, - part.militancy_by_strata[strata_index] + militancy_by_strata_running_total_raw[strata_index], strata_population, part.militancy_by_strata[strata_index] ); update_running_total_raw_128( - life_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population, - part.life_needs_fulfilled_by_strata[strata_index] + life_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population, + part.life_needs_fulfilled_by_strata[strata_index] ); update_running_total_raw_128( - everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population, - part.everyday_needs_fulfilled_by_strata[strata_index] + everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population, + part.everyday_needs_fulfilled_by_strata[strata_index] ); update_running_total_raw_128( - luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population, - part.luxury_needs_fulfilled_by_strata[strata_index] + luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population, + part.luxury_needs_fulfilled_by_strata[strata_index] ); ++strata_index; } @@ -174,21 +170,15 @@ void PopsAggregate::add_pops_aggregate(Pop const& pop) { const strata_index_t strata_index = pop_type.strata.index; population_by_strata[strata_index] += pop_size; + update_running_total_raw_128(militancy_by_strata_running_total_raw[strata_index], pop_size, pop.get_militancy()); update_running_total_raw_128( - militancy_by_strata_running_total_raw[strata_index], - pop_size, pop.get_militancy() - ); - update_running_total_raw_128( - life_needs_fulfilled_by_strata_running_total_raw[strata_index], - pop_size, pop.get_life_needs_fulfilled() + life_needs_fulfilled_by_strata_running_total_raw[strata_index], pop_size, pop.get_life_needs_fulfilled() ); update_running_total_raw_128( - everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], - pop_size, pop.get_everyday_needs_fulfilled() + everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], pop_size, pop.get_everyday_needs_fulfilled() ); update_running_total_raw_128( - luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], - pop_size, pop.get_luxury_needs_fulfilled() + luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], pop_size, pop.get_luxury_needs_fulfilled() ); population_by_type[pop_type_index] += pop_size; @@ -208,39 +198,37 @@ void PopsAggregate::add_pops_aggregate(Pop const& pop) { } constexpr void normalise(fixed_point_t& value, const boost::int128::int128_t running_total_raw, const pop_sum_t population) { - value = fixed_point_t::parse_raw(static_cast( - running_total_raw / type_safe::get(population) - )); + value = fixed_point_t::parse_raw(static_cast(running_total_raw / type_safe::get(population))); } void PopsAggregate::normalise_pops_aggregate() { if (total_population > 0) { const int64_t total_population_v = type_safe::get(total_population); average_literacy = fixed_point_t::parse_raw(static_cast(literacy_running_total_raw / total_population_v)); - average_consciousness = fixed_point_t::parse_raw(static_cast(consciousness_running_total_raw / total_population_v)); + average_consciousness = fixed_point_t::parse_raw( + static_cast(consciousness_running_total_raw / total_population_v) + ); average_militancy = fixed_point_t::parse_raw(static_cast(militancy_running_total_raw / total_population_v)); strata_index_t strata_index {}; for (const pop_sum_t strata_population : population_by_strata) { normalise( - militancy_by_strata[strata_index], - militancy_by_strata_running_total_raw[strata_index], - strata_population + militancy_by_strata[strata_index], militancy_by_strata_running_total_raw[strata_index], strata_population ); normalise( - life_needs_fulfilled_by_strata[strata_index], - life_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population + life_needs_fulfilled_by_strata[strata_index], + life_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population ); normalise( - everyday_needs_fulfilled_by_strata[strata_index], - everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population + everyday_needs_fulfilled_by_strata[strata_index], + everyday_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population ); normalise( - luxury_needs_fulfilled_by_strata[strata_index], - luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], - strata_population + luxury_needs_fulfilled_by_strata[strata_index], + luxury_needs_fulfilled_by_strata_running_total_raw[strata_index], + strata_population ); ++strata_index; } @@ -253,11 +241,9 @@ void PopsAggregate::update_parties_for_votes(CountryDefinition const* country_de return; } - auto view = country_definition->get_parties() | std::views::transform( - [](CountryParty const& key) { - return std::make_pair(&key, fixed_point_t::_0); - } - ); + auto view = country_definition->get_parties() | std::views::transform([](CountryParty const& key) { + return std::make_pair(&key, fixed_point_t::_0); + }); vote_equivalents_by_party.insert(view.begin(), view.end()); } void PopsAggregate::update_parties_for_votes(CountryInstance const* country_instance) { diff --git a/src/openvic-simulation/population/PopsAggregate.hpp b/src/openvic-simulation/population/PopsAggregate.hpp index d6f38e380..9082e9dc8 100644 --- a/src/openvic-simulation/population/PopsAggregate.hpp +++ b/src/openvic-simulation/population/PopsAggregate.hpp @@ -5,9 +5,9 @@ #include "openvic-simulation/core/memory/FixedVector.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/population/PopSum.hpp" -#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/types/TypedIndices.hpp" #include "openvic-simulation/types/OrderedContainers.hpp" +#include "openvic-simulation/types/TypedIndices.hpp" +#include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" #include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/reactive/MutableState.hpp" @@ -68,6 +68,7 @@ namespace OpenVic { void normalise_pops_aggregate(); void update_parties_for_votes(CountryDefinition const* country_definition); void update_parties_for_votes(CountryInstance const* country_instance); + public: // The values returned by these functions are scaled by population size, so they must be divided by population size // to get the support as a proportion of 1.0 diff --git a/src/openvic-simulation/population/PopsAggregateDeps.hpp b/src/openvic-simulation/population/PopsAggregateDeps.hpp index 6cf7dca17..99043c63a 100644 --- a/src/openvic-simulation/population/PopsAggregateDeps.hpp +++ b/src/openvic-simulation/population/PopsAggregateDeps.hpp @@ -10,4 +10,4 @@ namespace OpenVic { reform_index_t reform_count; strata_index_t strata_count; }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/population/Religion.cpp b/src/openvic-simulation/population/Religion.cpp index 10f27c103..2151a2c40 100644 --- a/src/openvic-simulation/population/Religion.cpp +++ b/src/openvic-simulation/population/Religion.cpp @@ -8,15 +8,8 @@ using namespace OpenVic::NodeTools; ReligionGroup::ReligionGroup(std::string_view new_identifier) : HasIdentifier { new_identifier } {} Religion::Religion( - std::string_view new_identifier, - colour_t new_colour, - ReligionGroup const& new_group, - icon_t new_icon, - bool new_pagan -) : HasIdentifierAndColour { new_identifier, new_colour, false }, - group { new_group }, - icon { new_icon }, - pagan { new_pagan } {} + std::string_view new_identifier, colour_t new_colour, ReligionGroup const& new_group, icon_t new_icon, bool new_pagan +) : HasIdentifierAndColour { new_identifier, new_colour, false }, group { new_group }, icon { new_icon }, pagan { new_pagan } {} bool ReligionManager::add_religion_group(std::string_view identifier) { if (identifier.empty()) { @@ -27,7 +20,7 @@ bool ReligionManager::add_religion_group(std::string_view identifier) { } bool ReligionManager::add_religion( - std::string_view identifier, colour_t colour, ReligionGroup const& group, Religion::icon_t icon, bool pagan + std::string_view identifier, colour_t colour, ReligionGroup const& group, Religion::icon_t icon, bool pagan ) { if (!religion_groups.is_locked()) { spdlog::error_s("Cannot register religions until religion groups are locked!"); @@ -41,10 +34,7 @@ bool ReligionManager::add_religion( spdlog::error_s("Invalid religion icon for {}: {}", identifier, icon); return false; } - return religions.emplace_item( - identifier, - identifier, colour, group, icon, pagan - ); + return religions.emplace_item(identifier, identifier, colour, group, icon, pagan); } /* REQUIREMENTS: @@ -53,33 +43,28 @@ bool ReligionManager::add_religion( */ bool ReligionManager::load_religion_file(ast::NodeCPtr root) { size_t total_expected_religions = 0; - bool ret = expect_dictionary_reserve_length( - religion_groups, - [this, &total_expected_religions](std::string_view key, ast::NodeCPtr value) -> bool { - bool ret = expect_length(add_variable_callback(total_expected_religions))(value); - ret &= add_religion_group(key); - return ret; - } - )(root); + bool ret = + expect_dictionary_reserve_length(religion_groups, [this, &total_expected_religions](std::string_view key, ast::NodeCPtr value) -> bool { + bool ret = expect_length(add_variable_callback(total_expected_religions))(value); + ret &= add_religion_group(key); + return ret; + })(root); lock_religion_groups(); reserve_more_religions(total_expected_religions); - ret &= expect_religion_group_dictionary( - [this](ReligionGroup const& religion_group, ast::NodeCPtr religion_group_value) -> bool { - return expect_dictionary([this, &religion_group](std::string_view key, ast::NodeCPtr value) -> bool { - colour_t colour = colour_t::null(); - Religion::icon_t icon = 0; - bool pagan = false; + ret &= expect_religion_group_dictionary([this](ReligionGroup const& religion_group, ast::NodeCPtr religion_group_value) -> bool { + return expect_dictionary([this, &religion_group](std::string_view key, ast::NodeCPtr value) -> bool { + colour_t colour = colour_t::null(); + Religion::icon_t icon = 0; + bool pagan = false; - bool ret = expect_dictionary_keys( - "icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), - "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), - "pagan", ZERO_OR_ONE, expect_bool(assign_variable_callback(pagan)) - )(value); - ret &= add_religion(key, colour, religion_group, icon, pagan); - return ret; - })(religion_group_value); - } - )(root); + bool ret = + expect_dictionary_keys("icon", ONE_EXACTLY, expect_uint(assign_variable_callback(icon)), "color", ONE_EXACTLY, expect_colour(assign_variable_callback(colour)), "pagan", ZERO_OR_ONE, expect_bool(assign_variable_callback(pagan)))( + value + ); + ret &= add_religion(key, colour, religion_group, icon, pagan); + return ret; + })(religion_group_value); + })(root); lock_religions(); return ret; } diff --git a/src/openvic-simulation/population/Religion.hpp b/src/openvic-simulation/population/Religion.hpp index 66287d9cb..a07a46f0f 100644 --- a/src/openvic-simulation/population/Religion.hpp +++ b/src/openvic-simulation/population/Religion.hpp @@ -20,8 +20,11 @@ namespace OpenVic { const bool pagan; Religion( - std::string_view new_identifier, colour_t new_colour, ReligionGroup const& new_group, icon_t new_icon, - bool new_pagan + std::string_view new_identifier, + colour_t new_colour, + ReligionGroup const& new_group, + icon_t new_icon, + bool new_pagan ); Religion(Religion&&) = default; }; @@ -35,7 +38,7 @@ namespace OpenVic { bool add_religion_group(std::string_view identifier); bool add_religion( - std::string_view identifier, colour_t colour, ReligionGroup const& group, Religion::icon_t icon, bool pagan + std::string_view identifier, colour_t colour, ReligionGroup const& group, Religion::icon_t icon, bool pagan ); bool load_religion_file(ast::NodeCPtr root); diff --git a/src/openvic-simulation/research/Invention.cpp b/src/openvic-simulation/research/Invention.cpp index 4c0d9d769..1cf34caa8 100644 --- a/src/openvic-simulation/research/Invention.cpp +++ b/src/openvic-simulation/research/Invention.cpp @@ -10,29 +10,25 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; Invention::Invention( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - bool new_is_news, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - crime_set_t&& new_enabled_crimes, - bool new_unlocks_gas_attack, - bool new_unlocks_gas_defence, - ConditionScript&& new_limit, - ConditionalWeightBase&& new_chance, - memory::vector&& new_raw_associated_tech_identifiers -) : HasIndex { new_index }, - Modifier { new_identifier, std::move(new_values), modifier_type_t::INVENTION }, - is_news { new_is_news }, - activated_units { std::move(new_activated_units) }, - activated_buildings { std::move(new_activated_buildings) }, - enabled_crimes { std::move(new_enabled_crimes) }, - unlocks_gas_attack { new_unlocks_gas_attack }, - unlocks_gas_defence { new_unlocks_gas_defence }, - limit { std::move(new_limit) }, - chance { std::move(new_chance) }, - raw_associated_tech_identifiers { std::move(new_raw_associated_tech_identifiers) } {} + index_t new_index, + std::string_view new_identifier, + ModifierValue&& new_values, + bool new_is_news, + unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, + crime_set_t&& new_enabled_crimes, + bool new_unlocks_gas_attack, + bool new_unlocks_gas_defence, + ConditionScript&& new_limit, + ConditionalWeightBase&& new_chance, + memory::vector&& new_raw_associated_tech_identifiers +) : + HasIndex { new_index }, Modifier { new_identifier, std::move(new_values), modifier_type_t::INVENTION }, + is_news { new_is_news }, activated_units { std::move(new_activated_units) }, + activated_buildings { std::move(new_activated_buildings) }, enabled_crimes { std::move(new_enabled_crimes) }, + unlocks_gas_attack { new_unlocks_gas_attack }, unlocks_gas_defence { new_unlocks_gas_defence }, + limit { std::move(new_limit) }, chance { std::move(new_chance) }, + raw_associated_tech_identifiers { std::move(new_raw_associated_tech_identifiers) } {} bool Invention::parse_scripts(DefinitionManager const& definition_manager) { bool ret = true; @@ -44,10 +40,17 @@ bool Invention::parse_scripts(DefinitionManager const& definition_manager) { } bool InventionManager::add_invention( - std::string_view identifier, ModifierValue&& values, bool news, Invention::unit_set_t&& activated_units, - Invention::building_set_t&& activated_buildings, Invention::crime_set_t&& enabled_crimes, bool unlock_gas_attack, - bool unlock_gas_defence, ConditionScript&& limit, ConditionalWeightBase&& chance, - memory::vector&& raw_associated_tech_identifiers + std::string_view identifier, + ModifierValue&& values, + bool news, + Invention::unit_set_t&& activated_units, + Invention::building_set_t&& activated_buildings, + Invention::crime_set_t&& enabled_crimes, + bool unlock_gas_attack, + bool unlock_gas_defence, + ConditionScript&& limit, + ConditionalWeightBase&& chance, + memory::vector&& raw_associated_tech_identifiers ) { if (identifier.empty()) { spdlog::error_s("Invalid invention identifier - empty!"); @@ -55,16 +58,29 @@ bool InventionManager::add_invention( } return inventions.emplace_item( - identifier, index_from_count(get_invention_count()), identifier, std::move(values), news, - std::move(activated_units), std::move(activated_buildings), std::move(enabled_crimes), unlock_gas_attack, - unlock_gas_defence, std::move(limit), std::move(chance), - std::move(raw_associated_tech_identifiers) + identifier, + index_from_count(get_invention_count()), + identifier, + std::move(values), + news, + std::move(activated_units), + std::move(activated_buildings), + std::move(enabled_crimes), + unlock_gas_attack, + unlock_gas_defence, + std::move(limit), + std::move(chance), + std::move(raw_associated_tech_identifiers) ); } bool InventionManager::load_inventions_file( - TechnologyManager const& tech_manager, ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, - BuildingTypeManager const& building_type_manager, CrimeManager const& crime_manager, ast::NodeCPtr root + TechnologyManager const& tech_manager, + ModifierManager const& modifier_manager, + UnitTypeManager const& unit_type_manager, + BuildingTypeManager const& building_type_manager, + CrimeManager const& crime_manager, + ast::NodeCPtr root ) { return expect_dictionary_reserve_length(inventions, [&](std::string_view identifier, ast::NodeCPtr value) -> bool { using enum scope_type_t; @@ -87,22 +103,19 @@ bool InventionManager::load_inventions_file( memory::vector found_tech_ids; auto parse_limit_and_find_techs = [&](ast::NodeCPtr node) -> bool { + if (!limit.expect_script()(node)) { + return false; + } - if (!limit.expect_script()(node)) { - return false; - } - - expect_dictionary( - [&](std::string_view key, ast::NodeCPtr /*value*/) -> bool { - if (tech_manager.get_technology_by_identifier(key) != nullptr) { - found_tech_ids.push_back(memory::string(key)); - } - return true; - } - )(node); + expect_dictionary([&](std::string_view key, ast::NodeCPtr /*value*/) -> bool { + if (tech_manager.get_technology_by_identifier(key) != nullptr) { + found_tech_ids.push_back(memory::string(key)); + } + return true; + })(node); - return true; - }; + return true; + }; bool ret = NodeTools::expect_dictionary_keys_and_default( modifier_manager.expect_base_country_modifier(loose_modifiers), @@ -127,9 +140,17 @@ bool InventionManager::load_inventions_file( modifiers += loose_modifiers; ret &= add_invention( - identifier, std::move(modifiers), news, std::move(activated_units), std::move(activated_buildings), - std::move(enabled_crimes), unlock_gas_attack, unlock_gas_defence, std::move(limit), std::move(chance), - std::move(found_tech_ids) + identifier, + std::move(modifiers), + news, + std::move(activated_units), + std::move(activated_buildings), + std::move(enabled_crimes), + unlock_gas_attack, + unlock_gas_defence, + std::move(limit), + std::move(chance), + std::move(found_tech_ids) ); return ret; diff --git a/src/openvic-simulation/research/Invention.hpp b/src/openvic-simulation/research/Invention.hpp index 9fe755763..ad083cf0f 100644 --- a/src/openvic-simulation/research/Invention.hpp +++ b/src/openvic-simulation/research/Invention.hpp @@ -23,7 +23,7 @@ namespace OpenVic { struct Invention : HasIndex, Modifier { friend struct InventionManager; - //TODO implement limit and chance + // TODO implement limit and chance using unit_set_t = ordered_set; using building_set_t = ordered_set; using crime_set_t = ordered_set; @@ -31,7 +31,7 @@ namespace OpenVic { private: ConditionScript PROPERTY(limit); ConditionalWeightBase PROPERTY(chance); - + memory::vector raw_associated_tech_identifiers; bool parse_scripts(DefinitionManager const& definition_manager); @@ -45,18 +45,18 @@ namespace OpenVic { const bool unlocks_gas_defence; Invention( - index_t new_index, - std::string_view new_identifier, - ModifierValue&& new_values, - bool new_is_news, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - crime_set_t&& new_enabled_crimes, - bool new_unlocks_gas_attack, - bool new_unlocks_gas_defence, - ConditionScript&& new_limit, - ConditionalWeightBase&& new_chance, - memory::vector&& new_raw_associated_tech_identifiers + index_t new_index, + std::string_view new_identifier, + ModifierValue&& new_values, + bool new_is_news, + unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, + crime_set_t&& new_enabled_crimes, + bool new_unlocks_gas_attack, + bool new_unlocks_gas_defence, + ConditionScript&& new_limit, + ConditionalWeightBase&& new_chance, + memory::vector&& new_raw_associated_tech_identifiers ); Invention(Invention&&) = default; }; @@ -66,20 +66,30 @@ namespace OpenVic { public: bool add_invention( - std::string_view identifier, ModifierValue&& values, bool news, Invention::unit_set_t&& activated_units, - Invention::building_set_t&& activated_buildings, Invention::crime_set_t&& enabled_crimes, bool unlock_gas_attack, - bool unlock_gas_defence, ConditionScript&& limit, ConditionalWeightBase&& chance, - memory::vector&& raw_associated_tech_identifiers + std::string_view identifier, + ModifierValue&& values, + bool news, + Invention::unit_set_t&& activated_units, + Invention::building_set_t&& activated_buildings, + Invention::crime_set_t&& enabled_crimes, + bool unlock_gas_attack, + bool unlock_gas_defence, + ConditionScript&& limit, + ConditionalWeightBase&& chance, + memory::vector&& raw_associated_tech_identifiers ); bool load_inventions_file( - TechnologyManager const& tech_manager, - ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, - BuildingTypeManager const& building_type_manager, CrimeManager const& crime_manager, ast::NodeCPtr root + TechnologyManager const& tech_manager, + ModifierManager const& modifier_manager, + UnitTypeManager const& unit_type_manager, + BuildingTypeManager const& building_type_manager, + CrimeManager const& crime_manager, + ast::NodeCPtr root ); // inventions/*.txt bool generate_invention_links(TechnologyManager& tech_manager); bool parse_scripts(DefinitionManager const& definition_manager); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/research/Technology.cpp b/src/openvic-simulation/research/Technology.cpp index 2d341d9b2..c00eb5ff2 100644 --- a/src/openvic-simulation/research/Technology.cpp +++ b/src/openvic-simulation/research/Technology.cpp @@ -9,43 +9,37 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -TechnologyFolder::TechnologyFolder(std::string_view new_identifier, index_t new_index) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} +TechnologyFolder::TechnologyFolder(std::string_view new_identifier, index_t new_index) : + HasIdentifier { new_identifier }, HasIndex { new_index } {} -TechnologyArea::TechnologyArea(std::string_view new_identifier, TechnologyFolder const& new_folder) - : HasIdentifier { new_identifier }, folder { new_folder } {} +TechnologyArea::TechnologyArea(std::string_view new_identifier, TechnologyFolder const& new_folder) : + HasIdentifier { new_identifier }, folder { new_folder } {} Technology::Technology( - std::string_view new_identifier, - index_t new_index, - TechnologyArea const& new_area, - Date::year_t new_year, - fixed_point_t new_cost, - area_index_t new_index_in_area, - bool new_unciv_military, - std::optional&& new_unit_variant, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - ModifierValue&& new_values, - ConditionalWeightFactorMul&& new_ai_chance -) : Modifier { new_identifier, std::move(new_values), modifier_type_t::TECHNOLOGY }, - HasIndex { new_index }, - area { new_area }, - year { new_year }, - cost { new_cost }, - index_in_area { new_index_in_area }, - unciv_military { new_unciv_military }, - unit_variant { std::move(new_unit_variant) }, - activated_units { std::move(new_activated_units) }, - activated_buildings { std::move(new_activated_buildings) }, - ai_chance { std::move(new_ai_chance) } {} + std::string_view new_identifier, + index_t new_index, + TechnologyArea const& new_area, + Date::year_t new_year, + fixed_point_t new_cost, + area_index_t new_index_in_area, + bool new_unciv_military, + std::optional&& new_unit_variant, + unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, + ModifierValue&& new_values, + ConditionalWeightFactorMul&& new_ai_chance +) : + Modifier { new_identifier, std::move(new_values), modifier_type_t::TECHNOLOGY }, HasIndex { new_index }, area { new_area }, + year { new_year }, cost { new_cost }, index_in_area { new_index_in_area }, unciv_military { new_unciv_military }, + unit_variant { std::move(new_unit_variant) }, activated_units { std::move(new_activated_units) }, + activated_buildings { std::move(new_activated_buildings) }, ai_chance { std::move(new_ai_chance) } {} bool Technology::parse_scripts(DefinitionManager const& definition_manager) { return ai_chance.parse_scripts(definition_manager); } -TechnologySchool::TechnologySchool(std::string_view new_identifier, ModifierValue&& new_values) - : Modifier { new_identifier, std::move(new_values), modifier_type_t::TECH_SCHOOL } {} +TechnologySchool::TechnologySchool(std::string_view new_identifier, ModifierValue&& new_values) : + Modifier { new_identifier, std::move(new_values), modifier_type_t::TECH_SCHOOL } {} bool TechnologyManager::add_technology_folder(std::string_view identifier) { if (identifier.empty()) { @@ -54,8 +48,7 @@ bool TechnologyManager::add_technology_folder(std::string_view identifier) { } return technology_folders.emplace_item( - identifier, - identifier, index_from_count(get_technology_folder_count()) + identifier, identifier, index_from_count(get_technology_folder_count()) ); } @@ -65,16 +58,20 @@ bool TechnologyManager::add_technology_area(std::string_view identifier, Technol return false; } - return technology_areas.emplace_item( - identifier, - identifier, folder - ); + return technology_areas.emplace_item(identifier, identifier, folder); } bool TechnologyManager::add_technology( - std::string_view identifier, TechnologyArea* area, Date::year_t year, fixed_point_t cost, bool unciv_military, - std::optional&& unit_variant, Technology::unit_set_t&& activated_units, - Technology::building_set_t&& activated_buildings, ModifierValue&& values, ConditionalWeightFactorMul&& ai_chance + std::string_view identifier, + TechnologyArea* area, + Date::year_t year, + fixed_point_t cost, + bool unciv_military, + std::optional&& unit_variant, + Technology::unit_set_t&& activated_units, + Technology::building_set_t&& activated_buildings, + ModifierValue&& values, + ConditionalWeightFactorMul&& ai_chance ) { if (identifier.empty()) { spdlog::error_s("Invalid technology identifier - empty!"); @@ -92,27 +89,29 @@ bool TechnologyManager::add_technology( if (index_in_area >= MAX_TECHS_IN_AREA) { spdlog::error_s( - "Cannot add technology \"{}\" - too many technologies in area \"{}\"! Each area can have at most {} technologies.", - identifier, *area, MAX_TECHS_IN_AREA + "Cannot add technology \"{}\" - too many technologies in area \"{}\"! Each area can have at most {} technologies.", + identifier, + *area, + MAX_TECHS_IN_AREA ); return false; } if (!technologies.emplace_item( - identifier, - identifier, - index_from_count(get_technology_count()), - *area, - year, - cost, - static_cast(index_in_area), - unciv_military, - std::move(unit_variant), - std::move(activated_units), - std::move(activated_buildings), - std::move(values), - std::move(ai_chance) - )) { + identifier, + identifier, + index_from_count(get_technology_count()), + *area, + year, + cost, + static_cast(index_in_area), + unciv_military, + std::move(unit_variant), + std::move(activated_units), + std::move(activated_buildings), + std::move(values), + std::move(ai_chance) + )) { return false; } @@ -126,10 +125,7 @@ bool TechnologyManager::add_technology_school(std::string_view identifier, Modif return false; } - return technology_schools.emplace_item( - identifier, - identifier, std::move(values) - ); + return technology_schools.emplace_item(identifier, identifier, std::move(values)); } bool TechnologyManager::load_technology_file_folders_and_areas(ast::NodeCPtr root) { @@ -167,9 +163,7 @@ bool TechnologyManager::load_technology_file_folders_and_areas(ast::NodeCPtr roo )(root); } -bool TechnologyManager::load_technology_file_schools( - ModifierManager const& modifier_manager, ast::NodeCPtr root -) { +bool TechnologyManager::load_technology_file_schools(ModifierManager const& modifier_manager, ast::NodeCPtr root) { if (!technology_folders.is_locked() || !technology_areas.is_locked()) { spdlog::error_s("Cannot load technology schools until technology folders and areas are locked!"); return false; @@ -202,12 +196,12 @@ bool TechnologyManager::load_technology_file_schools( } bool TechnologyManager::load_technologies_file( - ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, - BuildingTypeManager const& building_type_manager, ast::NodeCPtr root + ModifierManager const& modifier_manager, + UnitTypeManager const& unit_type_manager, + BuildingTypeManager const& building_type_manager, + ast::NodeCPtr root ) { - return expect_dictionary_reserve_length(technologies, [this, &modifier_manager, &unit_type_manager, &building_type_manager]( - std::string_view tech_key, ast::NodeCPtr tech_value - ) -> bool { + return expect_dictionary_reserve_length(technologies, [this, &modifier_manager, &unit_type_manager, &building_type_manager](std::string_view tech_key, ast::NodeCPtr tech_value) -> bool { using enum scope_type_t; ModifierValue modifiers; @@ -236,8 +230,16 @@ bool TechnologyManager::load_technologies_file( )(tech_value); ret &= add_technology( - tech_key, area, year, cost, unciv_military, std::move(unit_variant), std::move(activated_units), - std::move(activated_buildings), std::move(modifiers), std::move(ai_chance) + tech_key, + area, + year, + cost, + unciv_military, + std::move(unit_variant), + std::move(activated_units), + std::move(activated_buildings), + std::move(modifiers), + std::move(ai_chance) ); return ret; })(root); @@ -248,13 +250,11 @@ bool TechnologyManager::generate_modifiers(ModifierManager& modifier_manager) co using enum ModifierEffect::target_t; memory::FixedVector& research_bonus_effects = - modifier_manager.modifier_effect_cache.research_bonus_effects; + modifier_manager.modifier_effect_cache.research_bonus_effects; research_bonus_effects = std::move( - decltype(ModifierEffectCache::research_bonus_effects) { - generate_values, - technology_folder_index_t(get_technology_folder_count()) - } + decltype(ModifierEffectCache::research_bonus_effects) { + generate_values, technology_folder_index_t(get_technology_folder_count()) } ); bool ret = true; @@ -263,7 +263,7 @@ bool TechnologyManager::generate_modifiers(ModifierManager& modifier_manager) co const memory::string modifier_identifier = memory::fmt::format("{}_research_bonus", folder); ret &= modifier_manager.register_base_country_modifier_effect( - research_bonus_effects[folder.index], modifier_identifier, FORMAT_x100_1DP_PC_POS, modifier_identifier + research_bonus_effects[folder.index], modifier_identifier, FORMAT_x100_1DP_PC_POS, modifier_identifier ); } @@ -299,8 +299,10 @@ bool TechnologyManager::generate_technology_lists() { for (TechnologyArea const& area : technology_areas.get_items()) { if (area.get_technologies().size() != area.get_tech_count()) { spdlog::error_s( - "Technology area \"{}\" has a mismatch between tech count ({}) and tech list size ({})!", - area, area.get_tech_count(), area.get_technologies().size() + "Technology area \"{}\" has a mismatch between tech count ({}) and tech list size ({})!", + area, + area.get_tech_count(), + area.get_technologies().size() ); ret = false; } diff --git a/src/openvic-simulation/research/Technology.hpp b/src/openvic-simulation/research/Technology.hpp index a1cf5e967..4427fba12 100644 --- a/src/openvic-simulation/research/Technology.hpp +++ b/src/openvic-simulation/research/Technology.hpp @@ -71,18 +71,18 @@ namespace OpenVic { const building_set_t activated_buildings; Technology( - std::string_view new_identifier, - index_t new_index, - TechnologyArea const& new_area, - Date::year_t new_year, - fixed_point_t new_cost, - area_index_t new_index_in_area, - bool new_unciv_military, - std::optional&& new_unit_variant, - unit_set_t&& new_activated_units, - building_set_t&& new_activated_buildings, - ModifierValue&& new_values, - ConditionalWeightFactorMul&& new_ai_chance + std::string_view new_identifier, + index_t new_index, + TechnologyArea const& new_area, + Date::year_t new_year, + fixed_point_t new_cost, + area_index_t new_index_in_area, + bool new_unciv_military, + std::optional&& new_unit_variant, + unit_set_t&& new_activated_units, + building_set_t&& new_activated_buildings, + ModifierValue&& new_values, + ConditionalWeightFactorMul&& new_ai_chance ); Technology(Technology&&) = default; @@ -112,9 +112,16 @@ namespace OpenVic { bool add_technology_area(std::string_view identifier, TechnologyFolder const& folder); bool add_technology( - std::string_view identifier, TechnologyArea* area, Date::year_t year, fixed_point_t cost, bool unciv_military, - std::optional&& unit_variant, Technology::unit_set_t&& activated_units, - Technology::building_set_t&& activated_buildings, ModifierValue&& values, ConditionalWeightFactorMul&& ai_chance + std::string_view identifier, + TechnologyArea* area, + Date::year_t year, + fixed_point_t cost, + bool unciv_military, + std::optional&& unit_variant, + Technology::unit_set_t&& activated_units, + Technology::building_set_t&& activated_buildings, + ModifierValue&& values, + ConditionalWeightFactorMul&& ai_chance ); bool add_technology_school(std::string_view identifier, ModifierValue&& values); @@ -126,8 +133,10 @@ namespace OpenVic { /* Loaded from "technologies/.txt" files named after technology folders. */ bool load_technologies_file( - ModifierManager const& modifier_manager, UnitTypeManager const& unit_type_manager, - BuildingTypeManager const& building_type_manager, ast::NodeCPtr root + ModifierManager const& modifier_manager, + UnitTypeManager const& unit_type_manager, + BuildingTypeManager const& building_type_manager, + ast::NodeCPtr root ); bool generate_modifiers(ModifierManager& modifier_manager) const; diff --git a/src/openvic-simulation/research/TechnologyUnlockLevel.hpp b/src/openvic-simulation/research/TechnologyUnlockLevel.hpp index f87cbf8fd..068ab05cb 100644 --- a/src/openvic-simulation/research/TechnologyUnlockLevel.hpp +++ b/src/openvic-simulation/research/TechnologyUnlockLevel.hpp @@ -9,14 +9,14 @@ namespace OpenVic { struct technology_unlock_level_t - : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction, - type_safe::strong_typedef_op::mixed_relational_comparison, - type_safe::strong_typedef_op::mixed_equality_comparison { + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction, + type_safe::strong_typedef_op::mixed_relational_comparison, + type_safe::strong_typedef_op::mixed_equality_comparison { using strong_typedef::strong_typedef; }; } diff --git a/src/openvic-simulation/scripts/Condition.cpp b/src/openvic-simulation/scripts/Condition.cpp index 0372910a3..7b0be5fd1 100644 --- a/src/openvic-simulation/scripts/Condition.cpp +++ b/src/openvic-simulation/scripts/Condition.cpp @@ -2,8 +2,8 @@ #include -#include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/dataloader/NodeTools.hpp" using namespace OpenVic; using namespace OpenVic::NodeTools; @@ -13,23 +13,33 @@ using enum scope_type_t; using enum identifier_type_t; Condition::Condition( - std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, - scope_type_t new_scope_change, identifier_type_t new_key_identifier_type, - identifier_type_t new_value_identifier_type -) : HasIdentifier { new_identifier }, value_type { new_value_type }, scope { new_scope }, - scope_change { new_scope_change }, key_identifier_type { new_key_identifier_type }, - value_identifier_type { new_value_identifier_type } {} + std::string_view new_identifier, + value_type_t new_value_type, + scope_type_t new_scope, + scope_type_t new_scope_change, + identifier_type_t new_key_identifier_type, + identifier_type_t new_value_identifier_type +) : + HasIdentifier { new_identifier }, value_type { new_value_type }, scope { new_scope }, scope_change { new_scope_change }, + key_identifier_type { new_key_identifier_type }, value_identifier_type { new_value_identifier_type } {} ConditionNode::ConditionNode( - Condition const* new_condition, value_t&& new_value, bool new_valid, - HasIdentifier const* new_condition_key_item, - HasIdentifier const* new_condition_value_item -) : condition { new_condition }, value { std::move(new_value) }, valid { new_valid }, - condition_key_item { new_condition_key_item }, condition_value_item { new_condition_key_item } {} + Condition const* new_condition, + value_t&& new_value, + bool new_valid, + HasIdentifier const* new_condition_key_item, + HasIdentifier const* new_condition_value_item +) : + condition { new_condition }, value { std::move(new_value) }, valid { new_valid }, + condition_key_item { new_condition_key_item }, condition_value_item { new_condition_key_item } {} bool ConditionManager::add_condition( - std::string_view identifier, value_type_t value_type, scope_type_t scope, scope_type_t scope_change, - identifier_type_t key_identifier_type, identifier_type_t value_identifier_type + std::string_view identifier, + value_type_t value_type, + scope_type_t scope, + scope_type_t scope_change, + identifier_type_t key_identifier_type, + identifier_type_t value_identifier_type ) { if (identifier.empty()) { spdlog::error_s("Invalid condition identifier - empty!"); @@ -37,17 +47,11 @@ bool ConditionManager::add_condition( } if (value_type == NO_TYPE || value_type > MAX_VALUE) { - spdlog::error_s( - "Condition {} has invalid value type: {}", - identifier, static_cast(value_type) - ); + spdlog::error_s("Condition {} has invalid value type: {}", identifier, static_cast(value_type)); return false; } if (scope == NO_SCOPE || scope > MAX_SCOPE) { - spdlog::error_s( - "Condition {} has invalid scope: {}", - identifier, static_cast(scope) - ); + spdlog::error_s("Condition {} has invalid scope: {}", identifier, static_cast(scope)); return false; } @@ -64,8 +68,7 @@ bool ConditionManager::add_condition( } return conditions.emplace_item( - identifier, - identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type + identifier, identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type ); } @@ -75,7 +78,7 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana /* Special Scopes */ ret &= add_condition("THIS", GROUP, COUNTRY, THIS); ret &= add_condition("FROM", GROUP, COUNTRY, FROM); - ret &= add_condition("independence", GROUP, COUNTRY, COUNTRY); //only from rebels! + ret &= add_condition("independence", GROUP, COUNTRY, COUNTRY); // only from rebels! /* Trigger Country Scopes */ ret &= add_condition("all_core", GROUP, COUNTRY, PROVINCE); @@ -113,7 +116,7 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana /* Global Conditions */ ret &= add_condition("year", INTEGER, COUNTRY); ret &= add_condition("month", INTEGER, COUNTRY); - ret &= add_condition("has_global_flag", IDENTIFIER, COUNTRY, NO_SCOPE, NO_IDENTIFIER, GLOBAL_FLAG); + ret &= add_condition("has_global_flag", IDENTIFIER, COUNTRY, NO_SCOPE, NO_IDENTIFIER, GLOBAL_FLAG); ret &= add_condition("is_canal_enabled", INTEGER, COUNTRY); ret &= add_condition("always", BOOLEAN, COUNTRY); ret &= add_condition("world_wars_enabled", BOOLEAN, COUNTRY); @@ -339,112 +342,100 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana ret &= add_condition("strata", IDENTIFIER, POP, NO_SCOPE, NO_IDENTIFIER, POP_STRATA); ret &= add_condition("type", IDENTIFIER, POP, NO_SCOPE, NO_IDENTIFIER, POP_TYPE); - const auto import_identifiers = [this, &ret]( - memory::vector const& identifiers, - value_type_t value_type, - scope_type_t scope, - scope_type_t scope_change = NO_SCOPE, - identifier_type_t key_identifier_type = NO_IDENTIFIER, - identifier_type_t value_identifier_type = NO_IDENTIFIER - ) -> void { + const auto import_identifiers = + [this, &ret]( + memory::vector const& identifiers, + value_type_t value_type, + scope_type_t scope, + scope_type_t scope_change = NO_SCOPE, + identifier_type_t key_identifier_type = NO_IDENTIFIER, + identifier_type_t value_identifier_type = NO_IDENTIFIER + ) -> void { for (std::string_view const& identifier : identifiers) { - ret &= add_condition( - identifier, value_type, scope, scope_change, - key_identifier_type, value_identifier_type - ); + ret &= add_condition(identifier, value_type, scope, scope_change, key_identifier_type, value_identifier_type); } }; /* Scopes from other registries */ import_identifiers( - definition_manager.get_country_definition_manager().get_country_definition_identifiers(), - GROUP, - COUNTRY, - COUNTRY, - COUNTRY_TAG, - NO_IDENTIFIER + definition_manager.get_country_definition_manager().get_country_definition_identifiers(), + GROUP, + COUNTRY, + COUNTRY, + COUNTRY_TAG, + NO_IDENTIFIER ); import_identifiers( - definition_manager.get_map_definition().get_region_identifiers(), - GROUP, - COUNTRY, - STATE, - REGION, - NO_IDENTIFIER + definition_manager.get_map_definition().get_region_identifiers(), GROUP, COUNTRY, STATE, REGION, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_map_definition().get_province_definition_identifiers(), - GROUP, - COUNTRY, - PROVINCE, - PROVINCE_ID, - NO_IDENTIFIER + definition_manager.get_map_definition().get_province_definition_identifiers(), + GROUP, + COUNTRY, + PROVINCE, + PROVINCE_ID, + NO_IDENTIFIER ); /* Conditions from other registries */ import_identifiers( - definition_manager.get_politics_manager().get_ideology_manager().get_ideology_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - IDEOLOGY, - NO_IDENTIFIER + definition_manager.get_politics_manager().get_ideology_manager().get_ideology_identifiers(), + REAL, + COUNTRY, + NO_SCOPE, + IDEOLOGY, + NO_IDENTIFIER ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_reform_group_identifiers(), - IDENTIFIER, - COUNTRY, - NO_SCOPE, - REFORM_GROUP, - REFORM + definition_manager.get_politics_manager().get_issue_manager().get_reform_group_identifiers(), + IDENTIFIER, + COUNTRY, + NO_SCOPE, + REFORM_GROUP, + REFORM ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_reform_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - REFORM, - NO_IDENTIFIER + definition_manager.get_politics_manager().get_issue_manager().get_reform_identifiers(), + REAL, + COUNTRY, + NO_SCOPE, + REFORM, + NO_IDENTIFIER ); import_identifiers( - definition_manager.get_politics_manager().get_issue_manager().get_party_policy_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - PARTY_POLICY, - NO_IDENTIFIER + definition_manager.get_politics_manager().get_issue_manager().get_party_policy_identifiers(), + REAL, + COUNTRY, + NO_SCOPE, + PARTY_POLICY, + NO_IDENTIFIER ); import_identifiers( - definition_manager.get_pop_manager().get_pop_type_identifiers(), - REAL, - COUNTRY, - NO_SCOPE, - POP_TYPE, - NO_IDENTIFIER + definition_manager.get_pop_manager().get_pop_type_identifiers(), REAL, COUNTRY, NO_SCOPE, POP_TYPE, NO_IDENTIFIER ); import_identifiers( - definition_manager.get_research_manager().get_technology_manager().get_technology_identifiers(), - BOOLEAN_INT, - COUNTRY, - NO_SCOPE, - TECHNOLOGY, - NO_IDENTIFIER + definition_manager.get_research_manager().get_technology_manager().get_technology_identifiers(), + BOOLEAN_INT, + COUNTRY, + NO_SCOPE, + TECHNOLOGY, + NO_IDENTIFIER ); import_identifiers( - definition_manager.get_economy_manager().get_good_definition_manager().get_good_definition_identifiers(), - INTEGER, - COUNTRY, - NO_SCOPE, - TRADE_GOOD, - NO_IDENTIFIER + definition_manager.get_economy_manager().get_good_definition_manager().get_good_definition_identifiers(), + INTEGER, + COUNTRY, + NO_SCOPE, + TRADE_GOOD, + NO_IDENTIFIER ); lock_conditions(); @@ -461,36 +452,38 @@ bool ConditionManager::setup_conditions(DefinitionManager const& definition_mana } callback_t ConditionManager::expect_parse_identifier( - DefinitionManager const& definition_manager, identifier_type_t identifier_type, - callback_t callback + DefinitionManager const& definition_manager, identifier_type_t identifier_type, callback_t callback ) const { return [this, &definition_manager, identifier_type, callback](std::string_view identifier) mutable -> bool { HasIdentifier const* identified = nullptr; - #define EXPECT_CALL(type, name, manager, ...) \ - if (share_identifier_type(identifier_type, type)) { \ - identified = manager.get_##name##_by_identifier(identifier); \ - if (identified != nullptr) { \ - return callback(identified); \ - } __VA_OPT__(else { \ - /* TODO: the set is just a placeholder for actual logic */ \ - static const case_insensitive_string_set_t chances { __VA_ARGS__ }; \ - if (chances.contains(identifier)) { \ - return true; \ - } \ - }) \ - } +#define EXPECT_CALL(type, name, manager, ...) \ + if (share_identifier_type(identifier_type, type)) { \ + identified = manager.get_##name##_by_identifier(identifier); \ + if (identified != nullptr) { \ + return callback(identified); \ + } \ + __VA_OPT__(else { \ + /* TODO: the set is just a placeholder for actual logic */ \ + static const case_insensitive_string_set_t chances { __VA_ARGS__ }; \ + if (chances.contains(identifier)) { \ + return true; \ + } \ + }) \ + } - //TODO: placeholder for not implemented stuff - #define EXPECT_CALL_PLACEHOLDER(type) \ - if (share_identifier_type(identifier_type, type)) { return true; } +// TODO: placeholder for not implemented stuff +#define EXPECT_CALL_PLACEHOLDER(type) \ + if (share_identifier_type(identifier_type, type)) { \ + return true; \ + } EXPECT_CALL_PLACEHOLDER(VARIABLE); EXPECT_CALL_PLACEHOLDER(GLOBAL_FLAG); EXPECT_CALL_PLACEHOLDER(COUNTRY_FLAG); EXPECT_CALL_PLACEHOLDER(PROVINCE_FLAG); EXPECT_CALL( - COUNTRY_TAG, country_definition, definition_manager.get_country_definition_manager(), "THIS", "FROM", "OWNER" + COUNTRY_TAG, country_definition, definition_manager.get_country_definition_manager(), "THIS", "FROM", "OWNER" ); EXPECT_CALL(PROVINCE_ID, province_definition, definition_manager.get_map_definition(), "THIS", "FROM"); EXPECT_CALL(REGION, region, definition_manager.get_map_definition()); @@ -510,30 +503,35 @@ callback_t ConditionManager::expect_parse_identifier( EXPECT_CALL(BUILDING, building_type, definition_manager.get_economy_manager().get_building_type_manager(), "FACTORY"); EXPECT_CALL(CASUS_BELLI, wargoal_type, definition_manager.get_military_manager().get_wargoal_type_manager()); EXPECT_CALL(GOVERNMENT_TYPE, government_type, definition_manager.get_politics_manager().get_government_type_manager()); - EXPECT_CALL(COUNTRY_EVENT_MODIFIER | PROVINCE_EVENT_MODIFIER, event_modifier, definition_manager.get_modifier_manager()); + EXPECT_CALL( + COUNTRY_EVENT_MODIFIER | PROVINCE_EVENT_MODIFIER, event_modifier, definition_manager.get_modifier_manager() + ); EXPECT_CALL(COUNTRY_EVENT_MODIFIER, triggered_modifier, definition_manager.get_modifier_manager()); EXPECT_CALL(NATIONAL_VALUE, national_value, definition_manager.get_politics_manager().get_national_value_manager()); EXPECT_CALL( - CULTURE_UNION, country_definition, definition_manager.get_country_definition_manager(), "THIS", "FROM", "THIS_UNION" + CULTURE_UNION, country_definition, definition_manager.get_country_definition_manager(), "THIS", "FROM", "THIS_UNION" ); EXPECT_CALL(CONTINENT, continent, definition_manager.get_map_definition()); EXPECT_CALL(CRIME, crime_modifier, definition_manager.get_crime_manager()); EXPECT_CALL(TERRAIN, terrain_type, definition_manager.get_map_definition().get_terrain_type_manager()); - #undef EXPECT_CALL - #undef EXPECT_CALL_PLACEHOLDER +#undef EXPECT_CALL +#undef EXPECT_CALL_PLACEHOLDER return false; }; } node_callback_t ConditionManager::expect_condition_node( - DefinitionManager const& definition_manager, Condition const& condition, scope_type_t current_scope, - scope_type_t this_scope, scope_type_t from_scope, callback_t callback + DefinitionManager const& definition_manager, + Condition const& condition, + scope_type_t current_scope, + scope_type_t this_scope, + scope_type_t from_scope, + callback_t callback ) const { - return [this, &definition_manager, &condition, callback, current_scope, this_scope, from_scope]( - ast::NodeCPtr node - ) mutable -> bool { + return [this, &definition_manager, &condition, callback, current_scope, this_scope, from_scope](ast::NodeCPtr node) mutable + -> bool { bool ret = false; ConditionNode::value_t value; @@ -546,19 +544,15 @@ node_callback_t ConditionManager::expect_condition_node( HasIdentifier const* value_item = nullptr; - const auto get_identifiable = [this, &definition_manager]( - identifier_type_t item_type, std::string_view id, bool log - ) -> HasIdentifier const* { + const auto get_identifiable = + [this, &definition_manager](identifier_type_t item_type, std::string_view id, bool log) -> HasIdentifier const* { HasIdentifier const* keyval = nullptr; - bool ret = expect_parse_identifier( - definition_manager, - item_type, - assign_variable_callback(keyval) - )(id); + bool ret = expect_parse_identifier(definition_manager, item_type, assign_variable_callback(keyval))(id); if (log && !ret) { spdlog::error_s( - "Invalid identifier {} expected to have type {} found during condition node parsing!", - id, fmt::underlying(item_type) + "Invalid identifier {} expected to have type {} found during condition node parsing!", + id, + fmt::underlying(item_type) ); } return keyval; @@ -570,9 +564,9 @@ node_callback_t ConditionManager::expect_condition_node( if (ret) { value = ConditionNode::string_t { value_identifier }; value_item = get_identifiable( - value_identifier_type, - value_identifier, - value_type == IDENTIFIER // don't log if there's a fallback + value_identifier_type, + value_identifier, + value_type == IDENTIFIER // don't log if there's a fallback ); ret |= value_item != nullptr; } @@ -580,35 +574,27 @@ node_callback_t ConditionManager::expect_condition_node( if (!ret && share_value_type(value_type, STRING)) { std::string_view value_identifier {}; - bool local_ret = expect_identifier_or_string( - assign_variable_callback(value_identifier) - )(node); + bool local_ret = expect_identifier_or_string(assign_variable_callback(value_identifier))(node); ret |= local_ret; if (local_ret) { value = ConditionNode::string_t { value_identifier }; } } - ret |= (!ret && share_value_type(value_type, BOOLEAN)) - && expect_bool(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, BOOLEAN_INT)) - && expect_int_bool(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, INTEGER)) - && expect_uint64(assign_variable_callback(value))(node); - ret |= (!ret && share_value_type(value_type, REAL)) - && expect_fixed_point(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, BOOLEAN)) && expect_bool(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, BOOLEAN_INT)) && expect_int_bool(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, INTEGER)) && expect_uint64(assign_variable_callback(value))(node); + ret |= (!ret && share_value_type(value_type, REAL)) && expect_fixed_point(assign_variable_callback(value))(node); - //entries with magic syntax, thanks paradox! + // entries with magic syntax, thanks paradox! if (!ret && share_value_type(value_type, COMPLEX)) { - const auto expect_pair = [&ret, &value, node]( - std::string_view identifier_key, std::string_view value_key - ) -> void { + const auto expect_pair = [&ret, &value, node](std::string_view identifier_key, std::string_view value_key) -> void { std::string_view pair_identifier {}; fixed_point_t pair_value = 0; - ret |= expect_dictionary_keys( - identifier_key, ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(pair_identifier)), - value_key, ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pair_value)) - )(node); + ret |= + expect_dictionary_keys(identifier_key, ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(pair_identifier)), value_key, ONE_EXACTLY, expect_fixed_point(assign_variable_callback(pair_value)))( + node + ); if (ret) { value = ConditionNode::identifier_real_t { pair_identifier, pair_value }; } @@ -616,11 +602,10 @@ node_callback_t ConditionManager::expect_condition_node( if (identifier == "can_build_railway_in_capital" || identifier == "can_build_fort_in_capital") { bool in_whole_capital_state = false, limit_to_world_greatest_level = false; - ret |= expect_dictionary_keys( - "in_whole_capital_state", ONE_EXACTLY, expect_bool(assign_variable_callback(in_whole_capital_state)), - "limit_to_world_greatest_level", ONE_EXACTLY, - expect_bool(assign_variable_callback(limit_to_world_greatest_level)) - )(node); + ret |= + expect_dictionary_keys("in_whole_capital_state", ONE_EXACTLY, expect_bool(assign_variable_callback(in_whole_capital_state)), "limit_to_world_greatest_level", ONE_EXACTLY, expect_bool(assign_variable_callback(limit_to_world_greatest_level)))( + node + ); if (ret) { value = ConditionNode::double_boolean_t { in_whole_capital_state, limit_to_world_greatest_level }; } @@ -637,9 +622,10 @@ node_callback_t ConditionManager::expect_condition_node( } else if (identifier == "work_available") { // { worker = [type] } std::string_view worker {}; - ret |= expect_dictionary_keys( - "worker", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(worker)) - )(node); + ret |= + expect_dictionary_keys("worker", ONE_EXACTLY, expect_identifier_or_string(assign_variable_callback(worker)))( + node + ); if (ret) { value = ConditionNode::string_t { worker }; } @@ -647,18 +633,15 @@ node_callback_t ConditionManager::expect_condition_node( spdlog::error_s("Attempted to parse unknown complex condition {}!", identifier); } - #undef EXPECT_PAIR +#undef EXPECT_PAIR } if (!ret && share_value_type(value_type, GROUP)) { ConditionNode::condition_list_t node_list; - ret |= expect_condition_node_list( - definition_manager, - scope_change == NO_SCOPE ? current_scope : scope_change, - this_scope, - from_scope, - vector_callback(node_list) - )(node); + ret |= + expect_condition_node_list(definition_manager, scope_change == NO_SCOPE ? current_scope : scope_change, this_scope, from_scope, vector_callback(node_list))( + node + ); value = std::move(node_list); } @@ -672,8 +655,10 @@ node_callback_t ConditionManager::expect_condition_node( if (!share_scope_type(scope, effective_current_scope) && effective_current_scope > scope) { spdlog::warn_s( - "Condition or scope {} was found in wrong scope {}, expected {}!", - identifier, fmt::underlying(effective_current_scope), fmt::underlying(scope) + "Condition or scope {} was found in wrong scope {}, expected {}!", + identifier, + fmt::underlying(effective_current_scope), + fmt::underlying(scope) ); ret = false; } @@ -688,22 +673,10 @@ node_callback_t ConditionManager::expect_condition_node( if (!ret) { spdlog::warn_s("Could not parse condition node {}, will always evaluate to false!", identifier); Condition const* always_condition = conditions.get_item_by_identifier("always"); - return callback({ - always_condition, - std::move(ConditionNode::value_t(false)), - true, - key_item, - value_item - }); + return callback({ always_condition, std::move(ConditionNode::value_t(false)), true, key_item, value_item }); } - ret &= callback({ - &condition, - std::move(value), - ret, - key_item, - value_item - }); + ret &= callback({ &condition, std::move(value), ret, key_item, value_item }); return ret; }; @@ -721,70 +694,83 @@ static bool top_scope_fallback(std::string_view id, ast::NodeCPtr node) { }; node_callback_t ConditionManager::expect_condition_node_list( - DefinitionManager const& definition_manager, scope_type_t current_scope, scope_type_t this_scope, scope_type_t from_scope, - callback_t callback, bool top_scope + DefinitionManager const& definition_manager, + scope_type_t current_scope, + scope_type_t this_scope, + scope_type_t from_scope, + callback_t callback, + bool top_scope ) const { return [this, &definition_manager, callback, current_scope, this_scope, from_scope, top_scope](ast::NodeCPtr node) -> bool { - const auto expect_node = [this, &definition_manager, callback, current_scope, this_scope, from_scope] - (Condition const& condition, ast::NodeCPtr node) -> bool { - return expect_condition_node( - definition_manager, condition, current_scope, this_scope, from_scope, callback - )(node); + const auto expect_node = + [this, &definition_manager, callback, current_scope, this_scope, from_scope]( + Condition const& condition, ast::NodeCPtr node + ) -> bool { + return expect_condition_node(definition_manager, condition, current_scope, this_scope, from_scope, callback)(node); }; const auto invalid_condition_node = [this, &expect_node, top_scope](std::string_view id, ast::NodeCPtr node) -> bool { - if (top_scope && id == "factor") { return true; } + if (top_scope && id == "factor") { + return true; + } if (ast::FlatValue const* node_name = dryad::node_try_cast(node); node_name && node_name->value()) { spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", - id, node_name->value().view() + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", + id, + node_name->value().view() ); // TODO: make this error message more useful by pinning down node to an actual file or something } else if (ast::ListValue const* list_values = dryad::node_try_cast(node); list_values) { for (ast::Statement const* statement : list_values->statements()) { - dryad::visit_node(statement, - [&](ast::AssignStatement const* assign){ - if (ast::FlatValue const* node_name = dryad::node_try_cast(assign->left()); node_name && node_name->value()) { - spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", - id, node_name->value().view() - ); // TODO: make this error message more useful by pinning down node to an actual file or something - } - }, - [&](ast::ValueStatement const* value) { - if (ast::FlatValue const* node_name = dryad::node_try_cast(value->value()); node_name && node_name->value()) { - spdlog::warn_s( - "Condition {} does not exist in scope at condition node: {}, and will always evaluate to false!", - id, node_name->value().view() - ); // TODO: make this error message more useful by pinning down node to an actual file or something - } - } + dryad::visit_node( + statement, + [&](ast::AssignStatement const* assign) { + if (ast::FlatValue const* node_name = dryad::node_try_cast(assign->left()); + node_name && node_name->value()) { + spdlog::warn_s( + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to " + "false!", + id, + node_name->value().view() + ); // TODO: make this error message more useful by pinning down node to an actual file or + // something + } + }, + [&](ast::ValueStatement const* value) { + if (ast::FlatValue const* node_name = dryad::node_try_cast(value->value()); + node_name && node_name->value()) { + spdlog::warn_s( + "Condition {} does not exist in scope at condition node: {}, and will always evaluate to " + "false!", + id, + node_name->value().view() + ); // TODO: make this error message more useful by pinning down node to an actual file or + // something + } + } ); } } return true; }; - return conditions.expect_item_dictionary_and_default( - invalid_condition_node, - expect_node - )(node); + return conditions.expect_item_dictionary_and_default(invalid_condition_node, expect_node)(node); }; } bool ConditionManager::expect_condition_script( - DefinitionManager const& definition_manager, scope_type_t initial_scope, scope_type_t this_scope, - scope_type_t from_scope, NodeTools::callback_t callback, std::span nodes + DefinitionManager const& definition_manager, + scope_type_t initial_scope, + scope_type_t this_scope, + scope_type_t from_scope, + NodeTools::callback_t callback, + std::span nodes ) const { ConditionNode::condition_list_t conds; bool ret = true; for (const ast::NodeCPtr node : nodes) { - ret &= expect_condition_node_list( - definition_manager, - initial_scope, - this_scope, - from_scope, - NodeTools::vector_callback(conds), - true - )(node); + ret &= + expect_condition_node_list(definition_manager, initial_scope, this_scope, from_scope, NodeTools::vector_callback(conds), true)( + node + ); } ret &= callback({ root_condition, std::move(conds), true }); diff --git a/src/openvic-simulation/scripts/Condition.hpp b/src/openvic-simulation/scripts/Condition.hpp index 1411d05ca..72d5c1f16 100644 --- a/src/openvic-simulation/scripts/Condition.hpp +++ b/src/openvic-simulation/scripts/Condition.hpp @@ -17,69 +17,72 @@ namespace OpenVic { struct DefinitionManager; enum class value_type_t : uint8_t { - NO_TYPE = 0, - IDENTIFIER = 1 << 0, - STRING = 1 << 1, - BOOLEAN = 1 << 2, + NO_TYPE = 0, + IDENTIFIER = 1 << 0, + STRING = 1 << 1, + BOOLEAN = 1 << 2, BOOLEAN_INT = 1 << 3, - INTEGER = 1 << 4, - REAL = 1 << 5, - COMPLEX = 1 << 6, - GROUP = 1 << 7, - MAX_VALUE = (1 << 8) - 1 + INTEGER = 1 << 4, + REAL = 1 << 5, + COMPLEX = 1 << 6, + GROUP = 1 << 7, + MAX_VALUE = (1 << 8) - 1 }; // Order matters in this enum, for the fallback system to work // smaller entities must have smaller integers associated! - enum class scope_type_t : uint8_t { //TODO: maybe distinguish TRANSPARENT from NO_SCOPE - NO_SCOPE = 0, - POP = 1 << 0, - PROVINCE = 1 << 1, - STATE = 1 << 2, - COUNTRY = 1 << 3, - THIS = 1 << 4, - FROM = 1 << 5, - MAX_SCOPE = (1 << 6) - 1 + enum class scope_type_t : uint8_t { // TODO: maybe distinguish TRANSPARENT from NO_SCOPE + NO_SCOPE = 0, + POP = 1 << 0, + PROVINCE = 1 << 1, + STATE = 1 << 2, + COUNTRY = 1 << 3, + THIS = 1 << 4, + FROM = 1 << 5, + MAX_SCOPE = (1 << 6) - 1 }; enum class identifier_type_t : uint32_t { - NO_IDENTIFIER = 0, - VARIABLE = 1 << 0, - GLOBAL_FLAG = 1 << 1, - COUNTRY_FLAG = 1 << 2, - PROVINCE_FLAG = 1 << 3, - COUNTRY_TAG = 1 << 4, - PROVINCE_ID = 1 << 5, - REGION = 1 << 6, - IDEOLOGY = 1 << 7, - REFORM_GROUP = 1 << 8, - REFORM = 1 << 9, - PARTY_POLICY = 1 << 10, - POP_TYPE = 1 << 11, - POP_STRATA = 1 << 12, - TECHNOLOGY = 1 << 13, - INVENTION = 1 << 14, - TECH_SCHOOL = 1 << 15, - CULTURE = 1 << 16, - CULTURE_GROUP = 1 << 17, - RELIGION = 1 << 18, - TRADE_GOOD = 1 << 19, - BUILDING = 1 << 20, - CASUS_BELLI = 1 << 21, + NO_IDENTIFIER = 0, + VARIABLE = 1 << 0, + GLOBAL_FLAG = 1 << 1, + COUNTRY_FLAG = 1 << 2, + PROVINCE_FLAG = 1 << 3, + COUNTRY_TAG = 1 << 4, + PROVINCE_ID = 1 << 5, + REGION = 1 << 6, + IDEOLOGY = 1 << 7, + REFORM_GROUP = 1 << 8, + REFORM = 1 << 9, + PARTY_POLICY = 1 << 10, + POP_TYPE = 1 << 11, + POP_STRATA = 1 << 12, + TECHNOLOGY = 1 << 13, + INVENTION = 1 << 14, + TECH_SCHOOL = 1 << 15, + CULTURE = 1 << 16, + CULTURE_GROUP = 1 << 17, + RELIGION = 1 << 18, + TRADE_GOOD = 1 << 19, + BUILDING = 1 << 20, + CASUS_BELLI = 1 << 21, GOVERNMENT_TYPE = 1 << 22, COUNTRY_EVENT_MODIFIER = 1 << 23, PROVINCE_EVENT_MODIFIER = 1 << 24, - NATIONAL_VALUE = 1 << 25, - CULTURE_UNION = 1 << 26, // same as COUNTRY_TAG but also accepts scope this_union - CONTINENT = 1 << 27, - CRIME = 1 << 28, - TERRAIN = 1 << 29 + NATIONAL_VALUE = 1 << 25, + CULTURE_UNION = 1 << 26, // same as COUNTRY_TAG but also accepts scope this_union + CONTINENT = 1 << 27, + CRIME = 1 << 28, + TERRAIN = 1 << 29 }; /* Allows enum types to be used with bitwise operators. */ - template<> struct enable_bitfield : std::true_type {}; - template<> struct enable_bitfield : std::true_type {}; - template<> struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; + template<> + struct enable_bitfield : std::true_type {}; /* Returns true if the values have any bit in common. */ inline constexpr bool share_value_type(value_type_t lhs, value_type_t rhs) { @@ -208,9 +211,12 @@ namespace OpenVic { const identifier_type_t value_identifier_type; Condition( - std::string_view new_identifier, value_type_t new_value_type, scope_type_t new_scope, - scope_type_t new_scope_change, identifier_type_t new_key_identifier_type, - identifier_type_t new_value_identifier_type + std::string_view new_identifier, + value_type_t new_value_type, + scope_type_t new_scope, + scope_type_t new_scope_change, + identifier_type_t new_key_identifier_type, + identifier_type_t new_value_identifier_type ); Condition(Condition&&) = default; }; @@ -226,9 +232,8 @@ namespace OpenVic { using real_t = fixed_point_t; using identifier_real_t = std::pair; using condition_list_t = memory::vector; - using value_t = std::variant< - string_t, boolean_t, double_boolean_t, integer_t, real_t, identifier_real_t, condition_list_t - >; + using value_t = + std::variant; private: Condition const* PROPERTY(condition); @@ -238,10 +243,11 @@ namespace OpenVic { bool PROPERTY_CUSTOM_PREFIX(valid, is); ConditionNode( - Condition const* new_condition = nullptr, value_t&& new_value = 0, - bool new_valid = false, - HasIdentifier const* new_condition_key_item = nullptr, - HasIdentifier const* new_condition_value_item = nullptr + Condition const* new_condition = nullptr, + value_t&& new_value = 0, + bool new_valid = false, + HasIdentifier const* new_condition_key_item = nullptr, + HasIdentifier const* new_condition_value_item = nullptr ); }; @@ -251,33 +257,48 @@ namespace OpenVic { Condition const* root_condition = nullptr; bool add_condition( - std::string_view identifier, value_type_t value_type, scope_type_t scope, - scope_type_t scope_change = scope_type_t::NO_SCOPE, - identifier_type_t key_identifier_type = identifier_type_t::NO_IDENTIFIER, - identifier_type_t value_identifier_type = identifier_type_t::NO_IDENTIFIER + std::string_view identifier, + value_type_t value_type, + scope_type_t scope, + scope_type_t scope_change = scope_type_t::NO_SCOPE, + identifier_type_t key_identifier_type = identifier_type_t::NO_IDENTIFIER, + identifier_type_t value_identifier_type = identifier_type_t::NO_IDENTIFIER ); NodeTools::callback_t expect_parse_identifier( - DefinitionManager const& definition_manager, identifier_type_t identifier_type, - NodeTools::callback_t callback + DefinitionManager const& definition_manager, + identifier_type_t identifier_type, + NodeTools::callback_t callback ) const; NodeTools::node_callback_t expect_condition_node( - DefinitionManager const& definition_manager, Condition const& condition, scope_type_t current_scope, - scope_type_t this_scope, scope_type_t from_scope, NodeTools::callback_t callback + DefinitionManager const& definition_manager, + Condition const& condition, + scope_type_t current_scope, + scope_type_t this_scope, + scope_type_t from_scope, + NodeTools::callback_t callback ) const; NodeTools::node_callback_t expect_condition_node_list( - DefinitionManager const& definition_manager, scope_type_t current_scope, scope_type_t this_scope, - scope_type_t from_scope, NodeTools::callback_t callback, bool top_scope = false + DefinitionManager const& definition_manager, + scope_type_t current_scope, + scope_type_t this_scope, + scope_type_t from_scope, + NodeTools::callback_t callback, + bool top_scope = false ) const; public: bool setup_conditions(DefinitionManager const& definition_manager); bool expect_condition_script( - DefinitionManager const& definition_manager, scope_type_t initial_scope, scope_type_t this_scope, - scope_type_t from_scope, NodeTools::callback_t callback, std::span nodes + DefinitionManager const& definition_manager, + scope_type_t initial_scope, + scope_type_t this_scope, + scope_type_t from_scope, + NodeTools::callback_t callback, + std::span nodes ) const; }; } diff --git a/src/openvic-simulation/scripts/ConditionScript.cpp b/src/openvic-simulation/scripts/ConditionScript.cpp index 4fc97d83c..4c2627cea 100644 --- a/src/openvic-simulation/scripts/ConditionScript.cpp +++ b/src/openvic-simulation/scripts/ConditionScript.cpp @@ -5,17 +5,11 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -ConditionScript::ConditionScript( - scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope -) : initial_scope { new_initial_scope }, this_scope { new_this_scope }, from_scope { new_from_scope } {} +ConditionScript::ConditionScript(scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope) : + initial_scope { new_initial_scope }, this_scope { new_this_scope }, from_scope { new_from_scope } {} bool ConditionScript::_parse_script(std::span nodes, DefinitionManager const& definition_manager) { return definition_manager.get_script_manager().get_condition_manager().expect_condition_script( - definition_manager, - initial_scope, - this_scope, - from_scope, - move_variable_callback(condition_root), - nodes + definition_manager, initial_scope, this_scope, from_scope, move_variable_callback(condition_root), nodes ); } diff --git a/src/openvic-simulation/scripts/ConditionalWeight.cpp b/src/openvic-simulation/scripts/ConditionalWeight.cpp index f8c4b1901..a11f526db 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.cpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.cpp @@ -9,15 +9,15 @@ using enum conditional_weight_type_t; template ConditionalWeight::ConditionalWeight( - scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope -) - : initial_scope { new_initial_scope }, // - this_scope { new_this_scope }, // - from_scope { new_from_scope } {} + scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope +) : + initial_scope { new_initial_scope }, // + this_scope { new_this_scope }, // + from_scope { new_from_scope } {} template static NodeCallback auto expect_modifier( - memory::vector& items, scope_type_t initial_scope, scope_type_t this_scope, scope_type_t from_scope + memory::vector& items, scope_type_t initial_scope, scope_type_t this_scope, scope_type_t from_scope ) { return [&items, initial_scope, this_scope, from_scope](ast::NodeCPtr node) -> bool { fixed_point_t weight = 0; @@ -39,15 +39,13 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { key_map_t key_map; bool successfully_set_up_base_keys = true; - if constexpr(TYPE == BASE) { + if constexpr (TYPE == BASE) { successfully_set_up_base_keys &= add_key_map_entry( - key_map, - "base", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) + key_map, "base", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) ); } else if constexpr (TYPE == FACTOR_ADD || TYPE == FACTOR_MUL) { successfully_set_up_base_keys &= add_key_map_entry( - key_map, - "factor", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) + key_map, "factor", ONE_EXACTLY, expect_fixed_point(assign_variable_callback(base)) ); } else if constexpr (TYPE == TIME) { const auto time_callback = [this](std::string_view key, Timespan (*to_timespan)(Timespan::value_t)) -> auto { @@ -57,9 +55,11 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { return true; } else { spdlog::error_s( - "ConditionalWeight cannot have multiple base values - " - "trying to set base to {} {} when it already has a value equivalent to {} days!", - value, key, base + "ConditionalWeight cannot have multiple base values - " + "trying to set base to {} {} when it already has a value equivalent to {} days!", + value, + key, + base ); return false; } @@ -67,10 +67,18 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { }; successfully_set_up_base_keys &= add_key_map_entries( - key_map, - "days", ZERO_OR_ONE, expect_uint(time_callback("days", Timespan::from_days)), - "months", ZERO_OR_ONE, expect_uint(time_callback("months", Timespan::from_months)), - "years", ZERO_OR_ONE, expect_uint(time_callback("years", [](Timespan::value_t v) { return Timespan::from_years(v); })) + key_map, + "days", + ZERO_OR_ONE, + expect_uint(time_callback("days", Timespan::from_days)), + "months", + ZERO_OR_ONE, + expect_uint(time_callback("months", Timespan::from_months)), + "years", + ZERO_OR_ONE, + expect_uint(time_callback("years", [](Timespan::value_t v) { + return Timespan::from_years(v); + })) ); } else { successfully_set_up_base_keys = false; @@ -79,30 +87,35 @@ node_callback_t ConditionalWeight::expect_conditional_weight() { if (!successfully_set_up_base_keys) { return [](ast::NodeCPtr node) -> bool { spdlog::error_s( - "Failed to set up base keys for ConditionalWeight with base value: {}", static_cast(TYPE) + "Failed to set up base keys for ConditionalWeight with base value: {}", static_cast(TYPE) ); return false; }; } return expect_dictionary_key_map( - std::move(key_map), - "modifier", ZERO_OR_MORE, expect_modifier(condition_weight_items, initial_scope, this_scope, from_scope), - "group", ZERO_OR_MORE, [this](ast::NodeCPtr node) -> bool { - condition_weight_group_t items; - - const bool ret = expect_dictionary_keys( - "modifier", ONE_OR_MORE, expect_modifier(items, initial_scope, this_scope, from_scope) - )(node); - - if (!items.empty()) { - condition_weight_items.emplace_back(std::move(items)); - return ret; - } else { - spdlog::error_s("ConditionalWeight group must have at least one modifier!"); - return false; - } - } + std::move(key_map), + "modifier", + ZERO_OR_MORE, + expect_modifier(condition_weight_items, initial_scope, this_scope, from_scope), + "group", + ZERO_OR_MORE, + [this](ast::NodeCPtr node) -> bool { + condition_weight_group_t items; + + const bool ret = + expect_dictionary_keys("modifier", ONE_OR_MORE, expect_modifier(items, initial_scope, this_scope, from_scope))( + node + ); + + if (!items.empty()) { + condition_weight_items.emplace_back(std::move(items)); + return ret; + } else { + spdlog::error_s("ConditionalWeight group must have at least one modifier!"); + return false; + } + } ); } @@ -132,9 +145,7 @@ bool ConditionalWeight::parse_scripts(DefinitionManager const& definition_ template bool ConditionalWeight::operator==(ConditionalWeight const& other) const { - return initial_scope == other.initial_scope && - this_scope == other.this_scope && - from_scope == other.from_scope; + return initial_scope == other.initial_scope && this_scope == other.this_scope && from_scope == other.from_scope; } template struct OpenVic::ConditionalWeight; diff --git a/src/openvic-simulation/scripts/ConditionalWeight.hpp b/src/openvic-simulation/scripts/ConditionalWeight.hpp index d62fc42a1..5809cd0d9 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.hpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.hpp @@ -9,7 +9,10 @@ namespace OpenVic { enum class conditional_weight_type_t : uint8_t { - BASE, FACTOR_ADD, FACTOR_MUL, TIME + BASE, + FACTOR_ADD, + FACTOR_MUL, + TIME }; constexpr bool conditional_weight_type_is_additive(conditional_weight_type_t type) { @@ -36,9 +39,9 @@ namespace OpenVic { public: ConditionalWeight( - scope_type_t new_initial_scope = scope_type_t::NO_SCOPE, - scope_type_t new_this_scope = scope_type_t::NO_SCOPE, - scope_type_t new_from_scope = scope_type_t::NO_SCOPE + scope_type_t new_initial_scope = scope_type_t::NO_SCOPE, + scope_type_t new_this_scope = scope_type_t::NO_SCOPE, + scope_type_t new_from_scope = scope_type_t::NO_SCOPE ); ConditionalWeight(ConditionalWeight&&) = default; ConditionalWeight& operator=(ConditionalWeight&&) = default; diff --git a/src/openvic-simulation/testing/Requirement.hpp b/src/openvic-simulation/testing/Requirement.hpp index 06332b101..f72ea318b 100644 --- a/src/openvic-simulation/testing/Requirement.hpp +++ b/src/openvic-simulation/testing/Requirement.hpp @@ -1,5 +1,6 @@ #pragma once #include + #include "openvic-simulation/utility/Getters.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/testing/TestScript.cpp b/src/openvic-simulation/testing/TestScript.cpp index 58959918c..dd14e47e5 100644 --- a/src/openvic-simulation/testing/TestScript.cpp +++ b/src/openvic-simulation/testing/TestScript.cpp @@ -60,10 +60,10 @@ void TestScript::add_requirement(memory::unique_ptr&& req) { // Methods void TestScript::pass_or_fail_req_with_actual_and_target_values( - memory::string req_name, memory::string target_value, memory::string actual_value + memory::string req_name, memory::string target_value, memory::string actual_value ) { Requirement* req = get_requirement_by_id(req_name); - if (req == nullptr){ + if (req == nullptr) { return; } req->set_target_value(target_value); diff --git a/src/openvic-simulation/testing/TestScript.hpp b/src/openvic-simulation/testing/TestScript.hpp index 410a533ef..cd6b48362 100644 --- a/src/openvic-simulation/testing/TestScript.hpp +++ b/src/openvic-simulation/testing/TestScript.hpp @@ -1,7 +1,7 @@ #pragma once -#include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/testing/Requirement.hpp" namespace OpenVic { @@ -36,7 +36,7 @@ namespace OpenVic { // Methods void pass_or_fail_req_with_actual_and_target_values( - memory::string req_name, memory::string target_value, memory::string actual_value + memory::string req_name, memory::string target_value, memory::string actual_value ); }; } diff --git a/src/openvic-simulation/testing/Testing.hpp b/src/openvic-simulation/testing/Testing.hpp index 0ec672c59..8117845f9 100644 --- a/src/openvic-simulation/testing/Testing.hpp +++ b/src/openvic-simulation/testing/Testing.hpp @@ -4,16 +4,16 @@ #include +#include "openvic-simulation/DefinitionManager.hpp" #include "openvic-simulation/core/memory/SmartPtr.hpp" #include "openvic-simulation/core/memory/Vector.hpp" -#include "openvic-simulation/DefinitionManager.hpp" +#include "openvic-simulation/testing/TestScript.hpp" #include "openvic-simulation/testing/test_scripts/A_001_file_tests.cpp" #include "openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp" #include "openvic-simulation/testing/test_scripts/A_003_military_unit_tests.cpp" #include "openvic-simulation/testing/test_scripts/A_004_networking_tests.cpp" #include "openvic-simulation/testing/test_scripts/A_005_nation_tests.cpp" #include "openvic-simulation/testing/test_scripts/A_006_politics_tests.cpp" -#include "openvic-simulation/testing/TestScript.hpp" namespace OpenVic { diff --git a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp index dcce879a2..444114132 100644 --- a/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_001_file_tests.cpp @@ -10,112 +10,123 @@ namespace OpenVic { void add_requirements() { memory::unique_ptr FS_44 = memory::make_unique( - "FS_44", - "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename " - "Canned Food.png", - "The icon for the Canned Food good has been loaded into the program" + "FS_44", + "The icon for the Canned Food good shall be loaded from the R/art/economy/goods folder with the filename " + "Canned Food.png", + "The icon for the Canned Food good has been loaded into the program" ); add_requirement(std::move(FS_44)); memory::unique_ptr FS_48 = memory::make_unique( - "FS_48", - "The icon for the Coal good shall be loaded from the R/art/economy/goods folder with the filename Coal.png", - "The icon for the Coal good has been loaded into the program" + "FS_48", + "The icon for the Coal good shall be loaded from the R/art/economy/goods folder with the filename Coal.png", + "The icon for the Coal good has been loaded into the program" ); add_requirement(std::move(FS_48)); memory::unique_ptr FS_61 = memory::make_unique( - "FS_61", - "The icon for the Grain good shall be loaded from the R/art/economy/goods folder with the filename Grain.png", - "The icon for the Grain good has been loaded into the program" + "FS_61", + "The icon for the Grain good shall be loaded from the R/art/economy/goods folder with the filename Grain.png", + "The icon for the Grain good has been loaded into the program" ); add_requirement(std::move(FS_61)); memory::unique_ptr FS_62 = memory::make_unique( - "FS_62", - "The icon for the Iron good shall be loaded from the R/art/economy/goods folder with the filename Iron.png", - "The icon for the Iron good has been loaded into the program" + "FS_62", + "The icon for the Iron good shall be loaded from the R/art/economy/goods folder with the filename Iron.png", + "The icon for the Iron good has been loaded into the program" ); add_requirement(std::move(FS_62)); memory::unique_ptr FS_63 = memory::make_unique( - "FS_63", - "The icon for the Liquor good shall be loaded from the R/art/economy/goods folder with the filename Liquor.png", - "The icon for the Liquor good has been loaded into the program" + "FS_63", + "The icon for the Liquor good shall be loaded from the R/art/economy/goods folder with the filename Liquor.png", + "The icon for the Liquor good has been loaded into the program" ); add_requirement(std::move(FS_63)); memory::unique_ptr FS_67 = memory::make_unique( - "FS_67", - "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename " - "Machine Parts.png", - "The icon for the Machine Parts good has been loaded into the program" + "FS_67", + "The icon for the Machine Parts good shall be loaded from the R/art/economy/goods folder with the filename " + "Machine Parts.png", + "The icon for the Machine Parts good has been loaded into the program" ); add_requirement(std::move(FS_67)); memory::unique_ptr FS_86 = memory::make_unique( - "FS_86", - "The icon for the Wool good shall be loaded from the R/art/economy/goods folder with the filename Wool.png", - "The icon for the Wool good has been loaded into the program" + "FS_86", + "The icon for the Wool good shall be loaded from the R/art/economy/goods folder with the filename Wool.png", + "The icon for the Wool good has been loaded into the program" ); add_requirement(std::move(FS_86)); memory::unique_ptr FS_2 = memory::make_unique( - "FS_2", "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", - "User data is saved to the correct place" + "FS_2", + "User provided data shall be saved to an 'OpenVic' folder, located following platform convention", + "User data is saved to the correct place" ); add_requirement(std::move(FS_2)); memory::unique_ptr FS_20 = memory::make_unique( - "FS_20", "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", - "User data is saved to the correct place" + "FS_20", + "On Windows, user provided data shall be saved by default to '%APPDATA%/OpenVic/'", + "User data is saved to the correct place" ); add_requirement(std::move(FS_20)); memory::unique_ptr FS_21 = memory::make_unique( - "FS_21", "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", - "User data is saved to the correct place" + "FS_21", + "On Linux, user provided data shall be saved by default to '~/.local/share/OpenVic/'", + "User data is saved to the correct place" ); add_requirement(std::move(FS_21)); memory::unique_ptr FS_22 = memory::make_unique( - "FS_22", "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", - "User data is saved to the correct place" + "FS_22", + "On macOS, user provided data shall be saved by default to '~/Library/Application Support/OpenVic/'", + "User data is saved to the correct place" ); add_requirement(std::move(FS_22)); memory::unique_ptr FS_24 = memory::make_unique( - "FS_24", "All .csv files in the locale folder shall contain translation keys and translations", - "No errant files in locale directory" + "FS_24", + "All .csv files in the locale folder shall contain translation keys and translations", + "No errant files in locale directory" ); add_requirement(std::move(FS_24)); memory::unique_ptr FS_17 = memory::make_unique( - "FS_17", "List of available locales are loaded from R/localisation/ directory", "Locales loaded correctly" + "FS_17", "List of available locales are loaded from R/localisation/ directory", "Locales loaded correctly" ); add_requirement(std::move(FS_17)); memory::unique_ptr FS_333 = memory::make_unique( - "FS_333", "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", - "The unique colours of 'R/map/provinces.bmp' define provinces" + "FS_333", + "The map's provinces shall be defined by unique colours in 'R/map/provinces.bmp'", + "The unique colours of 'R/map/provinces.bmp' define provinces" ); add_requirement(std::move(FS_333)); memory::unique_ptr FS_335 = memory::make_unique( - "FS_335", "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", - "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID" + "FS_335", + "Unique province IDs shall be associated with their unique colours in 'R/map/definition.csv'", + "'R/map/definition.csv' associates every unique colour used to define a province with a unique ID" ); add_requirement(std::move(FS_335)); memory::unique_ptr FS_334 = memory::make_unique( - "FS_334", "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", - "'R/map/default.map' contains a list of province IDs which are used to define water provinces" + "FS_334", + "Water provinces shall be defined by a list of their IDs in 'R/map/default.map'", + "'R/map/default.map' contains a list of province IDs which are used to define water provinces" ); add_requirement(std::move(FS_334)); memory::unique_ptr FS_338 = memory::make_unique( - "FS_338", - "The image for the minimap background shall be loaded from the R/art/ui folder with the filename minimap.png", - "The image for the minimap background has been loaded into the program" + "FS_338", + "The image for the minimap background shall be loaded from the R/art/ui folder with the filename minimap.png", + "The image for the minimap background has been loaded into the program" ); add_requirement(std::move(FS_338)); memory::unique_ptr FS_343 = memory::make_unique( - "FS_343", "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", - "The textures making up the cosmetic terrain map have been loaded into the program" + "FS_343", + "The textures making up the cosmetic terrain map shall be loaded from the R/art/terrain folder", + "The textures making up the cosmetic terrain map have been loaded into the program" ); add_requirement(std::move(FS_343)); memory::unique_ptr FS_341 = memory::make_unique( - "FS_341", "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", - "'R/map/region.txt' defines state areas with lists of province IDs" + "FS_341", + "State areas shall be defined by lists of province IDs in 'R/map/region.txt'", + "'R/map/region.txt' defines state areas with lists of province IDs" ); add_requirement(std::move(FS_341)); memory::unique_ptr SND_10 = memory::make_unique( - "SND_10", "SFX shall be referred to by their filename, without the extension", - "Sound effects are identified by their filename without extension" + "SND_10", + "SFX shall be referred to by their filename, without the extension", + "Sound effects are identified by their filename without extension" ); add_requirement(std::move(SND_10)); } diff --git a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp index 0aa33c4d5..f94612590 100644 --- a/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp +++ b/src/openvic-simulation/testing/test_scripts/A_002_economy_tests.cpp @@ -11,243 +11,291 @@ namespace OpenVic { void add_requirements() { memory::unique_ptr ECON_123 = memory::make_unique( - "ECON_123", "The base price for Aeroplanes shall be 110", - "The base price of 110 for Aeroplanes can be seen in program output data" + "ECON_123", + "The base price for Aeroplanes shall be 110", + "The base price of 110 for Aeroplanes can be seen in program output data" ); add_requirement(std::move(ECON_123)); memory::unique_ptr ECON_124 = memory::make_unique( - "ECON_124", "The base price for Ammunition shall be 17.5", - "The base price of 17.5 for Ammunition can be seen in program output data" + "ECON_124", + "The base price for Ammunition shall be 17.5", + "The base price of 17.5 for Ammunition can be seen in program output data" ); add_requirement(std::move(ECON_124)); memory::unique_ptr ECON_125 = memory::make_unique( - "ECON_125", "The base price for Artillery shall be 60", - "The base price of 60 for Artillery can be seen in program output data" + "ECON_125", + "The base price for Artillery shall be 60", + "The base price of 60 for Artillery can be seen in program output data" ); add_requirement(std::move(ECON_125)); memory::unique_ptr ECON_126 = memory::make_unique( - "ECON_126", "The base price for Automobiles shall be 70", - "The base price of 70 for Automobiles can be seen in program output data" + "ECON_126", + "The base price for Automobiles shall be 70", + "The base price of 70 for Automobiles can be seen in program output data" ); add_requirement(std::move(ECON_126)); memory::unique_ptr ECON_127 = memory::make_unique( - "ECON_127", "The base price for Canned Food shall be 16", - "The base price of 16 for Canned Food can be seen in program output data" + "ECON_127", + "The base price for Canned Food shall be 16", + "The base price of 16 for Canned Food can be seen in program output data" ); add_requirement(std::move(ECON_127)); memory::unique_ptr ECON_128 = memory::make_unique( - "ECON_128", "The base price for Cattle shall be 2", - "The base price of 2 for Cattle can be seen in program output data" + "ECON_128", + "The base price for Cattle shall be 2", + "The base price of 2 for Cattle can be seen in program output data" ); add_requirement(std::move(ECON_128)); memory::unique_ptr ECON_129 = memory::make_unique( - "ECON_129", "The base price for Cement shall be 16", - "The base price of 16 for Cement can be seen in program output data" + "ECON_129", + "The base price for Cement shall be 16", + "The base price of 16 for Cement can be seen in program output data" ); add_requirement(std::move(ECON_129)); memory::unique_ptr ECON_130 = memory::make_unique( - "ECON_130", "The base price for Clipper Convoys shall be 42", - "The base price of 42 for Clipper Convoys can be seen in program output data" + "ECON_130", + "The base price for Clipper Convoys shall be 42", + "The base price of 42 for Clipper Convoys can be seen in program output data" ); add_requirement(std::move(ECON_130)); memory::unique_ptr ECON_131 = memory::make_unique( - "ECON_131", "The base price for Coal shall be 2.3", - "The base price of 2.3 for Coal can be seen in program output data" + "ECON_131", + "The base price for Coal shall be 2.3", + "The base price of 2.3 for Coal can be seen in program output data" ); add_requirement(std::move(ECON_131)); memory::unique_ptr ECON_132 = memory::make_unique( - "ECON_132", "The base price for Coffee shall be 2.1", - "The base price of 2.1 for Coffee can be seen in program output data" + "ECON_132", + "The base price for Coffee shall be 2.1", + "The base price of 2.1 for Coffee can be seen in program output data" ); add_requirement(std::move(ECON_132)); memory::unique_ptr ECON_133 = memory::make_unique( - "ECON_133", "The base price for Cotton shall be 2", - "The base price of 2 for Cotton can be seen in program output data" + "ECON_133", + "The base price for Cotton shall be 2", + "The base price of 2 for Cotton can be seen in program output data" ); add_requirement(std::move(ECON_133)); memory::unique_ptr ECON_134 = memory::make_unique( - "ECON_134", "The base price for Dye shall be 12", - "The base price of 12 for Dye can be seen in program output data" + "ECON_134", + "The base price for Dye shall be 12", + "The base price of 12 for Dye can be seen in program output data" ); add_requirement(std::move(ECON_134)); memory::unique_ptr ECON_135 = memory::make_unique( - "ECON_135", "The base price for Electric Gear shall be 16", - "The base price of 16 for Electric Gear can be seen in program output data" + "ECON_135", + "The base price for Electric Gear shall be 16", + "The base price of 16 for Electric Gear can be seen in program output data" ); add_requirement(std::move(ECON_135)); memory::unique_ptr ECON_136 = memory::make_unique( - "ECON_136", "The base price for Explosives shall be 20", - "The base price of 20 for Explosives can be seen in program output data" + "ECON_136", + "The base price for Explosives shall be 20", + "The base price of 20 for Explosives can be seen in program output data" ); add_requirement(std::move(ECON_136)); memory::unique_ptr ECON_137 = memory::make_unique( - "ECON_137", "The base price for Fabric shall be 1.8", - "The base price of 1.8 for Fabric can be seen in program output data" + "ECON_137", + "The base price for Fabric shall be 1.8", + "The base price of 1.8 for Fabric can be seen in program output data" ); add_requirement(std::move(ECON_137)); memory::unique_ptr ECON_138 = memory::make_unique( - "ECON_138", "The base price for Fertilizer shall be 10", - "The base price of 10 for Fertilizer can be seen in program output data" + "ECON_138", + "The base price for Fertilizer shall be 10", + "The base price of 10 for Fertilizer can be seen in program output data" ); add_requirement(std::move(ECON_138)); memory::unique_ptr ECON_139 = memory::make_unique( - "ECON_139", "The base price for Fish shall be 1.5", - "The base price of 1.5 for Fish can be seen in program output data" + "ECON_139", + "The base price for Fish shall be 1.5", + "The base price of 1.5 for Fish can be seen in program output data" ); add_requirement(std::move(ECON_139)); memory::unique_ptr ECON_140 = memory::make_unique( - "ECON_140", "The base price for Fruit shall be 1.8", - "The base price of 1.8 for Fruit can be seen in program output data" + "ECON_140", + "The base price for Fruit shall be 1.8", + "The base price of 1.8 for Fruit can be seen in program output data" ); add_requirement(std::move(ECON_140)); memory::unique_ptr ECON_141 = memory::make_unique( - "ECON_141", "The base price for Fuel shall be 25", - "The base price of 25 for Fuel can be seen in program output data" + "ECON_141", + "The base price for Fuel shall be 25", + "The base price of 25 for Fuel can be seen in program output data" ); add_requirement(std::move(ECON_141)); memory::unique_ptr ECON_142 = memory::make_unique( - "ECON_142", "The base price for Furniture shall be 4.9", - "The base price of 4.9 for Furniture can be seen in program output data" + "ECON_142", + "The base price for Furniture shall be 4.9", + "The base price of 4.9 for Furniture can be seen in program output data" ); add_requirement(std::move(ECON_142)); memory::unique_ptr ECON_234 = memory::make_unique( - "ECON_234", "The base price for Glass shall be 2.9", - "The base price of 2.9 for Glass can be seen in program output data" + "ECON_234", + "The base price for Glass shall be 2.9", + "The base price of 2.9 for Glass can be seen in program output data" ); add_requirement(std::move(ECON_234)); memory::unique_ptr ECON_235 = memory::make_unique( - "ECON_235", "The base price for Grain shall be 2.2", - "The base price of 2.2 for Grain can be seen in program output data" + "ECON_235", + "The base price for Grain shall be 2.2", + "The base price of 2.2 for Grain can be seen in program output data" ); add_requirement(std::move(ECON_235)); memory::unique_ptr ECON_236 = memory::make_unique( - "ECON_236", "The base price for Iron shall be 3.5", - "The base price of 3.5 for Iron can be seen in program output data" + "ECON_236", + "The base price for Iron shall be 3.5", + "The base price of 3.5 for Iron can be seen in program output data" ); add_requirement(std::move(ECON_236)); memory::unique_ptr ECON_237 = memory::make_unique( - "ECON_237", "The base price for Liquor shall be 6.4", - "The base price of 6.4 for Liquor can be seen in program output data" + "ECON_237", + "The base price for Liquor shall be 6.4", + "The base price of 6.4 for Liquor can be seen in program output data" ); add_requirement(std::move(ECON_237)); memory::unique_ptr ECON_238 = memory::make_unique( - "ECON_238", "The base price for Lumber shall be 1", - "The base price of 1 for Lumber can be seen in program output data" + "ECON_238", + "The base price for Lumber shall be 1", + "The base price of 1 for Lumber can be seen in program output data" ); add_requirement(std::move(ECON_238)); memory::unique_ptr ECON_239 = memory::make_unique( - "ECON_239", "The base price for Luxury Clothes shall be 65", - "The base price of 65 for Luxury Clothes can be seen in program output data" + "ECON_239", + "The base price for Luxury Clothes shall be 65", + "The base price of 65 for Luxury Clothes can be seen in program output data" ); add_requirement(std::move(ECON_239)); memory::unique_ptr ECON_240 = memory::make_unique( - "ECON_240", "The base price for Luxury Furniture shall be 59", - "The base price of 59 for Luxury Furniture can be seen in program output data" + "ECON_240", + "The base price for Luxury Furniture shall be 59", + "The base price of 59 for Luxury Furniture can be seen in program output data" ); add_requirement(std::move(ECON_240)); memory::unique_ptr ECON_241 = memory::make_unique( - "ECON_241", "The base price for Machine Parts shall be 36.5", - "The base price of 36.5 for Machine Parts can be seen in program output data" + "ECON_241", + "The base price for Machine Parts shall be 36.5", + "The base price of 36.5 for Machine Parts can be seen in program output data" ); add_requirement(std::move(ECON_241)); memory::unique_ptr ECON_242 = memory::make_unique( - "ECON_242", "The base price for Oil shall be 12", - "The base price of 12 for Oil can be seen in program output data" + "ECON_242", + "The base price for Oil shall be 12", + "The base price of 12 for Oil can be seen in program output data" ); add_requirement(std::move(ECON_242)); memory::unique_ptr ECON_243 = memory::make_unique( - "ECON_243", "The base price for Opium shall be 3.2", - "The base price of 3.2 for Opium can be seen in program output data" + "ECON_243", + "The base price for Opium shall be 3.2", + "The base price of 3.2 for Opium can be seen in program output data" ); add_requirement(std::move(ECON_243)); memory::unique_ptr ECON_244 = memory::make_unique( - "ECON_244", "The base price for Paper shall be 3.4", - "The base price of 3.4 for Paper can be seen in program output data" + "ECON_244", + "The base price for Paper shall be 3.4", + "The base price of 3.4 for Paper can be seen in program output data" ); add_requirement(std::move(ECON_244)); memory::unique_ptr ECON_245 = memory::make_unique( - "ECON_245", "The base price for Precious Metal shall be 8", - "The base price of 8 for Precious Metal can be seen in program output data" + "ECON_245", + "The base price for Precious Metal shall be 8", + "The base price of 8 for Precious Metal can be seen in program output data" ); add_requirement(std::move(ECON_245)); memory::unique_ptr ECON_246 = memory::make_unique( - "ECON_246", "The base price for Radios shall be 16", - "The base price of 16 for Radios can be seen in program output data" + "ECON_246", + "The base price for Radios shall be 16", + "The base price of 16 for Radios can be seen in program output data" ); add_requirement(std::move(ECON_246)); memory::unique_ptr ECON_247 = memory::make_unique( - "ECON_247", "The base price for Regular Clothes shall be 5.8", - "The base price of 5.8 for Regular Clothes can be seen in program output data" + "ECON_247", + "The base price for Regular Clothes shall be 5.8", + "The base price of 5.8 for Regular Clothes can be seen in program output data" ); add_requirement(std::move(ECON_247)); memory::unique_ptr ECON_248 = memory::make_unique( - "ECON_248", "The base price for Rubber shall be 7", - "The base price of 7 for Rubber can be seen in program output data" + "ECON_248", + "The base price for Rubber shall be 7", + "The base price of 7 for Rubber can be seen in program output data" ); add_requirement(std::move(ECON_248)); memory::unique_ptr ECON_249 = memory::make_unique( - "ECON_249", "The base price for Silk shall be 10", - "The base price of 10 for Silk can be seen in program output data" + "ECON_249", + "The base price for Silk shall be 10", + "The base price of 10 for Silk can be seen in program output data" ); add_requirement(std::move(ECON_249)); memory::unique_ptr ECON_250 = memory::make_unique( - "ECON_250", "The base price for Small Arms shall be 37", - "The base price of 37 for Small Arms can be seen in program output data" + "ECON_250", + "The base price for Small Arms shall be 37", + "The base price of 37 for Small Arms can be seen in program output data" ); add_requirement(std::move(ECON_250)); memory::unique_ptr ECON_251 = memory::make_unique( - "ECON_251", "The base price for Steamer Convoys shall be 65", - "The base price of 65 for Steamer Convoys can be seen in program output data" + "ECON_251", + "The base price for Steamer Convoys shall be 65", + "The base price of 65 for Steamer Convoys can be seen in program output data" ); add_requirement(std::move(ECON_251)); memory::unique_ptr ECON_252 = memory::make_unique( - "ECON_252", "The base price for Steel shall be 4.7", - "The base price of 4.7 for Steel can be seen in program output data" + "ECON_252", + "The base price for Steel shall be 4.7", + "The base price of 4.7 for Steel can be seen in program output data" ); add_requirement(std::move(ECON_252)); memory::unique_ptr ECON_253 = memory::make_unique( - "ECON_253", "The base price for Sulphur shall be 6", - "The base price of 6 for Sulphur can be seen in program output data" + "ECON_253", + "The base price for Sulphur shall be 6", + "The base price of 6 for Sulphur can be seen in program output data" ); add_requirement(std::move(ECON_253)); memory::unique_ptr ECON_254 = memory::make_unique( - "ECON_254", "The base price for Tanks shall be 98", - "The base price of 98 for Tanks can be seen in program output data" + "ECON_254", + "The base price for Tanks shall be 98", + "The base price of 98 for Tanks can be seen in program output data" ); add_requirement(std::move(ECON_254)); memory::unique_ptr ECON_255 = memory::make_unique( - "ECON_255", "The base price for Tea shall be 2.6", - "The base price of 2.6 for Tea can be seen in program output data" + "ECON_255", + "The base price for Tea shall be 2.6", + "The base price of 2.6 for Tea can be seen in program output data" ); add_requirement(std::move(ECON_255)); memory::unique_ptr ECON_256 = memory::make_unique( - "ECON_256", "The base price for Telephones shall be 16", - "The base price of 16 for Telephones can be seen in program output data" + "ECON_256", + "The base price for Telephones shall be 16", + "The base price of 16 for Telephones can be seen in program output data" ); add_requirement(std::move(ECON_256)); memory::unique_ptr ECON_257 = memory::make_unique( - "ECON_257", "The base price for Timber shall be 0.9", - "The base price of 0.9 for Timber can be seen in program output data" + "ECON_257", + "The base price for Timber shall be 0.9", + "The base price of 0.9 for Timber can be seen in program output data" ); add_requirement(std::move(ECON_257)); memory::unique_ptr ECON_258 = memory::make_unique( - "ECON_258", "The base price for Tobacco shall be 1.1", - "The base price of 1.1 for Tobacco can be seen in program output data" + "ECON_258", + "The base price for Tobacco shall be 1.1", + "The base price of 1.1 for Tobacco can be seen in program output data" ); add_requirement(std::move(ECON_258)); memory::unique_ptr ECON_259 = memory::make_unique( - "ECON_259", "The base price for Tropical Wood shall be 5.4", - "The base price of 5.4 for Tropical Wood can be seen in program output data" + "ECON_259", + "The base price for Tropical Wood shall be 5.4", + "The base price of 5.4 for Tropical Wood can be seen in program output data" ); add_requirement(std::move(ECON_259)); memory::unique_ptr ECON_260 = memory::make_unique( - "ECON_260", "The base price for Wine shall be 9.7", - "The base price of 9.7 for Wine can be seen in program output data" + "ECON_260", + "The base price for Wine shall be 9.7", + "The base price of 9.7 for Wine can be seen in program output data" ); add_requirement(std::move(ECON_260)); memory::unique_ptr ECON_261 = memory::make_unique( - "ECON_261", "The base price for Wool shall be 0.7", - "The base price of 0.7 for Wool can be seen in program output data" + "ECON_261", + "The base price for Wool shall be 0.7", + "The base price of 0.7 for Wool can be seen in program output data" ); add_requirement(std::move(ECON_261)); } @@ -552,11 +600,12 @@ namespace OpenVic { void check_base_price(memory::string identifier, memory::string target_value, memory::string req_name) { // Get string of base_price from goods manager - fixed_point_t base_price_fp = get_definition_manager() - ->get_economy_manager() - .get_good_definition_manager() - .get_good_definition_by_identifier(identifier) - ->base_price; + fixed_point_t base_price_fp = + get_definition_manager() + ->get_economy_manager() + .get_good_definition_manager() + .get_good_definition_by_identifier(identifier) + ->base_price; memory::string base_price = memory::fmt::format("{:.1f}", base_price_fp); // Perform req checks diff --git a/src/openvic-simulation/types/ClampedValue.hpp b/src/openvic-simulation/types/ClampedValue.hpp index 4427f9bc1..b9b690bba 100644 --- a/src/openvic-simulation/types/ClampedValue.hpp +++ b/src/openvic-simulation/types/ClampedValue.hpp @@ -13,20 +13,14 @@ namespace OpenVic { fixed_point_t PROPERTY_ACCESS(max, protected); OV_STATE_PROPERTY_ACCESS(fixed_point_t, value, protected); constexpr ReadOnlyClampedValue() {}; - ReadOnlyClampedValue( - const fixed_point_t new_min, - const fixed_point_t new_max - ) : min { new_min }, max { new_max } {}; + ReadOnlyClampedValue(const fixed_point_t new_min, const fixed_point_t new_max) : min { new_min }, max { new_max } {}; }; struct ClampedValue : public ReadOnlyClampedValue { public: constexpr ClampedValue() {}; - ClampedValue( - const fixed_point_t new_min, - const fixed_point_t new_max, - const fixed_point_t new_value - ) : ReadOnlyClampedValue(new_min, new_max) { + ClampedValue(const fixed_point_t new_min, const fixed_point_t new_max, const fixed_point_t new_value) : + ReadOnlyClampedValue(new_min, new_max) { set_value(new_value); }; diff --git a/src/openvic-simulation/types/ColonyStatus.hpp b/src/openvic-simulation/types/ColonyStatus.hpp index 5746ad23d..5345736f7 100644 --- a/src/openvic-simulation/types/ColonyStatus.hpp +++ b/src/openvic-simulation/types/ColonyStatus.hpp @@ -3,10 +3,14 @@ #include namespace OpenVic { - enum struct colony_status_t : uint8_t { STATE, PROTECTORATE, COLONY }; + enum struct colony_status_t : uint8_t { + STATE, + PROTECTORATE, + COLONY + }; // This combines COLONY and PROTECTORATE statuses, as opposed to non-colonial STATE provinces static constexpr bool is_colonial(colony_status_t colony_status) { return colony_status != colony_status_t::STATE; } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/ConstructorTags.hpp b/src/openvic-simulation/types/ConstructorTags.hpp index ec44c81b1..4c855cd5e 100644 --- a/src/openvic-simulation/types/ConstructorTags.hpp +++ b/src/openvic-simulation/types/ConstructorTags.hpp @@ -1,8 +1,8 @@ #pragma once namespace OpenVic { - struct create_empty_t { }; + struct create_empty_t {}; static constexpr create_empty_t create_empty {}; - struct generate_values_t { }; + struct generate_values_t {}; static constexpr generate_values_t generate_values {}; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/FlagStrings.cpp b/src/openvic-simulation/types/FlagStrings.cpp index 72d3b7b0a..1e4f2f296 100644 --- a/src/openvic-simulation/types/FlagStrings.cpp +++ b/src/openvic-simulation/types/FlagStrings.cpp @@ -13,10 +13,7 @@ bool FlagStrings::set_flag(std::string_view flag, bool warn) { } if (!flags.emplace(flag).second && warn) { - spdlog::warn_s( - "Attempted to set {} flag \"{}\": already set!", - name, flag - ); + spdlog::warn_s("Attempted to set {} flag \"{}\": already set!", name, flag); } return true; @@ -29,10 +26,7 @@ bool FlagStrings::clear_flag(std::string_view flag, bool warn) { } if (flags.erase(flag) == 0 && warn) { - spdlog::warn_s( - "Attempted to clear {} flag \"{}\": not set!", - name, flag - ); + spdlog::warn_s("Attempted to clear {} flag \"{}\": not set!", name, flag); } return true; diff --git a/src/openvic-simulation/types/HasIdentifier.hpp b/src/openvic-simulation/types/HasIdentifier.hpp index bac34ff32..f25df205e 100644 --- a/src/openvic-simulation/types/HasIdentifier.hpp +++ b/src/openvic-simulation/types/HasIdentifier.hpp @@ -23,7 +23,7 @@ namespace OpenVic { memory::string PROPERTY(identifier); protected: - HasIdentifier(std::string_view new_identifier): identifier { new_identifier } { + HasIdentifier(std::string_view new_identifier) : identifier { new_identifier } { assert(!identifier.empty()); } HasIdentifier(HasIdentifier const&) = default; @@ -33,16 +33,16 @@ namespace OpenVic { HasIdentifier& operator=(HasIdentifier const&) = delete; HasIdentifier& operator=(HasIdentifier&&) = delete; - template T, std::convertible_to U> - requires (!has_index) + template T, std::convertible_to U> + requires(!has_index) friend bool operator==(T const& lhs, U const& rhs) { return lhs.get_identifier() == static_cast(rhs).get_identifier(); } - template - requires specialization_of, std::reference_wrapper> - && std::derived_from::type, HasIdentifier> - && equalable::type const&, U> + template + requires specialization_of, std::reference_wrapper> && + std::derived_from::type, HasIdentifier> && + equalable::type const&, U> friend bool operator==(T const& lhs, U const& rhs) { return lhs.get() == rhs; } @@ -63,7 +63,7 @@ namespace OpenVic { const ColourT PROPERTY(colour); protected: - _HasColour(ColourT new_colour, bool cannot_be_null): colour { new_colour } { + _HasColour(ColourT new_colour, bool cannot_be_null) : colour { new_colour } { assert(!cannot_be_null || !colour.is_null()); } _HasColour(_HasColour const&) = default; @@ -83,8 +83,8 @@ namespace OpenVic { template class _HasIdentifierAndColour : public HasIdentifier, public _HasColour { protected: - _HasIdentifierAndColour(std::string_view new_identifier, ColourT new_colour, bool cannot_be_null) - : HasIdentifier { new_identifier }, _HasColour { new_colour, cannot_be_null } {} + _HasIdentifierAndColour(std::string_view new_identifier, ColourT new_colour, bool cannot_be_null) : + HasIdentifier { new_identifier }, _HasColour { new_colour, cannot_be_null } {} _HasIdentifierAndColour(_HasIdentifierAndColour const&) = default; public: @@ -98,7 +98,7 @@ namespace OpenVic { } template -requires (!OpenVic::has_get_name) +requires(!OpenVic::has_get_name) struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(T const& has_id, fmt::format_context& ctx) const { return fmt::formatter::format(has_id.get_identifier(), ctx); @@ -106,7 +106,7 @@ struct fmt::formatter : fmt::formatter { }; template -requires (!OpenVic::has_get_identifier) +requires(!OpenVic::has_get_identifier) struct fmt::formatter : fmt::formatter { fmt::format_context::iterator format(T const& has_id, fmt::format_context& ctx) const { return fmt::formatter::format(has_id.get_name(), ctx); @@ -115,20 +115,20 @@ struct fmt::formatter : fmt::formatter { namespace std { template - requires (!OpenVic::has_index) + requires(!OpenVic::has_index) struct hash { [[nodiscard]] std::size_t operator()(T const& obj) const noexcept { - return std::hash{}(obj.get_identifier()); + return std::hash {}(obj.get_identifier()); } }; } namespace std { template - requires (!OpenVic::has_index) + requires(!OpenVic::has_index) struct hash> { [[nodiscard]] std::size_t operator()(std::remove_const_t const& obj) const noexcept { - return std::hash{}(obj.get_identifier()); + return std::hash {}(obj.get_identifier()); } }; } diff --git a/src/openvic-simulation/types/HasIndex.hpp b/src/openvic-simulation/types/HasIndex.hpp index 358f3b8b5..8fe4d7cc2 100644 --- a/src/openvic-simulation/types/HasIndex.hpp +++ b/src/openvic-simulation/types/HasIndex.hpp @@ -37,7 +37,7 @@ namespace std { requires OpenVic::derived_from_specialization_of, OpenVic::HasIndex> struct hash { [[nodiscard]] std::size_t operator()(T const& obj) const noexcept { - return std::hash::index_t>{}(obj.index); + return std::hash::index_t> {}(obj.index); } }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/IdentifierRegistry.hpp b/src/openvic-simulation/types/IdentifierRegistry.hpp index 2464f242c..53b7a4480 100644 --- a/src/openvic-simulation/types/IdentifierRegistry.hpp +++ b/src/openvic-simulation/types/IdentifierRegistry.hpp @@ -3,9 +3,9 @@ #include #include "openvic-simulation/core/memory/SmartPtr.hpp" +#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/dataloader/NodeTools.hpp" #include "openvic-simulation/types/fixed_point/FixedPointMap.hpp" -#include "openvic-simulation/core/template/Concepts.hpp" #include "openvic-simulation/utility/Getters.hpp" #include "openvic-simulation/utility/Logger.hpp" @@ -13,15 +13,17 @@ namespace OpenVic { /* Callbacks for trying to add duplicate keys via UniqueKeyRegistry::add_item */ static bool duplicate_fail_callback(std::string_view registry_name, std::string_view duplicate_identifier) { spdlog::error_s( - "Failure adding item to the {} registry - an item with the identifier \"{}\" already exists!", - registry_name, duplicate_identifier + "Failure adding item to the {} registry - an item with the identifier \"{}\" already exists!", + registry_name, + duplicate_identifier ); return false; } static bool duplicate_warning_callback(std::string_view registry_name, std::string_view duplicate_identifier) { spdlog::warn_s( - "Warning adding item to the {} registry - an item with the identifier \"{}\" already exists!", - registry_name, duplicate_identifier + "Warning adding item to the {} registry - an item with the identifier \"{}\" already exists!", + registry_name, + duplicate_identifier ); return true; } @@ -32,7 +34,7 @@ namespace OpenVic { /* Registry Value Info - the type that is being registered, and a unique identifier string getter. */ template concept RegistryValueInfo = requires( - typename ValueInfo::internal_value_type& item, typename ValueInfo::internal_value_type const& const_item + typename ValueInfo::internal_value_type& item, typename ValueInfo::internal_value_type const& const_item ) { { ValueInfo::get_identifier(item) } -> std::same_as; { ValueInfo::get_external_value(item) } -> std::same_as; @@ -72,7 +74,7 @@ namespace OpenVic { /* Registry Item Info - how individual elements of the registered type are stored, and type from item getters. */ template typename ItemInfo, typename Value> concept RegistryItemInfo = requires( - typename ItemInfo::item_type& item, typename ItemInfo::item_type const& const_item + typename ItemInfo::item_type& item, typename ItemInfo::item_type const& const_item ) { { ItemInfo::get_value(item) } -> std::same_as; { ItemInfo::get_value(const_item) } -> std::same_as; @@ -114,15 +116,16 @@ namespace OpenVic { /* Registry Storage Info - how items are stored and indexed, and item-index conversion functions. */ template typename StorageInfo, typename Item> concept RegistryStorageInfo = - std::same_as::storage_type::value_type, Item> && - requires( - typename StorageInfo::storage_type& items, typename StorageInfo::storage_type const& const_items, - typename StorageInfo::index_type index - ) { - { StorageInfo::get_back_index(items) } -> std::same_as::index_type>; - { StorageInfo::get_item_from_index(items, index) } -> std::same_as; - { StorageInfo::get_item_from_index(const_items, index) } -> std::same_as; - }; + std::same_as::storage_type::value_type, Item> && + requires( + typename StorageInfo::storage_type& items, + typename StorageInfo::storage_type const& const_items, + typename StorageInfo::index_type index + ) { + { StorageInfo::get_back_index(items) } -> std::same_as::index_type>; + { StorageInfo::get_item_from_index(items, index) } -> std::same_as; + { StorageInfo::get_item_from_index(const_items, index) } -> std::same_as; + }; template struct RegistryStorageInfoVector { using storage_type = memory::vector; @@ -155,14 +158,15 @@ namespace OpenVic { }; template< - RegistryValueInfo ValueInfo, /* The type that is being registered and that has unique string identifiers */ - template typename _ItemInfo, /* How the type is being stored, usually either by value or std::unique_ptr */ - template typename _StorageInfo = RegistryStorageInfoVector, /* How items are stored, including indexing type */ - string_map_case Case = StringMapCaseSensitive /* Identifier map parameters */ - > + RegistryValueInfo ValueInfo, /* The type that is being registered and that has unique string identifiers */ + template typename _ItemInfo, /* How the type is being stored, usually either by value or std::unique_ptr */ + template typename _StorageInfo = RegistryStorageInfoVector, /* How items are stored, including indexing type + */ + string_map_case Case = StringMapCaseSensitive /* Identifier map parameters */ + > requires( - RegistryItemInfo<_ItemInfo, typename ValueInfo::internal_value_type> && - RegistryStorageInfo<_StorageInfo, typename _ItemInfo::item_type> + RegistryItemInfo<_ItemInfo, typename ValueInfo::internal_value_type> && + RegistryStorageInfo<_StorageInfo, typename _ItemInfo::item_type> ) class UniqueKeyRegistry { public: @@ -194,22 +198,21 @@ namespace OpenVic { /* Get item's identifier via index rather than using new_identifier, as it may have been invalidated item's move. */ identifier_index_map.emplace( - ValueInfo::get_identifier(ItemInfo::get_value(StorageInfo::get_item_from_index(items, index))), - StorageInfo::get_back_index(items) + ValueInfo::get_identifier(ItemInfo::get_value(StorageInfo::get_item_from_index(items, index))), + StorageInfo::get_back_index(items) ); } public: - constexpr UniqueKeyRegistry(std::string_view new_name, bool new_log_lock = true) - : name { new_name }, log_lock { new_log_lock } {} + constexpr UniqueKeyRegistry(std::string_view new_name, bool new_log_lock = true) : + name { new_name }, log_lock { new_log_lock } {} constexpr bool emplace_via_move(item_type&& item) { return emplace_via_move(std::move(item), duplicate_fail_callback); } constexpr bool emplace_via_move( - item_type&& item, - NodeTools::Callback auto duplicate_callback + item_type&& item, NodeTools::Callback auto duplicate_callback ) { if (locked) { spdlog::error_s("Cannot add item to the {} registry - locked!", name); @@ -228,9 +231,9 @@ namespace OpenVic { template constexpr bool emplace_item( - const std::string_view new_identifier, - NodeTools::Callback auto duplicate_callback, - Args&&... args + const std::string_view new_identifier, + NodeTools::Callback auto duplicate_callback, + Args&&... args ) { if (locked) { spdlog::error_s("Cannot add item to the {} registry - locked!", name); @@ -245,19 +248,13 @@ namespace OpenVic { emplace_identifier_index(); return true; } - + constexpr bool emplace_via_copy(item_type const& item_to_copy) { - return emplace_item( - ValueInfo::get_identifier(ItemInfo::get_value(item_to_copy)), - item_to_copy - ); + return emplace_item(ValueInfo::get_identifier(ItemInfo::get_value(item_to_copy)), item_to_copy); } template - constexpr bool emplace_item( - const std::string_view new_identifier, - Args&&... args - ) { + constexpr bool emplace_item(const std::string_view new_identifier, Args&&... args) { return emplace_item(new_identifier, duplicate_fail_callback, std::forward(args)...); } @@ -298,19 +295,13 @@ namespace OpenVic { constexpr void reserve(std::size_t size) { if constexpr (storage_type_reservable) { if (locked) { - spdlog::error_s( - "Failed to reserve space for {} items in {} registry - already locked!", - size, name - ); + spdlog::error_s("Failed to reserve space for {} items in {} registry - already locked!", size, name); } else { items.reserve(size); identifier_index_map.reserve(size); } } else { - spdlog::error_s( - "Cannot reserve space for {} {} - storage_type not reservable!", - size, name - ); + spdlog::error_s("Cannot reserve space for {} {} - storage_type not reservable!", size, name); } } @@ -336,7 +327,7 @@ namespace OpenVic { const typename decltype(identifier_index_map)::const_iterator it = identifier_index_map.find(identifier); \ if (it != identifier_index_map.end()) { \ return std::addressof( \ - ValueInfo::get_external_value(ItemInfo::get_value(StorageInfo::get_item_from_index(items, it->second))) \ + ValueInfo::get_external_value(ItemInfo::get_value(StorageInfo::get_item_from_index(items, it->second))) \ ); \ } \ return nullptr; \ @@ -353,8 +344,7 @@ namespace OpenVic { return reinterpret_cast(item); \ } \ spdlog::error_s( \ - "Invalid type for item \"{}\": {} (expected {})", \ - identifier, item->get_type(), T::get_type_static() \ + "Invalid type for item \"{}\": {} (expected {})", identifier, item->get_type(), T::get_type_static() \ ); \ } \ return nullptr; \ @@ -367,17 +357,14 @@ namespace OpenVic { return std::addressof(ValueInfo::get_external_value(ItemInfo::get_value(items[index]))); \ } \ constexpr NodeTools::Callback auto expect_item_str( \ - NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ + NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ ) CONST { \ return [this, callback, allow_empty, warn](std::string_view identifier) -> bool { \ if (identifier.empty()) { \ if (allow_empty) { \ return true; \ } else { \ - spdlog::log_s( \ - warn ? spdlog::level::warn : spdlog::level::err, \ - "Invalid {} identifier: empty!", name \ - ); \ + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Invalid {} identifier: empty!", name); \ return warn; \ } \ } \ @@ -385,125 +372,105 @@ namespace OpenVic { if (item != nullptr) { \ return callback(*item); \ } \ - spdlog::log_s( \ - warn ? spdlog::level::warn : spdlog::level::err, \ - "Invalid {} identifier: {}", name, identifier \ - ); \ + spdlog::log_s(warn ? spdlog::level::warn : spdlog::level::err, "Invalid {} identifier: {}", name, identifier); \ return warn; \ }; \ } \ constexpr NodeTools::NodeCallback auto expect_item_identifier( \ - NodeTools::Callback auto callback, bool warn = false \ + NodeTools::Callback auto callback, bool warn = false \ ) CONST { \ return NodeTools::expect_identifier(expect_item_str(callback, false, warn)); \ } \ constexpr NodeTools::NodeCallback auto expect_item_string( \ - NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ + NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ ) CONST { \ return NodeTools::expect_string(expect_item_str(callback, allow_empty, warn), allow_empty); \ } \ constexpr NodeTools::NodeCallback auto expect_item_identifier_or_string( \ - NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ + NodeTools::Callback auto callback, bool allow_empty, bool warn = false \ ) CONST { \ return NodeTools::expect_identifier_or_string(expect_item_str(callback, allow_empty, warn), allow_empty); \ } \ - constexpr NodeTools::NodeCallback auto expect_item_index( \ - NodeTools::Callback auto callback, bool warn = false \ - ) CONST { \ + constexpr NodeTools::NodeCallback auto expect_item_index(NodeTools::Callback auto callback, bool warn = false) \ + CONST { \ return expect_item_identifier( \ - [callback](external_value_type CONST& item) -> bool { \ - return callback(item.index); \ - }, \ - warn \ + [callback](external_value_type CONST& item) -> bool { \ + return callback(item.index); \ + }, \ + warn \ ); \ } \ constexpr NodeTools::Callback auto expect_item_index_str( \ - NodeTools::Callback auto callback, bool allow_empty = false, bool warn = false \ + NodeTools::Callback auto callback, bool allow_empty = false, bool warn = false \ ) CONST { \ return expect_item_str( \ - [callback](external_value_type CONST& item) -> bool { \ - return callback(item.index); \ - }, \ - allow_empty, warn \ + [callback](external_value_type CONST& item) -> bool { \ + return callback(item.index); \ + }, \ + allow_empty, \ + warn \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_assign_and_default( \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) CONST { \ return NodeTools::expect_assign( \ - [this, default_callback, callback](std::string_view key, ast::NodeCPtr value) -> bool { \ - external_value_type CONST* item = get_item_by_identifier(key); \ - if (item != nullptr) { \ - return callback(*item, value); \ - } else { \ - return default_callback(key, value); \ - } \ - } \ + [this, default_callback, callback](std::string_view key, ast::NodeCPtr value) -> bool { \ + external_value_type CONST* item = get_item_by_identifier(key); \ + if (item != nullptr) { \ + return callback(*item, value); \ + } else { \ + return default_callback(key, value); \ + } \ + } \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_assign( \ - NodeTools::Callback auto callback \ + NodeTools::Callback auto callback \ ) CONST { \ return expect_item_assign_and_default(key_value_invalid_callback(name), callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_length_and_default( \ - NodeTools::LengthCallback auto length_callback, \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::LengthCallback auto length_callback, \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) CONST { \ - return NodeTools::expect_list_and_length( \ - length_callback, expect_item_assign_and_default(default_callback, callback) \ - ); \ + return NodeTools::expect_list_and_length(length_callback, expect_item_assign_and_default(default_callback, callback)); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_length( \ - NodeTools::LengthCallback auto length_callback, \ - NodeTools::Callback auto callback \ + NodeTools::LengthCallback auto length_callback, \ + NodeTools::Callback auto callback \ ) CONST { \ - return expect_item_dictionary_and_length_and_default( \ - length_callback, \ - key_value_invalid_callback(name), \ - callback \ - ); \ + return expect_item_dictionary_and_length_and_default(length_callback, key_value_invalid_callback(name), callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_and_default( \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) CONST { \ - return expect_item_dictionary_and_length_and_default( \ - NodeTools::default_length_callback, \ - default_callback, \ - callback \ - ); \ + return expect_item_dictionary_and_length_and_default(NodeTools::default_length_callback, default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary( \ - NodeTools::Callback auto callback \ + NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::default_length_callback, \ - key_value_invalid_callback(name), \ - callback \ + NodeTools::default_length_callback, key_value_invalid_callback(name), callback \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_reserve_length_and_default( \ - reservable auto& reservable, \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + reservable auto& reservable, \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::reserve_length_callback(reservable), \ - default_callback, \ - callback \ + NodeTools::reserve_length_callback(reservable), default_callback, callback \ ); \ } \ constexpr NodeTools::NodeCallback auto expect_item_dictionary_reserve_length( \ - reservable auto& reservable, \ - NodeTools::Callback auto callback \ + reservable auto& reservable, NodeTools::Callback auto callback \ ) CONST { \ return expect_item_dictionary_and_length_and_default( \ - NodeTools::reserve_length_callback(reservable), \ - key_value_invalid_callback(name), \ - callback \ + NodeTools::reserve_length_callback(reservable), key_value_invalid_callback(name), callback \ ); \ } @@ -542,22 +509,19 @@ namespace OpenVic { * a fixed point to fixed point function fixed_point_functor, which will be applied to ever parsed value. */ template FixedPointFunctor = std::identity> constexpr NodeTools::NodeCallback auto expect_item_decimal_map( - NodeTools::Callback&&> auto callback, - FixedPointFunctor fixed_point_functor = {} + NodeTools::Callback&&> auto callback, + FixedPointFunctor fixed_point_functor = {} ) const { return [this, callback, fixed_point_functor](ast::NodeCPtr node) -> bool { fixed_point_map_t map; - bool ret = expect_item_dictionary( - [&map, fixed_point_functor](external_value_type const& key, ast::NodeCPtr value) -> bool { - return NodeTools::expect_fixed_point( - [&map, fixed_point_functor, &key](fixed_point_t val) -> bool { - map.emplace(&key, fixed_point_functor(val)); - return true; - } - )(value); - } - )(node); + bool ret = + expect_item_dictionary([&map, fixed_point_functor](external_value_type const& key, ast::NodeCPtr value) -> bool { + return NodeTools::expect_fixed_point([&map, fixed_point_functor, &key](fixed_point_t val) -> bool { + map.emplace(&key, fixed_point_functor(val)); + return true; + })(value); + })(node); ret &= callback(std::move(map)); @@ -568,53 +532,56 @@ namespace OpenVic { /* Item Specialisations */ template< - RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + RegistryValueInfo ValueInfo, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, + typename RegistryItemInfoValue::item_type> using ValueRegistry = UniqueKeyRegistry; template< - RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + RegistryValueInfo ValueInfo, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, + typename RegistryItemInfoInstance::item_type> using InstanceRegistry = UniqueKeyRegistry; template< - RegistryValueInfo ValueInfo, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > - requires - RegistryStorageInfo::item_type> + RegistryValueInfo ValueInfo, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> + requires RegistryStorageInfo< + StorageInfo, + typename RegistryItemInfoBaseInstance::item_type> using BaseInstanceRegistry = UniqueKeyRegistry; /* has_get_identifier Specialisations */ template< - has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + has_get_identifier Value, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> using IdentifierRegistry = ValueRegistry, StorageInfo, Case>; template< - has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + has_get_identifier Value, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> using IdentifierPointerRegistry = - ValueRegistry>, StorageInfo, Case>; + ValueRegistry>, StorageInfo, Case>; template< - has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + has_get_identifier Value, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> using IdentifierInstanceRegistry = InstanceRegistry, StorageInfo, Case>; template< - has_get_identifier Value, template typename StorageInfo = RegistryStorageInfoVector, - string_map_case Case = StringMapCaseSensitive - > + has_get_identifier Value, + template typename StorageInfo = RegistryStorageInfoVector, + string_map_case Case = StringMapCaseSensitive> using IdentifierBaseInstanceRegistry = BaseInstanceRegistry, StorageInfo, Case>; /* Case-Insensitive has_get_identifier Specialisations */ @@ -628,18 +595,19 @@ namespace OpenVic { using CaseInsensitiveIdentifierInstanceRegistry = IdentifierInstanceRegistry; template typename StorageInfo = RegistryStorageInfoVector> - using CaseInsensitiveIdentifierBaseInstanceRegistry = IdentifierBaseInstanceRegistry; + using CaseInsensitiveIdentifierBaseInstanceRegistry = + IdentifierBaseInstanceRegistry; -/* Macros to generate declaration and constant accessor methods for a UniqueKeyRegistry member variable. */ + /* Macros to generate declaration and constant accessor methods for a UniqueKeyRegistry member variable. */ -#define IDENTIFIER_REGISTRY(name, ...) \ - IDENTIFIER_REGISTRY_CUSTOM_PLURAL(name, name##s, __VA_ARGS__) +#define IDENTIFIER_REGISTRY(name, ...) IDENTIFIER_REGISTRY_CUSTOM_PLURAL(name, name##s, __VA_ARGS__) #define IDENTIFIER_REGISTRY_CUSTOM_PLURAL(singular, plural, ...) \ IDENTIFIER_REGISTRY_FULL_CUSTOM(singular, plural, plural, plural, __VA_ARGS__) #define IDENTIFIER_REGISTRY_FULL_CUSTOM(singular, plural, registry, debug_name, ...) \ - registry { #debug_name __VA_OPT__(,) __VA_ARGS__ }; \ + registry { #debug_name __VA_OPT__(, ) __VA_ARGS__ }; \ +\ public: \ constexpr void lock_##plural() { \ registry.lock(); \ @@ -648,11 +616,15 @@ public: \ return registry.is_locked(); \ } \ template \ - constexpr void reserve_##plural(size_t size) requires(decltype(registry)::storage_type_reservable) { \ + constexpr void reserve_##plural(size_t size) \ + requires(decltype(registry)::storage_type_reservable) \ + { \ registry.reserve(size); \ } \ template \ - constexpr void reserve_more_##plural(size_t size) requires(decltype(registry)::storage_type_reservable) { \ + constexpr void reserve_more_##plural(size_t size) \ + requires(decltype(registry)::storage_type_reservable) \ + { \ registry.reserve_more(size); \ } \ constexpr bool has_##singular##_identifier(std::string_view identifier) const { \ @@ -662,7 +634,9 @@ public: \ return registry.size(); \ } \ template \ - constexpr std::size_t get_##plural##_capacity() const requires(decltype(registry)::storage_type_reservable) { \ + constexpr std::size_t get_##plural##_capacity() const \ + requires(decltype(registry)::storage_type_reservable) \ + { \ return registry.capacity(); \ } \ constexpr bool plural##_empty() const { \ @@ -673,24 +647,23 @@ public: \ } \ template FixedPointFunctor = std::identity> \ constexpr NodeTools::NodeCallback auto expect_##singular##_decimal_map( \ - NodeTools::Callback&&> auto callback, \ - FixedPointFunctor fixed_point_functor = {} \ + NodeTools::Callback&&> auto callback, \ + FixedPointFunctor fixed_point_functor = {} \ ) const { \ return registry.expect_item_decimal_map(callback, fixed_point_functor); \ } \ IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, const) \ private: -/* Macros to generate non-constant accessor methods for a UniqueKeyRegistry member variable. */ + /* Macros to generate non-constant accessor methods for a UniqueKeyRegistry member variable. */ -#define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(name) \ - IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(name, name##s) +#define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS(name) IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(name, name##s) #define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_CUSTOM_PLURAL(singular, plural) \ IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_FULL_CUSTOM(singular, plural, plural, plural) #define IDENTIFIER_REGISTRY_NON_CONST_ACCESSORS_FULL_CUSTOM(singular, plural, registry, debug_name) \ - IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry,) + IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, ) #define IDENTIFIER_REGISTRY_INTERNAL_SHARED(singular, plural, registry, const_kw) \ constexpr decltype(registry)::external_value_type const_kw& get_front_##singular() const_kw { \ @@ -699,92 +672,96 @@ public: \ constexpr decltype(registry)::external_value_type const_kw& get_back_##singular() const_kw { \ return registry.back(); \ } \ - constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_identifier(std::string_view identifier) const_kw { \ + constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_identifier(std::string_view identifier) \ + const_kw { \ return registry.get_item_by_identifier(identifier); \ } \ template T> \ constexpr T const_kw* get_cast_##singular##_by_identifier(std::string_view identifier) const_kw { \ return registry.get_cast_item_by_identifier(identifier); \ } \ - constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_index(decltype(registry)::index_t index) const_kw { \ + constexpr decltype(registry)::external_value_type const_kw* get_##singular##_by_index(decltype(registry)::index_t index) \ + const_kw { \ return registry.get_item_by_index(index); \ } \ constexpr decltype(registry)::storage_type const_kw& get_##plural() const_kw { \ return registry.get_items(); \ } \ constexpr NodeTools::Callback auto expect_##singular##_str( \ - NodeTools::Callback auto callback, bool allow_empty = false, \ - bool warn = false \ + NodeTools::Callback auto callback, \ + bool allow_empty = false, \ + bool warn = false \ ) const_kw { \ return registry.expect_item_str(callback, allow_empty, warn); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_identifier( \ - NodeTools::Callback auto callback, bool warn = false \ + NodeTools::Callback auto callback, bool warn = false \ ) const_kw { \ return registry.expect_item_identifier(callback, warn); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_index( \ - NodeTools::Callback auto callback, bool warn = false \ + NodeTools::Callback auto callback, bool warn = false \ ) const_kw { \ return registry.expect_item_index(callback, warn); \ } \ constexpr NodeTools::Callback auto expect_##singular##_index_str( \ - NodeTools::Callback auto callback, bool allow_empty = false, \ - bool warn = false \ + NodeTools::Callback auto callback, bool allow_empty = false, bool warn = false \ ) const_kw { \ return registry.expect_item_index_str(callback, allow_empty, warn); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_string( \ - NodeTools::Callback auto callback, bool allow_empty = false, \ - bool warn = false \ + NodeTools::Callback auto callback, \ + bool allow_empty = false, \ + bool warn = false \ ) const_kw { \ return registry.expect_item_string(callback, allow_empty, warn); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_identifier_or_string( \ - NodeTools::Callback auto callback, bool allow_empty = false, \ - bool warn = false \ + NodeTools::Callback auto callback, \ + bool allow_empty = false, \ + bool warn = false \ ) const_kw { \ return registry.expect_item_identifier_or_string(callback, allow_empty, warn); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_assign_and_default( \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_assign_and_default(default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_assign( \ - NodeTools::Callback auto callback \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_assign(callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_and_length_and_default( \ - NodeTools::LengthCallback auto length_callback, \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::LengthCallback auto length_callback, \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_and_length_and_default(length_callback, default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_and_default( \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_and_default(default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary( \ - NodeTools::Callback auto callback \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary(callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_reserve_length_and_default( \ - reservable auto& reservable, \ - NodeTools::KeyValueCallback auto default_callback, \ - NodeTools::Callback auto callback \ + reservable auto& reservable, \ + NodeTools::KeyValueCallback auto default_callback, \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_reserve_length_and_default(reservable, default_callback, callback); \ } \ constexpr NodeTools::NodeCallback auto expect_##singular##_dictionary_reserve_length( \ - reservable auto& reservable, \ - NodeTools::Callback auto callback \ + reservable auto& reservable, \ + NodeTools::Callback auto callback \ ) const_kw { \ return registry.expect_item_dictionary_reserve_length(reservable, callback); \ } diff --git a/src/openvic-simulation/types/IndexedFlatMap.hpp b/src/openvic-simulation/types/IndexedFlatMap.hpp index 90a0baef0..fe2cb4609 100644 --- a/src/openvic-simulation/types/IndexedFlatMap.hpp +++ b/src/openvic-simulation/types/IndexedFlatMap.hpp @@ -26,60 +26,60 @@ public: \ return NAME; \ } \ [[nodiscard]] auto get_##NAME(KEYTYPE const& key) const \ - -> decltype(OpenVic::_get_property(std::declval>())); \ + -> decltype(OpenVic::_get_property(std::declval>())); \ ACCESS: namespace OpenVic { /** - * @brief A dictionary-like type that uses std::vector for contiguous storage, - * providing O(1) access time by directly using an integer index obtained from the KeyType. - * It strictly assumes that keys provided at construction are ordered and continuous - * in their index values. - * @tparam KeyType The type of keys used to access values. This type must provide a - * `size_t getIndex() const` method. - * @tparam ValueType The type of values to be stored in the map. - * - * This class assumes that an integer index can be obtained from the key type - * via its `getIndex()` method. The indices used with this map must be within - * the specified range [min_index, max_index]. - * - * @warning This class stores a `std::span` of the provided keys. This means the - * `IndexedFlatMap` does NOT own the lifetime of the keys. The caller is - * responsible for ensuring that the underlying data (the `std::vector` or array) - * that the `std::span` refers to remains valid and outlives the `IndexedFlatMap` instance. - */ - template + * @brief A dictionary-like type that uses std::vector for contiguous storage, + * providing O(1) access time by directly using an integer index obtained from the KeyType. + * It strictly assumes that keys provided at construction are ordered and continuous + * in their index values. + * @tparam KeyType The type of keys used to access values. This type must provide a + * `size_t getIndex() const` method. + * @tparam ValueType The type of values to be stored in the map. + * + * This class assumes that an integer index can be obtained from the key type + * via its `getIndex()` method. The indices used with this map must be within + * the specified range [min_index, max_index]. + * + * @warning This class stores a `std::span` of the provided keys. This means the + * `IndexedFlatMap` does NOT own the lifetime of the keys. The caller is + * responsible for ensuring that the underlying data (the `std::vector` or array) + * that the `std::span` refers to remains valid and outlives the `IndexedFlatMap` instance. + */ + template struct IndexedFlatMap { using keys_span_type = forwardable_span; using values_vector_type = std::conditional_t< - std::is_move_constructible_v || std::is_copy_constructible_v, - memory::vector, - memory::FixedVector - >; + std::is_move_constructible_v || std::is_copy_constructible_v, + memory::vector, + memory::FixedVector>; private: values_vector_type values; - keys_span_type keys; //non-owning! + keys_span_type keys; // non-owning! size_t min_index; size_t max_index; /** - * @brief Converts an external key's index to an internal vector index. - * Logs a fatal error if the key's index is out of bounds. - * @param key The key whose index is to be converted. - * @return The internal index, or 0 if out of bounds (after logging error). - */ + * @brief Converts an external key's index to an internal vector index. + * Logs a fatal error if the key's index is out of bounds. + * @param key The key whose index is to be converted. + * @return The internal index, or 0 if out of bounds (after logging error). + */ constexpr size_t get_internal_index_from_key(ForwardedKeyType const& key) const { static_assert(has_index); const size_t index = type_safe::get(key.index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access key with index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access key with index {} which is outside the " + "map's defined range [{}, {}].", + type_name(), + type_name(), + index, + min_index, + max_index ); assert(index >= min_index && index <= max_index); return 0; @@ -88,17 +88,18 @@ namespace OpenVic { } /** - * @brief Validates that the provided span of keys is ordered and continuous. - * Logs errors if validation fails. - * @param new_keys The span of keys to validate. - * @return True if keys are valid, false otherwise. - */ + * @brief Validates that the provided span of keys is ordered and continuous. + * Logs errors if validation fails. + * @param new_keys The span of keys to validate. + * @return True if keys are valid, false otherwise. + */ static bool validate_new_keys(keys_span_type new_keys) { static_assert(has_index); if (new_keys.empty()) { spdlog::warn_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{}, {}> should not be constructed with empty key span.", - type_name(), type_name() + "DEVELOPER: OpenVic::IndexedFlatMap<{}, {}> should not be constructed with empty key span.", + type_name(), + type_name() ); return false; } @@ -112,11 +113,12 @@ namespace OpenVic { if (new_keys.size() != expected_capacity) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with incremental indices. Expected capacity {} but got {} keys.", - type_name(), - type_name(), - expected_capacity, - new_keys.size() + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with " + "incremental indices. Expected capacity {} but got {} keys.", + type_name(), + type_name(), + expected_capacity, + new_keys.size() ); assert(new_keys.size() == expected_capacity); return false; @@ -126,13 +128,14 @@ namespace OpenVic { const auto expected_index = index_type { underlying_type(min_index + i) }; if (new_keys[i].index != expected_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with incremental indices. " - "Expected index {} but got {} at position {}.", - type_name(), - type_name(), - expected_index, - new_keys[i].index, - i + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> must be constructed with a continuous span of keys with " + "incremental indices. " + "Expected index {} but got {} at position {}.", + type_name(), + type_name(), + expected_index, + new_keys[i].index, + i ); assert(new_keys[i].index == expected_index); return false; @@ -142,10 +145,10 @@ namespace OpenVic { return true; } - //could be rewritten to return iterators for both this and other. - //that would overcomplicate it with const & non-const - template - keys_span_type get_shared_keys(IndexedFlatMap const& other) const { + // could be rewritten to return iterators for both this and other. + // that would overcomplicate it with const & non-const + template + keys_span_type get_shared_keys(IndexedFlatMap const& other) const { if (other.get_min_index() >= min_index && other.get_max_index() <= max_index) { return other.get_keys(); } @@ -159,74 +162,75 @@ namespace OpenVic { const size_t shared_count = 1 + max_shared_index - min_shared_index; const size_t other_keys_offset = min_shared_index - other.get_min_index(); - return {other.get_keys().data() + other_keys_offset, shared_count}; + return { other.get_keys().data() + other_keys_offset, shared_count }; } /** - * @brief Checks if the 'other' IndexedFlatMap's key span is a subset of 'this' map's key span, - * based purely on index ranges. - * Logs a fatal error if not compatible. - * @param other The other IndexedFlatMap to compare with. - * @return True if compatible as a subset, false otherwise. - */ - template - bool check_subset_span_match(IndexedFlatMap const& other) const { + * @brief Checks if the 'other' IndexedFlatMap's key span is a subset of 'this' map's key span, + * based purely on index ranges. + * Logs a fatal error if not compatible. + * @param other The other IndexedFlatMap to compare with. + * @return True if compatible as a subset, false otherwise. + */ + template + bool check_subset_span_match(IndexedFlatMap const& other) const { // Check if 'other's index range is contained within 'this's index range if (!(other.get_min_index() >= min_index && other.get_max_index() <= max_index)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> subset operation requires the right-hand map's index range " - "({}-{}) to be a subset of the left-hand map's index range ({}-{}).", - type_name(), - type_name(), - other.get_min_index(), - other.get_max_index(), - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> subset operation requires the right-hand map's index range " + "({}-{}) to be a subset of the left-hand map's index range ({}-{}).", + type_name(), + type_name(), + other.get_min_index(), + other.get_max_index(), + min_index, + max_index ); assert(other.get_min_index() >= min_index && other.get_max_index() <= max_index); return false; } - // There is no check for keys.data() being identical as KeyType objects are considered functionally equivalent if their index values match. + // There is no check for keys.data() being identical as KeyType objects are considered functionally equivalent if + // their index values match. return true; } public: - //vector + // vector constexpr IndexedFlatMap(const create_empty_t) requires std::is_move_constructible_v || std::is_copy_constructible_v - : values(), keys(), min_index(0), max_index(0) {} + : values(), keys(), min_index(0), max_index(0) {} - //FixedVector + // FixedVector constexpr IndexedFlatMap(const create_empty_t t) - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - : values(t), keys(), min_index(0), max_index(0) {} + requires(!std::is_move_constructible_v) && (!std::is_copy_constructible_v) + : values(t), keys(), min_index(0), max_index(0) {} /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct + * `ValueType`. This is used to generate values for each key in the provided span. + */ template - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - //value_generator(key) doesn't return std:tuple<...> - && (!specialization_of>, std::tuple>) - //ValueType(value_generator(key)) is valid constructor call - && std::constructible_from()(std::declval()))> - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) + // value_generator(key) doesn't return std:tuple<...> + && (!specialization_of< + std::remove_cvref_t>, + std::tuple>) + // ValueType(value_generator(key)) is valid constructor call + && std::constructible_from< + ValueType, + decltype(std::declval()(std::declval()))> + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -235,38 +239,39 @@ namespace OpenVic { values.reserve(new_keys.size()); for (ForwardedKeyType const& key : keys) { values.emplace_back( - std::forward()(std::declval()))>( - value_generator(key) - ) + std::forward()(std::declval()))>( + value_generator(key) + ) ); } } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns a single argument to construct + * `ValueType`. This is used to generate values for each key in the provided span. + */ template - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - //value_generator(key) doesn't return std:tuple<...> - && (!specialization_of>, std::tuple>) - //ValueType(value_generator(key)) is valid constructor call - && std::constructible_from()(std::declval()))> - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values { create_empty, new_keys.size() } { + requires(!std::is_move_constructible_v) && + (!std::is_copy_constructible_v) + // value_generator(key) doesn't return std:tuple<...> + && (!specialization_of< + std::remove_cvref_t>, + std::tuple>) + // ValueType(value_generator(key)) is valid constructor call + && std::constructible_from< + ValueType, + decltype(std::declval()(std::declval()))> + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values { create_empty, new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -274,45 +279,45 @@ namespace OpenVic { for (ForwardedKeyType const& key : keys) { values.emplace_back( - std::forward()(std::declval()))>( - value_generator(key) - ) + std::forward()(std::declval()))>( + value_generator(key) + ) ); } } /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. + * This is used to generate values for each key in the provided span. + */ template - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - //value_generator(key) returns tuple - && specialization_of>, std::tuple> - //ValueType(...value_generator(key)) is valid constructor call - && requires(GeneratorTemplateType&& value_generator) { { - std::apply( - [](auto&&... args) { - ValueType obj{std::forward(args)...}; - }, - value_generator(std::declval()) - ) - }; } - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType&& value_generator - ) : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) + // value_generator(key) returns tuple + && specialization_of< + std::remove_cvref_t>, + std::tuple> + // ValueType(...value_generator(key)) is valid constructor call + && requires(GeneratorTemplateType&& value_generator) { + { + std::apply( + [](auto&&... args) { + ValueType obj { std::forward(args)... }; + }, + value_generator(std::declval()) + ) + }; + } + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType&& value_generator) : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -321,46 +326,47 @@ namespace OpenVic { values.reserve(new_keys.size()); for (ForwardedKeyType const& key : keys) { std::apply( - [this](auto&&... args) { - values.emplace_back(std::forward(args)...); - }, - value_generator(key) + [this](auto&&... args) { + values.emplace_back(std::forward(args)...); + }, + value_generator(key) ); } } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys - * and a key-based generator. - * The map's range [min_idx, max_idx] is determined by the first and last key in the span. - * All elements are initialized using the `value_generator`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. - * This is used to generate values for each key in the provided span. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys + * and a key-based generator. + * The map's range [min_idx, max_idx] is determined by the first and last key in the span. + * All elements are initialized using the `value_generator`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * @param value_generator A callable that takes a `KeyType const&` and returns arguments to construct `ValueType`. + * This is used to generate values for each key in the provided span. + */ template - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - //value_generator(key) returns tuple - && specialization_of>, std::tuple> - //ValueType(...value_generator(key)) is valid constructor call - && requires(GeneratorTemplateType value_generator) { { - std::apply( - [](auto&&... args) { - ValueType obj{std::forward(args)...}; - }, - value_generator(std::declval()) - ) - }; } - IndexedFlatMap( - keys_span_type new_keys, - GeneratorTemplateType value_generator - ) : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values { create_empty, new_keys.size() } { + requires(!std::is_move_constructible_v) && + (!std::is_copy_constructible_v) + // value_generator(key) returns tuple + && specialization_of< + std::remove_cvref_t>, + std::tuple> + // ValueType(...value_generator(key)) is valid constructor call + && requires(GeneratorTemplateType value_generator) { + { + std::apply( + [](auto&&... args) { + ValueType obj { std::forward(args)... }; + }, + value_generator(std::declval()) + ) + }; + } + IndexedFlatMap(keys_span_type new_keys, GeneratorTemplateType value_generator) : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values { create_empty, new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -368,31 +374,32 @@ namespace OpenVic { for (ForwardedKeyType const& key : keys) { std::apply( - [this](auto&&... args) { - values.emplace_back(std::forward(args)...); - }, - value_generator(key) + [this](auto&&... args) { + values.emplace_back(std::forward(args)...); + }, + value_generator(key) ); } } /** vector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. - * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking `KeyType const&`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * - * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. + * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking + * `KeyType const&`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * + * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. + */ IndexedFlatMap(keys_span_type new_keys) - requires (std::is_move_constructible_v || std::is_copy_constructible_v) - && (std::default_initializable || std::constructible_from) - : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values() { + requires(std::is_move_constructible_v || std::is_copy_constructible_v) && + (std::default_initializable || std::constructible_from) + : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values() { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -410,22 +417,23 @@ namespace OpenVic { } /** FixedVector - * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. - * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking `KeyType const&`. - * @param new_keys A `std::span` of KeyType objects. These keys MUST be - * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). - * The `IndexedFlatMap` stores a reference to this span; the caller is responsible - * for ensuring the underlying data outlives this map instance. - * - * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. - */ + * @brief Constructs an IndexedFlatMap based on a provided span of ordered and continuous keys. + * All elements are constructed by passing `KeyType const&` or default-constructed if there is no constructor taking + * `KeyType const&`. + * @param new_keys A `std::span` of KeyType objects. These keys MUST be + * ordered by their index and continuous (i.e., `new_keys[i+1].getIndex() == new_keys[i].getIndex() + 1`). + * The `IndexedFlatMap` stores a reference to this span; the caller is responsible + * for ensuring the underlying data outlives this map instance. + * + * @note This constructor requires `ValueType` to be `std::default_initializable || std::constructible_from`. + */ IndexedFlatMap(keys_span_type new_keys) - requires (!std::is_move_constructible_v) && (!std::is_copy_constructible_v) - && (std::default_initializable || std::constructible_from) - : keys(new_keys), - min_index { type_safe::get(new_keys.front().index) }, - max_index { type_safe::get(new_keys.back().index) }, - values { create_empty, new_keys.size() } { + requires(!std::is_move_constructible_v) && (!std::is_copy_constructible_v) && + (std::default_initializable || std::constructible_from) + : + keys(new_keys), min_index { type_safe::get(new_keys.front().index) }, + max_index { type_safe::get(new_keys.back().index) }, values { create_empty, new_keys.size() } { static_assert(has_index); if (!validate_new_keys(new_keys)) { return; @@ -444,24 +452,23 @@ namespace OpenVic { } /** - * @brief Sets the value associated with a key using copy assignment. - */ + * @brief Sets the value associated with a key using copy assignment. + */ void set(ForwardedKeyType const& key, ValueType const& value) - requires std::assignable_from { + requires std::assignable_from + { static_assert(has_index); values[get_internal_index_from_key(key)] = value; } /** - * @brief Sets the value associated with a key using move assignment (via std::swap). - */ + * @brief Sets the value associated with a key using move assignment (via std::swap). + */ void set(ForwardedKeyType const& key, ValueType&& value) - requires std::movable { + requires std::movable + { static_assert(has_index); - std::swap( - values[get_internal_index_from_key(key)], - value - ); + std::swap(values[get_internal_index_from_key(key)], value); } constexpr ValueType& at(ForwardedKeyType const& key) { @@ -475,18 +482,18 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ValueType& at_index(const index_t typed_index) { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), + type_name(), + index, + min_index, + max_index ); assert(index >= min_index && index <= max_index); } @@ -494,18 +501,18 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ValueType const& at_index(const index_t typed_index) const { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), + type_name(), + index, + min_index, + max_index ); assert(index >= min_index && index <= max_index); } @@ -513,18 +520,18 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr ForwardedKeyType const& get_key_at_index(const index_t typed_index) const { const std::size_t index = get_index_as_size_t(typed_index); if (index < min_index || index > max_index) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined range [{}, {}].", - type_name(), - type_name(), - index, - min_index, - max_index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> attempted to access index {} which is outside the map's defined " + "range [{}, {}].", + type_name(), + type_name(), + index, + min_index, + max_index ); assert(index >= min_index && index <= max_index); } @@ -537,8 +544,7 @@ namespace OpenVic { } template - requires std::same_as::type> - && std::same_as + requires std::same_as::type> && std::same_as constexpr bool contains_index(const index_t typed_external_index) const { const std::size_t external_index = get_index_as_size_t(typed_external_index); return external_index >= min_index && external_index <= max_index; @@ -573,19 +579,21 @@ namespace OpenVic { } /** - * @brief Fills all elements in the map with a specified value. - * The capacity and index range remain unchanged. - * @param value The value to fill all elements with. - * - * @note This method requires `ValueType` to be copy-constructible and copy-assignable. - */ + * @brief Fills all elements in the map with a specified value. + * The capacity and index range remain unchanged. + * @param value The value to fill all elements with. + * + * @note This method requires `ValueType` to be copy-constructible and copy-assignable. + */ void fill(ValueType const& value) - requires std::copy_constructible && std::assignable_from { + requires std::copy_constructible && std::assignable_from + { values.assign(values.size(), value); } constexpr void copy_values_from(IndexedFlatMap const& other) - requires std::assignable_from { + requires std::assignable_from + { static_assert(has_index); for (ForwardedKeyType const& key : get_shared_keys(other)) { set(key, other.at(key)); @@ -593,16 +601,17 @@ namespace OpenVic { } /** - * @brief Reinitializes all elements in the map using a provided value generator function. - * This overload is chosen for types that are copyable (have a copy constructor and copy assignment). - * The capacity and index range remain unchanged. - * @param value_generator A callable that takes a `KeyType const&` and - * returns a `ValueType`. This is used to generate a new value for each slot. - * - * @note This method requires `ValueType` to be copy-assignable. - */ + * @brief Reinitializes all elements in the map using a provided value generator function. + * This overload is chosen for types that are copyable (have a copy constructor and copy assignment). + * The capacity and index range remain unchanged. + * @param value_generator A callable that takes a `KeyType const&` and + * returns a `ValueType`. This is used to generate a new value for each slot. + * + * @note This method requires `ValueType` to be copy-assignable. + */ void reinitialize_with_generator(strict_regular_invocable_r auto&& value_generator) - requires std::copyable { + requires std::copyable + { for (iterator it = begin(); it < end(); it++) { auto& [key, value] = *it; value = value_generator(key); // Copy/Move assignment @@ -610,17 +619,18 @@ namespace OpenVic { } /** - * @brief Reinitializes all elements in the map using a provided value generator function. - * This overload is chosen for types that are movable but NOT copyable. - * The capacity and index range remain unchanged. - * @param value_generator A callable that takes a `KeyType const&` and - * returns a `ValueType`. This is used to generate a new value for each slot. - * - * @note This method destroys existing elements and constructs new ones in place, - * which is often more efficient for move-only types. - */ + * @brief Reinitializes all elements in the map using a provided value generator function. + * This overload is chosen for types that are movable but NOT copyable. + * The capacity and index range remain unchanged. + * @param value_generator A callable that takes a `KeyType const&` and + * returns a `ValueType`. This is used to generate a new value for each slot. + * + * @note This method destroys existing elements and constructs new ones in place, + * which is often more efficient for move-only types. + */ void reinitialize_with_generator(strict_regular_invocable_r auto&& value_generator) - requires std::movable && (!std::copyable) { + requires std::movable && (!std::copyable) + { values.clear(); for (ForwardedKeyType const& key : keys) { // Emplace directly, using move construction if generator returns rvalue @@ -638,16 +648,20 @@ namespace OpenVic { // Unary minus operator IndexedFlatMap operator-() const - requires unary_negatable { + requires unary_negatable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return -this->at(key); }); } - template - IndexedFlatMap operator+(IndexedFlatMap const& other) const - requires addable { + template + IndexedFlatMap operator+( + IndexedFlatMap const& other + ) const + requires addable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -667,9 +681,12 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator-(IndexedFlatMap const& other) const - requires subtractable { + template + IndexedFlatMap operator-( + IndexedFlatMap const& other + ) const + requires subtractable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -684,9 +701,12 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator*(IndexedFlatMap const& other) const - requires multipliable { + template + IndexedFlatMap operator*( + IndexedFlatMap const& other + ) const + requires multipliable + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -701,9 +721,12 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator/(IndexedFlatMap const& other) const - requires divisible { + template + IndexedFlatMap operator/( + IndexedFlatMap const& other + ) const + requires divisible + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -714,13 +737,13 @@ namespace OpenVic { if (other.contains(key)) { if (other.at(key) == static_cast(0)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero detected at key index {}.", + type_name(), + type_name(), + key.index ); assert(other.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } return this->at(key) / other.at(key); } else { @@ -729,11 +752,13 @@ namespace OpenVic { }); } - template + template IndexedFlatMap divide_handle_zero( - IndexedFlatMap const& other, - strict_regular_invocable_r auto&& handle_div_by_zero - ) const requires divisible { + IndexedFlatMap const& other, + strict_regular_invocable_r auto&& handle_div_by_zero + ) const + requires divisible + { static_assert(has_index); if (!check_subset_span_match(other)) { return IndexedFlatMap(); @@ -742,10 +767,7 @@ namespace OpenVic { return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { if (other.contains(key)) { if (other.at(key) == static_cast(0)) { - return std::forward(handle_div_by_zero)( - this->at(key), - other.at(key) - ); + return std::forward(handle_div_by_zero)(this->at(key), other.at(key)); } return this->at(key) / other.at(key); } else { @@ -755,9 +777,10 @@ namespace OpenVic { } // Binary addition operator (Map + Scalar) - template + template IndexedFlatMap operator+(ScalarType const& scalar) const - requires addable { + requires addable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) + scalar; @@ -765,9 +788,10 @@ namespace OpenVic { } // Binary subtraction operator (Map - Scalar) - template + template IndexedFlatMap operator-(ScalarType const& scalar) const - requires subtractable { + requires subtractable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) - scalar; @@ -775,9 +799,10 @@ namespace OpenVic { } // Binary multiplication operator (Map * Scalar) - template + template IndexedFlatMap operator*(ScalarType const& scalar) const - requires multipliable { + requires multipliable + { static_assert(has_index); return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) * scalar; @@ -785,27 +810,29 @@ namespace OpenVic { } // Binary division operator (Map / Scalar) - template + template IndexedFlatMap operator/(ScalarType const& scalar) const - requires divisible { + requires divisible + { static_assert(has_index); if (scalar == static_cast(0)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero for scalar operation.", - type_name(), - type_name() + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> division by zero for scalar operation.", + type_name(), + type_name() ); assert(scalar != static_cast(0)); - //continue and let it throw + // continue and let it throw } return IndexedFlatMap(keys, [&](ForwardedKeyType const& key) { return this->at(key) / scalar; }); } - template - IndexedFlatMap& operator+=(IndexedFlatMap const& other) - requires add_assignable { + template + IndexedFlatMap& operator+=(IndexedFlatMap const& other) + requires add_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; // Return current state on error @@ -818,9 +845,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator-=(IndexedFlatMap const& other) - requires subtract_assignable { + template + IndexedFlatMap& operator-=(IndexedFlatMap const& other) + requires subtract_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -832,9 +860,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator*=(IndexedFlatMap const& other) - requires multiply_assignable { + template + IndexedFlatMap& operator*=(IndexedFlatMap const& other) + requires multiply_assignable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -846,9 +875,10 @@ namespace OpenVic { return *this; } - template - IndexedFlatMap& operator/=(IndexedFlatMap const& other) - requires divide_assignable && equalable { + template + IndexedFlatMap& operator/=(IndexedFlatMap const& other) + requires divide_assignable && equalable + { static_assert(has_index); if (!check_subset_span_match(other)) { return *this; @@ -857,13 +887,13 @@ namespace OpenVic { for (ForwardedKeyType const& key : other.get_keys()) { if (other.at(key) == static_cast(0)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero detected at key index {}.", + type_name(), + type_name(), + key.index ); assert(other.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } this->at(key) /= other.at(key); } @@ -871,9 +901,10 @@ namespace OpenVic { } // Compound assignment addition operator (Map += Scalar) - template + template IndexedFlatMap& operator+=(ScalarType const& scalar) - requires add_assignable { + requires add_assignable + { for (ValueType& val : values) { val += scalar; } @@ -881,9 +912,10 @@ namespace OpenVic { } // Compound assignment subtraction operator (Map -= Scalar) - template + template IndexedFlatMap& operator-=(ScalarType const& scalar) - requires subtract_assignable { + requires subtract_assignable + { for (ValueType& val : values) { val -= scalar; } @@ -891,9 +923,10 @@ namespace OpenVic { } // Compound assignment multiplication operator (Map *= Scalar) - template + template IndexedFlatMap& operator*=(ScalarType const& scalar) - requires multiply_assignable { + requires multiply_assignable + { for (ValueType& val : values) { val *= scalar; } @@ -901,17 +934,18 @@ namespace OpenVic { } // Compound assignment division operator (Map /= Scalar) - template + template IndexedFlatMap& operator/=(ScalarType const& scalar) - requires divide_assignable { + requires divide_assignable + { if (scalar == static_cast(0)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero for scalar operation.", - type_name(), - type_name() + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> compound division by zero for scalar operation.", + type_name(), + type_name() ); assert(scalar != static_cast(0)); - //continue and let it throw + // continue and let it throw } for (ValueType& val : values) { val /= scalar; @@ -919,12 +953,11 @@ namespace OpenVic { return *this; } - template + template constexpr IndexedFlatMap& rescale(ScalarType const& new_total) - requires std::default_initializable - && add_assignable - && multiply_assignable - && divide_assignable { + requires std::default_initializable && add_assignable && + multiply_assignable && divide_assignable + { static_assert(has_index); bool has_any_non_zero_value = false; const ValueType zero = static_cast(0); @@ -942,7 +975,7 @@ namespace OpenVic { } // --- Iterators for Key-Value Pairs --- - template + template class BasicIterator { public: using value_type = std::pair>; @@ -951,19 +984,21 @@ namespace OpenVic { using iterator_category = std::random_access_iterator_tag; private: - std::conditional_t value_it; + std::conditional_t + value_it; typename keys_span_type::iterator key_it; public: // Constructor BasicIterator( - std::conditional_t val_it, - typename keys_span_type::iterator k_it + std::conditional_t + val_it, + typename keys_span_type::iterator k_it ) : value_it(val_it), key_it(k_it) {} // Dereference operator reference operator*() const { - return {*key_it, *value_it}; + return { *key_it, *value_it }; } // Arrow operator (for member access) @@ -977,7 +1012,7 @@ namespace OpenVic { // For now, direct access to first/second is assumed. }; Proxy operator->() const { - return {*key_it, *value_it}; + return { *key_it, *value_it }; } // Pre-increment @@ -1099,19 +1134,17 @@ namespace OpenVic { }; // Non-member binary operators for (Scalar op Map) - template - IndexedFlatMap operator+( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires addable { + template + IndexedFlatMap operator+(ScalarType const& scalar, IndexedFlatMap const& map) + requires addable + { return map + scalar; // Delegate to the member operator } - template - IndexedFlatMap operator-( - ValueType const& scalar, - IndexedFlatMap const& map - ) requires subtractable { + template + IndexedFlatMap operator-(ValueType const& scalar, IndexedFlatMap const& map) + requires subtractable + { static_assert(has_index); // Scalar - Map is not simply map - scalar, so we implement it directly return IndexedFlatMap(map.get_keys(), [&](KeyType const& key) { @@ -1119,30 +1152,28 @@ namespace OpenVic { }); } - template - IndexedFlatMap operator*( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires multipliable { + template + IndexedFlatMap operator*(ScalarType const& scalar, IndexedFlatMap const& map) + requires multipliable + { return map * scalar; // Delegate to the member operator } - template - IndexedFlatMap operator/( - ScalarType const& scalar, - IndexedFlatMap const& map - ) requires divisible { + template + IndexedFlatMap operator/(ScalarType const& scalar, IndexedFlatMap const& map) + requires divisible + { static_assert(has_index); return IndexedFlatMap(map.get_keys(), [&](KeyType const& key) { if (map.at(key) == static_cast(0)) { spdlog::error_s( - "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> scalar division by zero detected at key index {}.", - type_name(), - type_name(), - key.index + "DEVELOPER: OpenVic::IndexedFlatMap<{},{}> scalar division by zero detected at key index {}.", + type_name(), + type_name(), + key.index ); assert(map.at(key) != static_cast(0)); - //continue and let it throw + // continue and let it throw } return scalar / map.at(key); }); diff --git a/src/openvic-simulation/types/OptionalBool.hpp b/src/openvic-simulation/types/OptionalBool.hpp index 4770eebac..b1140bf11 100644 --- a/src/openvic-simulation/types/OptionalBool.hpp +++ b/src/openvic-simulation/types/OptionalBool.hpp @@ -3,9 +3,9 @@ #include namespace OpenVic { - enum struct OptionalBool : std::uint8_t { - UNSPECIFIED = 0, - TRUE = 1, - FALSE = 2 - }; -} \ No newline at end of file + enum struct OptionalBool : std::uint8_t { + UNSPECIFIED = 0, + TRUE = 1, + FALSE = 2 + }; +} diff --git a/src/openvic-simulation/types/OrderedContainers.hpp b/src/openvic-simulation/types/OrderedContainers.hpp index a88e84720..cc718d33f 100644 --- a/src/openvic-simulation/types/OrderedContainers.hpp +++ b/src/openvic-simulation/types/OrderedContainers.hpp @@ -68,45 +68,66 @@ namespace OpenVic { // Useful for contiguous memory template< - class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using vector_ordered_map = - tsl::ordered_map, Allocator>, IndexType>; + tsl::ordered_map, Allocator>, IndexType>; // Useful for stable memory addresses (so long as you don't remove or insert values) template< - class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using deque_ordered_map = - tsl::ordered_map, Allocator>, IndexType>; + tsl::ordered_map, Allocator>, IndexType>; template< - class Key, class T, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using ordered_map = vector_ordered_map; // Useful for contiguous memory template< - class Key, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using vector_ordered_set = tsl::ordered_set, IndexType>; // Useful for stable memory addresses (so long as you don't remove or insert values) template< - class Key, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using deque_ordered_set = - tsl::ordered_set, IndexType>; + tsl::ordered_set, IndexType>; template< - class Key, class Hash = container_hash, class KeyEqual = default_equal_to, - class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class Hash = container_hash, + class KeyEqual = default_equal_to, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using ordered_set = vector_ordered_set; template @@ -154,40 +175,72 @@ namespace OpenVic { // Useful for contiguous memory template< - class Key, class T, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using case_insensitive_vector_ordered_map = vector_ordered_map< - Key, T, case_insensitive_string_hash, case_insensitive_string_equal, RawAllocator, IndexType, Allocator>; + Key, + T, + case_insensitive_string_hash, + case_insensitive_string_equal, + RawAllocator, + IndexType, + Allocator>; // Useful for stable memory addresses (so long as you don't remove or insert values) template< - class Key, class T, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using case_insensitive_deque_ordered_map = deque_ordered_map< - Key, T, case_insensitive_string_hash, case_insensitive_string_equal, RawAllocator, IndexType, Allocator>; + Key, + T, + case_insensitive_string_hash, + case_insensitive_string_equal, + RawAllocator, + IndexType, + Allocator>; template< - class Key, class T, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator, memory::tracker>> + class Key, + class T, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator, memory::tracker>> using case_insensitive_ordered_map = case_insensitive_vector_ordered_map; // Useful for contiguous memory template< - class Key, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using case_insensitive_vector_ordered_set = vector_ordered_set< - Key, case_insensitive_string_hash, case_insensitive_string_equal, RawAllocator, IndexType, Allocator>; + Key, + case_insensitive_string_hash, + case_insensitive_string_equal, + RawAllocator, + IndexType, + Allocator>; // Useful for stable memory addresses (so long as you don't remove or insert values) template< - class Key, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using case_insensitive_deque_ordered_set = - deque_ordered_set; + deque_ordered_set; template< - class Key, class RawAllocator = foonathan::memory::default_allocator, class IndexType = std::uint_least32_t, - class Allocator = foonathan::memory::std_allocator>> + class Key, + class RawAllocator = foonathan::memory::default_allocator, + class IndexType = std::uint_least32_t, + class Allocator = foonathan::memory::std_allocator>> using case_insensitive_ordered_set = case_insensitive_vector_ordered_set; struct StringMapCaseSensitive { diff --git a/src/openvic-simulation/types/OrderedContainersMath.hpp b/src/openvic-simulation/types/OrderedContainersMath.hpp index da099a363..3c07fa26a 100644 --- a/src/openvic-simulation/types/OrderedContainersMath.hpp +++ b/src/openvic-simulation/types/OrderedContainersMath.hpp @@ -7,110 +7,108 @@ #include "openvic-simulation/types/OrderedContainers.hpp" namespace OpenVic { - template + template constexpr ordered_map operator-(ordered_map const& rhs) { ordered_map result {}; - auto view = rhs | std::views::transform( - [](KeyType const& key, ValueType const& value) { - return std::make_pair(key, -value); - } - ); + auto view = rhs | std::views::transform([](KeyType const& key, ValueType const& value) { + return std::make_pair(key, -value); + }); result.insert(view.begin(), view.end()); return result; } - template + template constexpr ordered_map& operator+=( - ordered_map& lhs, - ordered_map const& rhs - ) requires add_assignable { + ordered_map& lhs, ordered_map const& rhs + ) + requires add_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] += rhs_value; } return lhs; } - template + template constexpr ordered_map& operator-=( - ordered_map& lhs, - ordered_map const& rhs - ) requires subtract_assignable { + ordered_map& lhs, ordered_map const& rhs + ) + requires subtract_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] -= rhs_value; } return lhs; } - template + template constexpr ordered_map& operator*=( - ordered_map& lhs, - ordered_map const& rhs - ) requires multiply_assignable { + ordered_map& lhs, ordered_map const& rhs + ) + requires multiply_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] *= rhs_value; } return lhs; } - template + template constexpr ordered_map& operator/=( - ordered_map& lhs, - ordered_map const& rhs - ) requires divide_assignable { + ordered_map& lhs, ordered_map const& rhs + ) + requires divide_assignable + { for (auto const& [key, rhs_value] : rhs) { lhs[key] = rhs_value; } return lhs; } - template - constexpr ordered_map& operator+=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires add_assignable { + template + constexpr ordered_map& operator+=(ordered_map& lhs, RhsValueType const& rhs) + requires add_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() += rhs; } return lhs; } - template - constexpr ordered_map& operator-=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires subtract_assignable { + template + constexpr ordered_map& operator-=(ordered_map& lhs, RhsValueType const& rhs) + requires subtract_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() -= rhs; } return lhs; } - template - constexpr ordered_map& operator*=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires multiply_assignable { + template + constexpr ordered_map& operator*=(ordered_map& lhs, RhsValueType const& rhs) + requires multiply_assignable + { for (typename decltype(lhs)::iterator it = lhs.begin(); it != lhs.end(); ++it) { it.value() *= rhs; } return lhs; } - template - constexpr ordered_map& operator/=( - ordered_map& lhs, - RhsValueType const& rhs - ) requires divide_assignable { + template + constexpr ordered_map& operator/=(ordered_map& lhs, RhsValueType const& rhs) + requires divide_assignable + { for (auto it = lhs.begin(); it != lhs.end(); ++it) { it.value() /= rhs; } return lhs; } - template - constexpr static ValueType get_total( - ordered_map const& map - ) requires std::is_default_constructible_v { + template + constexpr static ValueType get_total(ordered_map const& map) + requires std::is_default_constructible_v + { ValueType running_total {}; for (auto const& [key, value] : map) { running_total += value; @@ -118,14 +116,14 @@ namespace OpenVic { return running_total; } - template + template constexpr static typename ordered_map::const_iterator get_largest_item( - ordered_map const& map - ) requires std::three_way_comparable_with { - constexpr auto pred = []( - typename ordered_map::value_type const& lhs, - typename ordered_map::value_type const& rhs - ) -> bool { + ordered_map const& map + ) + requires std::three_way_comparable_with + { + constexpr auto pred = [](typename ordered_map::value_type const& lhs, + typename ordered_map::value_type const& rhs) -> bool { return lhs.second < rhs.second; }; @@ -133,27 +131,29 @@ namespace OpenVic { } /* This function includes a key comparator to choose between entries with equal values. */ - template + template constexpr static typename ordered_map::const_iterator get_largest_item_tie_break( - ordered_map const& map, const auto key_pred - ) requires std::three_way_comparable_with { - constexpr auto pred = [key_pred]( - typename ordered_map::value_type const& lhs, - typename ordered_map::value_type const& rhs - ) -> bool { + ordered_map const& map, const auto key_pred + ) + requires std::three_way_comparable_with + { + constexpr auto pred = + [key_pred]( + typename ordered_map::value_type const& lhs, + typename ordered_map::value_type const& rhs + ) -> bool { return lhs.second < rhs.second || (lhs.second == rhs.second && key_pred(lhs.first, rhs.first)); }; return std::max_element(map.begin(), map.end(), pred); } - template - constexpr static std::pair< - typename ordered_map::const_iterator, - typename ordered_map::const_iterator - > get_largest_two_items( - ordered_map const& map - ) requires std::three_way_comparable_with { + template + constexpr static std:: + pair::const_iterator, typename ordered_map::const_iterator> + get_largest_two_items(ordered_map const& map) + requires std::three_way_comparable_with + { typename ordered_map::const_iterator largest = map.end(), second_largest = map.end(); for (typename ordered_map::const_iterator it = map.begin(); it != map.end(); ++it) { @@ -165,9 +165,6 @@ namespace OpenVic { } } - return std::make_pair( - std::move(largest), - std::move(second_largest) - ); + return std::make_pair(std::move(largest), std::move(second_largest)); } } diff --git a/src/openvic-simulation/types/PopSprite.hpp b/src/openvic-simulation/types/PopSprite.hpp index 3d086342c..7b026c992 100644 --- a/src/openvic-simulation/types/PopSprite.hpp +++ b/src/openvic-simulation/types/PopSprite.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using pop_sprite_t = uint8_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/Signal.hpp b/src/openvic-simulation/types/Signal.hpp index 323320e5e..481ce9c84 100644 --- a/src/openvic-simulation/types/Signal.hpp +++ b/src/openvic-simulation/types/Signal.hpp @@ -11,16 +11,16 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/stl/containers/CowVector.hpp" #include "openvic-simulation/core/thread/NullMutex.hpp" -#include "openvic-simulation/core/Typedefs.hpp" // For OpenVic::_detail::signal::make_shared #ifdef DEBUG_ENABLED - #include "openvic-simulation/core/memory/allocators/NewAllocator.hpp" +#include "openvic-simulation/core/memory/allocators/NewAllocator.hpp" #else - #include "openvic-simulation/core/memory/SmartPtr.hpp" +#include "openvic-simulation/core/memory/SmartPtr.hpp" #endif // Based heavily on https://github.com/palacaze/sigslot and https://github.com/mousebyte/sigslot20 @@ -659,8 +659,8 @@ namespace OpenVic::_detail::signal { template struct slot_pmf final : public basic_slot { template - constexpr slot_pmf(cleanable& c, F&& f, P&& p, group_id gid) - : basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} + constexpr slot_pmf(cleanable& c, F&& f, P&& p, group_id gid) : + basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} protected: void call_slot(Args... args) override { @@ -683,8 +683,8 @@ namespace OpenVic::_detail::signal { template struct slot_pmf_extended final : public basic_slot { template - constexpr slot_pmf_extended(cleanable& c, F&& f, P&& p, group_id gid) - : basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} + constexpr slot_pmf_extended(cleanable& c, F&& f, P&& p, group_id gid) : + basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} connection conn; @@ -708,8 +708,8 @@ namespace OpenVic::_detail::signal { template struct slot_tracked final : public basic_slot { template - constexpr slot_tracked(cleanable& c, F&& f, P&& p, group_id gid) - : basic_slot(c, gid), func { std::forward(f) }, ptr { std::forward

(p) } {} + constexpr slot_tracked(cleanable& c, F&& f, P&& p, group_id gid) : + basic_slot(c, gid), func { std::forward(f) }, ptr { std::forward

(p) } {} bool connected() const override { return !ptr.expired() && slot_state::connected(); @@ -743,8 +743,8 @@ namespace OpenVic::_detail::signal { template struct slot_pmf_tracked final : public basic_slot { template - constexpr slot_pmf_tracked(cleanable& c, F&& f, P&& p, group_id gid) - : basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} + constexpr slot_pmf_tracked(cleanable& c, F&& f, P&& p, group_id gid) : + basic_slot(c, gid), pmf { std::forward(f) }, ptr { std::forward

(p) } {} bool connected() const override { return !ptr.expired() && slot_state::connected(); @@ -803,13 +803,15 @@ namespace OpenVic::_detail::signal { template using cow_type = std::conditional_t< - is_thread_safe::value, ::OpenVic::stl::cow_vector, - list_type>; + is_thread_safe::value, + ::OpenVic::stl::cow_vector, + list_type>; template using cow_copy_type = std::conditional_t< - is_thread_safe::value, ::OpenVic::stl::cow_vector, - list_type const&>; + is_thread_safe::value, + ::OpenVic::stl::cow_vector, + list_type const&>; public: using arg_list = std::tuple; @@ -1057,8 +1059,8 @@ namespace OpenVic::_detail::signal { */ template requires( - (Callable || Callable || MemberFunctionPointer) && - function_traits::is_disconnectable + (Callable || Callable || MemberFunctionPointer) && + function_traits::is_disconnectable ) size_t disconnect(C const& c) { return disconnect_if([&](slot_ptr const& s) { @@ -1434,8 +1436,8 @@ namespace OpenVic { template connection connect(basic_signal& sig1, basic_signal& sig2, Args&&... args) { return sig1.connect( - _detail::signal::signal_wrapper> { std::addressof(sig2) }, - std::forward(args)... + _detail::signal::signal_wrapper> { std::addressof(sig2) }, + std::forward(args)... ); } } diff --git a/src/openvic-simulation/types/TypedIndices.hpp b/src/openvic-simulation/types/TypedIndices.hpp index ab58df6d3..ee1a81842 100644 --- a/src/openvic-simulation/types/TypedIndices.hpp +++ b/src/openvic-simulation/types/TypedIndices.hpp @@ -12,15 +12,16 @@ #define TYPED_INDEX_CUSTOM(name, base_type) \ namespace OpenVic { \ - struct name : type_safe::strong_typedef, \ - type_safe::strong_typedef_op::equality_comparison, \ - type_safe::strong_typedef_op::relational_comparison, \ - type_safe::strong_typedef_op::integer_arithmetic { \ + struct name \ + : type_safe::strong_typedef, \ + type_safe::strong_typedef_op::equality_comparison, \ + type_safe::strong_typedef_op::relational_comparison, \ + type_safe::strong_typedef_op::integer_arithmetic { \ using strong_typedef::strong_typedef; \ }; \ } \ namespace std { \ - template <> \ + template<> \ struct hash : type_safe::hashable {}; \ } \ template<> \ @@ -69,17 +70,18 @@ TYPED_INDEX(terrain_type_index_t) TYPED_INDEX(unit_type_index_t) namespace OpenVic { - struct province_index_t : type_safe::strong_typedef, - type_safe::strong_typedef_op::equality_comparison, - type_safe::strong_typedef_op::relational_comparison, - type_safe::strong_typedef_op::integer_arithmetic, - type_safe::strong_typedef_op::mixed_addition, - type_safe::strong_typedef_op::mixed_subtraction { + struct province_index_t + : type_safe::strong_typedef, + type_safe::strong_typedef_op::equality_comparison, + type_safe::strong_typedef_op::relational_comparison, + type_safe::strong_typedef_op::integer_arithmetic, + type_safe::strong_typedef_op::mixed_addition, + type_safe::strong_typedef_op::mixed_subtraction { using strong_typedef::strong_typedef; }; } namespace std { - template <> + template<> struct hash : type_safe::hashable {}; } template<> diff --git a/src/openvic-simulation/types/UniqueId.hpp b/src/openvic-simulation/types/UniqueId.hpp index 27c1eed91..f72a7498c 100644 --- a/src/openvic-simulation/types/UniqueId.hpp +++ b/src/openvic-simulation/types/UniqueId.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using unique_id_t = uint64_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/UnitBranchType.hpp b/src/openvic-simulation/types/UnitBranchType.hpp index 2db89e5c3..bb67b46a3 100644 --- a/src/openvic-simulation/types/UnitBranchType.hpp +++ b/src/openvic-simulation/types/UnitBranchType.hpp @@ -4,7 +4,11 @@ #include namespace OpenVic { - enum struct unit_branch_t : uint8_t { INVALID_BRANCH, LAND, NAVAL }; + enum struct unit_branch_t : uint8_t { + INVALID_BRANCH, + LAND, + NAVAL + }; template struct UnitTypeBranched; @@ -12,7 +16,12 @@ namespace OpenVic { using RegimentType = UnitTypeBranched; // Each value is a subset of its predecessor, so smaller values contain larger values // The exact values here must be preserved to allow easy comparison against Pop::culture_status_t - enum struct regiment_allowed_cultures_t : uint8_t { ALL_CULTURES, ACCEPTED_CULTURES, PRIMARY_CULTURE, NO_CULTURES }; + enum struct regiment_allowed_cultures_t : uint8_t { + ALL_CULTURES, + ACCEPTED_CULTURES, + PRIMARY_CULTURE, + NO_CULTURES + }; using ShipType = UnitTypeBranched; @@ -26,53 +35,41 @@ namespace OpenVic { using ArmyInstance = UnitInstanceGroupBranched; using NavyInstance = UnitInstanceGroupBranched; - + static constexpr std::string_view get_branch_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "land"; - case NAVAL: - return "naval"; - default: - return "INVALID BRANCH"; + case LAND: return "land"; + case NAVAL: return "naval"; + default: return "INVALID BRANCH"; } } static constexpr std::string_view get_branched_unit_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "regiment"; - case NAVAL: - return "ship"; - default: - return "INVALID UNIT BRANCH"; + case LAND: return "regiment"; + case NAVAL: return "ship"; + default: return "INVALID UNIT BRANCH"; } } static constexpr std::string_view get_branched_unit_group_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "army"; - case NAVAL: - return "navy"; - default: - return "INVALID UNIT GROUP BRANCH"; + case LAND: return "army"; + case NAVAL: return "navy"; + default: return "INVALID UNIT GROUP BRANCH"; } } static constexpr std::string_view get_branched_leader_name(unit_branch_t branch) { using enum unit_branch_t; switch (branch) { - case LAND: - return "general"; - case NAVAL: - return "admiral"; - default: - return "INVALID LEADER BRANCH"; + case LAND: return "general"; + case NAVAL: return "admiral"; + default: return "INVALID LEADER BRANCH"; } } -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/UnitVariant.hpp b/src/openvic-simulation/types/UnitVariant.hpp index f1711281b..93533fb8f 100644 --- a/src/openvic-simulation/types/UnitVariant.hpp +++ b/src/openvic-simulation/types/UnitVariant.hpp @@ -4,4 +4,4 @@ namespace OpenVic { using unit_variant_t = uint8_t; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/types/ValueHistory.hpp b/src/openvic-simulation/types/ValueHistory.hpp index 9b56ad998..ab5ab685d 100644 --- a/src/openvic-simulation/types/ValueHistory.hpp +++ b/src/openvic-simulation/types/ValueHistory.hpp @@ -11,31 +11,31 @@ namespace OpenVic { using base_type = ::OpenVic::stl::RingBuffer; using typename base_type::allocator_type; - using typename base_type::size_type; - using typename base_type::iterator; using typename base_type::const_iterator; - using typename base_type::reverse_iterator; - using typename base_type::const_reverse_iterator; - using typename base_type::reference; - using typename base_type::const_reference; - using typename base_type::pointer; using typename base_type::const_pointer; + using typename base_type::const_reference; + using typename base_type::const_reverse_iterator; using typename base_type::difference_type; + using typename base_type::iterator; + using typename base_type::pointer; + using typename base_type::reference; + using typename base_type::reverse_iterator; + using typename base_type::size_type; using base_type::operator[]; - using base_type::size; - using base_type::capacity; - using base_type::empty; + using base_type::back; using base_type::begin; - using base_type::end; + using base_type::capacity; using base_type::cbegin; using base_type::cend; - using base_type::rbegin; - using base_type::rend; using base_type::crbegin; using base_type::crend; + using base_type::empty; + using base_type::end; using base_type::front; - using base_type::back; using base_type::push_back; + using base_type::rbegin; + using base_type::rend; + using base_type::size; constexpr ValueHistory() {}; explicit ValueHistory(size_type capacity) : base_type(capacity) {} diff --git a/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp b/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp index 90c1a08c4..abb1dc613 100644 --- a/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp +++ b/src/openvic-simulation/types/fixed_point/FixedPointMap.hpp @@ -27,7 +27,7 @@ namespace OpenVic { template constexpr fixed_point_map_t& fixed_point_map_mul_add( - fixed_point_map_t& lhs, fixed_point_map_t const& rhs, fixed_point_t factor + fixed_point_map_t& lhs, fixed_point_map_t const& rhs, fixed_point_t factor ) { if (factor != 0) { for (auto const& [key, value] : rhs) { @@ -90,7 +90,6 @@ namespace OpenVic { if (value_cmp != std::strong_ordering::equal) { return value_cmp == std::strong_ordering::less; } - } return rit != rhs.rcend(); diff --git a/src/openvic-simulation/utility/CompilerFeatureTesting.hpp b/src/openvic-simulation/utility/CompilerFeatureTesting.hpp index 8c9f961c8..154c23611 100644 --- a/src/openvic-simulation/utility/CompilerFeatureTesting.hpp +++ b/src/openvic-simulation/utility/CompilerFeatureTesting.hpp @@ -13,7 +13,7 @@ namespace OpenVic { std::for_each(first, last, f); #else #if defined(__linux__) || defined(__MINGW32__) - // We cannot use std::execution::par here as its implementation uses exceptions, which we have disabled + // We cannot use std::execution::par here as its implementation uses exceptions, which we have disabled std::for_each(first, last, f); #else if constexpr (__cpp_lib_execution >= 201603L) { diff --git a/src/openvic-simulation/utility/ConstexprIntToStr.hpp b/src/openvic-simulation/utility/ConstexprIntToStr.hpp index e346ebe96..06b469be4 100644 --- a/src/openvic-simulation/utility/ConstexprIntToStr.hpp +++ b/src/openvic-simulation/utility/ConstexprIntToStr.hpp @@ -34,7 +34,7 @@ namespace OpenVic::ConstexprIntToStr { if constexpr (next_value != 0) { return append_sequence( - integer_to_string_sequence(), std::integer_sequence {} + integer_to_string_sequence(), std::integer_sequence {} ); } else { return std::integer_sequence {}; diff --git a/src/openvic-simulation/utility/Getters.hpp b/src/openvic-simulation/utility/Getters.hpp index 36dd97820..6d081a4f0 100644 --- a/src/openvic-simulation/utility/Getters.hpp +++ b/src/openvic-simulation/utility/Getters.hpp @@ -6,11 +6,11 @@ #include #include +#include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep #include "openvic-simulation/core/memory/String.hpp" #include "openvic-simulation/core/portable/ForwardableSpan.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" #include "openvic-simulation/core/template/Concepts.hpp" -#include "openvic-simulation/core/Typedefs.hpp" // IWYU pragma: keep namespace OpenVic::utility { #if !defined(_MSC_VER) @@ -162,18 +162,16 @@ namespace OpenVic { result.emplace(property.value()); } return result; - }else { + } else { /* Return const reference */ return property; } } // Primary template: Default to forwardable_span - template + template struct SpanSelector { - using type = OpenVic::forwardable_span< - std::add_const_t - >; + using type = OpenVic::forwardable_span>; static constexpr type get(const Container& container) { return container; @@ -181,16 +179,10 @@ namespace OpenVic { }; // Specialization: Triggered if Container has an size_type that is strongly typed - template - requires ( - requires { typename Container::size_type; } - && is_strongly_typed - ) + template + requires(requires { typename Container::size_type; } && is_strongly_typed) struct SpanSelector { - using type = OpenVic::TypedSpan< - typename Container::size_type, - std::add_const_t - >; + using type = OpenVic::TypedSpan>; static constexpr type get(const Container& container) { return container; // Assumes TypedSpan can be constructed from the container @@ -227,7 +219,8 @@ public: \ // TODO: Special logic to decide argument type and control assignment. #define PROPERTY_RW(NAME, ...) PROPERTY_RW_ACCESS(NAME, private, __VA_ARGS__) -#define PROPERTY_RW_CUSTOM_NAME(NAME, GETTER_NAME, SETTER_NAME, ...) PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, private, __VA_ARGS__) +#define PROPERTY_RW_CUSTOM_NAME(NAME, GETTER_NAME, SETTER_NAME, ...) \ + PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, private, __VA_ARGS__) #define PROPERTY_RW_ACCESS(NAME, ACCESS, ...) PROPERTY_RW_FULL(NAME, get_##NAME, set_##NAME, ACCESS, __VA_ARGS__) #define PROPERTY_RW_FULL(NAME, GETTER_NAME, SETTER_NAME, ACCESS, ...) \ PROPERTY_FULL(NAME, GETTER_NAME, ACCESS, __VA_ARGS__) \ @@ -245,6 +238,7 @@ public: \ #define PROPERTY_PTR_ACCESS(NAME, ACCESS, ...) \ NAME __VA_OPT__(=) __VA_ARGS__; \ static_assert(std::is_pointer_v && !std::is_const_v>); \ +\ public: \ [[nodiscard]] constexpr decltype(NAME) get_##NAME() { \ return NAME; \ @@ -252,15 +246,14 @@ public: \ [[nodiscard]] constexpr std::add_pointer_t>> get_##NAME() const { \ return NAME; \ } \ -ACCESS: + ACCESS: #define SPAN_PROPERTY(NAME) SPAN_PROPERTY_ACCESS(NAME, private) #define SPAN_PROPERTY_ACCESS(NAME, ACCESS) \ NAME; \ \ public: \ - [[nodiscard]] constexpr auto get_##NAME() const \ - -> typename OpenVic::SpanSelector::type { \ + [[nodiscard]] constexpr auto get_##NAME() const -> typename OpenVic::SpanSelector::type { \ return OpenVic::SpanSelector::get(NAME); \ } \ ACCESS: diff --git a/src/openvic-simulation/utility/Logger.hpp b/src/openvic-simulation/utility/Logger.hpp index d54d11fec..26114a65b 100644 --- a/src/openvic-simulation/utility/Logger.hpp +++ b/src/openvic-simulation/utility/Logger.hpp @@ -16,28 +16,35 @@ namespace spdlog { template struct log_s { log_s( - level::level_enum level, format_string_t fmt, Args&&... args, - std::source_location const& location = std::source_location::current() + level::level_enum level, + format_string_t fmt, + Args&&... args, + std::source_location const& location = std::source_location::current() ) { memory_buf_t buf; fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); default_logger_raw()->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, - string_view_t(buf.data(), buf.size()) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + string_view_t(buf.data(), buf.size()) ); } log_s( - std::shared_ptr const& logger, level::level_enum level, format_string_t fmt, Args&&... args, - std::source_location const& location = std::source_location::current() + std::shared_ptr const& logger, + level::level_enum level, + format_string_t fmt, + Args&&... args, + std::source_location const& location = std::source_location::current() ) { memory_buf_t buf; fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); logger->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, - string_view_t(buf.data(), buf.size()) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + string_view_t(buf.data(), buf.size()) ); } }; @@ -52,38 +59,51 @@ namespace spdlog { template struct log_s { log_s( - level::level_enum level, format_string_t fmt, T&& arg, - std::source_location const& location = std::source_location::current() + level::level_enum level, + format_string_t fmt, + T&& arg, + std::source_location const& location = std::source_location::current() ) { default_logger_raw()->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, fmt, - std::forward(arg) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + fmt, + std::forward(arg) ); } log_s(level::level_enum level, T&& arg, std::source_location const& location = std::source_location::current()) { default_logger_raw()->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, - std::forward(arg) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + std::forward(arg) ); } log_s( - std::shared_ptr const& logger, level::level_enum level, format_string_t fmt, T&& arg, - std::source_location const& location = std::source_location::current() + std::shared_ptr const& logger, + level::level_enum level, + format_string_t fmt, + T&& arg, + std::source_location const& location = std::source_location::current() ) { logger->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, fmt, - std::forward(arg) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + fmt, + std::forward(arg) ); } log_s( - std::shared_ptr const& logger, level::level_enum level, T&& arg, - std::source_location const& location = std::source_location::current() + std::shared_ptr const& logger, + level::level_enum level, + T&& arg, + std::source_location const& location = std::source_location::current() ) { logger->log( - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, level, - std::forward(arg) + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, + level, + std::forward(arg) ); } }; @@ -97,28 +117,33 @@ namespace spdlog { template \ struct NAME { \ NAME( \ - format_string_t fmt, Args&&... args, \ - std::source_location const& location = std::source_location::current() \ + format_string_t fmt, \ + Args&&... args, \ + std::source_location const& location = std::source_location::current() \ ) { \ memory_buf_t buf; \ fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); \ \ default_logger_raw()->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, \ - string_view_t(buf.data(), buf.size()) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + string_view_t(buf.data(), buf.size()) \ ); \ } \ \ NAME( \ - std::shared_ptr const& logger, format_string_t fmt, Args&&... args, \ - std::source_location const& location = std::source_location::current() \ + std::shared_ptr const& logger, \ + format_string_t fmt, \ + Args&&... args, \ + std::source_location const& location = std::source_location::current() \ ) { \ memory_buf_t buf; \ fmt::vformat_to(fmt::appender(buf), fmt, fmt::make_format_args(args...)); \ \ logger->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, \ - string_view_t(buf.data(), buf.size()) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + string_view_t(buf.data(), buf.size()) \ ); \ } \ }; \ @@ -132,34 +157,43 @@ namespace spdlog { struct NAME { \ NAME(format_string_t fmt, T&& arg, std::source_location const& location = std::source_location::current()) { \ default_logger_raw()->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, fmt, \ - std::forward(arg) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + fmt, \ + std::forward(arg) \ ); \ } \ NAME(T&& arg, std::source_location const& location = std::source_location::current()) { \ default_logger_raw()->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, \ - std::forward(arg) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + std::forward(arg) \ ); \ } \ \ NAME( \ - std::shared_ptr const& logger, format_string_t fmt, T&& arg, \ - std::source_location const& location = std::source_location::current() \ + std::shared_ptr const& logger, \ + format_string_t fmt, \ + T&& arg, \ + std::source_location const& location = std::source_location::current() \ ) { \ logger->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, fmt, \ - std::forward(arg) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + fmt, \ + std::forward(arg) \ ); \ } \ \ NAME( \ - std::shared_ptr const& logger, T&& arg, \ - std::source_location const& location = std::source_location::current() \ + std::shared_ptr const& logger, \ + T&& arg, \ + std::source_location const& location = std::source_location::current() \ ) { \ logger->log( \ - source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, LEVEL, \ - std::forward(arg) \ + source_loc { location.file_name(), static_cast(location.line()), location.function_name() }, \ + LEVEL, \ + std::forward(arg) \ ); \ } \ }; \ @@ -195,8 +229,9 @@ namespace spdlog { std::shared_ptr back = stack.top(); if (back->name() != _logger->name()) { error( - "Tried exiting scope \"{}\" but \"{}\" would be removed instead. No scope was removed.", _logger->name(), - back->name() + "Tried exiting scope \"{}\" but \"{}\" would be removed instead. No scope was removed.", + _logger->name(), + back->name() ); return; } diff --git a/src/openvic-simulation/utility/ThreadPool.cpp b/src/openvic-simulation/utility/ThreadPool.cpp index 49610f095..9bef40f6c 100644 --- a/src/openvic-simulation/utility/ThreadPool.cpp +++ b/src/openvic-simulation/utility/ThreadPool.cpp @@ -17,51 +17,44 @@ using namespace OpenVic; void ThreadPool::loop_until_cancelled( - work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - const good_index_t good_count, - const strata_index_t strata_count, - forwardable_span work_bundles + work_t& work_type, + GameRulesManager const& game_rules_manager, + GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, + PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, + forwardable_span country_keys, + const good_index_t good_count, + const strata_index_t strata_count, + forwardable_span work_bundles ) { memory::FixedVector reusable_goods_mask { good_count, {} }; - memory::FixedVector reusable_country_map_0 { country_index_t(country_keys.size()), fixed_point_t::_0 }; - memory::FixedVector reusable_country_map_1 { country_index_t(country_keys.size()), fixed_point_t::_0 }; + memory::FixedVector reusable_country_map_0 { + country_index_t(country_keys.size()), fixed_point_t::_0 + }; + memory::FixedVector reusable_country_map_1 { + country_index_t(country_keys.size()), fixed_point_t::_0 + }; static constexpr std::size_t VECTOR_COUNT = std::max( - GoodMarket::VECTORS_FOR_EXECUTE_ORDERS, - std::max( - CountryInstance::VECTORS_FOR_COUNTRY_TICK, - ProvinceInstance::VECTORS_FOR_PROVINCE_TICK - ) + GoodMarket::VECTORS_FOR_EXECUTE_ORDERS, + std::max(CountryInstance::VECTORS_FOR_COUNTRY_TICK, ProvinceInstance::VECTORS_FOR_PROVINCE_TICK) ); std::array, VECTOR_COUNT> reusable_vectors; std::span, VECTOR_COUNT> reusable_vectors_span = std::span(reusable_vectors); memory::vector reusable_good_index_vector; PopValuesFromProvince reusable_pop_values { - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - production_type_manager, - pop_defines, - strata_count + game_rules_manager, good_instance_manager, modifier_effect_cache, production_type_manager, pop_defines, strata_count }; while (!is_cancellation_requested) { work_t work_type_copy; { std::unique_lock thread_lock { thread_mutex }; - thread_condition.wait( - thread_lock, - [this, &work_type]() -> bool { - return is_cancellation_requested || work_type != work_t::NONE; - } - ); + thread_condition.wait(thread_lock, [this, &work_type]() -> bool { + return is_cancellation_requested || work_type != work_t::NONE; + }); if (is_cancellation_requested) { return; @@ -71,63 +64,62 @@ void ThreadPool::loop_until_cancelled( } switch (work_type_copy) { - case work_t::NONE: - break; - case work_t::GOOD_EXECUTE_ORDERS: - for (WorkBundle& work_bundle : work_bundles) { - for (GoodMarket& good : work_bundle.goods_chunk) { - good.execute_orders( - reusable_country_map_0, - reusable_country_map_1, - reusable_vectors_span.first() - ); - } + case work_t::NONE: break; + case work_t::GOOD_EXECUTE_ORDERS: + for (WorkBundle& work_bundle : work_bundles) { + for (GoodMarket& good : work_bundle.goods_chunk) { + good.execute_orders( + reusable_country_map_0, + reusable_country_map_1, + reusable_vectors_span.first() + ); } - break; - case work_t::PROVINCE_TICK: - for (WorkBundle& work_bundle : work_bundles) { - for (ProvinceInstance& province : work_bundle.provinces_chunk) { - province.province_tick( - current_date, - reusable_pop_values, - work_bundle.random_number_generator, - reusable_goods_mask, - reusable_vectors_span.first() - ); - } + } + break; + case work_t::PROVINCE_TICK: + for (WorkBundle& work_bundle : work_bundles) { + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.province_tick( + current_date, + reusable_pop_values, + work_bundle.random_number_generator, + reusable_goods_mask, + reusable_vectors_span.first() + ); } - break; - case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: - for (WorkBundle& work_bundle : work_bundles) { - for (ProvinceInstance& province : work_bundle.provinces_chunk) { - province.initialise_for_new_game( - current_date, - reusable_pop_values, - work_bundle.random_number_generator, - reusable_goods_mask, - reusable_vectors_span.first() - ); - } + } + break; + case work_t::PROVINCE_INITIALISE_FOR_NEW_GAME: + for (WorkBundle& work_bundle : work_bundles) { + for (ProvinceInstance& province : work_bundle.provinces_chunk) { + province.initialise_for_new_game( + current_date, + reusable_pop_values, + work_bundle.random_number_generator, + reusable_goods_mask, + reusable_vectors_span.first() + ); } - break; - case work_t::COUNTRY_TICK_BEFORE_MAP: - for (WorkBundle& work_bundle : work_bundles) { - for (CountryInstance& country : work_bundle.countries_chunk) { - country.country_tick_before_map( - reusable_goods_mask, - reusable_vectors_span.first(), - reusable_good_index_vector - ); - } + } + break; + case work_t::COUNTRY_TICK_BEFORE_MAP: + for (WorkBundle& work_bundle : work_bundles) { + for (CountryInstance& country : work_bundle.countries_chunk) { + country.country_tick_before_map( + reusable_goods_mask, + reusable_vectors_span.first(), + reusable_good_index_vector + ); } - break; - case work_t::COUNTRY_TICK_AFTER_MAP: - for (WorkBundle& work_bundle : work_bundles) { - for (CountryInstance& country : work_bundle.countries_chunk) { - country.country_tick_after_map(current_date); - } + } + break; + case work_t::COUNTRY_TICK_AFTER_MAP: + for (WorkBundle& work_bundle : work_bundles) { + for (CountryInstance& country : work_bundle.countries_chunk) { + country.country_tick_after_map(current_date); } - break; + } + break; } { @@ -161,16 +153,12 @@ void ThreadPool::process_work(const work_t work_type) { void ThreadPool::await_completion() { std::unique_lock completed_lock { completed_mutex }; - completed_condition.wait( - completed_lock, - [this]() -> bool { - return active_work_count == 0; - } - ); + completed_condition.wait(completed_lock, [this]() -> bool { + return active_work_count == 0; + }); } -ThreadPool::ThreadPool(Date const& new_current_date) - : current_date {new_current_date} {} +ThreadPool::ThreadPool(Date const& new_current_date) : current_date { new_current_date } {} ThreadPool::~ThreadPool() { { @@ -184,41 +172,35 @@ ThreadPool::~ThreadPool() { } void ThreadPool::initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - const strata_index_t strata_count, - forwardable_span goods, - forwardable_span countries, - forwardable_span provinces + GameRulesManager const& game_rules_manager, + GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, + PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, + const strata_index_t strata_count, + forwardable_span goods, + forwardable_span countries, + forwardable_span provinces ) { if (threads.size() > 0) { spdlog::error_s("Attempted to initialise ThreadPool again."); return; } - RandomU32 master_rng { }; //TODO seed? + RandomU32 master_rng {}; // TODO seed? const auto [goods_quotient, goods_remainder] = std::ldiv(goods.size(), WORK_BUNDLE_COUNT); - const auto [countries_quotient, countries_remainder] = std::ldiv(countries.size(),WORK_BUNDLE_COUNT); - const auto [provinces_quotient, provinces_remainder] = std::ldiv(provinces.size(),WORK_BUNDLE_COUNT); + const auto [countries_quotient, countries_remainder] = std::ldiv(countries.size(), WORK_BUNDLE_COUNT); + const auto [provinces_quotient, provinces_remainder] = std::ldiv(provinces.size(), WORK_BUNDLE_COUNT); auto goods_begin = goods.begin(); auto countries_begin = countries.begin(); auto provinces_begin = provinces.begin(); for (std::size_t i = 0; i < WORK_BUNDLE_COUNT; i++) { - const std::size_t goods_chunk_size = i < goods_remainder - ? goods_quotient + 1 - : goods_quotient; - const std::size_t countries_chunk_size = i < countries_remainder - ? countries_quotient + 1 - : countries_quotient; - const std::size_t provinces_chunk_size = i < provinces_remainder - ? provinces_quotient + 1 - : provinces_quotient; + const std::size_t goods_chunk_size = i < goods_remainder ? goods_quotient + 1 : goods_quotient; + const std::size_t countries_chunk_size = i < countries_remainder ? countries_quotient + 1 : countries_quotient; + const std::size_t provinces_chunk_size = i < provinces_remainder ? provinces_quotient + 1 : provinces_quotient; auto goods_end = goods_begin + goods_chunk_size; auto countries_end = countries_begin + countries_chunk_size; @@ -226,12 +208,12 @@ void ThreadPool::initialise_threadpool( all_work_bundles[i] = WorkBundle { master_rng.generator().serialize(), - std::span{ countries_begin, countries_end }, - std::span{ goods_begin, goods_end }, - std::span{ provinces_begin, provinces_end } + std::span { countries_begin, countries_end }, + std::span { goods_begin, goods_end }, + std::span { provinces_begin, provinces_end } }; - //ensure different state for next WorkBundle + // ensure different state for next WorkBundle master_rng.generator().jump(); goods_begin = goods_end; @@ -240,51 +222,47 @@ void ThreadPool::initialise_threadpool( } const std::size_t max_worker_threads = std::min( - std::max(std::thread::hardware_concurrency(), 1), - WORK_BUNDLE_COUNT + std::max(std::thread::hardware_concurrency(), 1), WORK_BUNDLE_COUNT ); threads.reserve(max_worker_threads); work_per_thread.resize(max_worker_threads, work_t::NONE); - + const auto [work_bundles_quotient, work_bundles_remainder] = std::ldiv(WORK_BUNDLE_COUNT, max_worker_threads); auto work_bundles_begin = all_work_bundles.begin(); for (std::size_t i = 0; i < max_worker_threads; ++i) { - const std::size_t work_bundles_chunk_size = i < work_bundles_remainder - ? work_bundles_quotient + 1 - : work_bundles_quotient; + const std::size_t work_bundles_chunk_size = + i < work_bundles_remainder ? work_bundles_quotient + 1 : work_bundles_quotient; auto work_bundles_end = work_bundles_begin + work_bundles_chunk_size; threads.emplace_back( - [ - this, - &work_for_thread = work_per_thread[i], - &game_rules_manager, - &good_instance_manager, - &modifier_effect_cache, - &pop_defines, - &production_type_manager, - countries, - good_count = good_index_t(goods.size()), - strata_count, - work_bundles_begin, - work_bundles_end - ]() -> void { - loop_until_cancelled( - work_for_thread, - game_rules_manager, - good_instance_manager, - modifier_effect_cache, - pop_defines, - production_type_manager, - countries, - good_count, - strata_count, - std::span{ work_bundles_begin, work_bundles_end } - ); - } + [this, + &work_for_thread = work_per_thread[i], + &game_rules_manager, + &good_instance_manager, + &modifier_effect_cache, + &pop_defines, + &production_type_manager, + countries, + good_count = good_index_t(goods.size()), + strata_count, + work_bundles_begin, + work_bundles_end]() -> void { + loop_until_cancelled( + work_for_thread, + game_rules_manager, + good_instance_manager, + modifier_effect_cache, + pop_defines, + production_type_manager, + countries, + good_count, + strata_count, + std::span { work_bundles_begin, work_bundles_end } + ); + } ); work_bundles_begin = work_bundles_end; @@ -307,6 +285,6 @@ void ThreadPool::process_country_ticks_before_map() { process_work(work_t::COUNTRY_TICK_BEFORE_MAP); } -void ThreadPool::process_country_ticks_after_map(){ +void ThreadPool::process_country_ticks_after_map() { process_work(work_t::COUNTRY_TICK_AFTER_MAP); -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/ThreadPool.hpp b/src/openvic-simulation/utility/ThreadPool.hpp index 9d11236b8..ad00176ca 100644 --- a/src/openvic-simulation/utility/ThreadPool.hpp +++ b/src/openvic-simulation/utility/ThreadPool.hpp @@ -7,7 +7,6 @@ #include #include -#include "openvic-simulation/population/PopValuesFromProvince.hpp" #include "openvic-simulation/core/memory/Vector.hpp" #include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/portable/ForwardableSpan.hpp" @@ -25,8 +24,8 @@ namespace OpenVic { struct PopsDefines; struct ProductionTypeManager; struct Strata; - - //bundle work so they always have the same rng regardless of hardware concurrency + + // bundle work so they always have the same rng regardless of hardware concurrency struct WorkBundle { public: RandomU32 random_number_generator; @@ -37,15 +36,13 @@ namespace OpenVic { constexpr WorkBundle() {} WorkBundle( - RandomU32::state_type rng_state, - forwardable_span new_countries_chunk, - forwardable_span new_goods_chunk, - forwardable_span new_provinces_chunk - ) : random_number_generator { rng_state }, - countries_chunk { new_countries_chunk }, - goods_chunk { new_goods_chunk }, - provinces_chunk { new_provinces_chunk } - {} + RandomU32::state_type rng_state, + forwardable_span new_countries_chunk, + forwardable_span new_goods_chunk, + forwardable_span new_provinces_chunk + ) : + random_number_generator { rng_state }, countries_chunk { new_countries_chunk }, goods_chunk { new_goods_chunk }, + provinces_chunk { new_provinces_chunk } {} }; struct ThreadPool { @@ -70,16 +67,16 @@ namespace OpenVic { Date const& current_date; void loop_until_cancelled( - work_t& work_type, - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - forwardable_span country_keys, - const good_index_t good_count, - const strata_index_t strata_count, - forwardable_span work_bundles + work_t& work_type, + GameRulesManager const& game_rules_manager, + GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, + PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, + forwardable_span country_keys, + const good_index_t good_count, + const strata_index_t strata_count, + forwardable_span work_bundles ); void await_completion(); void process_work(const work_t work_type); @@ -89,15 +86,15 @@ namespace OpenVic { ~ThreadPool(); void initialise_threadpool( - GameRulesManager const& game_rules_manager, - GoodInstanceManager const& good_instance_manager, - ModifierEffectCache const& modifier_effect_cache, - PopsDefines const& pop_defines, - ProductionTypeManager const& production_type_manager, - const strata_index_t strata_count, - forwardable_span goods, - forwardable_span countries, - forwardable_span provinces + GameRulesManager const& game_rules_manager, + GoodInstanceManager const& good_instance_manager, + ModifierEffectCache const& modifier_effect_cache, + PopsDefines const& pop_defines, + ProductionTypeManager const& production_type_manager, + const strata_index_t strata_count, + forwardable_span goods, + forwardable_span countries, + forwardable_span provinces ); void process_good_execute_orders(); @@ -106,4 +103,4 @@ namespace OpenVic { void process_country_ticks_before_map(); void process_country_ticks_after_map(); }; -} \ No newline at end of file +} diff --git a/src/openvic-simulation/utility/reactive/DependencyTracker.hpp b/src/openvic-simulation/utility/reactive/DependencyTracker.hpp index 1ea60b491..97210f6ce 100644 --- a/src/openvic-simulation/utility/reactive/DependencyTracker.hpp +++ b/src/openvic-simulation/utility/reactive/DependencyTracker.hpp @@ -27,11 +27,12 @@ namespace OpenVic { changed(); } + protected: signal<> changed; bool is_dirty = true; std::mutex is_dirty_lock; - + virtual ~DependencyTracker() { disconnect_all(); } @@ -44,20 +45,19 @@ namespace OpenVic { const std::lock_guard lock_guard { connections_lock }; connections.clear(); } + public: void track(signal<>& dependency_changed) { const std::lock_guard lock_guard { connections_lock }; - connections.emplace_back( - dependency_changed.connect(&DependencyTracker::mark_dirty, this) - ); + connections.emplace_back(dependency_changed.connect(&DependencyTracker::mark_dirty, this)); } template void track(signal& dependency_changed) { const std::lock_guard lock_guard { connections_lock }; - connections.emplace_back( - dependency_changed.connect([this](Args...) { mark_dirty(); }) - ); + connections.emplace_back(dependency_changed.connect([this](Args...) { + mark_dirty(); + })); } }; } diff --git a/src/openvic-simulation/utility/reactive/DerivedState.hpp b/src/openvic-simulation/utility/reactive/DerivedState.hpp index ee19c263c..359d10bae 100644 --- a/src/openvic-simulation/utility/reactive/DerivedState.hpp +++ b/src/openvic-simulation/utility/reactive/DerivedState.hpp @@ -10,7 +10,7 @@ #include "DependencyTracker.hpp" namespace OpenVic { - template + template struct DerivedState : public DependencyTracker { private: T cached_value; @@ -29,11 +29,11 @@ namespace OpenVic { if (has_no_connections()) { spdlog::warn_s( - "DEVELOPER: OpenVic::DerivedState<{}> has no reactive dependencies. " - "Its value will never change again. " - "If it should be reactive, ensure 'calculate' accesses its dependencies. " - "Alternatively use a plain variable or MutableState.", - OpenVic::type_name() + "DEVELOPER: OpenVic::DerivedState<{}> has no reactive dependencies. " + "Its value will never change again. " + "If it should be reactive, ensure 'calculate' accesses its dependencies. " + "Alternatively use a plain variable or MutableState.", + OpenVic::type_name() ); } @@ -44,17 +44,14 @@ namespace OpenVic { public: template explicit DerivedState(Func&& new_calculate) - requires std::is_default_constructible_v - && std::is_convertible_v> - : calculate { std::forward(new_calculate) }, - cached_value() {} + requires std::is_default_constructible_v && std::is_convertible_v> + : calculate { std::forward(new_calculate) }, cached_value() {} template - requires std::is_convertible_v - && std::is_convertible_v> - explicit DerivedState(Func&& new_calculate, InitialValue&& empty_initial_value) - : calculate { std::forward(new_calculate) }, - cached_value { std::forward(empty_initial_value) } {} + requires std::is_convertible_v && + std::is_convertible_v> + explicit DerivedState(Func&& new_calculate, InitialValue&& empty_initial_value) : + calculate { std::forward(new_calculate) }, cached_value { std::forward(empty_initial_value) } {} DerivedState(DerivedState&&) = delete; DerivedState(DerivedState const&) = delete; @@ -78,7 +75,7 @@ namespace OpenVic { return cached_value; } - //special case where connection may be discarded as the observer handles it + // special case where connection may be discarded as the observer handles it template requires OpenVic::_detail::signal::Callable connection connect_using_observer(Pmf&& pmf, Ptr&& ptr, OpenVic::_detail::signal::group_id gid = 0) { diff --git a/src/openvic-simulation/utility/reactive/MutableState.hpp b/src/openvic-simulation/utility/reactive/MutableState.hpp index 302dea2a8..117364220 100644 --- a/src/openvic-simulation/utility/reactive/MutableState.hpp +++ b/src/openvic-simulation/utility/reactive/MutableState.hpp @@ -1,18 +1,21 @@ #pragma once -#include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/core/template/Concepts.hpp" +#include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/utility/reactive/DependencyTracker.hpp" namespace OpenVic { - template + template struct ReadOnlyMutableState { private: signal changed; + protected: T value; - constexpr ReadOnlyMutableState() requires std::is_default_constructible_v : value() {} + constexpr ReadOnlyMutableState() + requires std::is_default_constructible_v + : value() {} constexpr explicit ReadOnlyMutableState(T const& new_value) : value { new_value } {} constexpr explicit ReadOnlyMutableState(T&& new_value) : value { std::move(new_value) } {} ReadOnlyMutableState(ReadOnlyMutableState&&) = delete; @@ -29,6 +32,7 @@ namespace OpenVic { value = new_value; changed(value); } + public: template requires std::invocable&> @@ -43,8 +47,8 @@ namespace OpenVic { [[nodiscard]] constexpr T const& get_untracked() const { return value; } - - //special case where connection may be discarded as the observer handles it + + // special case where connection may be discarded as the observer handles it template requires OpenVic::_detail::signal::Callable connection connect_using_observer(Pmf&& pmf, Ptr&& ptr, OpenVic::_detail::signal::group_id gid = 0) { @@ -71,9 +75,11 @@ namespace OpenVic { return changed.disconnect(std::forward(args)...); } }; - template + template struct MutableState : public ReadOnlyMutableState { - constexpr MutableState() requires std::is_default_constructible_v : ReadOnlyMutableState() {} + constexpr MutableState() + requires std::is_default_constructible_v + : ReadOnlyMutableState() {} constexpr explicit MutableState(T const& new_value) : ReadOnlyMutableState(new_value) {} constexpr explicit MutableState(T&& new_value) : ReadOnlyMutableState(std::move(new_value)) {} MutableState(MutableState&&) = delete; @@ -91,21 +97,29 @@ namespace OpenVic { } using ReadOnlyMutableState::value; - MutableState& operator++() requires pre_incrementable { + MutableState& operator++() + requires pre_incrementable + { set(++value); return *this; } - void operator++(int) requires post_incrementable { + void operator++(int) + requires post_incrementable + { set(value++); } - MutableState& operator--() requires pre_decrementable { + MutableState& operator--() + requires pre_decrementable + { set(--value); return *this; } - void operator--(int) requires post_decrementable { + void operator--(int) + requires post_decrementable + { set(value--); } @@ -146,10 +160,10 @@ public: \ } \ template \ requires std::invocable&> \ - [[nodiscard]] T const& get_##NAME(ConnectTemplateType&& connect) { \ + [[nodiscard]] T const& get_##NAME(ConnectTemplateType && connect) { \ return NAME.get(std::forward(connect)); \ } \ - [[nodiscard]] T get_##NAME(DependencyTracker& tracker) { \ + [[nodiscard]] T get_##NAME(DependencyTracker & tracker) { \ return NAME.get(tracker); \ } \ [[nodiscard]] T get_##NAME##_untracked() const { \ diff --git a/tests/benchmarks/src/core/ecs/AliasingHotLoop.cpp b/tests/benchmarks/src/core/ecs/AliasingHotLoop.cpp index ee1aaf5a4..091946b73 100644 --- a/tests/benchmarks/src/core/ecs/AliasingHotLoop.cpp +++ b/tests/benchmarks/src/core/ecs/AliasingHotLoop.cpp @@ -1,16 +1,17 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + +#include + #include "openvic-simulation/core/ecs/ChunkSystem.hpp" #include "openvic-simulation/core/ecs/ChunkView.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" -#include -#include -#include - -#include #include using namespace OpenVic::ecs; @@ -98,9 +99,7 @@ namespace { for (std::size_t i = 0; i < n; ++i) { int64_t const seed = static_cast(i); world.create_entity( - AliasA { seed + 1, seed + 2 }, - AliasB { seed * 3 + 1, seed * 3 + 2 }, - AliasC { (seed % 7) + 1, (seed % 11) + 1 } + AliasA { seed + 1, seed + 2 }, AliasB { seed * 3 + 1, seed * 3 + 2 }, AliasC { (seed % 7) + 1, (seed % 11) + 1 } ); } } @@ -132,8 +131,7 @@ TEST_CASE("SystemThreaded<> aliasing hot loop (worker-count sweep)", "[benchmark populate(world, n); world.register_system(); - std::string const label = - "SystemThreaded workers=" + std::to_string(wc) + suffix(n); + std::string const label = "SystemThreaded workers=" + std::to_string(wc) + suffix(n); bench.batch(n).run(label, [&] { world.tick_systems(Date {}); }); diff --git a/tests/benchmarks/src/core/ecs/BulkCreate.cpp b/tests/benchmarks/src/core/ecs/BulkCreate.cpp index da7770974..fb6c806a4 100644 --- a/tests/benchmarks/src/core/ecs/BulkCreate.cpp +++ b/tests/benchmarks/src/core/ecs/BulkCreate.cpp @@ -1,13 +1,14 @@ -#include "openvic-simulation/core/ecs/CommandBuffer.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include #include + +#include "openvic-simulation/core/ecs/CommandBuffer.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/CommandBuffer.cpp b/tests/benchmarks/src/core/ecs/CommandBuffer.cpp index 7d83e46c9..f7699fcb4 100644 --- a/tests/benchmarks/src/core/ecs/CommandBuffer.cpp +++ b/tests/benchmarks/src/core/ecs/CommandBuffer.cpp @@ -1,6 +1,4 @@ #include "openvic-simulation/core/ecs/CommandBuffer.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" #include #include @@ -8,6 +6,10 @@ #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/ComponentAccess.cpp b/tests/benchmarks/src/core/ecs/ComponentAccess.cpp index 88d1b7b85..0259cec79 100644 --- a/tests/benchmarks/src/core/ecs/ComponentAccess.cpp +++ b/tests/benchmarks/src/core/ecs/ComponentAccess.cpp @@ -1,7 +1,3 @@ -#include "openvic-simulation/core/ecs/CachedRef.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include @@ -10,6 +6,11 @@ #include #include + +#include "openvic-simulation/core/ecs/CachedRef.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/EntityLifecycle.cpp b/tests/benchmarks/src/core/ecs/EntityLifecycle.cpp index 74b5198ba..b326536db 100644 --- a/tests/benchmarks/src/core/ecs/EntityLifecycle.cpp +++ b/tests/benchmarks/src/core/ecs/EntityLifecycle.cpp @@ -1,6 +1,3 @@ -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include @@ -8,6 +5,10 @@ #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/ImmutableEntity.cpp b/tests/benchmarks/src/core/ecs/ImmutableEntity.cpp index b2c91ddc7..748f449e3 100644 --- a/tests/benchmarks/src/core/ecs/ImmutableEntity.cpp +++ b/tests/benchmarks/src/core/ecs/ImmutableEntity.cpp @@ -1,14 +1,15 @@ -#include "openvic-simulation/core/object/Date.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/SystemImpl.hpp" -#include "openvic-simulation/core/ecs/SystemTypeID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/SystemImpl.hpp" +#include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" + #include using namespace OpenVic::ecs; @@ -91,8 +92,7 @@ TEST_CASE("System tick: EntityID handle vs ImmutableEntityID handle", "[benchmar World world; for (std::size_t i = 0; i < n; ++i) { world.create_entity( - ImmBenchValue { static_cast(i + 1) }, - ImmBenchDelta { static_cast((i * 17) % 13 + 1) } + ImmBenchValue { static_cast(i + 1) }, ImmBenchDelta { static_cast((i * 17) % 13 + 1) } ); } world.register_system(); @@ -104,8 +104,7 @@ TEST_CASE("System tick: EntityID handle vs ImmutableEntityID handle", "[benchmar World world; for (std::size_t i = 0; i < n; ++i) { world.create_entity( - ImmBenchValue { static_cast(i + 1) }, - ImmBenchDelta { static_cast((i * 17) % 13 + 1) } + ImmBenchValue { static_cast(i + 1) }, ImmBenchDelta { static_cast((i * 17) % 13 + 1) } ); } world.register_system(); diff --git a/tests/benchmarks/src/core/ecs/Iteration.cpp b/tests/benchmarks/src/core/ecs/Iteration.cpp index 02e1122c6..af2e97aa3 100644 --- a/tests/benchmarks/src/core/ecs/Iteration.cpp +++ b/tests/benchmarks/src/core/ecs/Iteration.cpp @@ -1,13 +1,14 @@ -#include "openvic-simulation/core/ecs/ChunkView.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/Query.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include + +#include "openvic-simulation/core/ecs/ChunkView.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/Query.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; @@ -59,7 +60,7 @@ namespace { } for (std::size_t i = 0; i < rest; ++i) { world.create_entity( - IterA { static_cast(i) }, IterB { static_cast(i) }, IterC { static_cast(i) } + IterA { static_cast(i) }, IterB { static_cast(i) }, IterC { static_cast(i) } ); } } @@ -75,7 +76,9 @@ TEST_CASE("for_each over single-archetype world", "[benchmarks][benchmark-ecs][e bench.batch(n).run("for_each" + suffix(n), [&] { int64_t acc = 0; - world.for_each([&](IterA& a) { acc += a.v; }); + world.for_each([&](IterA& a) { + acc += a.v; + }); ankerl::nanobench::doNotOptimizeAway(acc); }); @@ -107,7 +110,9 @@ TEST_CASE("for_each over multi-archetype world", "[benchmarks][benchmark-ecs][ec bench.batch(n).run("for_each (all 3)" + suffix(n), [&] { int64_t acc = 0; - world.for_each([&](IterA& a) { acc += a.v; }); + world.for_each([&](IterA& a) { + acc += a.v; + }); ankerl::nanobench::doNotOptimizeAway(acc); }); @@ -175,7 +180,9 @@ TEST_CASE("for_each with Query::exclude", "[benchmarks][benchmark-ecs][ecs- bench.batch(n).run("Query exclude" + suffix(n), [&] { int64_t acc = 0; - world.for_each(query, [&](IterA& a, IterB&) { acc += a.v; }); + world.for_each(query, [&](IterA& a, IterB&) { + acc += a.v; + }); ankerl::nanobench::doNotOptimizeAway(acc); }); } diff --git a/tests/benchmarks/src/core/ecs/Migration.cpp b/tests/benchmarks/src/core/ecs/Migration.cpp index 41825ccb8..ae94b4722 100644 --- a/tests/benchmarks/src/core/ecs/Migration.cpp +++ b/tests/benchmarks/src/core/ecs/Migration.cpp @@ -1,12 +1,13 @@ -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/Reductions.cpp b/tests/benchmarks/src/core/ecs/Reductions.cpp index f0cec49f6..3b80d53b4 100644 --- a/tests/benchmarks/src/core/ecs/Reductions.cpp +++ b/tests/benchmarks/src/core/ecs/Reductions.cpp @@ -1,4 +1,3 @@ -#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" #include "openvic-simulation/core/ecs/Reductions.hpp" #include @@ -8,6 +7,9 @@ #include #include + +#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" + #include using namespace OpenVic::ecs; @@ -44,8 +46,9 @@ TEST_CASE("reductions::parallel_sum sweep", "[benchmarks][benchmark-ecs][ecs-red EcsThreadPool pool { wc }; bench.batch(chunks).run("parallel_sum" + suffix(chunks, wc), [&] { int64_t const result = reductions::parallel_sum( - pool, chunks, int64_t { 0 }, - [](std::size_t chunk_idx) { return chunkSum(chunk_idx); } + pool, chunks, int64_t { 0 }, [](std::size_t chunk_idx) { + return chunkSum(chunk_idx); + } ); ankerl::nanobench::doNotOptimizeAway(result); }); @@ -62,8 +65,9 @@ TEST_CASE("reductions::parallel_min sweep", "[benchmarks][benchmark-ecs][ecs-red EcsThreadPool pool { wc }; bench.batch(chunks).run("parallel_min" + suffix(chunks, wc), [&] { int64_t const result = reductions::parallel_min( - pool, chunks, std::numeric_limits::max(), - [](std::size_t chunk_idx) { return chunkSum(chunk_idx); } + pool, chunks, std::numeric_limits::max(), [](std::size_t chunk_idx) { + return chunkSum(chunk_idx); + } ); ankerl::nanobench::doNotOptimizeAway(result); }); @@ -80,8 +84,9 @@ TEST_CASE("reductions::parallel_max sweep", "[benchmarks][benchmark-ecs][ecs-red EcsThreadPool pool { wc }; bench.batch(chunks).run("parallel_max" + suffix(chunks, wc), [&] { int64_t const result = reductions::parallel_max( - pool, chunks, std::numeric_limits::min(), - [](std::size_t chunk_idx) { return chunkSum(chunk_idx); } + pool, chunks, std::numeric_limits::min(), [](std::size_t chunk_idx) { + return chunkSum(chunk_idx); + } ); ankerl::nanobench::doNotOptimizeAway(result); }); diff --git a/tests/benchmarks/src/core/ecs/Scheduler.cpp b/tests/benchmarks/src/core/ecs/Scheduler.cpp index bacd3f878..8e8dcc1e1 100644 --- a/tests/benchmarks/src/core/ecs/Scheduler.cpp +++ b/tests/benchmarks/src/core/ecs/Scheduler.cpp @@ -1,14 +1,15 @@ -#include "openvic-simulation/core/object/Date.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/SystemImpl.hpp" -#include "openvic-simulation/core/ecs/SystemTypeID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/SystemImpl.hpp" +#include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" + #include using namespace OpenVic::ecs; diff --git a/tests/benchmarks/src/core/ecs/SystemShouldRun.cpp b/tests/benchmarks/src/core/ecs/SystemShouldRun.cpp index 155244793..4356e0699 100644 --- a/tests/benchmarks/src/core/ecs/SystemShouldRun.cpp +++ b/tests/benchmarks/src/core/ecs/SystemShouldRun.cpp @@ -1,14 +1,15 @@ -#include "openvic-simulation/core/object/Date.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/SystemImpl.hpp" -#include "openvic-simulation/core/ecs/SystemTypeID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include #include + +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/SystemImpl.hpp" +#include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" + #include using namespace OpenVic::ecs; @@ -90,8 +91,9 @@ namespace { } } -TEST_CASE("Skipped SystemThreaded, single-system stage: should_run vs in-body early-out", - "[benchmarks][benchmark-ecs][ecs-shouldrun]") { +TEST_CASE( + "Skipped SystemThreaded, single-system stage: should_run vs in-body early-out", "[benchmarks][benchmark-ecs][ecs-shouldrun]" +) { ankerl::nanobench::Bench bench; bench.title("skipped tick, single-system stage").unit("tick"); @@ -112,8 +114,9 @@ TEST_CASE("Skipped SystemThreaded, single-system stage: should_run vs in-body ea } } -TEST_CASE("Skipped SystemThreaded, multi-system stage: should_run vs in-body early-out", - "[benchmarks][benchmark-ecs][ecs-shouldrun]") { +TEST_CASE( + "Skipped SystemThreaded, multi-system stage: should_run vs in-body early-out", "[benchmarks][benchmark-ecs][ecs-shouldrun]" +) { ankerl::nanobench::Bench bench; bench.title("skipped tick, multi-system stage").unit("tick"); diff --git a/tests/benchmarks/src/core/ecs/SystemTick.cpp b/tests/benchmarks/src/core/ecs/SystemTick.cpp index 58f42d992..93cf94cfa 100644 --- a/tests/benchmarks/src/core/ecs/SystemTick.cpp +++ b/tests/benchmarks/src/core/ecs/SystemTick.cpp @@ -1,16 +1,17 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + +#include + #include "openvic-simulation/core/ecs/ChunkSystem.hpp" #include "openvic-simulation/core/ecs/ChunkView.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" -#include -#include -#include - -#include #include using namespace OpenVic::ecs; @@ -75,8 +76,7 @@ namespace { void populate(World& world, std::size_t n) { for (std::size_t i = 0; i < n; ++i) { world.create_entity( - TickValue { static_cast(i + 1) }, - TickDelta { static_cast((i * 17) % 13 + 1) } + TickValue { static_cast(i + 1) }, TickDelta { static_cast((i * 17) % 13 + 1) } ); } } @@ -123,8 +123,7 @@ TEST_CASE("SystemThreaded<> chunk-parallel tick (worker-count sweep)", "[benchma populate(world, n); world.register_system(); - std::string const label = - "SystemThreaded workers=" + std::to_string(wc) + suffix(n); + std::string const label = "SystemThreaded workers=" + std::to_string(wc) + suffix(n); bench.batch(n).run(label, [&] { world.tick_systems(Date {}); }); diff --git a/tests/benchmarks/src/dataloading/Dataloading.cpp b/tests/benchmarks/src/dataloading/Dataloading.cpp index f576bba56..dedaea22a 100644 --- a/tests/benchmarks/src/dataloading/Dataloading.cpp +++ b/tests/benchmarks/src/dataloading/Dataloading.cpp @@ -15,9 +15,9 @@ TEST_CASE("Dataloading benchmark", "[benchmarks][benchmark-dataloading]") { game_manager.set_base_path(roots); game_manager.load_definitions( - [](std::string_view key, Dataloader::locale_t locale, std::string_view localisation) -> bool { - return true; - } + [](std::string_view key, Dataloader::locale_t locale, std::string_view localisation) -> bool { + return true; + } ); }); } diff --git a/tests/src/Helper.hpp b/tests/src/Helper.hpp index 264941fc3..50673be6c 100644 --- a/tests/src/Helper.hpp +++ b/tests/src/Helper.hpp @@ -6,7 +6,7 @@ #define _EXPR(TYPE, EXPECTED, ASSIGN_VALUE, ...) \ auto SNITCH_CURRENT_EXPRESSION = \ - (snitch::impl::expression_extractor { TYPE, #__VA_ARGS__ } <= __VA_ARGS__).to_expression(); \ + (snitch::impl::expression_extractor { TYPE, #__VA_ARGS__ } <= __VA_ARGS__).to_expression(); \ ASSIGN_VALUE = SNITCH_CURRENT_EXPRESSION.success; #define _REQUIRE_IMPL(CHECK, EXPECTED, MAYBE_ABORT, ASSIGN_VALUE, ...) \ @@ -20,8 +20,9 @@ SNITCH_REPORT_EXPRESSION(MAYBE_ABORT); \ } else { \ ASSIGN_VALUE = static_cast(__VA_ARGS__); \ - const auto SNITCH_CURRENT_EXPRESSION = \ - snitch::impl::expression { CHECK, #__VA_ARGS__, {}, ASSIGN_VALUE == EXPECTED }; \ + const auto SNITCH_CURRENT_EXPRESSION = snitch::impl::expression { \ + CHECK, #__VA_ARGS__, {}, ASSIGN_VALUE == EXPECTED \ + }; \ SNITCH_REPORT_EXPRESSION(MAYBE_ABORT); \ } \ SNITCH_WARNING_POP \ @@ -35,10 +36,22 @@ // clang-format on #define _OVSIM_CHECK_IF(NAME, ...) \ - if (bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; [&] { _OVSIM_CHECK(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); }(), (SNITCH_MACRO_CONCAT(result_, __LINE__))) + if ( \ + bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; \ + [&] { \ + _OVSIM_CHECK(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); \ + }(), \ + (SNITCH_MACRO_CONCAT(result_, __LINE__)) \ + ) #define _OVSIM_CHECK_FALSE_IF(NAME, ...) \ - if (bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; [&] { _OVSIM_CHECK_FALSE(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); }(), (!SNITCH_MACRO_CONCAT(result_, __LINE__))) + if ( \ + bool SNITCH_MACRO_CONCAT(result_, __LINE__) = false; \ + [&] { \ + _OVSIM_CHECK_FALSE(NAME, (SNITCH_MACRO_CONCAT(result_, __LINE__)), __VA_ARGS__); \ + }(), \ + (!SNITCH_MACRO_CONCAT(result_, __LINE__)) \ + ) #define CHECK_IF(...) _OVSIM_CHECK_IF("_IF", __VA_ARGS__) @@ -48,13 +61,13 @@ _OVSIM_CHECK_IF("_RETURN_BOOL", __VA_ARGS__) { \ return true; \ } \ - else return false; + else return false #define CHECK_FALSE_RETURN_BOOL(...) \ _OVSIM_CHECK_FALSE_IF("_RETURN_BOOL", __VA_ARGS__) { \ return true; \ } \ - else return false; + else return false #define CHECK_OR_RETURN(...) \ _OVSIM_CHECK_IF("_OR_RETURN", __VA_ARGS__); \ @@ -69,3 +82,10 @@ #define CHECK_FALSE_OR_CONTINUE(...) \ _OVSIM_CHECK_FALSE_IF("_OR_CONTINUE", __VA_ARGS__); \ else continue + +#define CHECK_OR_BREAK(...) \ + _OVSIM_CHECK_IF("_OR_BREAK", __VA_ARGS__); \ + else break +#define CHECK_FALSE_OR_BREAK(...) \ + _OVSIM_CHECK_FALSE_IF("_OR_BREAK", __VA_ARGS__); \ + else break diff --git a/tests/src/SpyAllocator.hpp b/tests/src/SpyAllocator.hpp index 22a1d21e0..2037e2eb1 100644 --- a/tests/src/SpyAllocator.hpp +++ b/tests/src/SpyAllocator.hpp @@ -3,46 +3,44 @@ // Telemetry structure remains the same struct AllocationMetrics { - std::size_t total_allocated_bytes = 0; - std::size_t total_deallocated_bytes = 0; - std::size_t allocation_count = 0; - std::size_t deallocation_count = 0; - - void reset() { - total_allocated_bytes = 0; - total_deallocated_bytes = 0; - allocation_count = 0; - deallocation_count = 0; - } - - std::size_t active_bytes() const { - return total_allocated_bytes - total_deallocated_bytes; - } + std::size_t total_allocated_bytes = 0; + std::size_t total_deallocated_bytes = 0; + std::size_t allocation_count = 0; + std::size_t deallocation_count = 0; + + void reset() { + total_allocated_bytes = 0; + total_deallocated_bytes = 0; + allocation_count = 0; + deallocation_count = 0; + } + + std::size_t active_bytes() const { + return total_allocated_bytes - total_deallocated_bytes; + } }; // SpyAllocator now wraps an underlying Allocator type (defaults to std::allocator) -template > +template> class SpyAllocator { public: using value_type = T; - + // Shared telemetry state across allocator copies std::shared_ptr metrics; // The actual allocator doing the heavy lifting Allocator upstream; // Default Constructor - SpyAllocator() - : metrics(std::make_shared()), upstream() {} + SpyAllocator() : metrics(std::make_shared()), upstream() {} // Explicitly pass an existing upstream allocator instance if needed - explicit SpyAllocator(const Allocator& alloc) - : metrics(std::make_shared()), upstream(alloc) {} + explicit SpyAllocator(const Allocator& alloc) : metrics(std::make_shared()), upstream(alloc) {} value_type* allocate(const std::size_t n) { // Delegate allocation to the upstream allocator value_type* ptr = std::allocator_traits::allocate(upstream, n); - + if (metrics && ptr) { metrics->total_allocated_bytes += (n * sizeof(value_type)); metrics->allocation_count++; @@ -58,4 +56,4 @@ class SpyAllocator { // Delegate deallocation to the upstream allocator std::allocator_traits::deallocate(upstream, ptr, n); } -}; \ No newline at end of file +}; diff --git a/tests/src/core/BulkInsertWrapper.cpp b/tests/src/core/BulkInsertWrapper.cpp index 73d571965..7fa0b85c4 100644 --- a/tests/src/core/BulkInsertWrapper.cpp +++ b/tests/src/core/BulkInsertWrapper.cpp @@ -1,18 +1,17 @@ +#include "openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp" + #include #include #include -#include "openvic-simulation/core/stl/containers/BulkInsertWrapper.hpp" - -#include - #include "SpyAllocator.hpp" +#include -// A simple non-trivially destructible type to test constraint violations if needed, +// A simple non-trivially destructible type to test constraint violations if needed, // and a trivial one to satisfy emplace_back's requires clause. struct TrivialPoint { - int x = 0; - int y = 0; + int x = 0; + int y = 0; }; using namespace OpenVic; @@ -22,51 +21,39 @@ TEST_CASE("bulk_insert_wrapper Constructors", "[bulk_insert_wrapper][bulk_insert CONSTEXPR_CHECK(empty.empty()); CONSTEXPR_CHECK(empty.size() == 0); CONSTEXPR_CHECK(empty.capacity() == 0); - CONSTEXPR_CHECK(empty.begin() == empty.end()); - CONSTEXPR_CHECK(empty.cbegin() == empty.cend()); - CONSTEXPR_CHECK(empty.rbegin() == empty.rend()); + CONSTEXPR_CHECK(empty.begin() == empty.end()); + CONSTEXPR_CHECK(empty.cbegin() == empty.cend()); + CONSTEXPR_CHECK(empty.rbegin() == empty.rend()); constexpr std::size_t expected_size = 3; - bulk_insert_wrapper> filled { - std::vector { 1, 2, 3 } - }; + bulk_insert_wrapper> filled { std::vector { 1, 2, 3 } }; CHECK(!filled.empty()); CHECK(filled.size() == expected_size); CHECK(filled.capacity() >= expected_size); - CHECK(std::distance(filled.begin(), filled.end()) == expected_size); - CHECK(std::distance(filled.cbegin(), filled.cend()) == expected_size); - CHECK(std::distance(filled.rbegin(), filled.rend()) == expected_size); - CHECK(filled[0] == 1); + CHECK(std::distance(filled.begin(), filled.end()) == expected_size); + CHECK(std::distance(filled.cbegin(), filled.cend()) == expected_size); + CHECK(std::distance(filled.rbegin(), filled.rend()) == expected_size); + CHECK(filled[0] == 1); } TEST_CASE("bulk_insert_wrapper make_room does not allocate", "[bulk_insert_wrapper][bulk_insert_wrapper-make_room]") { - SpyAllocator spy_allocator{}; - bulk_insert_wrapper< - std::vector< - int, - SpyAllocator - > - > empty { spy_allocator }; + SpyAllocator spy_allocator {}; + bulk_insert_wrapper>> empty { spy_allocator }; empty.make_room_for(10); - + CHECK(empty.empty()); CHECK(empty.size() == 0); CHECK(empty.capacity() == 0); - CHECK(empty.begin() == empty.end()); - CHECK(empty.cbegin() == empty.cend()); - CHECK(empty.rbegin() == empty.rend()); + CHECK(empty.begin() == empty.end()); + CHECK(empty.cbegin() == empty.cend()); + CHECK(empty.rbegin() == empty.rend()); CHECK(spy_allocator.metrics->allocation_count == 0); } // correct usage TEST_CASE("bulk_insert_wrapper make_room + append_range", "[bulk_insert_wrapper][bulk_insert_wrapper-append_range]") { - SpyAllocator spy_allocator{}; - bulk_insert_wrapper< - std::vector< - int, - SpyAllocator - > - > wrapper { spy_allocator }; + SpyAllocator spy_allocator {}; + bulk_insert_wrapper>> wrapper { spy_allocator }; std::vector a { 1, 2 }; std::vector b { 3, 4, 5 }; @@ -88,13 +75,8 @@ TEST_CASE("bulk_insert_wrapper make_room + append_range", "[bulk_insert_wrapper] #ifdef NDEBUG // incorrect usage may not crash TEST_CASE("bulk_insert_wrapper append_range without make_room", "[bulk_insert_wrapper][bulk_insert_wrapper-append_range]") { - SpyAllocator spy_allocator{}; - bulk_insert_wrapper< - std::vector< - int, - SpyAllocator - > - > wrapper { spy_allocator }; + SpyAllocator spy_allocator {}; + bulk_insert_wrapper>> wrapper { spy_allocator }; std::vector a { 1, 2 }; std::vector b { 3, 4, 5 }; @@ -109,13 +91,8 @@ TEST_CASE("bulk_insert_wrapper append_range without make_room", "[bulk_insert_wr #endif TEST_CASE("bulk_insert_wrapper clear", "[bulk_insert_wrapper][bulk_insert_wrapper-clear]") { - SpyAllocator spy_allocator{}; - bulk_insert_wrapper< - std::vector< - int, - SpyAllocator - > - > wrapper { spy_allocator }; + SpyAllocator spy_allocator {}; + bulk_insert_wrapper>> wrapper { spy_allocator }; std::vector a { 1, 2 }; constexpr std::size_t extra_room = 1; @@ -133,13 +110,8 @@ TEST_CASE("bulk_insert_wrapper clear", "[bulk_insert_wrapper][bulk_insert_wrappe } TEST_CASE("bulk_insert_wrapper shrink_to_fit", "[bulk_insert_wrapper][bulk_insert_wrapper-shrink_to_fit]") { - SpyAllocator spy_allocator{}; - bulk_insert_wrapper< - std::vector< - int, - SpyAllocator - > - > wrapper { spy_allocator }; + SpyAllocator spy_allocator {}; + bulk_insert_wrapper>> wrapper { spy_allocator }; std::vector a { 1, 2 }; constexpr std::size_t extra_room = 1; @@ -159,4 +131,4 @@ TEST_CASE("bulk_insert_wrapper shrink_to_fit", "[bulk_insert_wrapper][bulk_inser CHECK(wrapper.capacity() <= capacity_before_shrink); CHECK(spy_allocator.metrics->allocation_count >= 1); CHECK(spy_allocator.metrics->allocation_count <= 2); -} \ No newline at end of file +} diff --git a/tests/src/core/DualAdjacent.cpp b/tests/src/core/DualAdjacent.cpp index 88cc72954..7c39f74f8 100644 --- a/tests/src/core/DualAdjacent.cpp +++ b/tests/src/core/DualAdjacent.cpp @@ -78,7 +78,7 @@ TEST_CASE("find_if_dual_adjacent", "[algorithm][dual-adjacent][find_if_dual_adja CONSTEXPR_CHECK(find_if_dual_adjacent(array_up.begin(), array_up.end(), callback_spread) == array_up.end()); CONSTEXPR_CHECK(find_if_dual_adjacent(array_down.begin(), array_down.end(), callback_spread) == array_down.end()); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_spread.begin(), array_spread.end(), callback_spread) == array_spread.begin() + 3 + find_if_dual_adjacent(array_spread.begin(), array_spread.end(), callback_spread) == array_spread.begin() + 3 ); CONSTEXPR_CHECK(find_if_dual_adjacent(array_up.begin(), array_up.end(), callback_none) == array_up.end()); @@ -86,23 +86,23 @@ TEST_CASE("find_if_dual_adjacent", "[algorithm][dual-adjacent][find_if_dual_adja CONSTEXPR_CHECK(find_if_dual_adjacent(array_spread.begin(), array_spread.end(), callback_none) == array_spread.end()); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_up.begin(), array_up.end(), std::bind_front(callback_bind, 1)) == array_up.end() + find_if_dual_adjacent(array_up.begin(), array_up.end(), std::bind_front(callback_bind, 1)) == array_up.end() ); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_down.begin(), array_down.end(), std::bind_front(callback_bind, 9)) == array_down.end() + find_if_dual_adjacent(array_down.begin(), array_down.end(), std::bind_front(callback_bind, 9)) == array_down.end() ); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_spread.begin(), array_spread.end(), std::bind_front(callback_bind, 5)) == array_spread.end() + find_if_dual_adjacent(array_spread.begin(), array_spread.end(), std::bind_front(callback_bind, 5)) == array_spread.end() ); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_up.begin(), array_up.end(), std::bind_front(callback_bind, 9)) == array_up.end() + find_if_dual_adjacent(array_up.begin(), array_up.end(), std::bind_front(callback_bind, 9)) == array_up.end() ); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_down.begin(), array_down.end(), std::bind_front(callback_bind, 1)) == array_down.end() + find_if_dual_adjacent(array_down.begin(), array_down.end(), std::bind_front(callback_bind, 1)) == array_down.end() ); CONSTEXPR_CHECK( - find_if_dual_adjacent(array_spread.begin(), array_spread.end(), std::bind_front(callback_bind, 6)) == array_spread.end() + find_if_dual_adjacent(array_spread.begin(), array_spread.end(), std::bind_front(callback_bind, 6)) == array_spread.end() ); } @@ -150,23 +150,23 @@ TEST_CASE("remove_if_dual_adjacent", "[algorithm][dual-adjacent][remove_if_dual_ remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 1)) == vector_up.end() ); CHECK( - remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 9)) == vector_down.end() + remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 9)) == vector_down.end() ); CHECK( - remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 5)) == - vector_spread.end() + remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 5)) == + vector_spread.end() ); CHECK( // remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 9)) == vector_up.end() - 1 ); CHECK( - remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 1)) == - vector_down.end() - 1 + remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 1)) == + vector_down.end() - 1 ); CHECK( - remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 6)) == - vector_spread.end() - 1 + remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), std::bind_front(callback_bind, 6)) == + vector_spread.end() - 1 ); static constexpr auto removed_vector_up = std::to_array({ 1, 2, 3, 5, 6, 7, 8, 9, 9 }); diff --git a/tests/src/core/ecs/Archetype.cpp b/tests/src/core/ecs/Archetype.cpp index 10675d788..da567433c 100644 --- a/tests/src/core/ecs/Archetype.cpp +++ b/tests/src/core/ecs/Archetype.cpp @@ -1,11 +1,12 @@ #include "openvic-simulation/core/ecs/Archetype.hpp" -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" #include #include #include +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" + #include #include @@ -104,13 +105,13 @@ TEST_CASE("Archetype matches_all on subset / superset / disjoint", "[ecs][Archet return v; }; - CHECK(arch.matches_all({})); // empty required - CHECK(arch.matches_all(sorted({ a }))); // subset - CHECK(arch.matches_all(sorted({ a, b }))); // subset - CHECK(arch.matches_all(sorted({ a, b, c }))); // exact - CHECK_FALSE(arch.matches_all(sorted({ a, d }))); // requires missing - CHECK_FALSE(arch.matches_all(sorted({ d }))); // entirely disjoint - CHECK_FALSE(arch.matches_all(sorted({ a, b, c, d }))); // superset of arch + CHECK(arch.matches_all({})); // empty required + CHECK(arch.matches_all(sorted({ a }))); // subset + CHECK(arch.matches_all(sorted({ a, b }))); // subset + CHECK(arch.matches_all(sorted({ a, b, c }))); // exact + CHECK_FALSE(arch.matches_all(sorted({ a, d }))); // requires missing + CHECK_FALSE(arch.matches_all(sorted({ d }))); // entirely disjoint + CHECK_FALSE(arch.matches_all(sorted({ a, b, c, d }))); // superset of arch } TEST_CASE("Archetype matches_none on disjoint / overlap / empty", "[ecs][Archetype]") { @@ -129,10 +130,10 @@ TEST_CASE("Archetype matches_none on disjoint / overlap / empty", "[ecs][Archety return v; }; - CHECK(arch.matches_none({})); // empty exclude - CHECK(arch.matches_none(sorted({ c }))); // disjoint - CHECK(arch.matches_none(sorted({ c, d }))); // disjoint - CHECK_FALSE(arch.matches_none(sorted({ a }))); // overlap - CHECK_FALSE(arch.matches_none(sorted({ a, c }))); // partial overlap - CHECK_FALSE(arch.matches_none(sorted({ a, b }))); // full overlap + CHECK(arch.matches_none({})); // empty exclude + CHECK(arch.matches_none(sorted({ c }))); // disjoint + CHECK(arch.matches_none(sorted({ c, d }))); // disjoint + CHECK_FALSE(arch.matches_none(sorted({ a }))); // overlap + CHECK_FALSE(arch.matches_none(sorted({ a, c }))); // partial overlap + CHECK_FALSE(arch.matches_none(sorted({ a, b }))); // full overlap } diff --git a/tests/src/core/ecs/BulkCreate.cpp b/tests/src/core/ecs/BulkCreate.cpp index 23d899b0c..494784620 100644 --- a/tests/src/core/ecs/BulkCreate.cpp +++ b/tests/src/core/ecs/BulkCreate.cpp @@ -1,11 +1,3 @@ -#include "openvic-simulation/core/object/Date.hpp" -#include "openvic-simulation/core/ecs/CommandBuffer.hpp" -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/SystemImpl.hpp" -#include "openvic-simulation/core/ecs/SystemTypeID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include @@ -15,6 +7,14 @@ #include #include +#include "openvic-simulation/core/ecs/CommandBuffer.hpp" +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/SystemImpl.hpp" +#include "openvic-simulation/core/ecs/SystemTypeID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" + #include #include @@ -104,9 +104,7 @@ TEST_CASE("Direct bulk create matches the equivalent create_entity loop", "[ecs] World loop_world; std::vector loop_ids; for (std::size_t i = 0; i < count; ++i) { - loop_ids.push_back(loop_world.create_entity( - BCA { static_cast(i) }, BCB { static_cast(i * 2) }, BCTag {} - )); + loop_ids.push_back(loop_world.create_entity(BCA { static_cast(i) }, BCB { static_cast(i * 2) }, BCTag {})); } World bulk_world; @@ -211,7 +209,9 @@ TEST_CASE("Bulk create with count == 0 is a no-op", "[ecs][BulkCreate]") { CHECK(world.create_entities(0, empty_out)); int found = 0; - world.for_each([&](BCA&) { ++found; }); + world.for_each([&](BCA&) { + ++found; + }); CHECK(found == 0); CommandBuffer cmd; @@ -231,7 +231,9 @@ TEST_CASE("Bulk create refuses mismatched out_ids / span lengths", "[ecs][BulkCr CHECK_FALSE(world.create_entities(5, out, short_span)); int found = 0; - world.for_each([&](BCA&) { ++found; }); + world.for_each([&](BCA&) { + ++found; + }); CHECK(found == 0); CommandBuffer cmd; @@ -417,8 +419,7 @@ TEST_CASE("CB serial bulk: out_ids are real and usable for same-buffer ops", "[e CHECK(world.is_alive(ids[3])); } -TEST_CASE("CB serial bulk: a slot destroyed between record and apply is skipped without leaking", - "[ecs][BulkCreate]") { +TEST_CASE("CB serial bulk: a slot destroyed between record and apply is skipped without leaking", "[ecs][BulkCreate]") { int const before = BCCounted::live; std::size_t const count = 6; std::size_t const dropped = 2; @@ -445,7 +446,9 @@ TEST_CASE("CB serial bulk: a slot destroyed between record and apply is skipped CHECK_FALSE(world.is_alive(ids[dropped])); int found = 0; - world.for_each([&](BCCounted&) { ++found; }); + world.for_each([&](BCCounted&) { + ++found; + }); CHECK(found == static_cast(count) - 1); for (std::size_t i = 0; i < count; ++i) { if (i == dropped) { @@ -460,8 +463,7 @@ TEST_CASE("CB serial bulk: a slot destroyed between record and apply is skipped CHECK(BCCounted::live == before); } -TEST_CASE("CB parallel bulk: sequential placeholders interleave correctly with single creates", - "[ecs][BulkCreate][deferred]") { +TEST_CASE("CB parallel bulk: sequential placeholders interleave correctly with single creates", "[ecs][BulkCreate][deferred]") { World world; CommandBuffer cmd; cmd.set_parallel_mode(true); @@ -495,7 +497,9 @@ TEST_CASE("CB parallel bulk: sequential placeholders interleave correctly with s cmd.apply(world); std::vector> pairs; // (BCA::v, BCB::w) - world.for_each([&](BCA& a, BCB& b) { pairs.push_back({ a.v, b.w }); }); + world.for_each([&](BCA& a, BCB& b) { + pairs.push_back({ a.v, b.w }); + }); std::sort(pairs.begin(), pairs.end()); REQUIRE(pairs.size() == 4u); CHECK(pairs[0] == std::pair { 10, 100 }); @@ -504,7 +508,9 @@ TEST_CASE("CB parallel bulk: sequential placeholders interleave correctly with s CHECK(pairs[3] == std::pair { 31, 301 }); int total = 0; - world.for_each([&](BCA&) { ++total; }); + world.for_each([&](BCA&) { + ++total; + }); CHECK(total == 6); } @@ -539,7 +545,9 @@ TEST_CASE("merge_from rebases bulk placeholder ranges across buffers", "[ecs][Bu system_pending.apply(world); std::vector> pairs; - world.for_each([&](BCA& a, BCB& b) { pairs.push_back({ a.v, b.w }); }); + world.for_each([&](BCA& a, BCB& b) { + pairs.push_back({ a.v, b.w }); + }); std::sort(pairs.begin(), pairs.end()); REQUIRE(pairs.size() == 4u); CHECK(pairs[0] == std::pair { 11, 110 }); @@ -548,7 +556,9 @@ TEST_CASE("merge_from rebases bulk placeholder ranges across buffers", "[ecs][Bu CHECK(pairs[3] == std::pair { 22, 220 }); int total = 0; - world.for_each([&](BCA&) { ++total; }); + world.for_each([&](BCA&) { + ++total; + }); CHECK(total == 6); } @@ -691,7 +701,9 @@ TEST_CASE("Bulk-created entities destroy normally and bump column versions", "[e CHECK(world.is_alive(ids[i]) == (i >= count / 2)); } int found = 0; - world.for_each([&](BCA&) { ++found; }); + world.for_each([&](BCA&) { + ++found; + }); CHECK(found == static_cast(count / 2 + 2)); } @@ -731,9 +743,7 @@ namespace { struct BCBulkSpawner : SystemThreaded { void tick(TickContext const& ctx, EntityID, BCSeed const& s) { std::array vals { - BCSpawned { s.seed * 31 + 1 }, - BCSpawned { s.seed * 31 + 2 }, - BCSpawned { s.seed * 31 + 3 } + BCSpawned { s.seed * 31 + 1 }, BCSpawned { s.seed * 31 + 2 }, BCSpawned { s.seed * 31 + 3 } }; std::array out {}; ctx.cmd.create_entities(ctx.world, 3, out, vals); @@ -778,8 +788,7 @@ namespace { } } -TEST_CASE("Threaded bulk spawner: digest is identical across worker counts", - "[ecs][determinism][BulkCreate][deferred]") { +TEST_CASE("Threaded bulk spawner: digest is identical across worker counts", "[ecs][determinism][BulkCreate][deferred]") { std::size_t const seeds = 300; int const ticks = 1; int64_t const baseline = bulk_spawn_and_digest(1, seeds, ticks); @@ -790,8 +799,10 @@ TEST_CASE("Threaded bulk spawner: digest is identical across worker counts", } } -TEST_CASE("Threaded bulk spawner produces the identical end state to the single-create spawner", - "[ecs][determinism][BulkCreate][deferred]") { +TEST_CASE( + "Threaded bulk spawner produces the identical end state to the single-create spawner", + "[ecs][determinism][BulkCreate][deferred]" +) { std::size_t const seeds = 300; for (int ticks : { 1, 3 }) { int64_t const loop_digest = bulk_spawn_and_digest(4, seeds, ticks); diff --git a/tests/src/core/ecs/CachedRef.cpp b/tests/src/core/ecs/CachedRef.cpp index 8dacb6ed5..0db6e7f83 100644 --- a/tests/src/core/ecs/CachedRef.cpp +++ b/tests/src/core/ecs/CachedRef.cpp @@ -1,9 +1,10 @@ #include "openvic-simulation/core/ecs/CachedRef.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" #include +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include #include @@ -131,8 +132,8 @@ TEST_CASE("CachedRef::get re-resolves after structural change in archetype", "[e auto ref_a = CachedRef::from(world, a); auto ref_b = CachedRef::from(world, b); - (void) ref_a.get(world); - (void) ref_b.get(world); + (void)ref_a.get(world); + (void)ref_b.get(world); // Destroying `a` swap-pops it. `b` (last row) gets relocated into a's slot. world.destroy_entity(a); diff --git a/tests/src/core/ecs/Checksum.cpp b/tests/src/core/ecs/Checksum.cpp index 1e0bb38ea..a897dcbd9 100644 --- a/tests/src/core/ecs/Checksum.cpp +++ b/tests/src/core/ecs/Checksum.cpp @@ -1,6 +1,11 @@ -#include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/Checksum.hpp" -#include "openvic-simulation/core/object/Date.hpp" + +#include +#include +#include +#include + +#include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/ChecksumTraits.hpp" #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" @@ -8,11 +13,7 @@ #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -324,10 +325,7 @@ namespace { } for (std::size_t i = 0; i < seed_count; ++i) { - world.create_entity( - CkSeed { static_cast((i * 17) % 251 + 1) }, - CkValue { static_cast(i + 1) } - ); + world.create_entity(CkSeed { static_cast((i * 17) % 251 + 1) }, CkValue { static_cast(i + 1) }); } world.set_singleton(CkVecSingleton { { 4, 5, 6 } }); @@ -342,8 +340,10 @@ namespace { } } -TEST_CASE("Full-state checksum is identical across worker counts and serial mode", - "[ecs][Checksum][determinism][WorkerCountInvariance]") { +TEST_CASE( + "Full-state checksum is identical across worker counts and serial mode", + "[ecs][Checksum][determinism][WorkerCountInvariance]" +) { std::size_t const seeds = 200; int const ticks = 5; uint64_t const baseline = run_and_checksum(1, false, seeds, ticks); diff --git a/tests/src/core/ecs/Chunk.cpp b/tests/src/core/ecs/Chunk.cpp index ac2f4fea4..ccf3139aa 100644 --- a/tests/src/core/ecs/Chunk.cpp +++ b/tests/src/core/ecs/Chunk.cpp @@ -1,11 +1,12 @@ -#include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/Chunk.hpp" + +#include + +#include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include - #include #include @@ -41,9 +42,9 @@ namespace { Archetype* found = nullptr; // We can't directly access World::archetypes (private). Use for_each_chunk to capture // the chunk capacity / column array layout for the entity's archetype. - (void) world; - (void) eid; - (void) found; + (void)world; + (void)eid; + (void)found; return nullptr; } } @@ -95,7 +96,9 @@ TEST_CASE("Tag-only archetype iterates all entities", "[ecs][Chunk][tag]") { } int count = 0; - world.for_each([&](CTagA&) { ++count; }); + world.for_each([&](CTagA&) { + ++count; + }); CHECK(count == 50); } diff --git a/tests/src/core/ecs/ChunkMigration.cpp b/tests/src/core/ecs/ChunkMigration.cpp index 6d855ee7b..01c7c5cf8 100644 --- a/tests/src/core/ecs/ChunkMigration.cpp +++ b/tests/src/core/ecs/ChunkMigration.cpp @@ -1,11 +1,11 @@ +#include +#include + #include "openvic-simulation/core/ecs/Chunk.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -73,11 +73,15 @@ TEST_CASE("add_component on an entity in a multi-chunk archetype migrates correc // Source archetype still has total - 1 entities; target archetype has 1. int a_count = 0; - world.for_each([&](CMigrA&) { ++a_count; }); - CHECK(a_count == static_cast(total)); // both archetypes carry CMigrA + world.for_each([&](CMigrA&) { + ++a_count; + }); + CHECK(a_count == static_cast(total)); // both archetypes carry CMigrA int b_count = 0; - world.for_each([&](CMigrA&, CMigrB&) { ++b_count; }); + world.for_each([&](CMigrA&, CMigrB&) { + ++b_count; + }); CHECK(b_count == 1); } @@ -108,6 +112,8 @@ TEST_CASE("Migrating many entities into the same target archetype overflows its // Source archetype {CMigrA} should be empty now. int src_count = 0; - world.for_each([&](CMigrA&) { ++src_count; }); + world.for_each([&](CMigrA&) { + ++src_count; + }); CHECK(src_count == static_cast(total)); } diff --git a/tests/src/core/ecs/ChunkOverflow.cpp b/tests/src/core/ecs/ChunkOverflow.cpp index 4740d9e43..f56be938d 100644 --- a/tests/src/core/ecs/ChunkOverflow.cpp +++ b/tests/src/core/ecs/ChunkOverflow.cpp @@ -1,11 +1,11 @@ +#include +#include + #include "openvic-simulation/core/ecs/Chunk.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -120,7 +120,9 @@ TEST_CASE("destroy_entity in the first chunk relocates last entity from last chu // After the destroy, only `total - 1` entities remain. int count = 0; - world.for_each([&](Heavy&) { ++count; }); + world.for_each([&](Heavy&) { + ++count; + }); CHECK(count == static_cast(total - 1)); } @@ -139,6 +141,8 @@ TEST_CASE("Destroying enough entities drops the trailing empty chunk", "[ecs][Ch world.destroy_entity(ids.back()); std::size_t chunk_count = 0; - world.for_each_chunk([&](ChunkView) { ++chunk_count; }); + world.for_each_chunk([&](ChunkView) { + ++chunk_count; + }); CHECK(chunk_count == 1u); } diff --git a/tests/src/core/ecs/ChunkPool.cpp b/tests/src/core/ecs/ChunkPool.cpp index bd451338f..59a31c47d 100644 --- a/tests/src/core/ecs/ChunkPool.cpp +++ b/tests/src/core/ecs/ChunkPool.cpp @@ -1,15 +1,16 @@ -#include "openvic-simulation/core/object/Date.hpp" -#include "openvic-simulation/core/ecs/Chunk.hpp" #include "openvic-simulation/core/ecs/ChunkPool.hpp" -#include "openvic-simulation/core/ecs/ChunkView.hpp" -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" #include #include #include +#include "openvic-simulation/core/ecs/Chunk.hpp" +#include "openvic-simulation/core/ecs/ChunkView.hpp" +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" + #include #include diff --git a/tests/src/core/ecs/ChunkSystem.cpp b/tests/src/core/ecs/ChunkSystem.cpp index c2baef37e..416d93f23 100644 --- a/tests/src/core/ecs/ChunkSystem.cpp +++ b/tests/src/core/ecs/ChunkSystem.cpp @@ -1,11 +1,11 @@ #include "openvic-simulation/core/ecs/ChunkSystem.hpp" -#include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" #include #include diff --git a/tests/src/core/ecs/ChunkView.cpp b/tests/src/core/ecs/ChunkView.cpp index cd4a7f01b..efbe1dae1 100644 --- a/tests/src/core/ecs/ChunkView.cpp +++ b/tests/src/core/ecs/ChunkView.cpp @@ -1,13 +1,14 @@ -#include "openvic-simulation/core/ecs/Chunk.hpp" #include "openvic-simulation/core/ecs/ChunkView.hpp" + +#include +#include + +#include "openvic-simulation/core/ecs/Chunk.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/Query.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -63,7 +64,9 @@ TEST_CASE("ChunkView::array yields the same values as for_each", "[ecs][ChunkVie } std::vector reference; - world.for_each([&](CVA& c) { reference.push_back(c.v); }); + world.for_each([&](CVA& c) { + reference.push_back(c.v); + }); std::vector via_chunk; world.for_each_chunk([&](ChunkView view) { @@ -119,7 +122,9 @@ TEST_CASE("Mutations through ChunkView::array are visible to subsequent for_each }); int sum = 0; - world.for_each([&](CVA& c) { sum += c.v; }); + world.for_each([&](CVA& c) { + sum += c.v; + }); CHECK(sum == (0 + 10 + 20 + 30)); } @@ -149,6 +154,8 @@ TEST_CASE("for_each_chunk(Query, fn) respects exclude", "[ecs][ChunkView][query] TEST_CASE("for_each_chunk on empty world is a no-op", "[ecs][ChunkView]") { World world; int chunk_visits = 0; - world.for_each_chunk([&](ChunkView) { ++chunk_visits; }); + world.for_each_chunk([&](ChunkView) { + ++chunk_visits; + }); CHECK(chunk_visits == 0); } diff --git a/tests/src/core/ecs/CommandBuffer.cpp b/tests/src/core/ecs/CommandBuffer.cpp index 10ee9c8b0..bc255b0cf 100644 --- a/tests/src/core/ecs/CommandBuffer.cpp +++ b/tests/src/core/ecs/CommandBuffer.cpp @@ -1,7 +1,4 @@ #include "openvic-simulation/core/ecs/CommandBuffer.hpp" -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" #include #include @@ -10,6 +7,10 @@ #include #include +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include #include @@ -90,13 +91,17 @@ TEST_CASE("add_component during for_each applies after iteration", "[ecs][Comman }); int with_b_before = 0; - world.for_each([&](CBA&, CBB&) { ++with_b_before; }); + world.for_each([&](CBA&, CBB&) { + ++with_b_before; + }); CHECK(with_b_before == 0); cmd.apply(world); int with_b_after = 0; - world.for_each([&](CBA&, CBB&) { ++with_b_after; }); + world.for_each([&](CBA&, CBB&) { + ++with_b_after; + }); CHECK(with_b_after == 3); } @@ -144,7 +149,7 @@ TEST_CASE("Tag components in CommandBuffer", "[ecs][CommandBuffer][tag]") { CHECK(world.has_component(eid)); CommandBuffer cmd2; - cmd2.add_component(eid); // already present — should be safe + cmd2.add_component(eid); // already present — should be safe cmd2.remove_component(eid); cmd2.apply(world); CHECK_FALSE(world.has_component(eid)); @@ -274,7 +279,9 @@ TEST_CASE("Same-buffer destroy on a deferred placeholder is a clean net no-op", cmd.apply(world); int found = 0; - world.for_each([&](CBA&) { ++found; }); + world.for_each([&](CBA&) { + ++found; + }); CHECK(found == 0); } @@ -295,13 +302,16 @@ TEST_CASE("Same-buffer remove_component on a deferred placeholder works", "[ecs] ++with_a_only; CHECK(a.v == 1); }); - world.for_each([&](CBA&, CBB&) { ++with_a_and_b; }); + world.for_each([&](CBA&, CBB&) { + ++with_a_and_b; + }); CHECK(with_a_only == 1); CHECK(with_a_and_b == 0); } -TEST_CASE("merge_from rebases deferred placeholders so each add resolves to its own create", - "[ecs][CommandBuffer][deferred][merge]") { +TEST_CASE( + "merge_from rebases deferred placeholders so each add resolves to its own create", "[ecs][CommandBuffer][deferred][merge]" +) { World world; CommandBuffer chunk_a; CommandBuffer chunk_b; @@ -328,7 +338,9 @@ TEST_CASE("merge_from rebases deferred placeholders so each add resolves to its // Walk the resulting entities and verify each (CBA::v, CBB::w) pair. std::vector> pairs; - world.for_each([&](CBA& a, CBB& b) { pairs.push_back({ a.v, b.w }); }); + world.for_each([&](CBA& a, CBB& b) { + pairs.push_back({ a.v, b.w }); + }); std::sort(pairs.begin(), pairs.end()); REQUIRE(pairs.size() == 2u); CHECK(pairs[0].first == 1); @@ -337,8 +349,7 @@ TEST_CASE("merge_from rebases deferred placeholders so each add resolves to its CHECK(pairs[1].second == 20); } -TEST_CASE("merge_from with multiple chunks resolves placeholders in chunk_idx order", - "[ecs][CommandBuffer][deferred][merge]") { +TEST_CASE("merge_from with multiple chunks resolves placeholders in chunk_idx order", "[ecs][CommandBuffer][deferred][merge]") { World world; std::vector chunks(4); for (auto& cb : chunks) { @@ -363,7 +374,9 @@ TEST_CASE("merge_from with multiple chunks resolves placeholders in chunk_idx or system_pending.apply(world); std::vector> pairs; - world.for_each([&](CBA& a, CBB& b) { pairs.push_back({ a.v, b.w }); }); + world.for_each([&](CBA& a, CBB& b) { + pairs.push_back({ a.v, b.w }); + }); std::sort(pairs.begin(), pairs.end()); REQUIRE(pairs.size() == 8u); for (std::size_t i = 0; i < pairs.size(); ++i) { @@ -375,8 +388,7 @@ TEST_CASE("merge_from with multiple chunks resolves placeholders in chunk_idx or } } -TEST_CASE("Empty parallel buffer apply is a no-op and resets deferred_count", - "[ecs][CommandBuffer][deferred]") { +TEST_CASE("Empty parallel buffer apply is a no-op and resets deferred_count", "[ecs][CommandBuffer][deferred]") { World world; CommandBuffer cmd; cmd.set_parallel_mode(true); @@ -384,7 +396,9 @@ TEST_CASE("Empty parallel buffer apply is a no-op and resets deferred_count", cmd.apply(world); CHECK(cmd.deferred_count() == 0u); int found = 0; - world.for_each([&](CBA&) { ++found; }); + world.for_each([&](CBA&) { + ++found; + }); CHECK(found == 0); } @@ -424,13 +438,14 @@ TEST_CASE("Tag components are first-class in the deferred path", "[ecs][CommandB CHECK(a.v == 1); CHECK(e.is_valid()); CHECK_FALSE(e.is_deferred()); - (void) ph; + (void)ph; }); CHECK(found == 1); } -TEST_CASE("Deferred placeholder is safe to pass to World accessors outside its buffer", - "[ecs][CommandBuffer][deferred][safety]") { +TEST_CASE( + "Deferred placeholder is safe to pass to World accessors outside its buffer", "[ecs][CommandBuffer][deferred][safety]" +) { World world; CommandBuffer cmd; cmd.set_parallel_mode(true); @@ -448,8 +463,9 @@ TEST_CASE("Deferred placeholder is safe to pass to World accessors outside its b cmd.apply(world); } -TEST_CASE("Real entity destroy via parallel buffer is unaffected by placeholder space", - "[ecs][CommandBuffer][deferred][safety]") { +TEST_CASE( + "Real entity destroy via parallel buffer is unaffected by placeholder space", "[ecs][CommandBuffer][deferred][safety]" +) { // Subtle bug class: confusing a real EntityID's small index with a placeholder's local_seq. // Pre-create 5 entities (real indices 0..4), then in parallel mode create 3 deferred and // destroy the first real eid. After apply: real_eid_0 is dead, the other 4 originals plus @@ -486,8 +502,7 @@ TEST_CASE("Real entity destroy via parallel buffer is unaffected by placeholder CHECK(high_value_count == 3); } -TEST_CASE("allocate_entity_slot generations stay below DEFERRED_GENERATION_BIT", - "[ecs][CommandBuffer][deferred][safety]") { +TEST_CASE("allocate_entity_slot generations stay below DEFERRED_GENERATION_BIT", "[ecs][CommandBuffer][deferred][safety]") { // Repeatedly create+destroy the same slot — generation increments on every reuse and must // never produce a value with the high bit set, otherwise a real EntityID could be confused // with a deferred placeholder. We don't push through 2^31 reuses (too slow); instead spot- diff --git a/tests/src/core/ecs/CommandBufferApplyOrder.cpp b/tests/src/core/ecs/CommandBufferApplyOrder.cpp index 28b242fe9..54cf4d39c 100644 --- a/tests/src/core/ecs/CommandBufferApplyOrder.cpp +++ b/tests/src/core/ecs/CommandBufferApplyOrder.cpp @@ -1,4 +1,5 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" @@ -6,8 +7,7 @@ #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -26,9 +26,15 @@ using OpenVic::Date; // buffer's value: the system with the GREATER type id wins. namespace { - struct CbaoIterA { int32_t v = 0; }; // iterated/written only by CbaoWriterA - struct CbaoIterB { int32_t v = 0; }; // iterated/written only by CbaoWriterB - struct CbaoProbe { int32_t v = 0; }; // on the probe entity; never in any tick signature + struct CbaoIterA { + int32_t v = 0; + }; // iterated/written only by CbaoWriterA + struct CbaoIterB { + int32_t v = 0; + }; // iterated/written only by CbaoWriterB + struct CbaoProbe { + int32_t v = 0; + }; // on the probe entity; never in any tick signature } ECS_COMPONENT(CbaoIterA, "test_CmdBufApplyOrder::IterA") ECS_COMPONENT(CbaoIterB, "test_CmdBufApplyOrder::IterB") @@ -63,8 +69,8 @@ ECS_SYSTEM(CbaoWriterA) ECS_SYSTEM(CbaoWriterB) TEST_CASE( - "Stage-barrier buffers apply in ascending system_type_id_t, independent of registration order", - "[ecs][CommandBuffer][SystemScheduler][determinism]" + "Stage-barrier buffers apply in ascending system_type_id_t, independent of registration order", + "[ecs][CommandBuffer][SystemScheduler][determinism]" ) { constexpr system_type_id_t id_a = system_type_id_of(); constexpr system_type_id_t id_b = system_type_id_of(); diff --git a/tests/src/core/ecs/Component.cpp b/tests/src/core/ecs/Component.cpp index 1cebd4442..8d336438f 100644 --- a/tests/src/core/ecs/Component.cpp +++ b/tests/src/core/ecs/Component.cpp @@ -1,8 +1,8 @@ +#include + #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include - #include #include diff --git a/tests/src/core/ecs/Coverage.cpp b/tests/src/core/ecs/Coverage.cpp index 5e3ba23fd..3916a68f1 100644 --- a/tests/src/core/ecs/Coverage.cpp +++ b/tests/src/core/ecs/Coverage.cpp @@ -1,6 +1,10 @@ // Coverage gap-fill — add tests for public API surfaces not directly hit by the // thematic test files. Each test below targets a method or scenario that // otherwise would not have explicit assertion coverage. +#include +#include +#include + #include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/CachedRef.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" @@ -8,10 +12,6 @@ #include "openvic-simulation/core/ecs/System.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include -#include - #include #include @@ -89,9 +89,7 @@ TEST_CASE("SystemHandle operator!= is the inverse of ==", "[ecs][System][coverag // === Many-component archetype === TEST_CASE("Entity with five distinct components round-trips correctly", "[ecs][World][coverage]") { World world; - EntityID const eid = world.create_entity( - CovA { 1 }, CovB { 2 }, CovC { 3 }, CovD { 4 }, CovE { 5 } - ); + EntityID const eid = world.create_entity(CovA { 1 }, CovB { 2 }, CovC { 3 }, CovD { 4 }, CovE { 5 }); CHECK(world.has_component(eid)); CHECK(world.has_component(eid)); CHECK(world.has_component(eid)); @@ -107,9 +105,7 @@ TEST_CASE("Entity with five distinct components round-trips correctly", "[ecs][W TEST_CASE("Migration preserves five-component values across add", "[ecs][World][coverage][migration]") { World world; - EntityID const eid = world.create_entity( - CovA { 11 }, CovB { 22 }, CovC { 33 }, CovD { 44 } - ); + EntityID const eid = world.create_entity(CovA { 11 }, CovB { 22 }, CovC { 33 }, CovD { 44 }); world.add_component(eid, CovE { 55 }); CHECK(world.get_component(eid)->v == 11); @@ -129,7 +125,9 @@ TEST_CASE("Archetype can be emptied and refilled", "[ecs][World][coverage]") { world.destroy_entity(b); int count = 0; - world.for_each([&](CovA&, CovB&) { ++count; }); + world.for_each([&](CovA&, CovB&) { + ++count; + }); CHECK(count == 0); // Refill — same archetype, slot-reuse path. @@ -139,7 +137,9 @@ TEST_CASE("Archetype can be emptied and refilled", "[ecs][World][coverage]") { CHECK(world.get_component(c)->w == 6); count = 0; - world.for_each([&](CovA&, CovB&) { ++count; }); + world.for_each([&](CovA&, CovB&) { + ++count; + }); CHECK(count == 1); } @@ -147,12 +147,16 @@ TEST_CASE("Archetype can be emptied and refilled", "[ecs][World][coverage]") { TEST_CASE("for_each_with_entity on empty World is safe and a no-op", "[ecs][World][iter][coverage]") { World world; int count = 0; - world.for_each_with_entity([&](EntityID, CovA&) { ++count; }); + world.for_each_with_entity([&](EntityID, CovA&) { + ++count; + }); CHECK(count == 0); Query q; q.with().build(); - world.for_each_with_entity(q, [&](EntityID, CovA&) { ++count; }); + world.for_each_with_entity(q, [&](EntityID, CovA&) { + ++count; + }); CHECK(count == 0); } @@ -162,9 +166,9 @@ TEST_CASE("CachedRef is trivially copyable", "[ecs][CachedRef][coverage]") { EntityID const eid = world.create_entity(CovA { 42 }); auto ref1 = CachedRef::from(world, eid); - CachedRef ref2 = ref1; // copy-construct + CachedRef ref2 = ref1; // copy-construct CachedRef ref3; - ref3 = ref1; // copy-assign + ref3 = ref1; // copy-assign CHECK(ref1.get(world)->v == 42); CHECK(ref2.get(world)->v == 42); @@ -176,12 +180,12 @@ TEST_CASE("CachedRef is trivially copyable", "[ecs][CachedRef][coverage]") { // === Queries match correctly across many archetypes === TEST_CASE("Query selects the intended subset across many archetypes", "[ecs][World][query][coverage]") { World world; - world.create_entity(CovA { 1 }); // A - world.create_entity(CovA { 2 }, CovB { 1 }); // AB - world.create_entity(CovA { 3 }, CovC { 1 }); // AC - world.create_entity(CovA { 4 }, CovB { 1 }, CovC { 1 }); // ABC - world.create_entity(CovA { 5 }, CovD { 1 }); // AD - world.create_entity(CovB { 1 }, CovC { 1 }); // BC (no A) + world.create_entity(CovA { 1 }); // A + world.create_entity(CovA { 2 }, CovB { 1 }); // AB + world.create_entity(CovA { 3 }, CovC { 1 }); // AC + world.create_entity(CovA { 4 }, CovB { 1 }, CovC { 1 }); // ABC + world.create_entity(CovA { 5 }, CovD { 1 }); // AD + world.create_entity(CovB { 1 }, CovC { 1 }); // BC (no A) // Want all entities with A but not D. Query q; @@ -192,7 +196,7 @@ TEST_CASE("Query selects the intended subset across many archetypes", "[ecs][Wor ++count; sum += a.v; }); - CHECK(count == 4); // A, AB, AC, ABC + CHECK(count == 4); // A, AB, AC, ABC CHECK(sum == 1 + 2 + 3 + 4); } @@ -211,11 +215,15 @@ TEST_CASE("Stress: many archetype migrations, query stays accurate", "[ecs][Worl } int with_b = 0; - world.for_each([&](CovA&, CovB&) { ++with_b; }); + world.for_each([&](CovA&, CovB&) { + ++with_b; + }); CHECK(with_b == 25); int total_a = 0; - world.for_each([&](CovA&) { ++total_a; }); + world.for_each([&](CovA&) { + ++total_a; + }); CHECK(total_a == 50); // Now demote half of the {CovA, CovB} entities back. @@ -227,11 +235,15 @@ TEST_CASE("Stress: many archetype migrations, query stays accurate", "[ecs][Worl } int after_b = 0; - world.for_each([&](CovA&, CovB&) { ++after_b; }); + world.for_each([&](CovA&, CovB&) { + ++after_b; + }); CHECK(after_b == 12); // 25 → 12 after removing 13 (i=0,2,...,24) int after_a = 0; - world.for_each([&](CovA&) { ++after_a; }); + world.for_each([&](CovA&) { + ++after_a; + }); CHECK(after_a == 50); } @@ -269,7 +281,9 @@ TEST_CASE("Component order at create_entity is normalised", "[ecs][World][covera // All three visible in a single for_each. int count = 0; - world.for_each([&](CovA&, CovB&, CovC&) { ++count; }); + world.for_each([&](CovA&, CovB&, CovC&) { + ++count; + }); CHECK(count == 3); } @@ -293,7 +307,9 @@ TEST_CASE("Tag-only archetype handles destroy + create cycles", "[ecs][World][ta } int count = 0; - world.for_each([&](CovTag&) { ++count; }); + world.for_each([&](CovTag&) { + ++count; + }); CHECK(count == 0); for (int i = 0; i < 3; ++i) { @@ -301,14 +317,16 @@ TEST_CASE("Tag-only archetype handles destroy + create cycles", "[ecs][World][ta } count = 0; - world.for_each([&](CovTag&) { ++count; }); + world.for_each([&](CovTag&) { + ++count; + }); CHECK(count == 3); } // === component_version_in distinguishes per-archetype-column versions === TEST_CASE("component_version_in is per-archetype, not global per type", "[ecs][World][version][coverage]") { World world; - EntityID const a = world.create_entity(CovA { 1 }); // archetype {A} + EntityID const a = world.create_entity(CovA { 1 }); // archetype {A} EntityID const b = world.create_entity(CovA { 2 }, CovB { 3 }); // archetype {A,B} uint64_t va_in_a = world.component_version_in(a); @@ -319,8 +337,8 @@ TEST_CASE("component_version_in is per-archetype, not global per type", "[ecs][W uint64_t va_in_a2 = world.component_version_in(a); uint64_t va_in_b2 = world.component_version_in(b); - CHECK(va_in_a2 > va_in_a); // mutated - CHECK(va_in_b2 == va_in_b); // {A,B} archetype untouched + CHECK(va_in_a2 > va_in_a); // mutated + CHECK(va_in_b2 == va_in_b); // {A,B} archetype untouched } // === Empty Query (only require_ids, no exclude) is the same as no Query === @@ -331,12 +349,16 @@ TEST_CASE("Query-overload matches non-Query for_each on identical require set", world.create_entity(CovA { 3 }, CovB { 0 }, CovC { 0 }); int n_plain = 0; - world.for_each([&](CovA&) { ++n_plain; }); + world.for_each([&](CovA&) { + ++n_plain; + }); Query q; q.with().build(); int n_query = 0; - world.for_each(q, [&](CovA&) { ++n_query; }); + world.for_each(q, [&](CovA&) { + ++n_query; + }); CHECK(n_plain == n_query); CHECK(n_plain == 3); diff --git a/tests/src/core/ecs/DenseSlotAllocator.cpp b/tests/src/core/ecs/DenseSlotAllocator.cpp index 38b6ae56c..525f7f661 100644 --- a/tests/src/core/ecs/DenseSlotAllocator.cpp +++ b/tests/src/core/ecs/DenseSlotAllocator.cpp @@ -34,12 +34,12 @@ TEST_CASE("dense growth then LIFO reuse, exact sequence", "[ecs][DenseSlotAlloca TEST_CASE("snapshot/restore continues exactly as the never-saved run", "[ecs][DenseSlotAllocator]") { DenseSlotAllocator original; for (int i = 0; i < 8; ++i) { - (void) original.allocate(); + (void)original.allocate(); } original.release(3); original.release(6); original.release(1); - (void) original.allocate(); // 1 — leaves [3, 6] on the stack + (void)original.allocate(); // 1 — leaves [3, 6] on the stack original.release(7); DenseSlotAllocator::Snapshot snap; @@ -76,15 +76,15 @@ TEST_CASE("snapshot/restore continues exactly as the never-saved run", "[ecs][De // Restore into a reset (non-fresh) allocator also works. DenseSlotAllocator reused; - (void) reused.allocate(); + (void)reused.allocate(); reused.reset(); CHECK(reused.restore(snap)); } TEST_CASE("restore validates and leaves state untouched on failure", "[ecs][DenseSlotAllocator]") { DenseSlotAllocator alloc; - (void) alloc.allocate(); - (void) alloc.allocate(); + (void)alloc.allocate(); + (void)alloc.allocate(); { // Free slot >= next_unallocated. @@ -118,7 +118,7 @@ TEST_CASE("restore validates and leaves state untouched on failure", "[ecs][Dens TEST_CASE("reset forgets everything (the end_game_session sweep)", "[ecs][DenseSlotAllocator]") { DenseSlotAllocator alloc; for (int i = 0; i < 6; ++i) { - (void) alloc.allocate(); + (void)alloc.allocate(); } alloc.release(4); alloc.release(2); @@ -135,11 +135,12 @@ TEST_CASE("reset forgets everything (the end_game_session sweep)", "[ecs][DenseS CHECK(snap.free_slots.empty()); } -TEST_CASE("release range-check ignores never-allocated slots; debug_validate catches double release", - "[ecs][DenseSlotAllocator]") { +TEST_CASE( + "release range-check ignores never-allocated slots; debug_validate catches double release", "[ecs][DenseSlotAllocator]" +) { DenseSlotAllocator alloc; for (int i = 0; i < 3; ++i) { - (void) alloc.allocate(); + (void)alloc.allocate(); } alloc.release(99); // never allocated — logged and ignored diff --git a/tests/src/core/ecs/EcsThreadPool.cpp b/tests/src/core/ecs/EcsThreadPool.cpp index b68799753..d5c7392fc 100644 --- a/tests/src/core/ecs/EcsThreadPool.cpp +++ b/tests/src/core/ecs/EcsThreadPool.cpp @@ -36,8 +36,7 @@ TEST_CASE("EcsThreadPool::parallel_for visits each chunk_idx exactly once", "[ec } } -TEST_CASE("EcsThreadPool::parallel_for produces same result regardless of worker count", - "[ecs][EcsThreadPool][determinism]") { +TEST_CASE("EcsThreadPool::parallel_for produces same result regardless of worker count", "[ecs][EcsThreadPool][determinism]") { std::vector baseline(500, 0); { EcsThreadPool serial { 1 }; @@ -62,9 +61,15 @@ TEST_CASE("EcsThreadPool::run_concurrent runs each function exactly once", "[ecs std::atomic b { 0 }; std::atomic c { 0 }; std::vector> bodies; - bodies.emplace_back([&a]() { a.fetch_add(1); }); - bodies.emplace_back([&b]() { b.fetch_add(1); }); - bodies.emplace_back([&c]() { c.fetch_add(1); }); + bodies.emplace_back([&a]() { + a.fetch_add(1); + }); + bodies.emplace_back([&b]() { + b.fetch_add(1); + }); + bodies.emplace_back([&c]() { + c.fetch_add(1); + }); pool.run_concurrent(std::span const>(bodies.data(), bodies.size())); CHECK(a.load() == 1); CHECK(b.load() == 1); diff --git a/tests/src/core/ecs/EntityID.cpp b/tests/src/core/ecs/EntityID.cpp index 13ce08aa6..1d65660b8 100644 --- a/tests/src/core/ecs/EntityID.cpp +++ b/tests/src/core/ecs/EntityID.cpp @@ -1,8 +1,9 @@ -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" + #include #include diff --git a/tests/src/core/ecs/EntityLifecycle.cpp b/tests/src/core/ecs/EntityLifecycle.cpp index a207a2306..5d351e15b 100644 --- a/tests/src/core/ecs/EntityLifecycle.cpp +++ b/tests/src/core/ecs/EntityLifecycle.cpp @@ -1,9 +1,9 @@ -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include #include diff --git a/tests/src/core/ecs/FNVHash.cpp b/tests/src/core/ecs/FNVHash.cpp index 3b573a88d..db480fe33 100644 --- a/tests/src/core/ecs/FNVHash.cpp +++ b/tests/src/core/ecs/FNVHash.cpp @@ -1,8 +1,8 @@ -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" - #include #include +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" + #include #include diff --git a/tests/src/core/ecs/IdentitySnapshot.cpp b/tests/src/core/ecs/IdentitySnapshot.cpp index ffcd9b859..8c5b8fede 100644 --- a/tests/src/core/ecs/IdentitySnapshot.cpp +++ b/tests/src/core/ecs/IdentitySnapshot.cpp @@ -1,11 +1,11 @@ +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -45,8 +45,7 @@ TEST_CASE("snapshot/restore: empty world round-trips", "[ecs][identity]") { CHECK(b == a); } -TEST_CASE("live entities reconstruct at original (index, generation); stale handles stay dead", - "[ecs][identity]") { +TEST_CASE("live entities reconstruct at original (index, generation); stale handles stay dead", "[ecs][identity]") { World original; // 8 entities across two archetypes, mixing mutable and immutable creation. diff --git a/tests/src/core/ecs/IdentitySnapshotInvariance.cpp b/tests/src/core/ecs/IdentitySnapshotInvariance.cpp index 5fe463142..3fa1292ac 100644 --- a/tests/src/core/ecs/IdentitySnapshotInvariance.cpp +++ b/tests/src/core/ecs/IdentitySnapshotInvariance.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -194,8 +194,7 @@ namespace { } } -TEST_CASE("restore + tick digest equals continue + tick digest across worker counts", - "[ecs][determinism][identity]") { +TEST_CASE("restore + tick digest equals continue + tick digest across worker counts", "[ecs][determinism][identity]") { RunResult const baseline = run_both_branches(1); CHECK(baseline.restored_digest == baseline.continued_digest); @@ -207,8 +206,7 @@ TEST_CASE("restore + tick digest equals continue + tick digest across worker cou } } -TEST_CASE("restored free-list reuse hands spawned entities identical EntityIDs", - "[ecs][determinism][identity]") { +TEST_CASE("restored free-list reuse hands spawned entities identical EntityIDs", "[ecs][determinism][identity]") { // Sharper failure message than a digest mismatch: the exact spawned-id sets must match — // early ticks drain the churned free list, later ticks grow fresh slots past it. RunResult const result = run_both_branches(4); diff --git a/tests/src/core/ecs/ImmutableEntity.cpp b/tests/src/core/ecs/ImmutableEntity.cpp index 387c2b32d..011b5317d 100644 --- a/tests/src/core/ecs/ImmutableEntity.cpp +++ b/tests/src/core/ecs/ImmutableEntity.cpp @@ -1,16 +1,16 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -54,23 +54,29 @@ namespace { template struct can_add_component : std::false_type {}; template - struct can_add_component().template add_component(std::declval()))>> - : std::true_type {}; + struct can_add_component< + Obj, + Handle, + C, + std::void_t().template add_component(std::declval()))>> : std::true_type {}; template struct can_remove_component : std::false_type {}; template - struct can_remove_component().template remove_component(std::declval()))>> - : std::true_type {}; + struct can_remove_component< + Obj, + Handle, + C, + std::void_t().template remove_component(std::declval()))>> : std::true_type {}; template struct can_get_component : std::false_type {}; template - struct can_get_component().template get_component(std::declval()))>> - : std::true_type {}; + struct can_get_component< + Obj, + Handle, + C, + std::void_t().template get_component(std::declval()))>> : std::true_type {}; // Structural mutation IS reachable on a plain EntityID, but NOT on an ImmutableEntityID // (no overload accepts it and there is no implicit conversion). This is the guarantee. @@ -99,8 +105,9 @@ namespace { static_assert(std::is_same_v().unsafe_mutable_id()), EntityID>); // The factory hands back the strong handle, not a plain EntityID. - static_assert(std::is_same_v< - decltype(std::declval().create_immutable_entity(std::declval())), ImmutableEntityID>); + static_assert( + std::is_same_v().create_immutable_entity(std::declval())), ImmutableEntityID> + ); } TEST_CASE("Immutable compile-time guarantees hold (static_assert wall)", "[ecs][World][immutable][compiletime]") { @@ -156,8 +163,7 @@ TEST_CASE("is_immutable reports per-entity immutability", "[ecs][World][immutabl CHECK_FALSE(world.is_immutable(reused)); } -TEST_CASE("is_immutable: a deferred immutable create is not immutable until apply", - "[ecs][World][immutable][cmd]") { +TEST_CASE("is_immutable: a deferred immutable create is not immutable until apply", "[ecs][World][immutable][cmd]") { World world; CommandBuffer cb; ImmutableEntityID const e = cb.create_immutable_entity(world, ImmA { 7 }); @@ -189,8 +195,10 @@ TEST_CASE("remove_component on a laundered immutable id is refused", "[ecs][Worl CHECK(world.has_component(e)); } -TEST_CASE("structural ops still succeed on a normal mutable entity (backstop is immutability-gated)", - "[ecs][World][immutable][backstop]") { +TEST_CASE( + "structural ops still succeed on a normal mutable entity (backstop is immutability-gated)", + "[ecs][World][immutable][backstop]" +) { World world; EntityID const e = world.create_entity(ImmA { 5 }); @@ -200,8 +208,9 @@ TEST_CASE("structural ops still succeed on a normal mutable entity (backstop is CHECK_FALSE(world.has_component(e)); } -TEST_CASE("CommandBuffer add_component on a laundered immutable id is refused at apply", - "[ecs][World][immutable][backstop][cmd]") { +TEST_CASE( + "CommandBuffer add_component on a laundered immutable id is refused at apply", "[ecs][World][immutable][backstop][cmd]" +) { World world; ImmutableEntityID const e = world.create_immutable_entity(ImmA { 5 }); @@ -213,8 +222,9 @@ TEST_CASE("CommandBuffer add_component on a laundered immutable id is refused at CHECK(world.get_component(e)->v == 5); } -TEST_CASE("CommandBuffer remove_component on a laundered immutable id is refused at apply", - "[ecs][World][immutable][backstop][cmd]") { +TEST_CASE( + "CommandBuffer remove_component on a laundered immutable id is refused at apply", "[ecs][World][immutable][backstop][cmd]" +) { World world; ImmutableEntityID const e = world.create_immutable_entity(ImmA { 5 }, ImmB { 6 }); @@ -225,8 +235,7 @@ TEST_CASE("CommandBuffer remove_component on a laundered immutable id is refused CHECK(world.has_component(e)); } -TEST_CASE("CommandBuffer::create_immutable_entity (serial) finalises an immutable entity", - "[ecs][World][immutable][cmd]") { +TEST_CASE("CommandBuffer::create_immutable_entity (serial) finalises an immutable entity", "[ecs][World][immutable][cmd]") { World world; CommandBuffer cb; ImmutableEntityID const e = cb.create_immutable_entity(world, ImmA { 11 }); @@ -244,8 +253,7 @@ TEST_CASE("CommandBuffer::create_immutable_entity (serial) finalises an immutabl CHECK_FALSE(world.has_component(e)); } -TEST_CASE("Deferred create_immutable_entity + same-buffer add: create runs, add refused", - "[ecs][World][immutable][cmd]") { +TEST_CASE("Deferred create_immutable_entity + same-buffer add: create runs, add refused", "[ecs][World][immutable][cmd]") { World world; CommandBuffer cb; ImmutableEntityID const e = cb.create_immutable_entity(world, ImmA { 2 }); @@ -257,8 +265,7 @@ TEST_CASE("Deferred create_immutable_entity + same-buffer add: create runs, add CHECK_FALSE(world.has_component(e)); } -TEST_CASE("A reused slot comes back mutable after an immutable entity is destroyed", - "[ecs][World][immutable][lifecycle]") { +TEST_CASE("A reused slot comes back mutable after an immutable entity is destroyed", "[ecs][World][immutable][lifecycle]") { World world; ImmutableEntityID const e = world.create_immutable_entity(ImmA { 1 }); uint32_t const idx = e.index; @@ -282,8 +289,7 @@ TEST_CASE("Stale ImmutableEntityID fails is_alive after slot reuse", "[ecs][Worl CHECK_FALSE(world.is_alive(e)); } -TEST_CASE("Immutable entity survives sibling churn (re-fetch, not pointer identity)", - "[ecs][World][immutable][stability]") { +TEST_CASE("Immutable entity survives sibling churn (re-fetch, not pointer identity)", "[ecs][World][immutable][stability]") { World world; ImmutableEntityID const keep = world.create_immutable_entity(ImmA { 100 }); @@ -409,8 +415,9 @@ namespace { } } -TEST_CASE("SystemThreaded can spawn immutable entities via cmd.create_immutable_entity", - "[ecs][World][immutable][cmd][system]") { +TEST_CASE( + "SystemThreaded can spawn immutable entities via cmd.create_immutable_entity", "[ecs][World][immutable][cmd][system]" +) { SpawnResult const r = run_immutable_spawn(4); std::size_t expected = 0; @@ -421,8 +428,7 @@ TEST_CASE("SystemThreaded can spawn immutable entities via cmd.create_immutable_ CHECK(r.immutable_count == expected); // all spawned entities are immutable } -TEST_CASE("Immutable in-system spawn is worker-count invariant", - "[ecs][World][immutable][cmd][system][determinism]") { +TEST_CASE("Immutable in-system spawn is worker-count invariant", "[ecs][World][immutable][cmd][system][determinism]") { SpawnResult const baseline = run_immutable_spawn(1); for (uint32_t wc : { 1u, 2u, 4u, 8u, 16u }) { diff --git a/tests/src/core/ecs/InTickMutationGuard.cpp b/tests/src/core/ecs/InTickMutationGuard.cpp index 9d5ba4d6f..298a92688 100644 --- a/tests/src/core/ecs/InTickMutationGuard.cpp +++ b/tests/src/core/ecs/InTickMutationGuard.cpp @@ -1,10 +1,10 @@ -#include "openvic-simulation/core/object/Date.hpp" #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -13,8 +13,12 @@ using namespace OpenVic::ecs; using OpenVic::Date; namespace { - struct GuardTag { int n = 0; }; - struct GuardTagB { int m = 0; }; + struct GuardTag { + int n = 0; + }; + struct GuardTagB { + int m = 0; + }; } ECS_COMPONENT(GuardTag, "test_InTickGuard::GuardTag") ECS_COMPONENT(GuardTagB, "test_InTickGuard::GuardTagB") @@ -49,8 +53,7 @@ TEST_CASE("World::add_component during tick is rejected", "[ecs][InTickMutationG CHECK_FALSE(world.has_component(eid)); } -TEST_CASE("ctx.cmd.add_component succeeds and applies at stage barrier", - "[ecs][InTickMutationGuard]") { +TEST_CASE("ctx.cmd.add_component succeeds and applies at stage barrier", "[ecs][InTickMutationGuard]") { World world; EntityID const eid = world.create_entity(GuardTag {}); world.register_system(); diff --git a/tests/src/core/ecs/Integration.cpp b/tests/src/core/ecs/Integration.cpp index 6fda73bc8..1b688172a 100644 --- a/tests/src/core/ecs/Integration.cpp +++ b/tests/src/core/ecs/Integration.cpp @@ -1,16 +1,16 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include +#include +#include + #include "openvic-simulation/core/ecs/CachedRef.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/Query.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -146,7 +146,7 @@ TEST_CASE("Integration: CachedRef survives sibling-induced swap-pop", "[ecs][int std::vector ids; for (int i = 0; i < 5; ++i) { - ids.push_back(world.create_entity(Position { (float) i, 0 })); + ids.push_back(world.create_entity(Position { (float)i, 0 })); } // Cache a ref into the middle entity. @@ -166,7 +166,7 @@ TEST_CASE("Integration: CachedRef survives sibling-induced swap-pop", "[ecs][int TEST_CASE("Integration: query cache survives across a system tick", "[ecs][integration][query]") { World world; for (int i = 0; i < 10; ++i) { - world.create_entity(Position { (float) i, 0 }, Velocity { 1, 0 }); + world.create_entity(Position { (float)i, 0 }, Velocity { 1, 0 }); } world.create_entity(Position { 99, 0 }, Velocity { 1, 0 }, Frozen {}); @@ -195,13 +195,13 @@ TEST_CASE("Integration: archetype mass-creation does not lose data", "[ecs][inte World world; std::vector ids; for (int i = 0; i < 100; ++i) { - ids.push_back(world.create_entity(Position { (float) i, (float) (i * 2) })); + ids.push_back(world.create_entity(Position { (float)i, (float)(i * 2) })); } for (int i = 0; i < 100; ++i) { Position* p = world.get_component(ids[i]); CHECK(p != nullptr); - CHECK(p->x == (float) i); - CHECK(p->y == (float) (i * 2)); + CHECK(p->x == (float)i); + CHECK(p->y == (float)(i * 2)); } } @@ -242,10 +242,10 @@ TEST_CASE("Integration: many migrations preserve component data", "[ecs][integra EntityID const eid = world.create_entity(Position { 13, 17 }); for (int i = 0; i < 10; ++i) { - world.add_component(eid, Velocity { (float) i, (float) (i * 2) }); + world.add_component(eid, Velocity { (float)i, (float)(i * 2) }); CHECK(world.get_component(eid)->x == 13.0f); CHECK(world.get_component(eid)->y == 17.0f); - CHECK(world.get_component(eid)->dx == (float) i); + CHECK(world.get_component(eid)->dx == (float)i); world.remove_component(eid); CHECK(world.get_component(eid)->x == 13.0f); } diff --git a/tests/src/core/ecs/IntraSystemParallel.cpp b/tests/src/core/ecs/IntraSystemParallel.cpp index 4beb29587..0338c095c 100644 --- a/tests/src/core/ecs/IntraSystemParallel.cpp +++ b/tests/src/core/ecs/IntraSystemParallel.cpp @@ -1,13 +1,13 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -35,8 +35,7 @@ namespace { } ECS_SYSTEM(ParMover) -TEST_CASE("SystemThreaded touches each row exactly once", - "[ecs][IntraSystemParallel]") { +TEST_CASE("SystemThreaded touches each row exactly once", "[ecs][IntraSystemParallel]") { for (uint32_t wc : { 1u, 2u, 4u, 8u, 16u }) { World world; world.set_ecs_worker_count(wc); @@ -45,10 +44,7 @@ TEST_CASE("SystemThreaded touches each row exactly once", std::size_t const N = 500; ids.reserve(N); for (std::size_t i = 0; i < N; ++i) { - ids.push_back(world.create_entity( - ParPos { static_cast(i) }, - ParVel { 7 } - )); + ids.push_back(world.create_entity(ParPos { static_cast(i) }, ParVel { 7 })); } world.register_system(); @@ -63,8 +59,7 @@ TEST_CASE("SystemThreaded touches each row exactly once", } } -TEST_CASE("SystemThreaded result is identical across worker counts", - "[ecs][IntraSystemParallel][determinism]") { +TEST_CASE("SystemThreaded result is identical across worker counts", "[ecs][IntraSystemParallel][determinism]") { auto run = [](uint32_t wc) { World world; world.set_ecs_worker_count(wc); @@ -72,10 +67,9 @@ TEST_CASE("SystemThreaded result is identical across worker counts", std::size_t const N = 250; ids.reserve(N); for (std::size_t i = 0; i < N; ++i) { - ids.push_back(world.create_entity( - ParPos { static_cast(i + 1) }, - ParVel { static_cast((i * 13) % 17 + 1) } - )); + ids.push_back( + world.create_entity(ParPos { static_cast(i + 1) }, ParVel { static_cast((i * 13) % 17 + 1) }) + ); } world.register_system(); for (int t = 0; t < 5; ++t) { diff --git a/tests/src/core/ecs/Iteration.cpp b/tests/src/core/ecs/Iteration.cpp index 176b13f26..e51549a3e 100644 --- a/tests/src/core/ecs/Iteration.cpp +++ b/tests/src/core/ecs/Iteration.cpp @@ -1,10 +1,10 @@ +#include +#include + #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/Query.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -47,7 +47,9 @@ TEST_CASE("for_each visits all entities of a single-component archetype", "[ecs] TEST_CASE("for_each visits zero entities when no archetype matches", "[ecs][World][iter]") { World world; int count = 0; - world.for_each([&](IA&) { ++count; }); + world.for_each([&](IA&) { + ++count; + }); CHECK(count == 0); } @@ -59,13 +61,15 @@ TEST_CASE("for_each visits only matching archetype superset", "[ecs][World][iter int a_only_count = 0; world.for_each([&](IA& a) { - (void) a; + (void)a; ++a_only_count; }); CHECK(a_only_count == 2); // both IA-only and IA+IB int both_count = 0; - world.for_each([&](IA&, IB&) { ++both_count; }); + world.for_each([&](IA&, IB&) { + ++both_count; + }); CHECK(both_count == 1); } @@ -75,7 +79,9 @@ TEST_CASE("for_each_with_entity passes the correct EntityID", "[ecs][World][iter EntityID const b = world.create_entity(IA { 11 }); std::set seen; - world.for_each_with_entity([&](EntityID e, IA&) { seen.insert(e.to_uint64()); }); + world.for_each_with_entity([&](EntityID e, IA&) { + seen.insert(e.to_uint64()); + }); CHECK(seen.count(a.to_uint64()) == 1u); CHECK(seen.count(b.to_uint64()) == 1u); @@ -87,10 +93,14 @@ TEST_CASE("for_each lambda can mutate components in place", "[ecs][World][iter]" for (int i = 0; i < 4; ++i) { world.create_entity(IA { i }); } - world.for_each([](IA& a) { a.v *= 2; }); + world.for_each([](IA& a) { + a.v *= 2; + }); int sum = 0; - world.for_each([&](IA& a) { sum += a.v; }); + world.for_each([&](IA& a) { + sum += a.v; + }); CHECK(sum == (0 + 2 + 4 + 6)); } @@ -124,7 +134,9 @@ TEST_CASE("Query overload of for_each_with_entity respects exclude", "[ecs][Worl q.with().exclude().build(); std::set seen; - world.for_each_with_entity(q, [&](EntityID e, IA&) { seen.insert(e.to_uint64()); }); + world.for_each_with_entity(q, [&](EntityID e, IA&) { + seen.insert(e.to_uint64()); + }); CHECK(seen.size() == 2u); CHECK(seen.count(a.to_uint64()) == 1u); CHECK(seen.count(c.to_uint64()) == 1u); @@ -137,7 +149,9 @@ TEST_CASE("for_each works repeatedly (cached query)", "[ecs][World][iter][cache] for (int round = 0; round < 3; ++round) { int count = 0; - world.for_each([&](IA&) { ++count; }); + world.for_each([&](IA&) { + ++count; + }); CHECK(count == 2); } } @@ -145,17 +159,21 @@ TEST_CASE("for_each works repeatedly (cached query)", "[ecs][World][iter][cache] TEST_CASE("Query cache is invalidated when a new archetype is created", "[ecs][World][iter][cache]") { World world; EntityID const a = world.create_entity(IA { 1 }); - (void) a; + (void)a; int count_before = 0; - world.for_each([&](IA&) { ++count_before; }); + world.for_each([&](IA&) { + ++count_before; + }); CHECK(count_before == 1); // New archetype: {IA, IB}. Cached "IA" query should now also include this. world.create_entity(IA { 2 }, IB { 0 }); int count_after = 0; - world.for_each([&](IA&) { ++count_after; }); + world.for_each([&](IA&) { + ++count_after; + }); CHECK(count_after == 2); } @@ -207,7 +225,9 @@ TEST_CASE("Query with empty require_ids matches all archetypes that don't carry Query q; q.with().build(); int count = 0; - world.for_each(q, [&](IA&) { ++count; }); + world.for_each(q, [&](IA&) { + ++count; + }); CHECK(count == 2); } @@ -221,7 +241,9 @@ TEST_CASE("for_each is safe to call from within another for_each (read-only)", " int inner_total = 0; world.for_each([&](IA&) { ++outer_count; - world.for_each([&](IA& a) { inner_total += a.v; }); + world.for_each([&](IA& a) { + inner_total += a.v; + }); }); CHECK(outer_count == 3); CHECK(inner_total == 3 * (1 + 2 + 3)); diff --git a/tests/src/core/ecs/KeyedReductions.cpp b/tests/src/core/ecs/KeyedReductions.cpp index b9cdc8f58..1602e7340 100644 --- a/tests/src/core/ecs/KeyedReductions.cpp +++ b/tests/src/core/ecs/KeyedReductions.cpp @@ -1,11 +1,11 @@ -#include "openvic-simulation/core/object/FixedPoint.hpp" -#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" -#include "openvic-simulation/core/ecs/Reductions.hpp" - #include #include #include +#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" +#include "openvic-simulation/core/ecs/Reductions.hpp" +#include "openvic-simulation/core/object/FixedPoint.hpp" + #include #include @@ -58,10 +58,11 @@ TEST_CASE("parallel_keyed_sum matches a serial reference", "[ecs][Reductions][ke EcsThreadPool pool { 4 }; std::vector out(key_count, 0); - reductions::parallel_keyed_sum(pool, chunk_count, key_count, out, - [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit_chunk(chunk_idx, key_count, emit); - }); + reductions::parallel_keyed_sum( + pool, chunk_count, key_count, out, [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit_chunk(chunk_idx, key_count, emit); + } + ); std::vector expected = serial_reference(chunk_count, key_count); for (std::size_t k = 0; k < key_count; ++k) { @@ -77,20 +78,22 @@ TEST_CASE("parallel_keyed_sum is bit-identical across worker counts", "[ecs][Red { EcsThreadPool serial { 1 }; std::vector out(key_count, 0); - reductions::parallel_keyed_sum(serial, chunk_count, key_count, out, - [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit_chunk(chunk_idx, key_count, emit); - }); + reductions::parallel_keyed_sum( + serial, chunk_count, key_count, out, [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit_chunk(chunk_idx, key_count, emit); + } + ); baseline = digest_out(out); } for (uint32_t wc : { 1u, 2u, 4u, 8u, 16u }) { EcsThreadPool pool { wc }; std::vector out(key_count, 0); - reductions::parallel_keyed_sum(pool, chunk_count, key_count, out, - [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit_chunk(chunk_idx, key_count, emit); - }); + reductions::parallel_keyed_sum( + pool, chunk_count, key_count, out, [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit_chunk(chunk_idx, key_count, emit); + } + ); CHECK(digest_out(out) == baseline); } } @@ -102,14 +105,15 @@ TEST_CASE("parallel_keyed_sum folds duplicate keys within a chunk", "[ecs][Reduc // One chunk emits key 3 consecutively (fast path), then key 5, then key 3 again // (linear-scan path), then key 5 again. std::vector out(key_count, 0); - reductions::parallel_keyed_sum(pool, 1, key_count, out, - [](std::size_t /*chunk_idx*/, reductions::KeyedEmitter& emit) { - emit.add(3, 10); - emit.add(3, 20); - emit.add(5, 100); - emit.add(3, 30); - emit.add(5, 200); - }); + reductions::parallel_keyed_sum( + pool, 1, key_count, out, [](std::size_t /*chunk_idx*/, reductions::KeyedEmitter& emit) { + emit.add(3, 10); + emit.add(3, 20); + emit.add(5, 100); + emit.add(3, 30); + emit.add(5, 200); + } + ); CHECK(out[3] == 60); CHECK(out[5] == 300); @@ -125,10 +129,11 @@ TEST_CASE("parallel_keyed_sum leaves untouched keys at their initial value", "[e // out pre-initialized to a sentinel: emitted keys get sentinel + contribution, // untouched keys keep the sentinel. std::vector out(key_count, 42); - reductions::parallel_keyed_sum(pool, 2, key_count, out, - [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit.add(chunk_idx, static_cast(chunk_idx + 1) * 100); - }); + reductions::parallel_keyed_sum( + pool, 2, key_count, out, [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit.add(chunk_idx, static_cast(chunk_idx + 1) * 100); + } + ); CHECK(out[0] == 142); CHECK(out[1] == 242); @@ -142,10 +147,11 @@ TEST_CASE("parallel_keyed_sum on zero chunks leaves out unchanged", "[ecs][Reduc EcsThreadPool pool { 4 }; std::vector out(key_count, 7); - reductions::parallel_keyed_sum(pool, 0, key_count, out, - [](std::size_t /*chunk_idx*/, reductions::KeyedEmitter& emit) { - emit.add(0, 1); - }); + reductions::parallel_keyed_sum( + pool, 0, key_count, out, [](std::size_t /*chunk_idx*/, reductions::KeyedEmitter& emit) { + emit.add(0, 1); + } + ); for (std::size_t k = 0; k < key_count; ++k) { CHECK(out[k] == 7); @@ -159,19 +165,21 @@ TEST_CASE("parallel_keyed_sum scratch reuse does not leak entries across calls", // First call: more chunks, different data — fills the scratch. std::vector first(key_count, 0); - reductions::parallel_keyed_sum(pool, 8, key_count, first, scratch, - [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit.add(chunk_idx % 16, static_cast(chunk_idx) * 1000 + 1); - emit.add((chunk_idx + 3) % 16, 5); - }); + reductions::parallel_keyed_sum( + pool, 8, key_count, first, scratch, [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit.add(chunk_idx % 16, static_cast(chunk_idx) * 1000 + 1); + emit.add((chunk_idx + 3) % 16, 5); + } + ); // Second call: fewer chunks through the same scratch. Stale entries from the first // call must not contribute. std::vector out(key_count, 0); - reductions::parallel_keyed_sum(pool, 3, key_count, out, scratch, - [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - emit.add(chunk_idx, static_cast(chunk_idx + 1)); - }); + reductions::parallel_keyed_sum( + pool, 3, key_count, out, scratch, [](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + emit.add(chunk_idx, static_cast(chunk_idx + 1)); + } + ); std::vector expected(key_count, 0); for (std::size_t i = 0; i < 3; ++i) { @@ -182,8 +190,9 @@ TEST_CASE("parallel_keyed_sum scratch reuse does not leak entries across calls", } } -TEST_CASE("parallel_keyed_sum works with fixed_point_t and stays worker-count-invariant", - "[ecs][Reductions][keyed][determinism]") { +TEST_CASE( + "parallel_keyed_sum works with fixed_point_t and stays worker-count-invariant", "[ecs][Reductions][keyed][determinism]" +) { std::size_t const chunk_count = 100; std::size_t const key_count = 13; @@ -191,15 +200,19 @@ TEST_CASE("parallel_keyed_sum works with fixed_point_t and stays worker-count-in { EcsThreadPool serial { 1 }; std::vector out(key_count, fixed_point_t::_0); - reductions::parallel_keyed_sum(serial, chunk_count, key_count, out, - [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - for (std::size_t row = 0; row < 8; ++row) { - emit.add( - (chunk_idx * 5 + row / 2) % key_count, - fixed_point_t { static_cast(chunk_idx * 7 + row) } / 3 - ); - } - }); + reductions::parallel_keyed_sum( + serial, + chunk_count, + key_count, + out, + [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + for (std::size_t row = 0; row < 8; ++row) { + emit.add( + (chunk_idx * 5 + row / 2) % key_count, fixed_point_t { static_cast(chunk_idx * 7 + row) } / 3 + ); + } + } + ); for (fixed_point_t const& v : out) { baseline_raw.push_back(v.get_raw_value()); } @@ -208,15 +221,19 @@ TEST_CASE("parallel_keyed_sum works with fixed_point_t and stays worker-count-in for (uint32_t wc : { 1u, 2u, 4u, 8u, 16u }) { EcsThreadPool pool { wc }; std::vector out(key_count, fixed_point_t::_0); - reductions::parallel_keyed_sum(pool, chunk_count, key_count, out, - [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { - for (std::size_t row = 0; row < 8; ++row) { - emit.add( - (chunk_idx * 5 + row / 2) % key_count, - fixed_point_t { static_cast(chunk_idx * 7 + row) } / 3 - ); - } - }); + reductions::parallel_keyed_sum( + pool, + chunk_count, + key_count, + out, + [key_count](std::size_t chunk_idx, reductions::KeyedEmitter& emit) { + for (std::size_t row = 0; row < 8; ++row) { + emit.add( + (chunk_idx * 5 + row / 2) % key_count, fixed_point_t { static_cast(chunk_idx * 7 + row) } / 3 + ); + } + } + ); for (std::size_t k = 0; k < key_count; ++k) { CHECK(out[k].get_raw_value() == baseline_raw[k]); } diff --git a/tests/src/core/ecs/MatcherHash.cpp b/tests/src/core/ecs/MatcherHash.cpp index e57508a9d..525acc074 100644 --- a/tests/src/core/ecs/MatcherHash.cpp +++ b/tests/src/core/ecs/MatcherHash.cpp @@ -1,12 +1,12 @@ +#include +#include + #include "openvic-simulation/core/ecs/Archetype.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/Query.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include -#include - #include #include @@ -45,11 +45,15 @@ TEST_CASE("Query results match for archetypes with require-only filter", "[ecs][ world.create_entity(MHA {}, MHB {}); int a_count = 0; - world.for_each([&](MHA&) { ++a_count; }); + world.for_each([&](MHA&) { + ++a_count; + }); CHECK(a_count == 2); int ab_count = 0; - world.for_each([&](MHA&, MHB&) { ++ab_count; }); + world.for_each([&](MHA&, MHB&) { + ++ab_count; + }); CHECK(ab_count == 1); } @@ -64,7 +68,9 @@ TEST_CASE("Query results respect exclude filter", "[ecs][MatcherHash]") { q.with().exclude().build(); int count = 0; - world.for_each(q, [&](MHA&) { ++count; }); + world.for_each(q, [&](MHA&) { + ++count; + }); CHECK(count == 2); // {A} and {A,C}, neither carries B } @@ -74,21 +80,27 @@ TEST_CASE("Query results survive new archetype creation", "[ecs][MatcherHash][ca world.create_entity(MHA {}); int count_before = 0; - world.for_each([&](MHA&) { ++count_before; }); + world.for_each([&](MHA&) { + ++count_before; + }); CHECK(count_before == 2); // Create a new archetype that should also match the cached query. world.create_entity(MHA {}, MHC {}); int count_after = 0; - world.for_each([&](MHA&) { ++count_after; }); + world.for_each([&](MHA&) { + ++count_after; + }); CHECK(count_after == 3); } TEST_CASE("matcher_hash bitfield has exactly N bits set for N distinct components", "[ecs][MatcherHash]") { component_type_id_t const ids[] = { - component_type_id_of(), component_type_id_of(), - component_type_id_of(), component_type_id_of(), + component_type_id_of(), + component_type_id_of(), + component_type_id_of(), + component_type_id_of(), component_type_id_of() }; @@ -118,8 +130,10 @@ TEST_CASE("Query with multiple require + exclude filters correctly", "[ecs][Matc q.with().exclude().build(); int count = 0; - world.for_each_with_entity(q, [&](EntityID, MHA&, MHB&) { ++count; }); + world.for_each_with_entity(q, [&](EntityID, MHA&, MHB&) { + ++count; + }); CHECK(count == 2); - (void) a; - (void) e; + (void)a; + (void)e; } diff --git a/tests/src/core/ecs/Migration.cpp b/tests/src/core/ecs/Migration.cpp index 8dcefc202..f0c1b3d55 100644 --- a/tests/src/core/ecs/Migration.cpp +++ b/tests/src/core/ecs/Migration.cpp @@ -1,8 +1,8 @@ +#include + #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/World.hpp" -#include - #include #include diff --git a/tests/src/core/ecs/MultiSystemMixedStage.cpp b/tests/src/core/ecs/MultiSystemMixedStage.cpp index bb3b5f783..ba5577524 100644 --- a/tests/src/core/ecs/MultiSystemMixedStage.cpp +++ b/tests/src/core/ecs/MultiSystemMixedStage.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -29,11 +29,21 @@ using OpenVic::Date; // the systems are conflict-free and the scheduler lands them in the same stage. namespace { - struct MmsA { int64_t v = 0; }; - struct MmsB { int64_t v = 0; }; - struct MmsC { int64_t v = 0; }; - struct MmsD { int64_t v = 0; }; - struct MmsSeed { int64_t k = 0; }; + struct MmsA { + int64_t v = 0; + }; + struct MmsB { + int64_t v = 0; + }; + struct MmsC { + int64_t v = 0; + }; + struct MmsD { + int64_t v = 0; + }; + struct MmsSeed { + int64_t k = 0; + }; } ECS_COMPONENT(MmsA, "test_MultiSystemMixedStage::A") ECS_COMPONENT(MmsB, "test_MultiSystemMixedStage::B") @@ -86,10 +96,7 @@ namespace { std::vector ids; ids.reserve(N); for (std::size_t i = 0; i < N; ++i) { - ids.push_back(world.create_entity( - MmsSeed { static_cast(i + 1) }, - MmsA {}, MmsB {}, MmsC {}, MmsD {} - )); + ids.push_back(world.create_entity(MmsSeed { static_cast(i + 1) }, MmsA {}, MmsB {}, MmsC {}, MmsD {})); } return ids; } @@ -99,8 +106,7 @@ namespace { // Test 1: Two SystemThreaded sharing a stage. // ============================================================================ -TEST_CASE("Two SystemThreaded sharing a stage write disjoint components correctly", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Two SystemThreaded sharing a stage write disjoint components correctly", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -125,8 +131,7 @@ TEST_CASE("Two SystemThreaded sharing a stage write disjoint components correctl // Test 2: Two plain System<> sharing a stage. // ============================================================================ -TEST_CASE("Two plain System<> sharing a stage write disjoint components correctly", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Two plain System<> sharing a stage write disjoint components correctly", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -151,8 +156,7 @@ TEST_CASE("Two plain System<> sharing a stage write disjoint components correctl // Test 3: Mixed 1 SystemThreaded + 1 plain System<>. // ============================================================================ -TEST_CASE("Mixed stage 1 SystemThreaded + 1 plain System<> both correct", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Mixed stage 1 SystemThreaded + 1 plain System<> both correct", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -177,8 +181,7 @@ TEST_CASE("Mixed stage 1 SystemThreaded + 1 plain System<> both correct", // Test 4: Mixed 2 SystemThreaded + 2 plain System<> (full combinatorial case). // ============================================================================ -TEST_CASE("Mixed stage with 2 SystemThreaded + 2 plain System<> all correct", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Mixed stage with 2 SystemThreaded + 2 plain System<> all correct", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -243,8 +246,7 @@ namespace { } } -TEST_CASE("Multi-system mixed stage: digest is identical across worker counts", - "[ecs][MultiSystemMixedStage][determinism]") { +TEST_CASE("Multi-system mixed stage: digest is identical across worker counts", "[ecs][MultiSystemMixedStage][determinism]") { std::size_t const entities = 500; int const ticks = 10; int64_t baseline = run_mixed_and_digest(1, entities, ticks); @@ -265,8 +267,12 @@ TEST_CASE("Multi-system mixed stage: digest is identical across worker counts", // ============================================================================ namespace { - struct MmsSpawnSrc { int32_t id = 0; }; - struct MmsSpawned { int32_t source_id = 0; }; + struct MmsSpawnSrc { + int32_t id = 0; + }; + struct MmsSpawned { + int32_t source_id = 0; + }; } ECS_COMPONENT(MmsSpawnSrc, "test_MultiSystemMixedStage::SpawnSrc") ECS_COMPONENT(MmsSpawned, "test_MultiSystemMixedStage::Spawned") @@ -297,10 +303,7 @@ namespace { // Sources carry both SpawnSrc (for the spawner) and Seed (for the noop). Same // archetype keeps the analysis simple. for (std::size_t i = 0; i < source_count; ++i) { - world.create_entity( - MmsSpawnSrc { static_cast(i) }, - MmsSeed { static_cast(i) } - ); + world.create_entity(MmsSpawnSrc { static_cast(i) }, MmsSeed { static_cast(i) }); } world.register_system(); @@ -315,8 +318,7 @@ namespace { } } -TEST_CASE("Multi-system stage with threaded spawner: finalised order invariant", - "[ecs][MultiSystemMixedStage][determinism]") { +TEST_CASE("Multi-system stage with threaded spawner: finalised order invariant", "[ecs][MultiSystemMixedStage][determinism]") { std::size_t const sources = 250; std::vector const baseline = spawn_and_capture(1, sources); REQUIRE(baseline.size() == sources); @@ -335,8 +337,7 @@ TEST_CASE("Multi-system stage with threaded spawner: finalised order invariant", // single plain System<> should keep producing the same results as before. // ============================================================================ -TEST_CASE("Single SystemThreaded stage still produces expected per-row results", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Single SystemThreaded stage still produces expected per-row results", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -353,8 +354,7 @@ TEST_CASE("Single SystemThreaded stage still produces expected per-row results", } } -TEST_CASE("Single plain System<> stage still produces expected per-row results", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Single plain System<> stage still produces expected per-row results", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); @@ -425,7 +425,7 @@ namespace mms_concurrency { for (int i = 0; i < 2000; ++i) { spin += i; } - (void) spin; + (void)spin; g_active.fetch_sub(1); } @@ -446,15 +446,14 @@ namespace mms_concurrency { ECS_SYSTEM(mms_concurrency::MmsConcThreadedA) ECS_SYSTEM(mms_concurrency::MmsConcThreadedB) -TEST_CASE("Multi-system stage actually runs bodies concurrently", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Multi-system stage actually runs bodies concurrently", "[ecs][MultiSystemMixedStage]") { using namespace mms_concurrency; World world; world.set_ecs_worker_count(4); std::size_t const N = 2000; // many chunks → many work items → ample overlap opportunity - (void) seed_world(world, N); + (void)seed_world(world, N); g_active.store(0); g_peak.store(0); @@ -470,8 +469,7 @@ TEST_CASE("Multi-system stage actually runs bodies concurrently", CHECK(peak >= 2); } -TEST_CASE("Multi-system stage applies deferred add_component at stage barrier", - "[ecs][MultiSystemMixedStage]") { +TEST_CASE("Multi-system stage applies deferred add_component at stage barrier", "[ecs][MultiSystemMixedStage]") { World world; world.set_ecs_worker_count(4); diff --git a/tests/src/core/ecs/Query.cpp b/tests/src/core/ecs/Query.cpp index a5a22986d..ed2bf5f11 100644 --- a/tests/src/core/ecs/Query.cpp +++ b/tests/src/core/ecs/Query.cpp @@ -1,9 +1,10 @@ -#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/Query.hpp" #include #include +#include "openvic-simulation/core/ecs/ComponentTypeID.hpp" + #include #include diff --git a/tests/src/core/ecs/Reductions.cpp b/tests/src/core/ecs/Reductions.cpp index 548ab022c..f86c6a13c 100644 --- a/tests/src/core/ecs/Reductions.cpp +++ b/tests/src/core/ecs/Reductions.cpp @@ -1,9 +1,10 @@ -#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" #include "openvic-simulation/core/ecs/Reductions.hpp" #include #include +#include "openvic-simulation/core/ecs/EcsThreadPool.hpp" + #include #include @@ -19,14 +20,16 @@ TEST_CASE("parallel_sum is bit-identical across worker counts", "[ecs][Reduction int64_t baseline = 0; { EcsThreadPool serial { 1 }; - baseline = reductions::parallel_sum(serial, N, int64_t { 0 }, - [&data](std::size_t i) { return data[i]; }); + baseline = reductions::parallel_sum(serial, N, int64_t { 0 }, [&data](std::size_t i) { + return data[i]; + }); } for (uint32_t wc : { 1u, 2u, 4u, 8u, 16u }) { EcsThreadPool pool { wc }; - int64_t result = reductions::parallel_sum(pool, N, int64_t { 0 }, - [&data](std::size_t i) { return data[i]; }); + int64_t result = reductions::parallel_sum(pool, N, int64_t { 0 }, [&data](std::size_t i) { + return data[i]; + }); CHECK(result == baseline); } } @@ -34,8 +37,9 @@ TEST_CASE("parallel_sum is bit-identical across worker counts", "[ecs][Reduction TEST_CASE("parallel_min returns smallest body result", "[ecs][Reductions]") { std::size_t const N = 100; EcsThreadPool pool { 4 }; - int64_t result = reductions::parallel_min(pool, N, INT64_MAX, - [](std::size_t i) { return static_cast((i * 13) % 97); }); + int64_t result = reductions::parallel_min(pool, N, INT64_MAX, [](std::size_t i) { + return static_cast((i * 13) % 97); + }); int64_t expected = INT64_MAX; for (std::size_t i = 0; i < N; ++i) { @@ -50,8 +54,9 @@ TEST_CASE("parallel_min returns smallest body result", "[ecs][Reductions]") { TEST_CASE("parallel_max returns largest body result", "[ecs][Reductions]") { std::size_t const N = 100; EcsThreadPool pool { 4 }; - int64_t result = reductions::parallel_max(pool, N, INT64_MIN, - [](std::size_t i) { return static_cast((i * 13) % 97); }); + int64_t result = reductions::parallel_max(pool, N, INT64_MIN, [](std::size_t i) { + return static_cast((i * 13) % 97); + }); int64_t expected = INT64_MIN; for (std::size_t i = 0; i < N; ++i) { @@ -65,7 +70,8 @@ TEST_CASE("parallel_max returns largest body result", "[ecs][Reductions]") { TEST_CASE("parallel_sum on zero chunks returns init", "[ecs][Reductions]") { EcsThreadPool pool { 4 }; - int64_t result = reductions::parallel_sum(pool, 0, int64_t { 42 }, - [](std::size_t /*i*/) { return int64_t { 0 }; }); + int64_t result = reductions::parallel_sum(pool, 0, int64_t { 42 }, [](std::size_t /*i*/) { + return int64_t { 0 }; + }); CHECK(result == 42); } diff --git a/tests/src/core/ecs/Singleton.cpp b/tests/src/core/ecs/Singleton.cpp index d8284c0c6..483a6af54 100644 --- a/tests/src/core/ecs/Singleton.cpp +++ b/tests/src/core/ecs/Singleton.cpp @@ -1,7 +1,7 @@ -#include "openvic-simulation/core/ecs/World.hpp" - #include +#include "openvic-simulation/core/ecs/World.hpp" + #include #include diff --git a/tests/src/core/ecs/System.cpp b/tests/src/core/ecs/System.cpp index d9b9645d1..1ccc28eed 100644 --- a/tests/src/core/ecs/System.cpp +++ b/tests/src/core/ecs/System.cpp @@ -1,11 +1,11 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -102,7 +102,7 @@ TEST_CASE("tick_systems calls tick on alive systems", "[ecs][System]") { seed(world); int counter = 0; SystemHandle h = world.register_system(); - (void) h; + (void)h; // Set the counter pointer on the registered instance. // The instance is owned by the World's registry; registration parameters aren't // supported in the templated form (we keep it simple — `register_system()` only @@ -110,7 +110,7 @@ TEST_CASE("tick_systems calls tick on alive systems", "[ecs][System]") { // `set_*` member after registration. // (For brevity here we skip configuration; the `tick` body checks for nullptr.) world.tick_systems(Date {}); - (void) counter; + (void)counter; } TEST_CASE("tick_systems with one system", "[ecs][System]") { diff --git a/tests/src/core/ecs/SystemAccess.cpp b/tests/src/core/ecs/SystemAccess.cpp index 66f566671..b8c5d2acf 100644 --- a/tests/src/core/ecs/SystemAccess.cpp +++ b/tests/src/core/ecs/SystemAccess.cpp @@ -8,22 +8,11 @@ using namespace OpenVic::ecs; TEST_CASE("access_overlaps detects W/W and W/R", "[ecs][SystemAccess]") { - std::vector a = { - ComponentAccess { 100, AccessMode::Write }, - ComponentAccess { 200, AccessMode::Read } - }; - std::vector b_ww = { - ComponentAccess { 100, AccessMode::Write } - }; - std::vector b_rw = { - ComponentAccess { 200, AccessMode::Write } - }; - std::vector b_rr = { - ComponentAccess { 200, AccessMode::Read } - }; - std::vector b_disjoint = { - ComponentAccess { 999, AccessMode::Write } - }; + std::vector a = { ComponentAccess { 100, AccessMode::Write }, ComponentAccess { 200, AccessMode::Read } }; + std::vector b_ww = { ComponentAccess { 100, AccessMode::Write } }; + std::vector b_rw = { ComponentAccess { 200, AccessMode::Write } }; + std::vector b_rr = { ComponentAccess { 200, AccessMode::Read } }; + std::vector b_disjoint = { ComponentAccess { 999, AccessMode::Write } }; CHECK(access_overlaps(a, b_ww)); CHECK(access_overlaps(a, b_rw)); @@ -32,10 +21,7 @@ TEST_CASE("access_overlaps detects W/W and W/R", "[ecs][SystemAccess]") { } TEST_CASE("access_conflict_components reports overlapping ids", "[ecs][SystemAccess]") { - std::vector a = { - ComponentAccess { 100, AccessMode::Write }, - ComponentAccess { 200, AccessMode::Read } - }; + std::vector a = { ComponentAccess { 100, AccessMode::Write }, ComponentAccess { 200, AccessMode::Read } }; std::vector b = { ComponentAccess { 100, AccessMode::Read }, ComponentAccess { 200, AccessMode::Write }, @@ -48,9 +34,7 @@ TEST_CASE("access_conflict_components reports overlapping ids", "[ecs][SystemAcc } TEST_CASE("merge_extra_reads adds Read entries; W coalesces over R", "[ecs][SystemAccess]") { - std::vector set = { - ComponentAccess { 100, AccessMode::Write } - }; + std::vector set = { ComponentAccess { 100, AccessMode::Write } }; std::vector extras = { 100, 200 }; merge_extra_reads(set, extras); canonicalise_access_set(set); @@ -64,9 +48,7 @@ TEST_CASE("merge_extra_reads adds Read entries; W coalesces over R", "[ecs][Syst } TEST_CASE("merge_extra_writes adds Write entries; existing R upgrades to W", "[ecs][SystemAccess]") { - std::vector set = { - ComponentAccess { 100, AccessMode::Read } - }; + std::vector set = { ComponentAccess { 100, AccessMode::Read } }; std::vector extras = { 100, 200 }; merge_extra_writes(set, extras); canonicalise_access_set(set); @@ -79,8 +61,7 @@ TEST_CASE("merge_extra_writes adds Write entries; existing R upgrades to W", "[e CHECK(set[1].mode == AccessMode::Write); } -TEST_CASE("Same id in extra_reads and extra_writes coalesces to W in either merge order", - "[ecs][SystemAccess]") { +TEST_CASE("Same id in extra_reads and extra_writes coalesces to W in either merge order", "[ecs][SystemAccess]") { std::vector extras = { 100 }; std::vector reads_first; diff --git a/tests/src/core/ecs/SystemFilters.cpp b/tests/src/core/ecs/SystemFilters.cpp index 33f5eb2c5..52b42660f 100644 --- a/tests/src/core/ecs/SystemFilters.cpp +++ b/tests/src/core/ecs/SystemFilters.cpp @@ -1,4 +1,8 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include +#include + #include "openvic-simulation/core/ecs/ChunkSystem.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" @@ -7,11 +11,7 @@ #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -24,8 +24,12 @@ using OpenVic::Date; // The worker-count-invariance determinism gate lives in SystemFiltersWorkerCountInvariance.cpp. namespace { - struct SfCore { int64_t v = 0; }; - struct SfOther { int64_t v = 0; }; + struct SfCore { + int64_t v = 0; + }; + struct SfOther { + int64_t v = 0; + }; struct SfDead {}; // tag: "logically dead" — the component systems below exclude struct SfNever {}; // never instantiated — for the "exclude matches everything" edge } @@ -114,16 +118,14 @@ TEST_CASE("Filter::exclude_ids extracts, sorts, and dedups component ids", "[ecs std::vector const none = Filter<>::exclude_ids(); CHECK(none.empty()); - std::vector const many = - Filter, Without, Without>::exclude_ids(); + std::vector const many = Filter, Without, Without>::exclude_ids(); REQUIRE(many.size() == 2u); // SfOther duplicate collapsed CHECK(std::is_sorted(many.begin(), many.end())); CHECK(std::find(many.begin(), many.end(), component_type_id_of()) != many.end()); CHECK(std::find(many.begin(), many.end(), component_type_id_of()) != many.end()); } -TEST_CASE("system_filters_t defaults to empty; compute_tick_query_exclude_ids reflects Filters", - "[ecs][SystemFilters]") { +TEST_CASE("system_filters_t defaults to empty; compute_tick_query_exclude_ids reflects Filters", "[ecs][SystemFilters]") { CHECK(system_filters_t::exclude_ids().empty()); CHECK(SfPlainSystem::compute_tick_query_exclude_ids().empty()); @@ -137,8 +139,7 @@ TEST_CASE("system_filters_t defaults to empty; compute_tick_query_exclude_ids re CHECK(req[0] == component_type_id_of()); } -TEST_CASE("Without filter adds no access; the written component keeps Write access", - "[ecs][SystemFilters]") { +TEST_CASE("Without filter adds no access; the written component keeps Write access", "[ecs][SystemFilters]") { std::array const access = SfExcludeDeadSystem::declared_access(); CHECK(access[0].component_id == component_type_id_of()); CHECK(access[0].mode == AccessMode::Write); @@ -151,8 +152,7 @@ TEST_CASE("Without filter adds no access; the written component keeps Write acce // === Serial behaviour === -TEST_CASE("System Without filter skips archetypes carrying the excluded component", - "[ecs][SystemFilters]") { +TEST_CASE("System Without filter skips archetypes carrying the excluded component", "[ecs][SystemFilters]") { World world; EntityID const a = world.create_entity(SfCore { 0 }); EntityID const b = world.create_entity(SfCore { 0 }, SfDead {}); @@ -202,8 +202,7 @@ TEST_CASE("ChunkSystem Without filter skips excluded archetypes", "[ecs][SystemF // === Threaded behaviour (single-system stage → dispatch_threaded → collect_matching_chunks) === -TEST_CASE("SystemThreaded single-system stage respects the Without filter", - "[ecs][SystemFilters][threaded]") { +TEST_CASE("SystemThreaded single-system stage respects the Without filter", "[ecs][SystemFilters][threaded]") { World world; world.set_ecs_worker_count(4); @@ -227,8 +226,7 @@ TEST_CASE("SystemThreaded single-system stage respects the Without filter", // === Edge cases === -TEST_CASE("Without a never-instantiated component matches every archetype", - "[ecs][SystemFilters][edge]") { +TEST_CASE("Without a never-instantiated component matches every archetype", "[ecs][SystemFilters][edge]") { World world; EntityID const a = world.create_entity(SfCore { 0 }); EntityID const b = world.create_entity(SfCore { 0 }, SfDead {}); @@ -242,8 +240,7 @@ TEST_CASE("Without a never-instantiated component matches every archetype", CHECK(core_value(world, c) == 1); } -TEST_CASE("Without filter excluding every matched archetype visits nothing", - "[ecs][SystemFilters][edge]") { +TEST_CASE("Without filter excluding every matched archetype visits nothing", "[ecs][SystemFilters][edge]") { World world; EntityID const b1 = world.create_entity(SfCore { 0 }, SfDead {}); EntityID const b2 = world.create_entity(SfCore { 0 }, SfDead {}, SfOther { 0 }); @@ -255,8 +252,7 @@ TEST_CASE("Without filter excluding every matched archetype visits nothing", CHECK(core_value(world, b2) == 0); } -TEST_CASE("Filtered query re-resolves when a new matching archetype appears (serial)", - "[ecs][SystemFilters][edge][cache]") { +TEST_CASE("Filtered query re-resolves when a new matching archetype appears (serial)", "[ecs][SystemFilters][edge][cache]") { World world; EntityID const a = world.create_entity(SfCore { 0 }); EntityID const b = world.create_entity(SfCore { 0 }, SfDead {}); @@ -275,8 +271,9 @@ TEST_CASE("Filtered query re-resolves when a new matching archetype appears (ser CHECK(core_value(world, c) == 1); } -TEST_CASE("Filtered query re-resolves for a new archetype on the threaded path", - "[ecs][SystemFilters][edge][cache][threaded]") { +TEST_CASE( + "Filtered query re-resolves for a new archetype on the threaded path", "[ecs][SystemFilters][edge][cache][threaded]" +) { World world; world.set_ecs_worker_count(4); EntityID const a = world.create_entity(SfCore { 0 }); diff --git a/tests/src/core/ecs/SystemFiltersWorkerCountInvariance.cpp b/tests/src/core/ecs/SystemFiltersWorkerCountInvariance.cpp index b85e3d786..110c0242a 100644 --- a/tests/src/core/ecs/SystemFiltersWorkerCountInvariance.cpp +++ b/tests/src/core/ecs/SystemFiltersWorkerCountInvariance.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/QueryFilter.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -25,10 +25,16 @@ using OpenVic::Date; // detail::build_tick_query. namespace { - struct SfwSeed { int64_t k = 0; }; - struct SfwValue { int64_t v = 0; }; + struct SfwSeed { + int64_t k = 0; + }; + struct SfwValue { + int64_t v = 0; + }; struct SfwDead {}; // excluded tag - struct SfwOther { int64_t v = 0; }; // extra archetype variety (not excluded here) + struct SfwOther { + int64_t v = 0; + }; // extra archetype variety (not excluded here) } ECS_COMPONENT(SfwSeed, "test_SystemFiltersWCI::Seed") ECS_COMPONENT(SfwValue, "test_SystemFiltersWCI::Value") @@ -88,8 +94,10 @@ namespace { } } -TEST_CASE("Filtered serial system: digest is identical across worker counts", - "[ecs][SystemFilters][determinism][WorkerCountInvariance]") { +TEST_CASE( + "Filtered serial system: digest is identical across worker counts", + "[ecs][SystemFilters][determinism][WorkerCountInvariance]" +) { std::size_t const entities = 400; int const ticks = 10; int64_t const baseline = run_single_and_digest(1, entities, ticks); @@ -98,8 +106,10 @@ TEST_CASE("Filtered serial system: digest is identical across worker counts", } } -TEST_CASE("Filtered threaded system: digest is identical across worker counts", - "[ecs][SystemFilters][determinism][WorkerCountInvariance]") { +TEST_CASE( + "Filtered threaded system: digest is identical across worker counts", + "[ecs][SystemFilters][determinism][WorkerCountInvariance]" +) { std::size_t const entities = 400; int const ticks = 10; int64_t const baseline = run_single_and_digest(1, entities, ticks); @@ -118,11 +128,21 @@ TEST_CASE("Filtered threaded system: digest is identical across worker counts", // ============================================================================ namespace { - struct MfSeed { int64_t k = 0; }; - struct MfA { int64_t v = 0; }; - struct MfB { int64_t v = 0; }; - struct MfC { int64_t v = 0; }; - struct MfD { int64_t v = 0; }; + struct MfSeed { + int64_t k = 0; + }; + struct MfA { + int64_t v = 0; + }; + struct MfB { + int64_t v = 0; + }; + struct MfC { + int64_t v = 0; + }; + struct MfD { + int64_t v = 0; + }; struct MfDead {}; // excluded by A and D struct MfOther {}; // excluded by B } @@ -176,8 +196,7 @@ namespace { ids.push_back(world.create_entity(MfSeed { k }, MfA {}, MfB {}, MfC {}, MfD {})); // P ids.push_back(world.create_entity(MfSeed { k }, MfA {}, MfB {}, MfC {}, MfD {}, MfDead {})); // Q ids.push_back(world.create_entity(MfSeed { k }, MfA {}, MfB {}, MfC {}, MfD {}, MfOther {})); // R - ids.push_back(world.create_entity( - MfSeed { k }, MfA {}, MfB {}, MfC {}, MfD {}, MfDead {}, MfOther {})); // S + ids.push_back(world.create_entity(MfSeed { k }, MfA {}, MfB {}, MfC {}, MfD {}, MfDead {}, MfOther {})); // S } return ids; } @@ -221,8 +240,10 @@ ECS_SYSTEM(MfExcludeBSerial) ECS_SYSTEM(MfPlainCThreaded) ECS_SYSTEM(MfExcludeDSerial) -TEST_CASE("Multi-system filtered parallel stage: digest is identical across worker counts", - "[ecs][SystemFilters][determinism][WorkerCountInvariance]") { +TEST_CASE( + "Multi-system filtered parallel stage: digest is identical across worker counts", + "[ecs][SystemFilters][determinism][WorkerCountInvariance]" +) { // wc=1 runs the same multi-system branch but with a single worker — the prewarm still happens, // yet with no concurrency the result is race-free → trusted baseline. wc>=2 introduces real // concurrency, where each filtered system's worker-side query_cache lookup must hit the @@ -236,8 +257,7 @@ TEST_CASE("Multi-system filtered parallel stage: digest is identical across work } } -TEST_CASE("Multi-system filtered parallel stage applies each filter independently", - "[ecs][SystemFilters]") { +TEST_CASE("Multi-system filtered parallel stage applies each filter independently", "[ecs][SystemFilters]") { World world; world.set_ecs_worker_count(4); std::vector ids = seed_multi(world, 1); // exactly P, Q, R, S @@ -279,8 +299,7 @@ TEST_CASE("Multi-system filtered parallel stage applies each filter independentl CHECK(comp_v(world, S) == 0); } -TEST_CASE("Filtered systems with disjoint writes share a stage (schedule_hash stable)", - "[ecs][SystemFilters][determinism]") { +TEST_CASE("Filtered systems with disjoint writes share a stage (schedule_hash stable)", "[ecs][SystemFilters][determinism]") { uint64_t h1 = 0; uint64_t h2 = 0; { @@ -323,7 +342,7 @@ namespace sfw_concurrency { for (int i = 0; i < 2000; ++i) { spin += i; } - (void) spin; + (void)spin; g_active.fetch_sub(1); } @@ -345,8 +364,7 @@ namespace sfw_concurrency { ECS_SYSTEM(sfw_concurrency::SfwConcA) ECS_SYSTEM(sfw_concurrency::SfwConcC) -TEST_CASE("Filtered systems in a multi-system stage run bodies concurrently", - "[ecs][SystemFilters]") { +TEST_CASE("Filtered systems in a multi-system stage run bodies concurrently", "[ecs][SystemFilters]") { using namespace sfw_concurrency; World world; @@ -379,9 +397,15 @@ TEST_CASE("Filtered systems in a multi-system stage run bodies concurrently", // ============================================================================ namespace { - struct DjShared { int64_t v = 0; }; // written by both systems, on disjoint entities - struct DjGate { int64_t k = 0; }; // required by the threaded writer; excluded by the plain one - struct DjOther { int64_t v = 0; }; // neutral archetype variety + struct DjShared { + int64_t v = 0; + }; // written by both systems, on disjoint entities + struct DjGate { + int64_t k = 0; + }; // required by the threaded writer; excluded by the plain one + struct DjOther { + int64_t v = 0; + }; // neutral archetype variety } ECS_COMPONENT(DjShared, "test_SystemFiltersWCI::DjShared") ECS_COMPONENT(DjGate, "test_SystemFiltersWCI::DjGate") @@ -409,10 +433,10 @@ namespace { ids.reserve(n * 4); for (std::size_t i = 0; i < n; ++i) { int64_t const k = static_cast(i + 1); - ids.push_back(world.create_entity(DjShared { 0 }, DjGate { k })); // gated - ids.push_back(world.create_entity(DjShared { 0 })); // ungated - ids.push_back(world.create_entity(DjShared { 0 }, DjGate { k }, DjOther { k })); // gated + variety - ids.push_back(world.create_entity(DjShared { 0 }, DjOther { k })); // ungated + variety + ids.push_back(world.create_entity(DjShared { 0 }, DjGate { k })); // gated + ids.push_back(world.create_entity(DjShared { 0 })); // ungated + ids.push_back(world.create_entity(DjShared { 0 }, DjGate { k }, DjOther { k })); // gated + variety + ids.push_back(world.create_entity(DjShared { 0 }, DjOther { k })); // ungated + variety } return ids; } @@ -440,8 +464,10 @@ namespace { ECS_SYSTEM(DjThreadedWithGate) ECS_SYSTEM(DjPlainWithoutGate) -TEST_CASE("Disjoint-filter same-component writers: digest is identical across worker counts", - "[ecs][SystemFilters][determinism][WorkerCountInvariance]") { +TEST_CASE( + "Disjoint-filter same-component writers: digest is identical across worker counts", + "[ecs][SystemFilters][determinism][WorkerCountInvariance]" +) { // Guard against a vacuous pass: confirm the two writers actually co-schedule into one // stage (the dropped-edge path). If they serialised, the gate below would still pass but // would no longer be testing concurrent same-component writes. diff --git a/tests/src/core/ecs/SystemPhaseAnchors.cpp b/tests/src/core/ecs/SystemPhaseAnchors.cpp index 7dd77b586..ecd722da5 100644 --- a/tests/src/core/ecs/SystemPhaseAnchors.cpp +++ b/tests/src/core/ecs/SystemPhaseAnchors.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/QueryFilter.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemPhase.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -29,9 +29,15 @@ using OpenVic::Date; // is a hard error outside any SFINAE-probeable context. namespace { - struct PhaseTagA { int64_t v = 0; }; - struct PhaseTagB { int64_t v = 0; }; - struct PhaseTagC { int64_t v = 0; }; + struct PhaseTagA { + int64_t v = 0; + }; + struct PhaseTagB { + int64_t v = 0; + }; + struct PhaseTagC { + int64_t v = 0; + }; } ECS_COMPONENT(PhaseTagA, "test_SystemPhase::TagA") ECS_COMPONENT(PhaseTagB, "test_SystemPhase::TagB") @@ -142,16 +148,46 @@ namespace { // declared_run_after / declared_run_before reference these types via system_type_id_of<> (see // the note in SystemScheduler_DAG.cpp). Specialise up front against the forward declarations. namespace OpenVic::ecs { - template<> struct SystemName { static constexpr std::string_view value = "PhaseSugarP0"; }; - template<> struct SystemName { static constexpr std::string_view value = "PhaseSugarP1"; }; - template<> struct SystemName { static constexpr std::string_view value = "PhaseSugarP2"; }; - template<> struct SystemName { static constexpr std::string_view value = "PhaseSugarP3"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP0SysA"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP0SysB"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP1SysA"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP1SysB"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP2SysA"; }; - template<> struct SystemName { static constexpr std::string_view value = "SugarP2SysB"; }; + template<> + struct SystemName { + static constexpr std::string_view value = "PhaseSugarP0"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "PhaseSugarP1"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "PhaseSugarP2"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "PhaseSugarP3"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP0SysA"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP0SysB"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP1SysA"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP1SysB"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP2SysA"; + }; + template<> + struct SystemName { + static constexpr std::string_view value = "SugarP2SysB"; + }; } namespace { struct HandPhaseP0 : PhaseAnchorSystem {}; @@ -293,22 +329,27 @@ TEST_CASE("Phase members land strictly between their anchors", "[ecs][SystemPhas // only — unrelated systems may legally co-stage with an anchor at the same depth.) std::size_t const p0_sys_a = stage_of(world, system_type_id_of()); std::size_t const p0_sys_b = stage_of(world, system_type_id_of()); - CHECK(p0 < p0_sys_a); CHECK(p0_sys_a < p1); - CHECK(p0 < p0_sys_b); CHECK(p0_sys_b < p1); + CHECK(p0 < p0_sys_a); + CHECK(p0_sys_a < p1); + CHECK(p0 < p0_sys_b); + CHECK(p0_sys_b < p1); std::size_t const p1_sys_a = stage_of(world, system_type_id_of()); std::size_t const p1_sys_b = stage_of(world, system_type_id_of()); - CHECK(p1 < p1_sys_a); CHECK(p1_sys_a < p2); - CHECK(p1 < p1_sys_b); CHECK(p1_sys_b < p2); + CHECK(p1 < p1_sys_a); + CHECK(p1_sys_a < p2); + CHECK(p1 < p1_sys_b); + CHECK(p1_sys_b < p2); std::size_t const p2_sys_a = stage_of(world, system_type_id_of()); std::size_t const p2_sys_b = stage_of(world, system_type_id_of()); - CHECK(p2 < p2_sys_a); CHECK(p2_sys_a < p3); - CHECK(p2 < p2_sys_b); CHECK(p2_sys_b < p3); + CHECK(p2 < p2_sys_a); + CHECK(p2_sys_a < p3); + CHECK(p2 < p2_sys_b); + CHECK(p2_sys_b < p3); } -TEST_CASE("Macro-built schedule hashes identically to the hand-written form", - "[ecs][SystemPhase][Hash]") { +TEST_CASE("Macro-built schedule hashes identically to the hand-written form", "[ecs][SystemPhase][Hash]") { World macro_world; register_macro_set(macro_world); @@ -329,8 +370,7 @@ TEST_CASE("Macro-built schedule hashes identically to the hand-written form", CHECK(macro_world.debug_stage_count() == hand_world.debug_stage_count()); } -TEST_CASE("Variadic ECS_IN_PHASE extras order systems within a phase", - "[ecs][SystemPhase]") { +TEST_CASE("Variadic ECS_IN_PHASE extras order systems within a phase", "[ecs][SystemPhase]") { World world; register_macro_set(world); @@ -345,8 +385,7 @@ TEST_CASE("Variadic ECS_IN_PHASE extras order systems within a phase", CHECK(sys_b < p2); } -TEST_CASE("Anchor/member registration order does not affect schedule_hash", - "[ecs][SystemPhase][Hash][determinism]") { +TEST_CASE("Anchor/member registration order does not affect schedule_hash", "[ecs][SystemPhase][Hash][determinism]") { World forward; register_macro_set(forward); @@ -367,8 +406,7 @@ TEST_CASE("Anchor/member registration order does not affect schedule_hash", CHECK(forward.schedule_hash() == shuffled.schedule_hash()); } -TEST_CASE("Members execute in phase order; anchors contribute nothing", - "[ecs][SystemPhase]") { +TEST_CASE("Members execute in phase order; anchors contribute nothing", "[ecs][SystemPhase]") { std::vector log; g_phase_log = &log; @@ -394,15 +432,18 @@ TEST_CASE("Members execute in phase order; anchors contribute nothing", for (std::size_t i = 0; i < log.size(); ++i) { pos[static_cast(log[i])] = i; } - CHECK(pos[1] < pos[3]); CHECK(pos[1] < pos[4]); - CHECK(pos[2] < pos[3]); CHECK(pos[2] < pos[4]); + CHECK(pos[1] < pos[3]); + CHECK(pos[1] < pos[4]); + CHECK(pos[2] < pos[3]); + CHECK(pos[2] < pos[4]); CHECK(pos[3] < pos[4]); // intra-phase variadic edge - CHECK(pos[3] < pos[5]); CHECK(pos[3] < pos[6]); - CHECK(pos[4] < pos[5]); CHECK(pos[4] < pos[6]); + CHECK(pos[3] < pos[5]); + CHECK(pos[3] < pos[6]); + CHECK(pos[4] < pos[5]); + CHECK(pos[4] < pos[6]); } -TEST_CASE("SystemThreaded member with Filters works unchanged inside a phase", - "[ecs][SystemPhase]") { +TEST_CASE("SystemThreaded member with Filters works unchanged inside a phase", "[ecs][SystemPhase]") { World world; EntityID const plain = world.create_entity(PhaseTagA { 0 }); EntityID const filtered = world.create_entity(PhaseTagA { 0 }, PhaseTagC { 0 }); @@ -417,7 +458,7 @@ TEST_CASE("SystemThreaded member with Filters works unchanged inside a phase", PhaseTagA const* filtered_a = world.get_component(filtered); REQUIRE(plain_a != nullptr); REQUIRE(filtered_a != nullptr); - CHECK(plain_a->v == 1); // {A} — visited + CHECK(plain_a->v == 1); // {A} — visited CHECK(filtered_a->v == 0); // {A, C} — excluded by Filters std::size_t const p1 = stage_of(world, system_type_id_of()); @@ -427,8 +468,7 @@ TEST_CASE("SystemThreaded member with Filters works unchanged inside a phase", CHECK(member < p2); } -TEST_CASE("Same-phase write conflict still auto-serialises between the anchors", - "[ecs][SystemPhase]") { +TEST_CASE("Same-phase write conflict still auto-serialises between the anchors", "[ecs][SystemPhase]") { World world; world.create_entity(PhaseTagA { 0 }); world.register_system(); @@ -444,12 +484,13 @@ TEST_CASE("Same-phase write conflict still auto-serialises between the anchors", std::size_t const sys_a = stage_of(world, system_type_id_of()); std::size_t const sys_b = stage_of(world, system_type_id_of()); CHECK(sys_a != sys_b); - CHECK(p1 < sys_a); CHECK(sys_a < p2); - CHECK(p1 < sys_b); CHECK(sys_b < p2); + CHECK(p1 < sys_a); + CHECK(sys_a < p2); + CHECK(p1 < sys_b); + CHECK(sys_b < p2); } -TEST_CASE("Cross-phase writers of the same component occupy distinct stages", - "[ecs][SystemPhase]") { +TEST_CASE("Cross-phase writers of the same component occupy distinct stages", "[ecs][SystemPhase]") { World world; register_macro_set(world); diff --git a/tests/src/core/ecs/SystemSchedulerDisjointWriters.cpp b/tests/src/core/ecs/SystemSchedulerDisjointWriters.cpp index 6af4d3eda..b48cddfc9 100644 --- a/tests/src/core/ecs/SystemSchedulerDisjointWriters.cpp +++ b/tests/src/core/ecs/SystemSchedulerDisjointWriters.cpp @@ -1,4 +1,9 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include +#include +#include + #include "openvic-simulation/core/ecs/ChunkSystem.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" @@ -8,12 +13,7 @@ #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -32,9 +32,15 @@ using OpenVic::Date; // determinism gate for this path lives in SystemFiltersWorkerCountInvariance.cpp. namespace { - struct DwShared { int64_t v = 0; }; // written by both gate-partitioned systems - struct DwGate { int64_t g = 0; }; // read by the with-gate system; excluded by the other - struct DwOther { int64_t v = 0; }; // separate write target for the extra_reads soundness case + struct DwShared { + int64_t v = 0; + }; // written by both gate-partitioned systems + struct DwGate { + int64_t g = 0; + }; // read by the with-gate system; excluded by the other + struct DwOther { + int64_t v = 0; + }; // separate write target for the extra_reads soundness case } ECS_COMPONENT(DwShared, "test_DisjointWriters::Shared") ECS_COMPONENT(DwGate, "test_DisjointWriters::Gate") @@ -145,10 +151,10 @@ TEST_CASE("sorted_intersects detects shared elements in sorted lists", "[ecs][Sy std::vector const empty {}; std::vector const a { 1, 3, 5, 7 }; std::vector const disjoint { 2, 4, 6, 8 }; - std::vector const overlap_first { 1, 100 }; // shares 1 (start of a) - std::vector const overlap_mid { 0, 5, 99 }; // shares 5 (middle of a) - std::vector const overlap_last { 7 }; // shares 7 (end of a) - std::vector const multi { 3, 5 }; // shares 3 and 5 + std::vector const overlap_first { 1, 100 }; // shares 1 (start of a) + std::vector const overlap_mid { 0, 5, 99 }; // shares 5 (middle of a) + std::vector const overlap_last { 7 }; // shares 7 (end of a) + std::vector const multi { 3, 5 }; // shares 3 and 5 CHECK_FALSE(sorted_intersects(empty, empty)); CHECK_FALSE(sorted_intersects(empty, a)); @@ -163,8 +169,7 @@ TEST_CASE("sorted_intersects detects shared elements in sorted lists", "[ecs][Sy // === Structural decisions (which stage each system lands in) === -TEST_CASE("Disjoint-filter writers of the same component share a stage", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("Disjoint-filter writers of the same component share a stage", "[ecs][SystemScheduler][DisjointWriters]") { // Writes DwShared from both, but one requires DwGate and the other excludes it — provably // disjoint, so the conflict edge is dropped and they co-schedule into one stage. World world; @@ -172,8 +177,7 @@ TEST_CASE("Disjoint-filter writers of the same component share a stage", world.register_system(); std::size_t const stage_with = world.debug_stage_index_of(system_type_id_of()); - std::size_t const stage_without = - world.debug_stage_index_of(system_type_id_of()); + std::size_t const stage_without = world.debug_stage_index_of(system_type_id_of()); CHECK(stage_with != SIZE_MAX); CHECK(stage_without != SIZE_MAX); @@ -181,15 +185,16 @@ TEST_CASE("Disjoint-filter writers of the same component share a stage", CHECK(world.debug_stage_count() == 1u); } -TEST_CASE("Unfiltered writers of the same component stay in different stages", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("Unfiltered writers of the same component stay in different stages", "[ecs][SystemScheduler][DisjointWriters]") { // No filters → not provably disjoint → the write/write conflict edge is kept → serialised. World world; world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } @@ -200,15 +205,16 @@ TEST_CASE("A one-sided filter does not prove disjointness", "[ecs][SystemSchedul world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } // === Soundness guard: a cross-archetype extra_read is NOT separated by disjoint iteration === -TEST_CASE("extra_reads on the conflicting component keeps systems serialised", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("extra_reads on the conflicting component keeps systems serialised", "[ecs][SystemScheduler][DisjointWriters]") { // DwExtraReader writes DwOther and extra-reads DwShared; DwWriterWithoutOther writes // DwShared and excludes DwOther. Their ITERATIONS are disjoint (DwOther required vs // excluded), but the conflict is on DwShared, which DwExtraReader reaches CROSS-ARCHETYPE @@ -217,13 +223,14 @@ TEST_CASE("extra_reads on the conflicting component keeps systems serialised", world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } -TEST_CASE("Without the extra_read the same pair has no conflict at all", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("Without the extra_read the same pair has no conflict at all", "[ecs][SystemScheduler][DisjointWriters]") { // DwPlainOtherWriter is DwExtraReader minus the extra_reads declaration. It only // touches DwOther, which DwWriterWithoutOther never touches → no shared component → no edge // → one stage. Isolates that the extra_read (not the iteration shape) caused the @@ -232,13 +239,17 @@ TEST_CASE("Without the extra_read the same pair has no conflict at all", world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - == world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) == + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 1u); } -TEST_CASE("extra_writes on an also-required component defeats the disjoint-iteration override", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE( + "extra_writes on an also-required component defeats the disjoint-iteration override", + "[ecs][SystemScheduler][DisjointWriters]" +) { // DwHybridWriter requires {DwShared, DwGate} and ALSO declares extra_writes(DwShared); // DwWriterWithoutGate writes DwShared excluding DwGate. Rule 1 holds (DwGate required vs // excluded) and DwShared is in BOTH require sets — pre-hardening this pair co-scheduled, @@ -248,13 +259,17 @@ TEST_CASE("extra_writes on an also-required component defeats the disjoint-itera world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } -TEST_CASE("extra_reads of an also-required component defeats the disjoint-iteration override", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE( + "extra_reads of an also-required component defeats the disjoint-iteration override", + "[ecs][SystemScheduler][DisjointWriters]" +) { // Read-side twin of the previous test: DwShared is in DwHybridReader's tick pack (Read) // AND in its extra_reads, so the read reaches rows outside its iteration. The pre-existing // Rule 2 (require membership only) wrongly dropped this edge. @@ -262,13 +277,16 @@ TEST_CASE("extra_reads of an also-required component defeats the disjoint-iterat world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } -TEST_CASE("Co-scheduled disjoint writers: schedule_hash is registration-order independent", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE( + "Co-scheduled disjoint writers: schedule_hash is registration-order independent", "[ecs][SystemScheduler][DisjointWriters]" +) { uint64_t h1 = 0; uint64_t h2 = 0; { @@ -289,8 +307,7 @@ TEST_CASE("Co-scheduled disjoint writers: schedule_hash is registration-order in // === End-to-end correctness === -TEST_CASE("Co-scheduled disjoint writers each write only their own entities", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("Co-scheduled disjoint writers each write only their own entities", "[ecs][SystemScheduler][DisjointWriters]") { auto run = [](bool serial) { World world; world.set_ecs_worker_count(4); @@ -303,7 +320,7 @@ TEST_CASE("Co-scheduled disjoint writers each write only their own entities", ungated.push_back(world.create_entity(DwShared { 0 })); } - world.register_system(); // +1 on entities WITH DwGate + world.register_system(); // +1 on entities WITH DwGate world.register_system(); // +100 on entities WITHOUT DwGate world.tick_systems(Date {}); @@ -315,7 +332,7 @@ TEST_CASE("Co-scheduled disjoint writers each write only their own entities", } }; - run(/*serial=*/true); // baseline + run(/*serial=*/true); // baseline run(/*serial=*/false); // co-scheduled parallel — must match the baseline } @@ -335,7 +352,7 @@ namespace dw_concurrency { for (int i = 0; i < 2000; ++i) { spin += i; } - (void) spin; + (void)spin; g_active.fetch_sub(1); } @@ -357,8 +374,7 @@ namespace dw_concurrency { ECS_SYSTEM(dw_concurrency::DwConcWithGate) ECS_SYSTEM(dw_concurrency::DwConcWithoutGate) -TEST_CASE("Co-scheduled disjoint writers run their tick bodies concurrently", - "[ecs][SystemScheduler][DisjointWriters]") { +TEST_CASE("Co-scheduled disjoint writers run their tick bodies concurrently", "[ecs][SystemScheduler][DisjointWriters]") { using namespace dw_concurrency; World world; @@ -367,7 +383,7 @@ TEST_CASE("Co-scheduled disjoint writers run their tick bodies concurrently", std::size_t const N = 2000; // many chunks on both sides → ample overlap opportunity for (std::size_t i = 0; i < N; ++i) { world.create_entity(DwShared { 0 }, DwGate { 0 }); // → DwConcWithGate - world.create_entity(DwShared { 0 }); // → DwConcWithoutGate + world.create_entity(DwShared { 0 }); // → DwConcWithoutGate } g_active.store(0); diff --git a/tests/src/core/ecs/SystemSchedulerSingletonWrites.cpp b/tests/src/core/ecs/SystemSchedulerSingletonWrites.cpp index 17159de50..e6443f491 100644 --- a/tests/src/core/ecs/SystemSchedulerSingletonWrites.cpp +++ b/tests/src/core/ecs/SystemSchedulerSingletonWrites.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include +#include + #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -25,9 +25,15 @@ using OpenVic::Date; // worker-count-invariance digest for a declared singleton pipeline. namespace { - struct SgwState { int64_t acc = 0; }; // the singleton — never attached to an entity - struct SgwA { int64_t v = 0; }; // writer-side iterated rows - struct SgwB { int64_t v = 0; }; // reader-side iterated rows + struct SgwState { + int64_t acc = 0; + }; // the singleton — never attached to an entity + struct SgwA { + int64_t v = 0; + }; // writer-side iterated rows + struct SgwB { + int64_t v = 0; + }; // reader-side iterated rows } ECS_COMPONENT(SgwState, "test_SingletonWrites::State") ECS_COMPONENT(SgwA, "test_SingletonWrites::A") @@ -128,8 +134,7 @@ ECS_SYSTEM(SgwReaderThreaded) // === Structural decisions (stage assignment from declared singleton access) === -TEST_CASE("Declared singleton writer and reader land in different stages", - "[ecs][SystemScheduler][SingletonWrites]") { +TEST_CASE("Declared singleton writer and reader land in different stages", "[ecs][SystemScheduler][SingletonWrites]") { // The only shared id is the singleton (W via extra_writes vs R via extra_reads) — // singletons are never in a require set, so the disjoint-iteration override can never // drop this edge. @@ -147,34 +152,37 @@ TEST_CASE("Declared singleton writer and reader land in different stages", CHECK(world.debug_stage_count() == 2u); } -TEST_CASE("Two declared singleton writers are serialised", - "[ecs][SystemScheduler][SingletonWrites]") { +TEST_CASE("Two declared singleton writers are serialised", "[ecs][SystemScheduler][SingletonWrites]") { // Different iterated components (SgwA vs SgwB) — the singleton W/W is the only conflict. World world; world.set_singleton(); world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - != world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) != + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 2u); } -TEST_CASE("Two declared singleton readers share a stage", - "[ecs][SystemScheduler][SingletonWrites]") { +TEST_CASE("Two declared singleton readers share a stage", "[ecs][SystemScheduler][SingletonWrites]") { // R/R on the singleton is not a conflict; nothing else is shared → one stage. World world; world.set_singleton(); world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - == world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) == + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 1u); } -TEST_CASE("Undeclared singleton access co-schedules — the hazard the declaration prevents", - "[ecs][SystemScheduler][SingletonWrites]") { +TEST_CASE( + "Undeclared singleton access co-schedules — the hazard the declaration prevents", "[ecs][SystemScheduler][SingletonWrites]" +) { // Same iterated shapes as SgwWriter/SgwReader but with no extra_* declarations: the // scheduler sees no shared component and puts them in ONE stage. This is the silent // corruption vector for a real writer/reader pair — declarations are mandatory. @@ -183,15 +191,16 @@ TEST_CASE("Undeclared singleton access co-schedules — the hazard the declarati world.register_system(); world.register_system(); - CHECK(world.debug_stage_index_of(system_type_id_of()) - == world.debug_stage_index_of(system_type_id_of())); + CHECK( + world.debug_stage_index_of(system_type_id_of()) == + world.debug_stage_index_of(system_type_id_of()) + ); CHECK(world.debug_stage_count() == 1u); } // === Deterministic auto-orientation === -TEST_CASE("Singleton conflict auto-orientation is registration-order independent", - "[ecs][SystemScheduler][SingletonWrites]") { +TEST_CASE("Singleton conflict auto-orientation is registration-order independent", "[ecs][SystemScheduler][SingletonWrites]") { std::vector log_run1; std::vector log_run2; uint64_t h1 = 0; @@ -240,9 +249,7 @@ namespace { // threaded declared reader consume the singleton into SgwB rows. All three conflict on // the singleton (and the readers on SgwB), so the schedule is fully serialised between // them — the digest must be bit-identical at every worker count. - int64_t run_singleton_pipeline_and_digest( - uint32_t worker_count, bool serial_mode, std::size_t per_side, int tick_count - ) { + int64_t run_singleton_pipeline_and_digest(uint32_t worker_count, bool serial_mode, std::size_t per_side, int tick_count) { World world; world.set_ecs_worker_count(worker_count); world.set_serial_mode(serial_mode); @@ -285,8 +292,10 @@ namespace { } } -TEST_CASE("Declared singleton pipeline: digest is identical across worker counts", - "[ecs][determinism][WorkerCountInvariance][SingletonWrites]") { +TEST_CASE( + "Declared singleton pipeline: digest is identical across worker counts", + "[ecs][determinism][WorkerCountInvariance][SingletonWrites]" +) { std::size_t const per_side = 200; int const ticks = 100; int64_t const baseline = run_singleton_pipeline_and_digest(1, /*serial_mode=*/false, per_side, ticks); diff --git a/tests/src/core/ecs/SystemScheduler_Conflicts.cpp b/tests/src/core/ecs/SystemScheduler_Conflicts.cpp index 8a9dd6673..480b5b082 100644 --- a/tests/src/core/ecs/SystemScheduler_Conflicts.cpp +++ b/tests/src/core/ecs/SystemScheduler_Conflicts.cpp @@ -1,10 +1,10 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include + #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -13,8 +13,12 @@ using namespace OpenVic::ecs; using OpenVic::Date; namespace { - struct ConflictTagX { int n = 0; }; - struct ConflictTagY { int n = 0; }; + struct ConflictTagX { + int n = 0; + }; + struct ConflictTagY { + int n = 0; + }; } ECS_COMPONENT(ConflictTagX, "test_SystemScheduler_Conflicts::TagX") ECS_COMPONENT(ConflictTagY, "test_SystemScheduler_Conflicts::TagY") @@ -64,8 +68,7 @@ ECS_SYSTEM(ConflictWriterB) ECS_SYSTEM(ConflictReaderA) ECS_SYSTEM(ConflictReaderB) -TEST_CASE("Auto-orientation produces deterministic order on W/W conflict", - "[ecs][SystemScheduler][Conflicts]") { +TEST_CASE("Auto-orientation produces deterministic order on W/W conflict", "[ecs][SystemScheduler][Conflicts]") { // Run the same registration twice with the same systems but different orderings // — auto-orientation must pick the same direction both times. std::vector log_run1; diff --git a/tests/src/core/ecs/SystemScheduler_DAG.cpp b/tests/src/core/ecs/SystemScheduler_DAG.cpp index b23dd3306..9e0c3951a 100644 --- a/tests/src/core/ecs/SystemScheduler_DAG.cpp +++ b/tests/src/core/ecs/SystemScheduler_DAG.cpp @@ -1,11 +1,11 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include + #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -14,9 +14,15 @@ using namespace OpenVic::ecs; using OpenVic::Date; namespace { - struct SchedulerTagA { int n = 0; }; - struct SchedulerTagB { int n = 0; }; - struct SchedulerTagC { int n = 0; }; + struct SchedulerTagA { + int n = 0; + }; + struct SchedulerTagB { + int n = 0; + }; + struct SchedulerTagC { + int n = 0; + }; } ECS_COMPONENT(SchedulerTagA, "test_SystemScheduler_DAG::TagA") ECS_COMPONENT(SchedulerTagB, "test_SystemScheduler_DAG::TagB") @@ -54,9 +60,7 @@ namespace { struct SchedDagSystemB : System { // B explicitly runs after A. static constexpr auto declared_run_after() { - return std::array { - system_type_id_of() - }; + return std::array { system_type_id_of() }; } void tick(TickContext const& /*ctx*/, SchedulerTagB& /*t*/) { if (g_scheduler_dag_log) { @@ -68,9 +72,7 @@ namespace { struct SchedDagSystemC : System { // C explicitly runs before A. static constexpr auto declared_run_before() { - return std::array { - system_type_id_of() - }; + return std::array { system_type_id_of() }; } void tick(TickContext const& /*ctx*/, SchedulerTagC& /*t*/) { if (g_scheduler_dag_log) { @@ -105,8 +107,7 @@ TEST_CASE("Scheduler honours run_after / run_before ordering", "[ecs][SystemSche g_scheduler_dag_log = nullptr; } -TEST_CASE("Scheduler order is identical regardless of registration order", - "[ecs][SystemScheduler][determinism]") { +TEST_CASE("Scheduler order is identical regardless of registration order", "[ecs][SystemScheduler][determinism]") { std::vector log_first; std::vector log_second; @@ -141,8 +142,7 @@ TEST_CASE("Scheduler order is identical regardless of registration order", CHECK(log_first == log_second); } -TEST_CASE("schedule_hash is non-zero and stable across registration orders", - "[ecs][SystemScheduler][Hash][determinism]") { +TEST_CASE("schedule_hash is non-zero and stable across registration orders", "[ecs][SystemScheduler][Hash][determinism]") { uint64_t h_first = 0; uint64_t h_second = 0; diff --git a/tests/src/core/ecs/SystemShouldRun.cpp b/tests/src/core/ecs/SystemShouldRun.cpp index ee9168aec..b29ec3f71 100644 --- a/tests/src/core/ecs/SystemShouldRun.cpp +++ b/tests/src/core/ecs/SystemShouldRun.cpp @@ -1,4 +1,7 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/Checksum.hpp" #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" @@ -6,10 +9,7 @@ #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -54,17 +54,25 @@ ECS_COMPONENT(SrEvalLog, "test_SystemShouldRun::EvalLog") // the traits don't require the CRTP System base. === namespace { struct SrValidPred { - static bool should_run(TickContext const&) { return true; } + static bool should_run(TickContext const&) { + return true; + } }; struct SrNoexceptPred { - static bool should_run(TickContext const&) noexcept { return true; } + static bool should_run(TickContext const&) noexcept { + return true; + } }; struct SrAbsent {}; struct SrNonStatic { - bool should_run(TickContext const&) { return true; } + bool should_run(TickContext const&) { + return true; + } }; struct SrWrongParam { - static bool should_run(int) { return true; } + static bool should_run(int) { + return true; + } }; struct SrWrongRet { static void should_run(TickContext const&) {} @@ -84,8 +92,12 @@ namespace { // (address-of is ambiguous), validity fails (ambiguous &) — hard error, never a // silent pick-one. struct SrOverloaded { - static bool should_run(TickContext const&) { return true; } - static bool should_run(Date) { return true; } + static bool should_run(TickContext const&) { + return true; + } + static bool should_run(Date) { + return true; + } }; static_assert(has_should_run_v && should_run_signature_valid_v); @@ -99,8 +111,7 @@ namespace { static_assert(has_should_run_v && !should_run_signature_valid_v); } -TEST_CASE("should_run compile-time guarantees hold (static_assert wall)", - "[ecs][scheduler][should_run][compiletime]") { +TEST_CASE("should_run compile-time guarantees hold (static_assert wall)", "[ecs][scheduler][should_run][compiletime]") { // The static_assert block above is the real test; this case just surfaces it in the report. CHECK(true); } @@ -131,15 +142,25 @@ namespace { namespace { // (a) gate semantics. struct SrAlwaysOff : System { - static bool should_run(TickContext const&) { return false; } - void tick(TickContext const&, SrA& a) { a.v += 1000; } + static bool should_run(TickContext const&) { + return false; + } + void tick(TickContext const&, SrA& a) { + a.v += 1000; + } }; struct SrAlwaysOn : System { - static bool should_run(TickContext const&) { return true; } - void tick(TickContext const&, SrB& b) { b.v += 1; } + static bool should_run(TickContext const&) { + return true; + } + void tick(TickContext const&, SrB& b) { + b.v += 1; + } }; struct SrNoPredicateSys : System { - void tick(TickContext const&, SrC& c) { c.v += 1; } + void tick(TickContext const&, SrC& c) { + c.v += 1; + } }; // (b) exactly-once + main-thread. @@ -148,21 +169,29 @@ namespace { sr_record_eval(ctx); return true; } - void tick(TickContext const&, SrA& a) { a.v += 1; } + void tick(TickContext const&, SrA& a) { + a.v += 1; + } }; struct SrEvalCounterOff : System { static bool should_run(TickContext const& ctx) { sr_record_eval(ctx); return false; } - void tick(TickContext const&, SrA& a) { a.v += 1000; } + void tick(TickContext const&, SrA& a) { + a.v += 1000; + } }; // Disjoint fillers to force a multi-system stage around the counter. struct SrFillerB : System { - void tick(TickContext const&, SrB& b) { b.v += 1; } + void tick(TickContext const&, SrB& b) { + b.v += 1; + } }; struct SrFillerC : System { - void tick(TickContext const&, SrC& c) { c.v += 1; } + void tick(TickContext const&, SrC& c) { + c.v += 1; + } }; // (c)/(d) multi-system stage with a date-gated SystemThreaded. Disjoint write targets @@ -171,17 +200,25 @@ namespace { static bool should_run(TickContext const& ctx) { return ctx.today.is_month_start(); } - void tick(TickContext const&, SrA& a) { a.v = a.v * 31 + 7; } + void tick(TickContext const&, SrA& a) { + a.v = a.v * 31 + 7; + } }; // Predicate-free twin with identical access — for the (d) stage-layout comparison. struct SrThreadedTwin : SystemThreaded { - void tick(TickContext const&, SrA& a) { a.v = a.v * 31 + 7; } + void tick(TickContext const&, SrA& a) { + a.v = a.v * 31 + 7; + } }; struct SrThreadedRun : SystemThreaded { - void tick(TickContext const&, SrB& b) { b.v = b.v * 31 + 3; } + void tick(TickContext const&, SrB& b) { + b.v = b.v * 31 + 3; + } }; struct SrSerialRun : System { - void tick(TickContext const&, SrC& c) { c.v = c.v * 31 + 5; } + void tick(TickContext const&, SrC& c) { + c.v = c.v * 31 + 5; + } }; // (e) gate ≡ in-body early-out, serial and threaded variants. Same kernel, same @@ -190,7 +227,9 @@ namespace { static bool should_run(TickContext const& ctx) { return ctx.today.is_month_start(); } - void tick(TickContext const&, SrA& a) { a.v = a.v * 31 + 7; } + void tick(TickContext const&, SrA& a) { + a.v = a.v * 31 + 7; + } }; struct SrMonthlyEarlyOut : System { void tick(TickContext const& ctx, SrA& a) { @@ -204,7 +243,9 @@ namespace { static bool should_run(TickContext const& ctx) { return ctx.today.is_month_start(); } - void tick(TickContext const&, SrA& a) { a.v = a.v * 31 + 7; } + void tick(TickContext const&, SrA& a) { + a.v = a.v * 31 + 7; + } }; struct SrMonthlyEarlyOutThreaded : SystemThreaded { void tick(TickContext const& ctx, SrA& a) { @@ -233,13 +274,10 @@ ECS_SYSTEM(SrMonthlyEarlyOutThreaded) // === (a) gate semantics === -TEST_CASE("should_run false skips the tick body; true and absent always run", - "[ecs][scheduler][should_run]") { +TEST_CASE("should_run false skips the tick body; true and absent always run", "[ecs][scheduler][should_run]") { World world; for (std::size_t i = 0; i < 100; ++i) { - world.create_entity( - SrA { static_cast(i) }, SrB { 0 }, SrC { 0 } - ); + world.create_entity(SrA { static_cast(i) }, SrB { 0 }, SrC { 0 }); } world.register_system(); world.register_system(); @@ -278,10 +316,14 @@ namespace { if (multi_stage) { world.register_system(); world.register_system(); - REQUIRE(world.debug_stage_index_of(system_type_id_of()) - == world.debug_stage_index_of(system_type_id_of())); - REQUIRE(world.debug_stage_index_of(system_type_id_of()) - == world.debug_stage_index_of(system_type_id_of())); + REQUIRE( + world.debug_stage_index_of(system_type_id_of()) == + world.debug_stage_index_of(system_type_id_of()) + ); + REQUIRE( + world.debug_stage_index_of(system_type_id_of()) == + world.debug_stage_index_of(system_type_id_of()) + ); } for (int t = 0; t < ticks; ++t) { @@ -290,7 +332,9 @@ namespace { if (out_a_sum != nullptr) { int64_t sum = 0; - world.for_each([&](SrA& a) { sum += a.v; }); + world.for_each([&](SrA& a) { + sum += a.v; + }); *out_a_sum = sum; } SrEvalLog const* log = world.get_singleton(); @@ -299,8 +343,7 @@ namespace { } } -TEST_CASE("should_run is evaluated exactly once per tick, on the main thread", - "[ecs][scheduler][should_run]") { +TEST_CASE("should_run is evaluated exactly once per tick, on the main thread", "[ecs][scheduler][should_run]") { sr_main_tid = std::this_thread::get_id(); sr_all_evals_on_main = true; int const ticks = 9; @@ -330,17 +373,15 @@ TEST_CASE("should_run is evaluated exactly once per tick, on the main thread", namespace { // Tick the gated trio across `tick_count` consecutive days starting 1836-01-01 (the // skip pattern flips at every month boundary) and return the full-state checksum. - uint64_t run_trio_and_checksum( - uint32_t worker_count, bool serial_mode, std::size_t entity_count, int tick_count - ) { + uint64_t run_trio_and_checksum(uint32_t worker_count, bool serial_mode, std::size_t entity_count, int tick_count) { World world; world.set_ecs_worker_count(worker_count); world.set_serial_mode(serial_mode); for (std::size_t i = 0; i < entity_count; ++i) { world.create_entity( - SrA { static_cast(i + 1) }, - SrB { static_cast((i * 17) % 13 + 1) }, - SrC { static_cast((i * 7) % 11 + 1) } + SrA { static_cast(i + 1) }, + SrB { static_cast((i * 17) % 13 + 1) }, + SrC { static_cast((i * 7) % 11 + 1) } ); } world.register_system(); @@ -356,8 +397,9 @@ namespace { } } -TEST_CASE("Skipping SystemThreaded in a multi-system stage: checksum identical across worker counts", - "[ecs][determinism][should_run]") { +TEST_CASE( + "Skipping SystemThreaded in a multi-system stage: checksum identical across worker counts", "[ecs][determinism][should_run]" +) { std::size_t const entities = 500; int const ticks = 65; // spans the Feb 1 and Mar 1 month starts → skip pattern varies @@ -385,8 +427,9 @@ TEST_CASE("Skipping SystemThreaded in a multi-system stage: checksum identical a CHECK(serial_result == baseline); } -TEST_CASE("Skipping SystemThreaded alone in its stage: checksum identical across worker counts", - "[ecs][determinism][should_run]") { +TEST_CASE( + "Skipping SystemThreaded alone in its stage: checksum identical across worker counts", "[ecs][determinism][should_run]" +) { // Single-system-stage branch: the skip happens by not calling tick_all at all. std::size_t const entities = 500; int const ticks = 65; @@ -416,8 +459,9 @@ TEST_CASE("Skipping SystemThreaded alone in its stage: checksum identical across // === (d) schedule stability — predicates and skip patterns never touch the schedule === -TEST_CASE("schedule_hash and stage layout are constant across ticks with varying skip patterns", - "[ecs][scheduler][should_run][Hash]") { +TEST_CASE( + "schedule_hash and stage layout are constant across ticks with varying skip patterns", "[ecs][scheduler][should_run][Hash]" +) { World world; for (std::size_t i = 0; i < 50; ++i) { world.create_entity(SrA { 1 }, SrB { 1 }, SrC { 1 }); @@ -439,8 +483,9 @@ TEST_CASE("schedule_hash and stage layout are constant across ticks with varying } } -TEST_CASE("A predicated system occupies the same stage layout as its predicate-free twin", - "[ecs][scheduler][should_run][Hash]") { +TEST_CASE( + "A predicated system occupies the same stage layout as its predicate-free twin", "[ecs][scheduler][should_run][Hash]" +) { // schedule_hash folds (stage_idx, type_id), and the predicate is part of the type — so // two DIFFERENT types can never compare hash-equal. The schedule-invariance claim is // about layout: predicate presence must not move a system between stages or change the @@ -456,12 +501,18 @@ TEST_CASE("A predicated system occupies the same stage layout as its predicate-f without_pred.register_system(); CHECK(with_pred.debug_stage_count() == without_pred.debug_stage_count()); - CHECK(with_pred.debug_stage_index_of(system_type_id_of()) - == without_pred.debug_stage_index_of(system_type_id_of())); - CHECK(with_pred.debug_stage_index_of(system_type_id_of()) - == without_pred.debug_stage_index_of(system_type_id_of())); - CHECK(with_pred.debug_stage_index_of(system_type_id_of()) - == without_pred.debug_stage_index_of(system_type_id_of())); + CHECK( + with_pred.debug_stage_index_of(system_type_id_of()) == + without_pred.debug_stage_index_of(system_type_id_of()) + ); + CHECK( + with_pred.debug_stage_index_of(system_type_id_of()) == + without_pred.debug_stage_index_of(system_type_id_of()) + ); + CHECK( + with_pred.debug_stage_index_of(system_type_id_of()) == + without_pred.debug_stage_index_of(system_type_id_of()) + ); } // === (e) should_run gating ≡ in-body early-out === @@ -483,16 +534,21 @@ namespace { } } -TEST_CASE("is_month_start gating via should_run equals an in-body early-out", - "[ecs][determinism][should_run]") { +TEST_CASE("is_month_start gating via should_run equals an in-body early-out", "[ecs][determinism][should_run]") { std::size_t const entities = 300; int const ticks = 65; // 1836-01-01 .. 1836-03-05 — three month starts hit - CHECK(run_monthly_and_checksum(entities, ticks) - == run_monthly_and_checksum(entities, ticks)); - CHECK(run_monthly_and_checksum(entities, ticks) - == run_monthly_and_checksum(entities, ticks)); + CHECK( + run_monthly_and_checksum(entities, ticks) == + run_monthly_and_checksum(entities, ticks) + ); + CHECK( + run_monthly_and_checksum(entities, ticks) == + run_monthly_and_checksum(entities, ticks) + ); // Gated serial ≡ gated threaded ≡ early-out serial — all four agree. - CHECK(run_monthly_and_checksum(entities, ticks) - == run_monthly_and_checksum(entities, ticks)); + CHECK( + run_monthly_and_checksum(entities, ticks) == + run_monthly_and_checksum(entities, ticks) + ); } diff --git a/tests/src/core/ecs/SystemThreadedSpawn.cpp b/tests/src/core/ecs/SystemThreadedSpawn.cpp index 693d9531d..e00e5e437 100644 --- a/tests/src/core/ecs/SystemThreadedSpawn.cpp +++ b/tests/src/core/ecs/SystemThreadedSpawn.cpp @@ -1,14 +1,14 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -94,10 +94,9 @@ namespace { std::vector source_ids; source_ids.reserve(source_count); for (std::size_t i = 0; i < source_count; ++i) { - source_ids.push_back(world.create_entity( - STSSource { static_cast(i) }, - STSSpawnCount { static_cast((i % 4) + 1) } - )); + source_ids.push_back( + world.create_entity(STSSource { static_cast(i) }, STSSpawnCount { static_cast((i % 4) + 1) }) + ); } world.register_system(); @@ -137,8 +136,7 @@ namespace { } } -TEST_CASE("SystemThreaded can spawn via cmd.create_entity, downstream stage observes them", - "[ecs][SystemThreadedSpawn]") { +TEST_CASE("SystemThreaded can spawn via cmd.create_entity, downstream stage observes them", "[ecs][SystemThreadedSpawn]") { std::size_t const sources = 100; ScenarioResult r = run_scenario(8, sources); @@ -154,8 +152,9 @@ TEST_CASE("SystemThreaded can spawn via cmd.create_entity, downstream stage obse CHECK(r.spawned_source_ids.size() == static_cast(expected_total)); } -TEST_CASE("SystemThreaded spawn produces identical finalised order across worker counts", - "[ecs][SystemThreadedSpawn][determinism]") { +TEST_CASE( + "SystemThreaded spawn produces identical finalised order across worker counts", "[ecs][SystemThreadedSpawn][determinism]" +) { std::size_t const sources = 200; ScenarioResult baseline = run_scenario(1, sources); diff --git a/tests/src/core/ecs/Tag.cpp b/tests/src/core/ecs/Tag.cpp index c8ab8d527..05e8b3ea8 100644 --- a/tests/src/core/ecs/Tag.cpp +++ b/tests/src/core/ecs/Tag.cpp @@ -1,10 +1,10 @@ -#include "openvic-simulation/core/ecs/EntityID.hpp" -#include "openvic-simulation/core/ecs/World.hpp" - #include #include #include +#include "openvic-simulation/core/ecs/EntityID.hpp" +#include "openvic-simulation/core/ecs/World.hpp" + #include #include @@ -53,7 +53,9 @@ TEST_CASE("for_each over a tag-only archetype iterates all rows", "[ecs][World][ world.create_entity(Tag1 {}); int count = 0; - world.for_each([&](Tag1&) { ++count; }); + world.for_each([&](Tag1&) { + ++count; + }); CHECK(count == 3); } @@ -86,7 +88,9 @@ TEST_CASE("destroy_entity in a tag archetype works", "[ecs][World][tag]") { CHECK(world.is_alive(c)); int count = 0; - world.for_each([&](Tag1&) { ++count; }); + world.for_each([&](Tag1&) { + ++count; + }); CHECK(count == 2); } @@ -127,7 +131,9 @@ TEST_CASE("for_each_with_entity over tag passes correct EntityIDs", "[ecs][World EntityID const b = world.create_entity(Tag1 {}); std::set seen; - world.for_each_with_entity([&](EntityID e, Tag1&) { seen.insert(e.to_uint64()); }); + world.for_each_with_entity([&](EntityID e, Tag1&) { + seen.insert(e.to_uint64()); + }); CHECK(seen.size() == 2u); CHECK(seen.count(a.to_uint64()) == 1u); CHECK(seen.count(b.to_uint64()) == 1u); diff --git a/tests/src/core/ecs/WorkerCountInvariance.cpp b/tests/src/core/ecs/WorkerCountInvariance.cpp index 2bde53522..f4ec60a2e 100644 --- a/tests/src/core/ecs/WorkerCountInvariance.cpp +++ b/tests/src/core/ecs/WorkerCountInvariance.cpp @@ -1,13 +1,13 @@ -#include "openvic-simulation/core/object/Date.hpp" +#include +#include + #include "openvic-simulation/core/ecs/CommandBuffer.hpp" #include "openvic-simulation/core/ecs/ComponentTypeID.hpp" #include "openvic-simulation/core/ecs/EntityID.hpp" #include "openvic-simulation/core/ecs/SystemImpl.hpp" #include "openvic-simulation/core/ecs/SystemTypeID.hpp" #include "openvic-simulation/core/ecs/World.hpp" - -#include -#include +#include "openvic-simulation/core/object/Date.hpp" #include #include @@ -63,8 +63,7 @@ namespace { ids.reserve(entity_count); for (std::size_t i = 0; i < entity_count; ++i) { ids.push_back(world.create_entity( - WciValue { static_cast(i + 1) }, - WciDelta { static_cast((i * 17) % 13 + 1) } + WciValue { static_cast(i + 1) }, WciDelta { static_cast((i * 17) % 13 + 1) } )); } @@ -86,8 +85,7 @@ namespace { } } -TEST_CASE("Serial system: digest is identical across worker counts", - "[ecs][determinism][WorkerCountInvariance]") { +TEST_CASE("Serial system: digest is identical across worker counts", "[ecs][determinism][WorkerCountInvariance]") { std::size_t const entities = 500; int const ticks = 10; int64_t baseline = run_and_digest(1, entities, ticks); @@ -98,8 +96,7 @@ TEST_CASE("Serial system: digest is identical across worker counts", } } -TEST_CASE("Threaded system: digest is identical across worker counts", - "[ecs][determinism][WorkerCountInvariance]") { +TEST_CASE("Threaded system: digest is identical across worker counts", "[ecs][determinism][WorkerCountInvariance]") { std::size_t const entities = 500; int const ticks = 10; int64_t baseline = run_and_digest(1, entities, ticks); @@ -110,8 +107,7 @@ TEST_CASE("Threaded system: digest is identical across worker counts", } } -TEST_CASE("Serial and threaded systems produce identical results", - "[ecs][determinism][WorkerCountInvariance]") { +TEST_CASE("Serial and threaded systems produce identical results", "[ecs][determinism][WorkerCountInvariance]") { std::size_t const entities = 500; int const ticks = 10; int64_t serial_digest = run_and_digest(1, entities, ticks); @@ -176,8 +172,10 @@ namespace { } } -TEST_CASE("Deferred-create from SystemThreaded: digest is identical across worker counts", - "[ecs][determinism][WorkerCountInvariance][deferred]") { +TEST_CASE( + "Deferred-create from SystemThreaded: digest is identical across worker counts", + "[ecs][determinism][WorkerCountInvariance][deferred]" +) { std::size_t const seeds = 500; int const ticks = 1; int64_t baseline = spawn_and_digest(1, seeds, ticks); @@ -188,8 +186,10 @@ TEST_CASE("Deferred-create from SystemThreaded: digest is identical across worke } } -TEST_CASE("Deferred-create from SystemThreaded: digest stays identical across multiple ticks", - "[ecs][determinism][WorkerCountInvariance][deferred]") { +TEST_CASE( + "Deferred-create from SystemThreaded: digest stays identical across multiple ticks", + "[ecs][determinism][WorkerCountInvariance][deferred]" +) { // Multi-tick: each tick adds another generation of WciSpawned. Catches ordering instability // that compounds across tick boundaries. std::size_t const seeds = 200; diff --git a/tests/src/core/object/Approx.hpp b/tests/src/core/object/Approx.hpp index b7080d470..95e9b4063 100644 --- a/tests/src/core/object/Approx.hpp +++ b/tests/src/core/object/Approx.hpp @@ -18,10 +18,10 @@ namespace OpenVic::testing { concept explicit_convertible_to = requires { static_cast(std::declval()); }; struct approx { - constexpr approx(double value) - : _epsilon(static_cast(std::numeric_limits::epsilon()) * 100), // - _scale(1.0), // - _value(value) {} + constexpr approx(double value) : + _epsilon(static_cast(std::numeric_limits::epsilon()) * 100), // + _scale(1.0), // + _value(value) {} constexpr approx operator()(double value) const { approx approx(value); diff --git a/tests/src/core/object/Colour.cpp b/tests/src/core/object/Colour.cpp index 6a6ba9159..1898bebe8 100644 --- a/tests/src/core/object/Colour.cpp +++ b/tests/src/core/object/Colour.cpp @@ -5,9 +5,9 @@ #include +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Colour.hpp" // IWYU pragma: keep #include "core/object/Numeric.hpp" // IWYU pragma: keep -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -23,9 +23,9 @@ TEMPLATE_LIST_TEST_CASE("basic_colour_t Constructor methods", "[basic_colour_t][ using value_t = TestType::value_type; static constexpr TestType blue_rgb = TestType( - (value_t)(63.0 / 255 * TestType::max_value), // - (value_t)(96.0 / 255 * TestType::max_value), // - (value_t)(1.0 * TestType::max_value) + (value_t)(63.0 / 255 * TestType::max_value), + (value_t)(96.0 / 255 * TestType::max_value), + (value_t)(1.0 * TestType::max_value) ); static constexpr TestType blue_float = TestType::from_floats(0.25098, 0.376471, 1); @@ -128,11 +128,7 @@ TEMPLATE_LIST_TEST_CASE("basic_colour_t Formatting", "[basic_colour_t][basic_col } TEST_CASE("colour_rgb_t Constructor methods", "[basic_colour_t][colour_rgb_t][colour_rgb_t-constructor]") { - static constexpr colour_rgb_t blue_rgb = colour_rgb_t( - 63.0 / 255 * 255, // - 96.0 / 255 * 255, // - 1.0 * 255 - ); + static constexpr colour_rgb_t blue_rgb = colour_rgb_t(63.0 / 255 * 255, 96.0 / 255 * 255, 1.0 * 255); static constexpr colour_rgb_t blue_int = colour_rgb_t::from_integer(0x3F'60'FF); static constexpr colour_rgb_t blue_rgba = colour_rgb_t::from_rgba(0x3F'60'FF'FF); static constexpr colour_rgb_t blue_argb = colour_rgb_t::from_argb(0xFF'3F'60'FF); @@ -149,11 +145,7 @@ TEST_CASE("colour_rgb_t Constructor methods", "[basic_colour_t][colour_rgb_t][co } TEST_CASE("colour_argb_t Constructor methods", "[basic_colour_t][colour_argb_t][colour_argb_t-constructor]") { - static constexpr colour_argb_t blue_rgb = colour_argb_t( - 63.0 / 255 * 255, // - 96.0 / 255 * 255, // - 1.0 * 255 - ); + static constexpr colour_argb_t blue_rgb = colour_argb_t(63.0 / 255 * 255, 96.0 / 255 * 255, 1.0 * 255); static constexpr colour_argb_t blue_int = colour_argb_t::from_integer(0x3F'60'FF'FF); static constexpr colour_argb_t blue_rgba = colour_argb_t::from_rgba(0x3F'60'FF'FF); static constexpr colour_argb_t blue_argb = colour_argb_t::from_argb(0xFF'3F'60'FF); diff --git a/tests/src/core/object/FixedPoint.cpp b/tests/src/core/object/FixedPoint.cpp index 7ca6cf746..a0e6e0bd6 100644 --- a/tests/src/core/object/FixedPoint.cpp +++ b/tests/src/core/object/FixedPoint.cpp @@ -9,9 +9,9 @@ #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/object/FixedPoint/String.hpp" +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Approx.hpp" #include "core/object/Numeric.hpp" // IWYU pragma: keep -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -142,13 +142,13 @@ TEST_CASE("fixed_point_t Parse methods", "[fixed_point_t][fixed_point_t-parse]") static constexpr std::string_view plus_fixed_point_str = "+4.5432"sv; fixed_point_t fp = fixed_point_t::_0; CHECK( - fp::from_chars(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()).ec == - std::errc::invalid_argument + fp::from_chars(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()).ec == + std::errc::invalid_argument ); CHECK(fp == 0.0_a); CHECK( - fp::from_chars_with_plus(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()).ec == - std::errc {} + fp::from_chars_with_plus(fp, plus_fixed_point_str.data(), plus_fixed_point_str.data() + plus_fixed_point_str.size()) + .ec == std::errc {} ); CHECK(fp == 4.5432_a); } @@ -266,24 +266,21 @@ TEST_CASE("fixed_point_t Operators", "[fixed_point_t][fixed_point_t-operators]") CONSTEXPR_CHECK(((int32_t)decimal4) == 3); CONSTEXPR_CHECK( - fp::mul_div( - fixed_point_t::parse_raw(2), - fixed_point_t::parse_raw(3), - fixed_point_t::parse_raw(6) - ) == fixed_point_t::parse_raw(1) + fp::mul_div(fixed_point_t::parse_raw(2), fixed_point_t::parse_raw(3), fixed_point_t::parse_raw(6)) == + fixed_point_t::parse_raw(1) ); CONSTEXPR_CHECK( - fp::multiply_truncate( - 4294967295LL, //2^32 - 1 - fixed_point_t::usable_max //2^31 / 2^16 - ) == 140737488322560LL //2^47 - 2^15 + fp::multiply_truncate( + 4294967295LL, // 2^32 - 1 + fixed_point_t::usable_max // 2^31 / 2^16 + ) == 140737488322560LL // 2^47 - 2^15 ); CONSTEXPR_CHECK( - fp::multiply_truncate( - 281474976710655LL, //2^48 - 1 - fixed_point_t::_0_50 - ) == 140737488355327LL //2^47 - 1 + fp::multiply_truncate( + 281474976710655LL, // 2^48 - 1 + fixed_point_t::_0_50 + ) == 140737488355327LL // 2^47 - 1 ); } diff --git a/tests/src/core/object/FixedPoint/Atomic.cpp b/tests/src/core/object/FixedPoint/Atomic.cpp index ec1232b21..d37cc60ae 100644 --- a/tests/src/core/object/FixedPoint/Atomic.cpp +++ b/tests/src/core/object/FixedPoint/Atomic.cpp @@ -5,8 +5,8 @@ #include "openvic-simulation/core/object/FixedPoint.hpp" -#include "core/object/Numeric.hpp" // IWYU pragma: keep #include "Helper.hpp" // IWYU pragma: keep +#include "core/object/Numeric.hpp" // IWYU pragma: keep #include #include #include diff --git a/tests/src/core/object/Timespan.cpp b/tests/src/core/object/Timespan.cpp index be3f88e49..585ed0a27 100644 --- a/tests/src/core/object/Timespan.cpp +++ b/tests/src/core/object/Timespan.cpp @@ -1,9 +1,9 @@ +#include "openvic-simulation/core/object/Timespan.hpp" + #include #include #include -#include "openvic-simulation/core/object/Timespan.hpp" - #include "Helper.hpp" // IWYU pragma: keep #include #include diff --git a/tests/src/core/object/Vector.hpp b/tests/src/core/object/Vector.hpp index dbb7d4566..2b9fe19f1 100644 --- a/tests/src/core/object/Vector.hpp +++ b/tests/src/core/object/Vector.hpp @@ -22,8 +22,10 @@ namespace OpenVic::testing { inline constexpr fvec4_t parse_unsafe_v4(double x, double y, double z, double w) { return fvec4_t( - fixed_point_t::parse_unsafe(x), fixed_point_t::parse_unsafe(y), fixed_point_t::parse_unsafe(z), - fixed_point_t::parse_unsafe(w) + fixed_point_t::parse_unsafe(x), + fixed_point_t::parse_unsafe(y), + fixed_point_t::parse_unsafe(z), + fixed_point_t::parse_unsafe(w) ); } @@ -36,11 +38,11 @@ namespace OpenVic::testing { } inline dvec4_t approx_value(fvec4_t value, dvec4_t compare) { - return { // - approx_value(value.x, compare.x), // - approx_value(value.y, compare.y), // - approx_value(value.z, compare.z), // - approx_value(value.w, compare.w) + return { + approx_value(value.x, compare.x), + approx_value(value.y, compare.y), + approx_value(value.z, compare.z), + approx_value(value.w, compare.w), }; } @@ -53,11 +55,11 @@ namespace OpenVic::testing { } inline dvec4_t approx_value(dvec4_t value, dvec4_t compare) { - return { // - approx_value(value.x, compare.x), // - approx_value(value.y, compare.y), // - approx_value(value.z, compare.z), // - approx_value(value.w, compare.w) + return { + approx_value(value.x, compare.x), + approx_value(value.y, compare.y), + approx_value(value.z, compare.z), + approx_value(value.w, compare.w), }; } } diff --git a/tests/src/core/object/Vector2.cpp b/tests/src/core/object/Vector2.cpp index 4f1904e86..b05f13625 100644 --- a/tests/src/core/object/Vector2.cpp +++ b/tests/src/core/object/Vector2.cpp @@ -5,10 +5,10 @@ #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/object/Vector.hpp" +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Approx.hpp" #include "core/object/Numeric.hpp" #include "core/object/Vector.hpp" -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -143,20 +143,20 @@ TEST_CASE("fvec2_t Operators", "[vec2_t][fvec2_t][fvec2_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec2 { 1.25, 1.625 }); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec2 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON) // - } + decimal1 - decimal2 == + testing::approx_vec2 { + (1.1_a).epsilon(testing::INACCURATE_EPSILON), // + (1.5_a).epsilon(testing::INACCURATE_EPSILON) // + } ); CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec2 { 0.25, 1.375 }); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec2 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON) // - } + decimal1 * decimal2 == + testing::approx_vec2 { + (2.76_a).epsilon(testing::INACCURATE_EPSILON), // + (16.66_a).epsilon(testing::INACCURATE_EPSILON) // + } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec2 { 0.375, 0.1875 }); diff --git a/tests/src/core/object/Vector3.cpp b/tests/src/core/object/Vector3.cpp index 11ab62f65..355805d53 100644 --- a/tests/src/core/object/Vector3.cpp +++ b/tests/src/core/object/Vector3.cpp @@ -5,10 +5,10 @@ #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/object/Vector.hpp" +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Approx.hpp" #include "core/object/Numeric.hpp" #include "core/object/Vector.hpp" -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -118,8 +118,8 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; static constexpr fixed_point_t _7_80 = // - fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + - fixed_point_t::_0_10; + fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + + fixed_point_t::_0_10; static constexpr fixed_point_t _1_20 = fixed_point_t::_0_20 * 6; static constexpr fixed_point_t _3_40 = fixed_point_t::_0_20 * 17; static constexpr fixed_point_t _5_60 = fixed_point_t::_4 + fixed_point_t::_1_50 + fixed_point_t::_0_10; @@ -138,22 +138,22 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec3(1.25, 1.625, 0.875)); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec3 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON), // - (2.2_a).epsilon(testing::INACCURATE_EPSILON) // - } + decimal1 - decimal2 == + testing::approx_vec3 { + (1.1_a).epsilon(testing::INACCURATE_EPSILON), // + (1.5_a).epsilon(testing::INACCURATE_EPSILON), // + (2.2_a).epsilon(testing::INACCURATE_EPSILON) // + } ); CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec3(0.25, 1.375, 0.375)); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec3 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON), // - (43.68_a).epsilon(testing::INACCURATE_EPSILON) // - } + decimal1 * decimal2 == + testing::approx_vec3 { + (2.76_a).epsilon(testing::INACCURATE_EPSILON), // + (16.66_a).epsilon(testing::INACCURATE_EPSILON), // + (43.68_a).epsilon(testing::INACCURATE_EPSILON) // + } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec3(0.375, 0.1875, 0.15625)); diff --git a/tests/src/core/object/Vector4.cpp b/tests/src/core/object/Vector4.cpp index 1de334853..0747b654f 100644 --- a/tests/src/core/object/Vector4.cpp +++ b/tests/src/core/object/Vector4.cpp @@ -5,10 +5,10 @@ #include "openvic-simulation/core/object/FixedPoint/Math.hpp" #include "openvic-simulation/core/object/Vector.hpp" +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Approx.hpp" #include "core/object/Numeric.hpp" #include "core/object/Vector.hpp" // IWYU pragma: keep -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -118,8 +118,8 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; static constexpr fixed_point_t _7_80 = // - fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + - fixed_point_t::_0_10; + fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + + fixed_point_t::_0_10; static constexpr fixed_point_t _3_20 = fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_20; static constexpr fixed_point_t _1_20 = fixed_point_t::_0_20 * 6; static constexpr fixed_point_t _3_40 = fixed_point_t::_0_20 * 17; @@ -140,32 +140,32 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK(power1 + power2 == testing::approx_vec4(1.25, 1.625, 0.875, 0.875)); CONSTEXPR_CHECK( - decimal1 - decimal2 == - testing::approx_vec4 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON), // - (2.2_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON) // - - } + decimal1 - decimal2 == + testing::approx_vec4 { + (1.1_a).epsilon(testing::INACCURATE_EPSILON), // + (1.5_a).epsilon(testing::INACCURATE_EPSILON), // + (2.2_a).epsilon(testing::INACCURATE_EPSILON), // + (1.5_a).epsilon(testing::INACCURATE_EPSILON) // + + } ); CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec4(0.25, 1.375, 0.375, -0.625)); CONSTEXPR_CHECK( - decimal1 * decimal2 == - testing::approx_vec4 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON), // - (43.68_a).epsilon(testing::INACCURATE_EPSILON), // - (5.44_a).epsilon(testing::INACCURATE_EPSILON) // - } + decimal1 * decimal2 == + testing::approx_vec4 { + (2.76_a).epsilon(testing::INACCURATE_EPSILON), // + (16.66_a).epsilon(testing::INACCURATE_EPSILON), // + (43.68_a).epsilon(testing::INACCURATE_EPSILON), // + (5.44_a).epsilon(testing::INACCURATE_EPSILON) // + } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec4(0.375, 0.1875, 0.15625, 0.09375)); CONSTEXPR_CHECK(int1 / int2 == testing::approx_vec4(4, 2.5, 3, 2)); CONSTEXPR_CHECK( - decimal1 / decimal2 == - testing::approx_vec4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.88235294118) + decimal1 / decimal2 == + testing::approx_vec4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.88235294118) ); CONSTEXPR_CHECK(power1 / power2 == testing::approx_vec4(1.5, 12.0, 2.5, 1.0 / 6.0)); @@ -199,7 +199,7 @@ TEST_CASE("dvec4_t Operators", "[vec4_t][dvec4_t][dvec4_t-operators]") { CONSTEXPR_CHECK(int1 / int2 == dvec4_t(4, 2.5, 3, 2)); CONSTEXPR_CHECK( - decimal1 / decimal2 == testing::approx_vec4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.8823529411) + decimal1 / decimal2 == testing::approx_vec4(1.91666666666666666, 1.44117647058823529, 1.39285714285714286, 1.8823529411) ); CONSTEXPR_CHECK(power1 / power2 == dvec4_t(1.5, 12.0, 2.5, 1.0 / 6.0)); diff --git a/tests/src/core/random/WeightedSampling.cpp b/tests/src/core/random/WeightedSampling.cpp index 5eb1ad2d1..cefaf19f9 100644 --- a/tests/src/core/random/WeightedSampling.cpp +++ b/tests/src/core/random/WeightedSampling.cpp @@ -2,6 +2,7 @@ #include #include + #include #include "openvic-simulation/core/object/FixedPoint.hpp" @@ -15,27 +16,23 @@ constexpr uint32_t max_random_value = std::numeric_limits().max(); TEST_CASE("WeightedSampling limits", "[WeightedSampling]") { const fixed_point_t weights_sum = fixed_point_t::usable_max; - constexpr size_t perfect_divisor = 257; //4294967295 is perfectly divisible by 257 + constexpr size_t perfect_divisor = 257; // 4294967295 is perfectly divisible by 257 std::array weights {}; assert(weights.size() < std::numeric_limits::max()); constexpr uint32_t step_size = max_random_value / weights.size(); weights.fill(weights_sum / static_cast(weights.size())); for (size_t i = 0; i < weights.size(); ++i) { - CHECK(sample_weighted_index( - i * step_size, - weights, - weights_sum - ) == i); + CHECK(sample_weighted_index(i * step_size, weights, weights_sum) == i); } } TEST_CASE("WeightedSampling weights", "[WeightedSampling]") { - constexpr size_t max_length = 255; //weights_sum = (size^2+size)/2, this needs to be <= fixed_point_t::usable_max + constexpr size_t max_length = 255; // weights_sum = (size^2+size)/2, this needs to be <= fixed_point_t::usable_max std::array weights {}; - + fixed_point_t weights_sum = 0; assert(weights.size() < std::numeric_limits::max()); for (size_t i = 0; i < weights.size(); ++i) { - const fixed_point_t weight = static_cast(1+i); + const fixed_point_t weight = static_cast(1 + i); weights_sum += weight; weights[i] = weight; } @@ -49,10 +46,6 @@ TEST_CASE("WeightedSampling weights", "[WeightedSampling]") { const boost::int128::int128_t max_random_value_128 = max_random_value; const boost::int128::int128_t weights_sum_128 = weights_sum.get_raw_value(); const boost::int128::int128_t random_value = cumulative_weight_128 * max_random_value_128 / weights_sum_128; - CHECK(sample_weighted_index( - static_cast(random_value), - weights, - weights_sum - ) == i); + CHECK(sample_weighted_index(static_cast(random_value), weights, weights_sum) == i); } -} \ No newline at end of file +} diff --git a/tests/src/core/stl/containers/FixedVector.cpp b/tests/src/core/stl/containers/FixedVector.cpp index a70413335..63d3164a0 100644 --- a/tests/src/core/stl/containers/FixedVector.cpp +++ b/tests/src/core/stl/containers/FixedVector.cpp @@ -13,51 +13,55 @@ using namespace OpenVic::stl; // It has a multi-argument constructor to test emplace_back. struct ComplexType { public: - int index; - std::string name; + int index; + std::string name; - ComplexType(int new_index, std::string name_val) : index {new_index}, name(std::move(name_val)) {} + ComplexType(int new_index, std::string name_val) : index { new_index }, name(std::move(name_val)) {} - // Equality operator for assertions - bool operator==(const ComplexType& other) const { - return index == other.index && name == other.name; - } + // Equality operator for assertions + bool operator==(const ComplexType& other) const { + return index == other.index && name == other.name; + } }; // A type that is explicitly non-copyable and non-movable. struct NonCopyableNonMovable { public: - int value; + int value; - // A simple constructor - NonCopyableNonMovable(int new_value) : value {new_value} {} + // A simple constructor + NonCopyableNonMovable(int new_value) : value { new_value } {} - // Explicitly delete copy and move operations - NonCopyableNonMovable(const NonCopyableNonMovable&) = delete; - NonCopyableNonMovable& operator=(const NonCopyableNonMovable&) = delete; - NonCopyableNonMovable(NonCopyableNonMovable&&) = delete; - NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete; + // Explicitly delete copy and move operations + NonCopyableNonMovable(const NonCopyableNonMovable&) = delete; + NonCopyableNonMovable& operator=(const NonCopyableNonMovable&) = delete; + NonCopyableNonMovable(NonCopyableNonMovable&&) = delete; + NonCopyableNonMovable& operator=(NonCopyableNonMovable&&) = delete; - bool operator==(const NonCopyableNonMovable& other) const { - return value == other.value; - } + bool operator==(const NonCopyableNonMovable& other) const { + return value == other.value; + } }; // A custom type to verify constructors and destructors are called correctly. struct DestructionCounter { public: - static int constructor_count; - static int destructor_count; - - DestructionCounter() { constructor_count++; } - ~DestructionCounter() { destructor_count++; } - - // Must be non-copyable/non-movable to be safe to use in a fixed vector - // and for better testing of in-place construction. - DestructionCounter(const DestructionCounter&) = delete; - DestructionCounter(DestructionCounter&&) = delete; - DestructionCounter& operator=(const DestructionCounter&) = delete; - DestructionCounter& operator=(DestructionCounter&&) = delete; + static int constructor_count; + static int destructor_count; + + DestructionCounter() { + constructor_count++; + } + ~DestructionCounter() { + destructor_count++; + } + + // Must be non-copyable/non-movable to be safe to use in a fixed vector + // and for better testing of in-place construction. + DestructionCounter(const DestructionCounter&) = delete; + DestructionCounter(DestructionCounter&&) = delete; + DestructionCounter& operator=(const DestructionCounter&) = delete; + DestructionCounter& operator=(DestructionCounter&&) = delete; }; // Define the static member variables outside the class. @@ -66,7 +70,7 @@ int DestructionCounter::constructor_count = 0; int DestructionCounter::destructor_count = 0; // A simple test case to check the basic constructor and accessors with a simple type. -TEST_CASE("FixedVector Construction and basic accessors","[FixedVector]") { +TEST_CASE("FixedVector Construction and basic accessors", "[FixedVector]") { constexpr size_t capacity = 5; FixedVector vec { create_empty, capacity }; @@ -78,9 +82,9 @@ TEST_CASE("FixedVector Construction and basic accessors","[FixedVector]") { } // Test the generator constructor with a single value return. -TEST_CASE("FixedVector Generator constructor (single value)","[FixedVector]") { +TEST_CASE("FixedVector Generator constructor (single value)", "[FixedVector]") { constexpr size_t capacity = 3; - FixedVector vec(capacity, [](const size_t i)->auto { + FixedVector vec(capacity, [](const size_t i) -> auto { return std::make_tuple(static_cast(i), std::to_string(i)); }); @@ -89,14 +93,14 @@ TEST_CASE("FixedVector Generator constructor (single value)","[FixedVector]") { REQUIRE(vec.max_size() == capacity); for (size_t i = 0; i < capacity; ++i) { - CHECK(vec[i] == ComplexType{static_cast(i), std::to_string(i)}); + CHECK(vec[i] == ComplexType { static_cast(i), std::to_string(i) }); } } // Test the generator constructor with a tuple return. -TEST_CASE("FixedVector Generator constructor (tuple)","[FixedVector]") { +TEST_CASE("FixedVector Generator constructor (tuple)", "[FixedVector]") { constexpr size_t capacity = 3; - FixedVector vec(capacity, [](const size_t i)->auto { + FixedVector vec(capacity, [](const size_t i) -> auto { return std::make_tuple(static_cast(i), std::to_string(i)); }); @@ -105,41 +109,41 @@ TEST_CASE("FixedVector Generator constructor (tuple)","[FixedVector]") { REQUIRE(vec.max_size() == capacity); for (size_t i = 0; i < capacity; ++i) { - CHECK(vec[i] == ComplexType{static_cast(i), std::to_string(i)}); + CHECK(vec[i] == ComplexType { static_cast(i), std::to_string(i) }); } } // Test emplace_back, pop_back, and clear with a complex type. -TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)","[FixedVector]") { +TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)", "[FixedVector]") { constexpr size_t capacity = 4; FixedVector vec { create_empty, capacity }; // Emplace elements with multiple arguments vec.emplace_back(1, "hello"); REQUIRE(vec.size() == 1); - CHECK(vec.back() == ComplexType{1, "hello"}); + CHECK(vec.back() == ComplexType { 1, "hello" }); // Emplace up to capacity vec.emplace_back(2, "world"); vec.emplace_back(3, "!"); vec.emplace_back(4, "done"); REQUIRE(vec.size() == 4); - CHECK(vec.back() == ComplexType{4, "done"}); + CHECK(vec.back() == ComplexType { 4, "done" }); // Test emplace_back on a full vector (should not change size) auto it = vec.emplace_back(5, "oops"); CHECK(vec.size() == 4); CHECK(it == vec.end()); - CHECK(vec.back() == ComplexType{4, "done"}); // The last element is unchanged + CHECK(vec.back() == ComplexType { 4, "done" }); // The last element is unchanged // Test pop_back vec.pop_back(); REQUIRE(vec.size() == 3); - CHECK(vec.back() == ComplexType{3, "!"}); + CHECK(vec.back() == ComplexType { 3, "!" }); vec.pop_back(); REQUIRE(vec.size() == 2); - CHECK(vec.back() == ComplexType{2, "world"}); + CHECK(vec.back() == ComplexType { 2, "world" }); // Test clear vec.clear(); @@ -152,7 +156,7 @@ TEST_CASE("FixedVector Manipulation (emplace_back, pop_back, clear)","[FixedVect } // Test that accessor methods return references to the same memory location -TEST_CASE("FixedVector Accessor reference consistency","[FixedVector]") { +TEST_CASE("FixedVector Accessor reference consistency", "[FixedVector]") { constexpr size_t capacity = 3; FixedVector vec { create_empty, capacity }; @@ -170,7 +174,7 @@ TEST_CASE("FixedVector Accessor reference consistency","[FixedVector]") { } // Test with a non-copyable and non-movable type to ensure in-place construction. -TEST_CASE("FixedVector Non-copyable, non-movable type","[FixedVector]") { +TEST_CASE("FixedVector Non-copyable, non-movable type", "[FixedVector]") { constexpr size_t capacity = 2; FixedVector vec { create_empty, capacity }; @@ -188,7 +192,7 @@ TEST_CASE("FixedVector Non-copyable, non-movable type","[FixedVector]") { CHECK(&vec.back() == it1); } -TEST_CASE("FixedVector Destruction, Clear, and Refill","[FixedVector]") { +TEST_CASE("FixedVector Destruction, Clear, and Refill", "[FixedVector]") { // Reset the counters for a clean test DestructionCounter::constructor_count = 0; DestructionCounter::destructor_count = 0; diff --git a/tests/src/dataloader/NodeTools.cpp b/tests/src/dataloader/NodeTools.cpp index b3a33ced0..5d769ce07 100644 --- a/tests/src/dataloader/NodeTools.cpp +++ b/tests/src/dataloader/NodeTools.cpp @@ -29,9 +29,9 @@ #include "openvic-simulation/core/object/Timespan.hpp" #include "openvic-simulation/core/string/CharConv.hpp" +#include "Helper.hpp" // IWYU pragma: keep #include "core/object/Colour.hpp" // IWYU pragma: keep #include "core/object/Numeric.hpp" // IWYU pragma: keep -#include "Helper.hpp" // IWYU pragma: keep #include #include #include @@ -171,7 +171,8 @@ struct Ast : ovdl::SymbolIntern { StatementList slist; for (size_t index : ranges::views::iota(static_cast(0), count)) { std::to_chars_result result = std::to_chars(hex_array.data(), hex_array.data() + hex_array.size(), index); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { continue; } @@ -190,7 +191,8 @@ struct Ast : ovdl::SymbolIntern { for (auto [index, lhs] : ranges::views::iota(static_cast(0), count) | ranges::views::enumerate) { index %= span_rhs.size(); std::to_chars_result result = std::to_chars(hex_array.data(), hex_array.data() + hex_array.size(), lhs); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { continue; } @@ -205,7 +207,7 @@ TEST_CASE("NodeTools AST get_type_name", "[NodeTools][NodeTools-ast-get_type_nam ast::get_type_name(ovdl::v2script::ast::NodeKind::FileTree) == "ovdl::v2script::ast::FileTree"sv ); CONSTEXPR_CHECK( - ast::get_type_name(ovdl::v2script::ast::NodeKind::IdentifierValue) == "ovdl::v2script::ast::IdentifierValue"sv + ast::get_type_name(ovdl::v2script::ast::NodeKind::IdentifierValue) == "ovdl::v2script::ast::IdentifierValue"sv ); CONSTEXPR_CHECK( // ast::get_type_name(ovdl::v2script::ast::NodeKind::StringValue) == "ovdl::v2script::ast::StringValue"sv @@ -217,13 +219,13 @@ TEST_CASE("NodeTools AST get_type_name", "[NodeTools][NodeTools-ast-get_type_nam ast::get_type_name(ovdl::v2script::ast::NodeKind::NullValue) == "ovdl::v2script::ast::NullValue"sv ); CONSTEXPR_CHECK( - ast::get_type_name(ovdl::v2script::ast::NodeKind::EventStatement) == "ovdl::v2script::ast::EventStatement"sv + ast::get_type_name(ovdl::v2script::ast::NodeKind::EventStatement) == "ovdl::v2script::ast::EventStatement"sv ); CONSTEXPR_CHECK( - ast::get_type_name(ovdl::v2script::ast::NodeKind::AssignStatement) == "ovdl::v2script::ast::AssignStatement"sv + ast::get_type_name(ovdl::v2script::ast::NodeKind::AssignStatement) == "ovdl::v2script::ast::AssignStatement"sv ); CONSTEXPR_CHECK( - ast::get_type_name(ovdl::v2script::ast::NodeKind::ValueStatement) == "ovdl::v2script::ast::ValueStatement"sv + ast::get_type_name(ovdl::v2script::ast::NodeKind::ValueStatement) == "ovdl::v2script::ast::ValueStatement"sv ); } @@ -237,7 +239,7 @@ TEST_CASE("NodeTools Default Callback functions", "[NodeTools][NodeTools-default CONSTEXPR_CHECK(NodeTools::default_length_callback(0) == 0); CONSTEXPR_CHECK(NodeTools::default_length_callback(5) == 5); CONSTEXPR_CHECK( - NodeTools::default_length_callback(std::numeric_limits::max()) == std::numeric_limits::max() + NodeTools::default_length_callback(std::numeric_limits::max()) == std::numeric_limits::max() ); } @@ -331,7 +333,8 @@ TEST_CASE("NodeTools expect integer functions", "[NodeTools][NodeTools-expect-fu decltype(val) check; std::from_chars_result result = std::from_chars(sv.data(), sv.data() + sv.size(), check); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -380,7 +383,8 @@ TEST_CASE("NodeTools expect integer functions", "[NodeTools][NodeTools-expect-fu decltype(val) check; std::from_chars_result result = string_to_uint64(sv, check, base); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -427,8 +431,8 @@ TEST_CASE("NodeTools expect integer functions", "[NodeTools][NodeTools-expect-fu } TEST_CASE( - "NodeTools expect fixed_point_t functions", - "[NodeTools][NodeTools-expect-functions][NodeTools-expect-fixed_point_t-functions]" + "NodeTools expect fixed_point_t functions", + "[NodeTools][NodeTools-expect-functions][NodeTools-expect-fixed_point_t-functions]" ) { Ast ast; @@ -444,7 +448,8 @@ TEST_CASE( fixed_point_t check = 0; std::from_chars_result result = fp::from_chars(check, sv.data(), sv.data() + sv.size()); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -486,7 +491,8 @@ TEST_CASE("NodeTools expect colour functions", "[NodeTools][NodeTools-expect-fun auto callback = [](ListValue const* ptr, colour_t val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == 3); + CHECK_IF (ranges::distance(list) == 3) + ; else { return false; } @@ -519,7 +525,7 @@ TEST_CASE("NodeTools expect colour functions", "[NodeTools][NodeTools-expect-fun } TEST_CASE( - "NodeTools expect colour hex functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-colour-hex-functions]" + "NodeTools expect colour hex functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-colour-hex-functions]" ) { Ast ast; @@ -531,7 +537,8 @@ TEST_CASE( colour_argb_t check; std::from_chars_result result = check.from_chars_argb(sv.data(), sv.data() + sv.size()); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -544,7 +551,7 @@ TEST_CASE( } TEST_CASE( - "NodeTools expect text format functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-text-format-functions]" + "NodeTools expect text format functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-text-format-functions]" ) { Ast ast; @@ -561,14 +568,9 @@ TEST_CASE( auto callback = [](FlatValue const* ptr, text_format_t val) -> bool { using enum text_format_t; - static const string_map_t format_map = // - { // - { "left", left }, // - { "right", right }, - { "centre", centre }, - { "center", centre }, - { "justified", justified } - }; + static const string_map_t format_map = { + { "left", left }, { "right", right }, { "centre", centre }, { "center", centre }, { "justified", justified }, + }; std::string_view sv = ptr->value().view(); text_format_t check = format_map.find(sv).value(); @@ -597,7 +599,8 @@ TEST_CASE("NodeTools expect Date functions", "[NodeTools][NodeTools-expect-funct static auto sv_callback = [](std::string_view sv, Date val) -> bool { Date::from_chars_result result = {}; Date check = Date::from_string(sv, &result); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } @@ -622,27 +625,32 @@ TEST_CASE("NodeTools expect Date functions", "[NodeTools][NodeTools-expect-funct } TEST_CASE( - "NodeTools expect Timespan functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-timespan-functions]" + "NodeTools expect Timespan functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-timespan-functions]" ) { Ast ast; auto* _5_id = ast.create_with_intern("5"sv); auto* _5_str = ast.create_with_intern("5"sv); - enum class TimespanType : uint8_t { Day, Month, Year }; + enum class TimespanType : uint8_t { + Day, + Month, + Year + }; auto callback = [](FlatValue const* ptr, TimespanType type, Timespan val) -> bool { std::string_view sv = ptr->value().view(); int64_t check_int; std::from_chars_result result = string_to_int64(sv, check_int); - CHECK_IF(result.ec == std::errc {}); + CHECK_IF (result.ec == std::errc {}) + ; else { return false; } Timespan check = [&] { switch (type) { - case TimespanType::Day: return Timespan::from_days(check_int); + case TimespanType::Day: return Timespan::from_days(check_int); case TimespanType::Month: return Timespan::from_months(check_int); case TimespanType::Year: return Timespan::from_years(check_int); } @@ -676,7 +684,8 @@ TEST_CASE("NodeTools expect vector functions", "[NodeTools][NodeTools-expect-fun static auto callback = [](ListValue const* ptr, auto val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == val.size()); + CHECK_IF (ranges::distance(list) == val.size()) + ; else { return false; } @@ -826,8 +835,8 @@ TEST_CASE("NodeTools expect assign functions", "[NodeTools][NodeTools-expect-fun auto* value = dryad::node_cast(rhs); - CHECK_IF(ptr_lhs->value().view() == lhs) { - CHECK_IF(ptr_rhs->value().view() == value->value().view()) { + CHECK_IF (ptr_lhs->value().view() == lhs) { + CHECK_IF (ptr_rhs->value().view() == value->value().view()) { return true; } } @@ -860,7 +869,7 @@ TEST_CASE("NodeTools expect list functions", "[NodeTools][NodeTools-expect-funct auto* _24_str_list = ast.create_assign_list(24, str_value); static auto length_callback = [](size_t size, size_t check) { - CHECK_IF(size == check) { + CHECK_IF (size == check) { return true; } return false; @@ -868,7 +877,8 @@ TEST_CASE("NodeTools expect list functions", "[NodeTools][NodeTools-expect-funct static auto callback = [](ListValue const* ptr, size_t count, NodeCPtr val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == count); + CHECK_IF (ranges::distance(list) == count) + ; else { return false; } @@ -984,7 +994,8 @@ TEST_CASE("NodeTools expect length functions", "[NodeTools][NodeTools-expect-fun static auto callback = [](ListValue const* ptr, size_t count, size_t val) -> bool { auto list = ptr->statements(); - CHECK_IF(ranges::distance(list) == count); + CHECK_IF (ranges::distance(list) == count) + ; else { return false; } @@ -1005,7 +1016,8 @@ TEST_CASE("NodeTools expect length functions", "[NodeTools][NodeTools-expect-fun static auto callback_false = [](ListValue const* ptr, size_t count, size_t val) -> bool { auto list = ptr->statements(); - CHECK_FALSE_IF(ranges::distance(list) == count); + CHECK_FALSE_IF (ranges::distance(list) == count) + ; else { return false; } @@ -1279,7 +1291,7 @@ TEST_CASE("NodeTools expect key functions", "[NodeTools][NodeTools-expect-functi } TEST_CASE( - "NodeTools expect dictionary functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-dictionary-functions]" + "NodeTools expect dictionary functions", "[NodeTools][NodeTools-expect-functions][NodeTools-expect-dictionary-functions]" ) { Ast ast; @@ -1394,20 +1406,20 @@ TEST_CASE( } TEST_CASE( - "NodeTools expect mapped string functions", - "[NodeTools][NodeTools-expect-functions][NodeTools-expect-mapped-string-functions]" + "NodeTools expect mapped string functions", + "[NodeTools][NodeTools-expect-functions][NodeTools-expect-mapped-string-functions]" ) { Ast ast; - static const string_map_t map // - { // - { "key_test1", "value_test1"sv }, - { "key_test2", "value_test2"sv }, - { "key_test3", "value_test3"sv } - }; + static const string_map_t map { + { "key_test1", "value_test1"sv }, + { "key_test2", "value_test2"sv }, + { "key_test3", "value_test3"sv }, + }; static auto callback = [](string_map_t const& map, size_t expected_index, std::string_view val) { - CHECK_IF(map.size() > expected_index); + CHECK_IF (map.size() > expected_index) + ; else { return false; } diff --git a/tests/src/economy/trading/GoodMarket.cpp b/tests/src/economy/trading/GoodMarket.cpp index 1036a3314..9b7cb86d1 100644 --- a/tests/src/economy/trading/GoodMarket.cpp +++ b/tests/src/economy/trading/GoodMarket.cpp @@ -1,4 +1,3 @@ -#include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/economy/trading/GoodMarket.hpp" #include @@ -6,6 +5,7 @@ #include "openvic-simulation/core/object/Colour.hpp" #include "openvic-simulation/core/object/FixedPoint.hpp" #include "openvic-simulation/core/stl/containers/TypedSpan.hpp" +#include "openvic-simulation/economy/GoodDefinition.hpp" #include "openvic-simulation/misc/GameRulesManager.hpp" #include "openvic-simulation/types/TypedIndices.hpp" @@ -14,7 +14,7 @@ using namespace OpenVic; -GoodCategory good_category {"test_good_category", good_category_index_t{0}}; +GoodCategory good_category { "test_good_category", good_category_index_t { 0 } }; const fixed_point_t base_price = 16; constexpr bool is_not_available_from_start = false; @@ -23,83 +23,53 @@ constexpr bool is_not_money = false; constexpr bool does_not_counter_overseas_penalty = false; GoodDefinition good_definition { - "test_good", - colour_rgb_t {}, - good_index_t{0}, - good_category, - base_price, - is_not_available_from_start, - is_tradeable, - is_not_money, - does_not_counter_overseas_penalty + "test_good", colour_rgb_t {}, good_index_t { 0 }, + good_category, base_price, is_not_available_from_start, + is_tradeable, is_not_money, does_not_counter_overseas_penalty }; GameRulesManager game_rules_manager {}; struct Trader { public: - std::function buy_callback = []( - BuyResult const& buy_result - ) -> void { + std::function buy_callback = [](BuyResult const& buy_result) -> void { FAIL("Did not expect buy callback"); }; - std::function&)> sell_callback = []( - SellResult const& sell_result, memory::vector& reusable_vector - ) -> void { + std::function&)> sell_callback = + [](SellResult const& sell_result, memory::vector& reusable_vector) -> void { FAIL("Did not expect sell callback"); }; - static void after_buy(void* actor, BuyResult const& buy_result) { - } - static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) { - } + static void after_buy(void* actor, BuyResult const& buy_result) {} + static void after_sell(void* actor, SellResult const& sell_result, memory::vector& reusable_vector) {} }; TEST_CASE("GoodMarket no trading when good isn't available", "[GoodMarket]") { GoodMarket good_market { game_rules_manager, good_definition }; const std::optional country_index_optional = std::nullopt; - Trader buyer { - .buy_callback=[](BuyResult const& buy_result) -> void { - CHECK(buy_result.good_index == good_definition.index); - CHECK(buy_result.quantity_bought == 0); - CHECK(buy_result.money_spent_total == 0); - CHECK(buy_result.money_spent_on_imports == 0); - } - }; + Trader buyer { .buy_callback = [](BuyResult const& buy_result) -> void { + CHECK(buy_result.good_index == good_definition.index); + CHECK(buy_result.quantity_bought == 0); + CHECK(buy_result.money_spent_total == 0); + CHECK(buy_result.money_spent_on_imports == 0); + } }; const fixed_point_t quantity_to_buy = 1; const fixed_point_t money_to_spend = quantity_to_buy * good_market.get_max_next_price(); - good_market.add_buy_up_to_order({ - country_index_optional, - quantity_to_buy, - money_to_spend, - &buyer, - Trader::after_buy - }); + good_market.add_buy_up_to_order({ country_index_optional, quantity_to_buy, money_to_spend, &buyer, Trader::after_buy }); - Trader seller { - .sell_callback=[](SellResult const& sell_result, memory::vector& reusable_vector) -> void { - CHECK(sell_result.good_index == good_definition.index); - CHECK(sell_result.quantity_sold == 0); - CHECK(sell_result.money_gained == 0); - } - }; + Trader seller { .sell_callback = [](SellResult const& sell_result, memory::vector& reusable_vector) -> void { + CHECK(sell_result.good_index == good_definition.index); + CHECK(sell_result.quantity_sold == 0); + CHECK(sell_result.money_gained == 0); + } }; const fixed_point_t quantity_to_sell = 1; - good_market.add_market_sell_order({ - country_index_optional, - quantity_to_sell, - &seller, - Trader::after_sell - }); + good_market.add_market_sell_order({ country_index_optional, quantity_to_sell, &seller, Trader::after_sell }); TypedSpan reusable_country_map_0 {}; TypedSpan reusable_country_map_1 {}; std::array, GoodMarket::VECTORS_FOR_EXECUTE_ORDERS> reusable_vectors; - good_market.execute_orders( - reusable_country_map_0, - reusable_country_map_1, - reusable_vectors - ); + good_market.execute_orders(reusable_country_map_0, reusable_country_map_1, reusable_vectors); CHECK(good_market.get_price() == base_price); CHECK(good_market.get_price_change_yesterday() == 0); -} \ No newline at end of file +} diff --git a/tests/src/pathfinding/AStarPathing.cpp b/tests/src/pathfinding/AStarPathing.cpp index 560583e91..72e2c8621 100644 --- a/tests/src/pathfinding/AStarPathing.cpp +++ b/tests/src/pathfinding/AStarPathing.cpp @@ -13,7 +13,12 @@ using namespace OpenVic; namespace { struct ABC final : public PointMap, public AStarPathing { - enum { A, B, C, D }; + enum { + A, + B, + C, + D + }; ABC() : PointMap(), AStarPathing(this) { add_point(A, ivec2_t(0, 0)); @@ -40,7 +45,7 @@ namespace { TEST_CASE("AStarPathing ABC path", "[astar-pathing][astar-pathing-abc-path]") { ABC abc; memory::vector path = abc.get_id_path(ABC::A, ABC::C); - CHECK_IF(path.size() == 3) { + CHECK_IF (path.size() == 3) { CHECK(path[0] == ABC::A); CHECK(path[1] == ABC::B); CHECK(path[2] == ABC::C); diff --git a/tests/src/pathfinding/FringePathing.cpp b/tests/src/pathfinding/FringePathing.cpp index 18e1f9903..ebd06499b 100644 --- a/tests/src/pathfinding/FringePathing.cpp +++ b/tests/src/pathfinding/FringePathing.cpp @@ -13,7 +13,12 @@ using namespace OpenVic; namespace { struct ABC final : public PointMap, public FringePathing { - enum { A, B, C, D }; + enum { + A, + B, + C, + D + }; ABC() : PointMap(), FringePathing(this) { add_point(A, ivec2_t(0, 0)); @@ -40,7 +45,7 @@ namespace { TEST_CASE("FringePathing ABC path", "[fringe-pathing][fringe-pathing-abc-path]") { ABC abc; memory::vector path = abc.get_id_path(ABC::A, ABC::C); - CHECK_IF(path.size() == 3) { + CHECK_IF (path.size() == 3) { CHECK(path[0] == ABC::A); CHECK(path[1] == ABC::B); CHECK(path[2] == ABC::C); diff --git a/tests/src/pathfinding/Pathing.hpp b/tests/src/pathfinding/Pathing.hpp index d71958bf8..6f859d75e 100644 --- a/tests/src/pathfinding/Pathing.hpp +++ b/tests/src/pathfinding/Pathing.hpp @@ -125,7 +125,7 @@ namespace OpenVic::testing { // Reachable. { INFO(fmt::format("From {} to {}: Fringe did not find a path", u, v)); - CHECK_FALSE_IF(route.size() == 0) { + CHECK_FALSE_IF (route.size() == 0) { match = false; goto exit; } @@ -135,9 +135,9 @@ namespace OpenVic::testing { CAPTURE(i); { INFO( - fmt::format("From {} to {}: edge ({}, {}) does not exist", u, v, route[i - 1], route[i]) + fmt::format("From {} to {}: edge ({}, {}) does not exist", u, v, route[i - 1], route[i]) ); - CHECK_FALSE_IF(!adjacent[route[i - 1]][route[i]]) { + CHECK_FALSE_IF (!adjacent[route[i - 1]][route[i]]) { match = false; goto exit; } @@ -145,11 +145,16 @@ namespace OpenVic::testing { astar_dist += std::sqrt(points[route[i - 1]].distance_squared(points[route[i]])); } { - INFO(fmt::format( - "From {} to {}: Floyd-Warshall gives {:.6}, Fringe gives {:.6}", u, v, dist[u][v], - astar_dist - )); - CHECK_FALSE_IF(std::abs(astar_dist - dist[u][v]) >= accuracy_threshold) { + INFO( + fmt::format( + "From {} to {}: Floyd-Warshall gives {:.6}, Fringe gives {:.6}", + u, + v, + dist[u][v], + astar_dist + ) + ); + CHECK_FALSE_IF (std::abs(astar_dist - dist[u][v]) >= accuracy_threshold) { match = false; goto exit; } @@ -157,7 +162,7 @@ namespace OpenVic::testing { } else { // Unreachable. INFO(fmt::format("From {} to {}: Fringe somehow found a nonexistent path", u, v)); - CHECK_FALSE_IF(route.size() > 0) { + CHECK_FALSE_IF (route.size() > 0) { match = false; goto exit; } diff --git a/tests/src/pathfinding/PointMap.cpp b/tests/src/pathfinding/PointMap.cpp index 9f51763a6..e1ddd188c 100644 --- a/tests/src/pathfinding/PointMap.cpp +++ b/tests/src/pathfinding/PointMap.cpp @@ -74,8 +74,8 @@ TEST_CASE("PointMap Add/Remove", "[point-map][point-map-add-remove]") { // Tests for get_closest_position_in_segment. a.connect_points(2, 3); CHECK( - a.get_closest_position_in_segment(fvec2_t { fixed_point_t::_0_50, fixed_point_t::_0_50 }) == - fvec2_t { fixed_point_t::_0_50, 1 } + a.get_closest_position_in_segment(fvec2_t { fixed_point_t::_0_50, fixed_point_t::_0_50 }) == + fvec2_t { fixed_point_t::_0_50, 1 } ); a.connect_points(3, 4); diff --git a/tests/src/types/IdentifierRegistry.cpp b/tests/src/types/IdentifierRegistry.cpp index f9e3f8770..c2ee44884 100644 --- a/tests/src/types/IdentifierRegistry.cpp +++ b/tests/src/types/IdentifierRegistry.cpp @@ -38,8 +38,8 @@ namespace { /* Lightweight registry item carrying both a string identifier and a typed index. */ struct TestItem : HasIdentifier, HasIndex { - TestItem(index_t new_index, std::string_view new_identifier) - : HasIdentifier { new_identifier }, HasIndex { new_index } {} + TestItem(index_t new_index, std::string_view new_identifier) : + HasIdentifier { new_identifier }, HasIndex { new_index } {} TestItem(TestItem&&) = default; }; } @@ -96,12 +96,10 @@ TEST_CASE("IdentifierRegistry expect_item_identifier", "[IdentifierRegistry]") { auto* alpha_id = ast.create_with_intern("alpha"sv); bool invoked = false; - CHECK(registry.expect_item_identifier( - [&invoked](TestItem const& item) -> bool { - invoked = true; - CHECK_RETURN_BOOL(item.get_identifier() == "alpha"sv); - } - )(alpha_id)); + CHECK(registry.expect_item_identifier([&invoked](TestItem const& item) -> bool { + invoked = true; + CHECK_RETURN_BOOL(item.get_identifier() == "alpha"sv); + })(alpha_id)); CHECK(invoked); } @@ -117,24 +115,20 @@ TEST_CASE("IdentifierRegistry expect_item_index", "[IdentifierRegistry]") { /* Known identifier delivers the item's typed index. */ good_index_t result { 0 }; bool invoked = false; - CHECK(registry.expect_item_index( - [&result, &invoked](good_index_t index) -> bool { - invoked = true; - result = index; - return true; - } - )(beta_id)); + CHECK(registry.expect_item_index([&result, &invoked](good_index_t index) -> bool { + invoked = true; + result = index; + return true; + })(beta_id)); CHECK(invoked); CHECK(result == good_index_t { 1 }); /* Unknown identifier: callback not invoked, returns false without warn. */ invoked = false; - CHECK_FALSE(registry.expect_item_index( - [&invoked](good_index_t) -> bool { - invoked = true; - return true; - } - )(unknown_id)); + CHECK_FALSE(registry.expect_item_index([&invoked](good_index_t) -> bool { + invoked = true; + return true; + })(unknown_id)); CHECK_FALSE(invoked); /* Unknown identifier with warn = true returns true, callback still not invoked. */ @@ -157,24 +151,20 @@ TEST_CASE("IdentifierRegistry expect_item_index_str", "[IdentifierRegistry]") { /* Known key resolves to its typed index via the string path. */ good_index_t result { 0 }; bool invoked = false; - CHECK(registry.expect_item_index_str( - [&result, &invoked](good_index_t index) -> bool { - invoked = true; - result = index; - return true; - } - )("beta"sv)); + CHECK(registry.expect_item_index_str([&result, &invoked](good_index_t index) -> bool { + invoked = true; + result = index; + return true; + })("beta"sv)); CHECK(invoked); CHECK(result == good_index_t { 1 }); /* Unknown key: callback not invoked, returns false without warn. */ invoked = false; - CHECK_FALSE(registry.expect_item_index_str( - [&invoked](good_index_t) -> bool { - invoked = true; - return true; - } - )("gamma"sv)); + CHECK_FALSE(registry.expect_item_index_str([&invoked](good_index_t) -> bool { + invoked = true; + return true; + })("gamma"sv)); CHECK_FALSE(invoked); /* Unknown key with warn = true returns true, callback still not invoked. */ diff --git a/tests/src/types/Signal.cpp b/tests/src/types/Signal.cpp index cdeb6f274..da92adf83 100644 --- a/tests/src/types/Signal.cpp +++ b/tests/src/types/Signal.cpp @@ -17,7 +17,7 @@ using namespace OpenVic; using namespace std::string_view_literals; using SignalTypes = - snitch::type_list, nothread::signal, basic_signal>; + snitch::type_list, nothread::signal, basic_signal>; void test_func(int& sum, int i) { sum += i; diff --git a/tests/src/utility/reactive/DerivedState.cpp b/tests/src/utility/reactive/DerivedState.cpp index fd08a8c4f..d1443d641 100644 --- a/tests/src/utility/reactive/DerivedState.cpp +++ b/tests/src/utility/reactive/DerivedState.cpp @@ -1,6 +1,7 @@ +#include "openvic-simulation/utility/reactive/DerivedState.hpp" + #include "openvic-simulation/types/Signal.hpp" #include "openvic-simulation/utility/reactive/DependencyTracker.hpp" -#include "openvic-simulation/utility/reactive/DerivedState.hpp" #include "openvic-simulation/utility/reactive/MutableState.hpp" #include @@ -11,12 +12,12 @@ using namespace OpenVic; TEST_CASE("DerivedState untracked", "[DerivedState-untracked]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); CHECK(sum.get_untracked() == 0); mutable_state_a.set(1); @@ -28,25 +29,25 @@ TEST_CASE("DerivedState untracked", "[DerivedState-untracked]") { TEST_CASE("DerivedState reactive", "[DerivedState-reactive]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); int times_marked_dirty = 0; - connection conn = sum.connect([×_marked_dirty]()->void { + connection conn = sum.connect([×_marked_dirty]() -> void { ++times_marked_dirty; }); mutable_state_a.set(1); - CHECK(times_marked_dirty == 0); //starts dirty - CHECK(sum.get_untracked() == 1); //force update + CHECK(times_marked_dirty == 0); // starts dirty + CHECK(sum.get_untracked() == 1); // force update mutable_state_b.set(2); CHECK(times_marked_dirty == 1); - + mutable_state_a.set(2); CHECK(times_marked_dirty == 1); @@ -58,16 +59,16 @@ TEST_CASE("DerivedState reactive", "[DerivedState-reactive]") { TEST_CASE("DerivedState untracked in callback", "[DerivedState-untracked-in-callback]") { MutableState mutable_state_a(0); MutableState mutable_state_b(0); - DerivedState sum([ - &a=static_cast&>(mutable_state_a), - &b=static_cast&>(mutable_state_b) - ](DependencyTracker& tracker)->int { - return a.get(tracker) + b.get(tracker); - }); + DerivedState sum( + [&a = static_cast&>(mutable_state_a), + &b = static_cast&>(mutable_state_b)](DependencyTracker& tracker) -> int { + return a.get(tracker) + b.get(tracker); + } + ); connection conn; - int sum_value = sum.get([&sum,&conn,&sum_value](OpenVic::signal<>& sum_changed) mutable -> void { - conn = sum_changed.connect([&sum,&sum_value]() mutable -> void { + int sum_value = sum.get([&sum, &conn, &sum_value](OpenVic::signal<>& sum_changed) mutable -> void { + conn = sum_changed.connect([&sum, &sum_value]() mutable -> void { sum_value = sum.get_untracked(); }); }); @@ -76,4 +77,4 @@ TEST_CASE("DerivedState untracked in callback", "[DerivedState-untracked-in-call CHECK(sum_value == 1); mutable_state_a.set(2); CHECK(sum_value == 2); -} \ No newline at end of file +} diff --git a/tests/src/utility/reactive/MutableState.cpp b/tests/src/utility/reactive/MutableState.cpp index 4e0463c7f..42e12abbe 100644 --- a/tests/src/utility/reactive/MutableState.cpp +++ b/tests/src/utility/reactive/MutableState.cpp @@ -8,7 +8,9 @@ using namespace OpenVic; TEST_CASE("MutableState", "[MutableState]") { int sum = 0; MutableState mutable_state(0); - connection conn = mutable_state.connect([&sum](const int new_value) { sum += new_value; }); + connection conn = mutable_state.connect([&sum](const int new_value) { + sum += new_value; + }); CHECK(sum == 0); mutable_state.set(1); CHECK(sum == 1); @@ -19,4 +21,4 @@ TEST_CASE("MutableState", "[MutableState]") { conn.disconnect(); mutable_state.set(3); CHECK(sum == 5); -} \ No newline at end of file +} From 498d1f34e3db78c288a184844a75d80e93b48a8d Mon Sep 17 00:00:00 2001 From: Spartan322 Date: Thu, 10 Sep 2026 05:47:22 -0400 Subject: [PATCH 2/2] Fix empty comments used as formatting hacks --- src/headless/main.cpp | 46 ++++--- src/openvic-simulation/core/object/Colour.hpp | 8 +- src/openvic-simulation/core/object/Date.hpp | 4 +- .../core/object/FixedPoint/Atomic.hpp | 28 ++-- .../core/portable/ForwardableSpan.hpp | 13 +- .../core/stl/BasicIterator.hpp | 28 ++-- .../core/stl/containers/CowVector.hpp | 13 +- .../core/stl/containers/RingBuffer.hpp | 4 +- .../core/string/CharConv.hpp | 37 +++-- .../core/string/StringLiteral.hpp | 23 ++-- .../core/string/Utility.hpp | 4 +- .../country/CountryDefinition.cpp | 2 +- .../dataloader/Vic2PathSearch_Windows.hpp | 4 +- .../diplomacy/CountryRelation.cpp | 128 +++++------------- .../diplomacy/CountryRelation.hpp | 44 +++--- .../diplomacy/DiplomaticAction.cpp | 118 +++++++--------- src/openvic-simulation/misc/SoundEffect.cpp | 26 ++-- .../modifier/ModifierSum.hpp | 1 - .../pathfinding/AStarPathing.cpp | 2 +- .../pathfinding/AStarPathing.hpp | 4 +- .../pathfinding/FringePathing.cpp | 2 +- .../pathfinding/FringePathing.hpp | 4 +- .../pathfinding/PathingBase.hpp | 14 +- .../pathfinding/PointMap.hpp | 6 +- src/openvic-simulation/population/Pop.cpp | 8 +- src/openvic-simulation/population/PopSum.hpp | 16 +-- .../scripts/ConditionalWeight.cpp | 5 +- src/openvic-simulation/utility/Logger.hpp | 5 +- tests/src/core/DualAdjacent.cpp | 16 +-- tests/src/core/object/Approx.hpp | 4 +- tests/src/core/object/Colour.hpp | 4 +- tests/src/core/object/Vector2.cpp | 8 +- tests/src/core/object/Vector3.cpp | 14 +- tests/src/core/object/Vector4.cpp | 18 +-- tests/src/core/string/StringLiteral.cpp | 4 +- tests/src/dataloader/NodeTools.cpp | 16 +-- tests/src/types/Signal.cpp | 3 - 37 files changed, 281 insertions(+), 403 deletions(-) diff --git a/src/headless/main.cpp b/src/headless/main.cpp index 32042be5a..f3003bd01 100644 --- a/src/headless/main.cpp +++ b/src/headless/main.cpp @@ -26,8 +26,8 @@ using namespace OpenVic; -inline static void print_memory_usage( // - std::string_view prefix, std::source_location const& location = std::source_location::current() +inline static void print_memory_usage( + std::string_view prefix, std::source_location const& location = std::source_location::current() ) { #ifdef DEBUG_ENABLED // memory tracking will return 0 without DEBUG_ENABLED #if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO @@ -80,12 +80,12 @@ static void print_rgo(ProvinceInstance const& province) { "revenue_yesterday: {:.3}, " "total owner income: {:.3}, " "total employee income: {:.3}", - production_type.output_good, // - production_type, // - rgo.get_size_multiplier(), // - rgo.get_output_quantity_yesterday(), // - rgo.get_revenue_yesterday(), // - rgo.get_total_owner_income_cache(), // + production_type.output_good, + production_type, + rgo.get_size_multiplier(), + rgo.get_output_quantity_yesterday(), + rgo.get_revenue_yesterday(), + rgo.get_total_owner_income_cache(), rgo.get_total_employee_income_cache() ); @@ -208,7 +208,7 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("State updated"); }, nullptr, - nullptr // + nullptr }; SPDLOG_INFO("Commit hash: {}", GameManager::get_commit_hash()); @@ -264,15 +264,16 @@ static bool run_headless(fs::path const& root, memory::vector& m // TODO - REMOVE TEST CODE SPDLOG_INFO("===== Ranking system test... ====="); if (game_manager.get_instance_manager()) { - const auto print_ranking_list = [ // - ](std::string_view title, OpenVic::forwardable_span> countries) -> void { + const auto print_ranking_list = + [](std::string_view title, + OpenVic::forwardable_span> countries) -> void { memory::string countries_str; for (CountryInstance& country : countries) { countries_str += fmt::format( - "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", // - country, // + "\n\t{} - Total #{} ({:.1}), Prestige #{} ({:.1}), Industry #{} ({:.1}), Military #{} ({:.1})", + country, country.get_total_rank(), - country.total_score.get_untracked(), // + country.total_score.get_untracked(), country.get_prestige_rank(), country.get_prestige_untracked(), country.get_industrial_rank(), @@ -318,13 +319,13 @@ static bool run_headless(fs::path const& root, memory::vector& m MapInstance& map_instance = game_manager.get_instance_manager()->get_map_instance(); SPDLOG_INFO("===== Land Pathfinding test... ====="); - test_duration_t duration = std::chrono::duration_cast( // + test_duration_t duration = std::chrono::duration_cast( run_pathing_test(map_instance.get_land_pathing(), LAND_SEED) ); SPDLOG_INFO("Ran {} land pathing tests in {}", TESTS, duration); SPDLOG_INFO("===== Sea Pathfinding test... ====="); - duration = std::chrono::duration_cast( // + duration = std::chrono::duration_cast( run_pathing_test(map_instance.get_sea_pathing(), SEA_SEED) ); SPDLOG_INFO("Ran {} sea pathing tests in {}", TESTS, duration); @@ -335,9 +336,8 @@ static bool run_headless(fs::path const& root, memory::vector& m SPDLOG_INFO("===== Game Tick test... ====="); size_t ticks_passed = 0; - test_duration_t min_tick_duration = test_duration_t::max(), // - max_tick_duration = test_duration_t::min(), // - total_tick_duration {}; + test_duration_t min_tick_duration = test_duration_t::max(), max_tick_duration = test_duration_t::min(), + total_tick_duration {}; const test_time_point_t start_time = testing_clock_t::now(); while (++ticks_passed < TICK_COUNT) { const test_time_point_t tick_start = testing_clock_t::now(); @@ -367,7 +367,7 @@ static bool run_headless(fs::path const& root, memory::vector& m duration, total_tps, total_tick_duration, - tick_tps, // + tick_tps, min_tick_duration, max_tick_duration ); @@ -402,8 +402,10 @@ int main(int argc, char const* argv[]) { /* Reads the next argument and converts it to a path via path_transform. If reading or converting fails, an error * message and the help text are displayed, along with returning false to signify the program should exit. */ - const auto _read = [&root, &argn, argc, argv, &program_name // - ](std::string_view command, std::string_view path_use, std::invocable auto path_transform) -> bool { + const auto _read = + [&root, &argn, argc, argv, &program_name]( + std::string_view command, std::string_view path_use, std::invocable auto path_transform + ) -> bool { if (root.empty()) { if (++argn < argc) { char const* path = argv[argn]; diff --git a/src/openvic-simulation/core/object/Colour.hpp b/src/openvic-simulation/core/object/Colour.hpp index 8be725f2a..8684fa941 100644 --- a/src/openvic-simulation/core/object/Colour.hpp +++ b/src/openvic-simulation/core/object/Colour.hpp @@ -222,8 +222,8 @@ namespace OpenVic { colour_traits::blue_from_argb(integer) }; } - OV_SPEED_INLINE static constexpr basic_colour_t from_floats( // - float r, float g, float b, float a = colour_traits::alpha_to_float(max_value) + OV_SPEED_INLINE static constexpr basic_colour_t from_floats( + float r, float g, float b, float a = colour_traits::alpha_to_float(max_value) ) requires(colour_traits::has_alpha) { @@ -240,8 +240,8 @@ namespace OpenVic { } private: - OV_SPEED_INLINE static constexpr std::from_chars_result parse_from_chars( // - const char* first, const char* last, integer_type& value + OV_SPEED_INLINE static constexpr std::from_chars_result parse_from_chars( + const char* first, const char* last, integer_type& value ) { if (first < last && first[0] == '0' && (first + 1 < last) && (first[1] == 'x' || first[1] == 'X')) { first += 2; diff --git a/src/openvic-simulation/core/object/Date.hpp b/src/openvic-simulation/core/object/Date.hpp index 9cf09381c..fa97367ee 100644 --- a/src/openvic-simulation/core/object/Date.hpp +++ b/src/openvic-simulation/core/object/Date.hpp @@ -176,8 +176,8 @@ namespace OpenVic { return WEEKDAY_NAMES[get_day_of_week()]; } - OV_SPEED_INLINE constexpr std::to_chars_result to_chars( // - char* first, char* last, bool pad_year = false, bool pad_month = true, bool pad_day = true + OV_SPEED_INLINE constexpr std::to_chars_result to_chars( + char* first, char* last, bool pad_year = false, bool pad_month = true, bool pad_day = true ) const { year_t year = get_year(); if (year < 0) { diff --git a/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp b/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp index 0187c6d73..d32feae02 100644 --- a/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp +++ b/src/openvic-simulation/core/object/FixedPoint/Atomic.hpp @@ -131,35 +131,35 @@ namespace std { return value_type::parse_raw(base_type::exchange(fp.get_raw_value(), m)); } - OV_ALWAYS_INLINE bool compare_exchange_weak( // - value_type& fp1, value_type fp2, memory_order m1, memory_order m2 + OV_ALWAYS_INLINE bool compare_exchange_weak( + value_type& fp1, value_type fp2, memory_order m1, memory_order m2 ) noexcept { return base_type::compare_exchange_weak(*reinterpret_cast(&fp1), fp2.get_raw_value(), m1, m2); } - OV_ALWAYS_INLINE bool compare_exchange_weak( // - value_type& fp1, value_type fp2, memory_order m1, memory_order m2 + OV_ALWAYS_INLINE bool compare_exchange_weak( + value_type& fp1, value_type fp2, memory_order m1, memory_order m2 ) volatile noexcept { return base_type::compare_exchange_weak(*reinterpret_cast(&fp1), fp2.get_raw_value(), m1, m2); } - OV_ALWAYS_INLINE bool compare_exchange_weak( // - value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst + OV_ALWAYS_INLINE bool compare_exchange_weak( + value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst ) noexcept { return base_type::compare_exchange_weak(*reinterpret_cast(&fp1), fp2.get_raw_value(), m); } - OV_ALWAYS_INLINE bool compare_exchange_weak( // - value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst + OV_ALWAYS_INLINE bool compare_exchange_weak( + value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst ) volatile noexcept { return base_type::compare_exchange_weak(*reinterpret_cast(&fp1), fp2.get_raw_value(), m); } - OV_ALWAYS_INLINE bool compare_exchange_strong( // - value_type& fp1, value_type fp2, memory_order m1, memory_order m2 + OV_ALWAYS_INLINE bool compare_exchange_strong( + value_type& fp1, value_type fp2, memory_order m1, memory_order m2 ) noexcept { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m1, m2); } - OV_ALWAYS_INLINE bool compare_exchange_strong( // - value_type& fp1, value_type fp2, memory_order m1, memory_order m2 + OV_ALWAYS_INLINE bool compare_exchange_strong( + value_type& fp1, value_type fp2, memory_order m1, memory_order m2 ) volatile noexcept { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m1, m2); } @@ -169,8 +169,8 @@ namespace std { ) noexcept { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m); } - OV_ALWAYS_INLINE bool compare_exchange_strong( // - value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst + OV_ALWAYS_INLINE bool compare_exchange_strong( + value_type& fp1, value_type fp2, memory_order m = memory_order_seq_cst ) volatile noexcept { return base_type::compare_exchange_strong(*reinterpret_cast(&fp1), fp2.get_raw_value(), m); } diff --git a/src/openvic-simulation/core/portable/ForwardableSpan.hpp b/src/openvic-simulation/core/portable/ForwardableSpan.hpp index d84483482..242e9f749 100644 --- a/src/openvic-simulation/core/portable/ForwardableSpan.hpp +++ b/src/openvic-simulation/core/portable/ForwardableSpan.hpp @@ -35,12 +35,9 @@ namespace OpenVic::_detail::forwardable_span { template concept span_compatible_range = - !is_std_span>::value && // - std::ranges::contiguous_range && // - std::ranges::sized_range && // - (std::ranges::borrowed_range || std::is_const_v) && // - !is_std_array>::value && // - !std::is_array_v> && // + !is_std_span>::value && std::ranges::contiguous_range && + std::ranges::sized_range && (std::ranges::borrowed_range || std::is_const_v) && + !is_std_array>::value && !std::is_array_v> && std::is_convertible_v> (*)[], ElementType (*)[]>; template @@ -291,8 +288,8 @@ namespace OpenVic::_detail::forwardable_span { } } - [[nodiscard]] constexpr span subspan( // - size_type offset, size_type count = dynamic_extent + [[nodiscard]] constexpr span subspan( + size_type offset, size_type count = dynamic_extent ) const { if (std::is_constant_evaluated() && !(offset <= size())) { std::abort(); diff --git a/src/openvic-simulation/core/stl/BasicIterator.hpp b/src/openvic-simulation/core/stl/BasicIterator.hpp index ddaec66f8..f40c4f097 100644 --- a/src/openvic-simulation/core/stl/BasicIterator.hpp +++ b/src/openvic-simulation/core/stl/BasicIterator.hpp @@ -80,8 +80,8 @@ namespace OpenVic { }; template - [[nodiscard]] OV_ALWAYS_INLINE constexpr bool operator==( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr bool operator==( + basic_iterator const& lhs, basic_iterator const& rhs ) requires requires { { lhs.base() == rhs.base() } -> std::convertible_to; @@ -91,15 +91,15 @@ namespace OpenVic { } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator<=>( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator<=>( + basic_iterator const& lhs, basic_iterator const& rhs ) { return three_way_compare(lhs.base(), rhs.base()); } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr bool operator==( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr bool operator==( + basic_iterator const& lhs, basic_iterator const& rhs ) requires requires { { lhs.base() == rhs.base() } -> std::convertible_to; @@ -109,29 +109,29 @@ namespace OpenVic { } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator<=>( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator<=>( + basic_iterator const& lhs, basic_iterator const& rhs ) { return three_way_compare(lhs.base(), rhs.base()); } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator-( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr auto operator-( + basic_iterator const& lhs, basic_iterator const& rhs ) -> decltype(lhs.base() - rhs.base()) { return lhs.base() - rhs.base(); } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr typename basic_iterator::difference_type operator-( // - basic_iterator const& lhs, basic_iterator const& rhs + [[nodiscard]] OV_ALWAYS_INLINE constexpr typename basic_iterator::difference_type operator-( + basic_iterator const& lhs, basic_iterator const& rhs ) { return lhs.base() - rhs.base(); } template - [[nodiscard]] OV_ALWAYS_INLINE constexpr basic_iterator operator+( // - typename basic_iterator::difference_type n, basic_iterator const& i + [[nodiscard]] OV_ALWAYS_INLINE constexpr basic_iterator operator+( + typename basic_iterator::difference_type n, basic_iterator const& i ) { return basic_iterator(i.base() + n); } diff --git a/src/openvic-simulation/core/stl/containers/CowVector.hpp b/src/openvic-simulation/core/stl/containers/CowVector.hpp index 0f7226db3..101bee3eb 100644 --- a/src/openvic-simulation/core/stl/containers/CowVector.hpp +++ b/src/openvic-simulation/core/stl/containers/CowVector.hpp @@ -1136,15 +1136,16 @@ namespace OpenVic::cow { namespace std { template - inline void swap( // - typename ::OpenVic::stl::cow_vector::writer& x, typename ::OpenVic::stl::cow_vector::writer& y + inline void swap( + typename ::OpenVic::stl::cow_vector::writer& x, + typename ::OpenVic::stl::cow_vector::writer& y ) { x.swap(y); } template - inline typename ::OpenVic::stl::cow_vector::size_type erase_if( // - typename ::OpenVic::stl::cow_vector::writer& cont, Predicate pred + inline typename ::OpenVic::stl::cow_vector::size_type erase_if( + typename ::OpenVic::stl::cow_vector::writer& cont, Predicate pred ) { typename ::OpenVic::stl::cow_vector::writer& ucont = cont; const auto orig_size = cont.size(); @@ -1159,8 +1160,8 @@ namespace std { } template - inline typename ::OpenVic::stl::cow_vector::size_type erase( // - typename ::OpenVic::stl::cow_vector::writer& cont, U const& value + inline typename ::OpenVic::stl::cow_vector::size_type erase( + typename ::OpenVic::stl::cow_vector::writer& cont, U const& value ) { typename ::OpenVic::stl::cow_vector::writer& ucont = cont; const auto orig_size = cont.size(); diff --git a/src/openvic-simulation/core/stl/containers/RingBuffer.hpp b/src/openvic-simulation/core/stl/containers/RingBuffer.hpp index e8a126086..6f06d804d 100644 --- a/src/openvic-simulation/core/stl/containers/RingBuffer.hpp +++ b/src/openvic-simulation/core/stl/containers/RingBuffer.hpp @@ -548,9 +548,7 @@ namespace OpenVic::stl { /// Moves the read_size of the buffer from the front into r_buffer and erases read_size from the buffer. /// If read_size exceeds capacity(), read_size will become capacity(). - std::span read_buffer_to( // - pointer r_buffer, size_type read_size = std::numeric_limits::max() - ) { + std::span read_buffer_to(pointer r_buffer, size_type read_size = std::numeric_limits::max()) { read_size = std::min(read_size, capacity()); iterator last = begin(); ranges::advance(last, read_size); diff --git a/src/openvic-simulation/core/string/CharConv.hpp b/src/openvic-simulation/core/string/CharConv.hpp index 3d6dd8425..a6f6acf24 100644 --- a/src/openvic-simulation/core/string/CharConv.hpp +++ b/src/openvic-simulation/core/string/CharConv.hpp @@ -8,8 +8,8 @@ namespace OpenVic { template - [[nodiscard]] inline constexpr std::from_chars_result from_chars( // - char const* const first, char const* const last, T& raw_value, const int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result from_chars( + char const* const first, char const* const last, T& raw_value, const int base = 10 ) noexcept { if (!std::is_constant_evaluated()) { return std::from_chars(first, last, raw_value, base); @@ -108,18 +108,17 @@ namespace OpenVic { } template - [[nodiscard]] inline constexpr std::to_chars_result to_chars( // - char* first, char* const last, const T raw_value, const int base = 10 + [[nodiscard]] inline constexpr std::to_chars_result to_chars( + char* first, char* const last, const T raw_value, const int base = 10 ) noexcept { if (!std::is_constant_evaluated()) { return std::to_chars(first, last, raw_value, base); } - constexpr char digits[] = // - { // - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' - }; + constexpr char digits[] = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', + 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + }; static_assert(std::size(digits) == 36); using unsigned_type = std::make_unsigned_t; @@ -275,14 +274,14 @@ namespace OpenVic { return from_chars(str, end, value, base); } - [[nodiscard]] inline constexpr std::from_chars_result string_to_uint64( // - char const* const str, size_t length, std::uint64_t& value, int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result string_to_uint64( + char const* const str, size_t length, std::uint64_t& value, int base = 10 ) { return string_to_uint64(str, str + length, value, base); } - [[nodiscard]] inline constexpr std::from_chars_result string_to_uint64( // - std::string_view str, std::uint64_t& value, int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result string_to_uint64( + std::string_view str, std::uint64_t& value, int base = 10 ) { return string_to_uint64(str.data(), str.length(), value, base); } @@ -295,8 +294,8 @@ namespace OpenVic { * still starts with "0", otherwise 10. The std::from_chars_result return value is used to report whether * or not conversion was successful. */ - [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( // - char const* str, char const* const end, std::int64_t& value, int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( + char const* str, char const* const end, std::int64_t& value, int base = 10 ) { // If base is zero, base is determined by the string prefix. if (base == 0) { @@ -320,14 +319,14 @@ namespace OpenVic { return from_chars(str, end, value, base); } - [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( // - char const* str, size_t length, std::int64_t& value, int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( + char const* str, size_t length, std::int64_t& value, int base = 10 ) { return string_to_int64(str, str + length, value, base); } - [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( // - std::string_view str, std::int64_t& value, int base = 10 + [[nodiscard]] inline constexpr std::from_chars_result string_to_int64( + std::string_view str, std::int64_t& value, int base = 10 ) { return string_to_int64(str.data(), str.length(), value, base); } diff --git a/src/openvic-simulation/core/string/StringLiteral.hpp b/src/openvic-simulation/core/string/StringLiteral.hpp index 7075163cc..ccd8edaef 100644 --- a/src/openvic-simulation/core/string/StringLiteral.hpp +++ b/src/openvic-simulation/core/string/StringLiteral.hpp @@ -173,22 +173,21 @@ namespace OpenVic { } template - [[nodiscard]] constexpr string_literal append( // - string_literal str + [[nodiscard]] constexpr string_literal append( + string_literal str ) const noexcept { return *this + str; } template - [[nodiscard]] constexpr string_literal append( // - const value_type (&literal)[N2] + [[nodiscard]] constexpr string_literal append( + const value_type (&literal)[N2] ) const noexcept { return *this + literal; } template - [[nodiscard]] constexpr decltype(auto) substr() // - const noexcept { + [[nodiscard]] constexpr decltype(auto) substr() const noexcept { static_assert(pos <= size(), "pos must be less than or equal to size"); constexpr size_type result_size = std::min(count, size() - pos) + 1; @@ -204,8 +203,8 @@ namespace OpenVic { return *this; } - [[nodiscard]] constexpr std::basic_string_view substr( // - size_type pos, size_type count = npos + [[nodiscard]] constexpr std::basic_string_view substr( + size_type pos, size_type count = npos ) const noexcept { return as_string_view().substr(pos, count); } @@ -258,7 +257,7 @@ namespace OpenVic { } template - [[nodiscard]] constexpr string_literal operator+( // + [[nodiscard]] constexpr string_literal operator+( string_literal const& other ) const noexcept { string_literal result; @@ -273,15 +272,15 @@ namespace OpenVic { } template - [[nodiscard]] constexpr string_literal operator+( // + [[nodiscard]] constexpr string_literal operator+( const value_type (&rhs)[N2] ) const noexcept { return *this + _to_string(rhs); } template - [[nodiscard]] friend constexpr string_literal operator+( // - const value_type (&lhs)[N2], string_literal rhs + [[nodiscard]] friend constexpr string_literal operator+( + const value_type (&lhs)[N2], string_literal rhs ) noexcept { return _to_string(lhs) + rhs; } diff --git a/src/openvic-simulation/core/string/Utility.hpp b/src/openvic-simulation/core/string/Utility.hpp index 892dba1b5..0e62bfbfb 100644 --- a/src/openvic-simulation/core/string/Utility.hpp +++ b/src/openvic-simulation/core/string/Utility.hpp @@ -90,8 +90,8 @@ namespace OpenVic { } template - static memory::string string_join( // - tsl::ordered_map const& map, std::string_view delimiter = ", " + static memory::string string_join( + tsl::ordered_map const& map, std::string_view delimiter = ", " ) { if (map.empty()) { return ""; diff --git a/src/openvic-simulation/country/CountryDefinition.cpp b/src/openvic-simulation/country/CountryDefinition.cpp index 1893421fa..7beb901a5 100644 --- a/src/openvic-simulation/country/CountryDefinition.cpp +++ b/src/openvic-simulation/country/CountryDefinition.cpp @@ -66,7 +66,7 @@ bool CountryDefinitionManager::add_country( static constexpr colour_t default_colour = colour_t::fill_as(colour_t::max_value); return country_definitions.emplace_item( - identifier, // + identifier, identifier, colour, index_from_count(get_country_definition_count()), diff --git a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp index 657fced48..06212b721 100644 --- a/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp +++ b/src/openvic-simulation/dataloader/Vic2PathSearch_Windows.hpp @@ -142,8 +142,8 @@ namespace OpenVic::Windows { }; template - memory::basic_string ReadRegValue( // - HKEY root, std::basic_string_view key, std::basic_string_view name + memory::basic_string ReadRegValue( + HKEY root, std::basic_string_view key, std::basic_string_view name ) { RegistryKey registry_key(root, key, name); if constexpr (std::is_same_v) { diff --git a/src/openvic-simulation/diplomacy/CountryRelation.cpp b/src/openvic-simulation/diplomacy/CountryRelation.cpp index 9fb0c2fa1..20e7829dc 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.cpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.cpp @@ -11,9 +11,7 @@ using influence_value_type = OpenVic::CountryRelationManager::influence_value_ty using OpinionType = OpenVic::CountryRelationManager::OpinionType; using influence_priority_value_type = OpenVic::CountryRelationManager::influence_priority_value_type; -relation_value_type CRM::get_country_relation( // - CountryInstance const* country, CountryInstance const* recipient -) const { +relation_value_type CRM::get_country_relation(CountryInstance const* country, CountryInstance const* recipient) const { decltype(relations)::const_iterator it = relations.find({ country, recipient }); if (it == relations.end()) { return {}; @@ -21,8 +19,8 @@ relation_value_type CRM::get_country_relation( // return it->second; } -relation_value_type& CRM::assign_or_get_country_relation( // - CountryInstance* country, CountryInstance* recipient, relation_value_type default_value +relation_value_type& CRM::assign_or_get_country_relation( + CountryInstance* country, CountryInstance* recipient, relation_value_type default_value ) { decltype(relations)::iterator it = relations.find({ country, recipient }); if (it == relations.end()) { @@ -31,9 +29,7 @@ relation_value_type& CRM::assign_or_get_country_relation( // return it.value(); } -bool CRM::set_country_relation( // - CountryInstance* country, CountryInstance* recipient, relation_value_type value -) { +bool CRM::set_country_relation(CountryInstance* country, CountryInstance* recipient, relation_value_type value) { decltype(relations)::iterator it = relations.find({ country, recipient }); if (it == relations.end()) { it = relations.insert({ { country, recipient }, value }).first; @@ -47,9 +43,7 @@ decltype(CRM::relations)::values_container_type const& CRM::get_country_relation return relations.values_container(); } -bool CRM::get_country_alliance( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_country_alliance(CountryInstance const* country, CountryInstance const* recipient) const { decltype(alliances)::const_iterator it = alliances.find({ country, recipient }); if (it == alliances.end()) { return {}; @@ -57,9 +51,7 @@ bool CRM::get_country_alliance( // return it->second; } -bool& CRM::assign_or_get_country_alliance( // - CountryInstance* country, CountryInstance* recipient, bool default_value -) { +bool& CRM::assign_or_get_country_alliance(CountryInstance* country, CountryInstance* recipient, bool default_value) { decltype(alliances)::iterator it = alliances.find({ country, recipient }); if (it == alliances.end()) { it = alliances.insert({ { country, recipient }, default_value }).first; @@ -67,9 +59,7 @@ bool& CRM::assign_or_get_country_alliance( // return it.value(); } -bool CRM::set_country_alliance( // - CountryInstance* country, CountryInstance* recipient, bool value -) { +bool CRM::set_country_alliance(CountryInstance* country, CountryInstance* recipient, bool value) { decltype(alliances)::iterator it = alliances.find({ country, recipient }); if (it == alliances.end()) { it = alliances.insert({ { country, recipient }, value }).first; @@ -83,9 +73,7 @@ decltype(CRM::alliances)::values_container_type const& CRM::get_country_alliance return alliances.values_container(); } -bool CRM::get_at_war_with( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_at_war_with(CountryInstance const* country, CountryInstance const* recipient) const { decltype(at_war)::const_iterator it = at_war.find({ country, recipient }); if (it == at_war.end()) { return {}; @@ -93,9 +81,7 @@ bool CRM::get_at_war_with( // return it->second; } -bool& CRM::assign_or_get_at_war_with( // - CountryInstance* country, CountryInstance* recipient, bool default_value -) { +bool& CRM::assign_or_get_at_war_with(CountryInstance* country, CountryInstance* recipient, bool default_value) { decltype(at_war)::iterator it = at_war.find({ country, recipient }); if (it == at_war.end()) { it = at_war.insert({ { country, recipient }, default_value }).first; @@ -103,9 +89,7 @@ bool& CRM::assign_or_get_at_war_with( // return it.value(); } -bool CRM::set_at_war_with( // - CountryInstance* country, CountryInstance* recipient, bool value -) { +bool CRM::set_at_war_with(CountryInstance* country, CountryInstance* recipient, bool value) { decltype(at_war)::iterator it = at_war.find({ country, recipient }); if (it == at_war.end()) { it = at_war.insert({ { country, recipient }, value }).first; @@ -119,9 +103,7 @@ decltype(CRM::at_war)::values_container_type const& CRM::get_at_war_with_values( return at_war.values_container(); } -bool CRM::get_has_military_access_to( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_has_military_access_to(CountryInstance const* country, CountryInstance const* recipient) const { decltype(military_access)::const_iterator it = military_access.find({ country, recipient }); if (it == military_access.end()) { return {}; @@ -129,8 +111,8 @@ bool CRM::get_has_military_access_to( // return it->second; } -bool& CRM::assign_or_get_has_military_access_to( // - CountryInstance* country, CountryInstance const* recipient, bool default_value +bool& CRM::assign_or_get_has_military_access_to( + CountryInstance* country, CountryInstance const* recipient, bool default_value ) { decltype(military_access)::iterator it = military_access.find({ country, recipient }); if (it == military_access.end()) { @@ -139,9 +121,7 @@ bool& CRM::assign_or_get_has_military_access_to( // return it.value(); } -bool CRM::set_has_military_access_to( // - CountryInstance* country, CountryInstance const* recipient, bool value -) { +bool CRM::set_has_military_access_to(CountryInstance* country, CountryInstance const* recipient, bool value) { decltype(military_access)::iterator it = military_access.find({ country, recipient }); if (it == military_access.end()) { it = military_access.insert({ { country, recipient }, value }).first; @@ -155,9 +135,7 @@ decltype(CRM::military_access)::values_container_type const& CRM::get_has_milita return military_access.values_container(); } -bool CRM::get_war_subsidies_to( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_war_subsidies_to(CountryInstance const* country, CountryInstance const* recipient) const { decltype(war_subsidies)::const_iterator it = war_subsidies.find({ country, recipient }); if (it == war_subsidies.end()) { return {}; @@ -165,9 +143,7 @@ bool CRM::get_war_subsidies_to( // return it->second; } -bool& CRM::assign_or_get_war_subsidies_to( // - CountryInstance* country, CountryInstance const* recipient, bool default_value -) { +bool& CRM::assign_or_get_war_subsidies_to(CountryInstance* country, CountryInstance const* recipient, bool default_value) { decltype(war_subsidies)::iterator it = war_subsidies.find({ country, recipient }); if (it == war_subsidies.end()) { it = war_subsidies.insert({ { country, recipient }, default_value }).first; @@ -175,9 +151,7 @@ bool& CRM::assign_or_get_war_subsidies_to( // return it.value(); } -bool CRM::set_war_subsidies_to( // - CountryInstance* country, CountryInstance const* recipient, bool value -) { +bool CRM::set_war_subsidies_to(CountryInstance* country, CountryInstance const* recipient, bool value) { decltype(war_subsidies)::iterator it = war_subsidies.find({ country, recipient }); if (it == war_subsidies.end()) { it = war_subsidies.insert({ { country, recipient }, value }).first; @@ -191,9 +165,7 @@ decltype(CRM::war_subsidies)::values_container_type const& CRM::get_war_subsidie return war_subsidies.values_container(); } -bool CRM::get_commands_units( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_commands_units(CountryInstance const* country, CountryInstance const* recipient) const { decltype(command_units)::const_iterator it = command_units.find({ country, recipient }); if (it == command_units.end()) { return {}; @@ -201,9 +173,7 @@ bool CRM::get_commands_units( // return it->second; } -bool& CRM::assign_or_get_commands_units( // - CountryInstance* country, CountryInstance const* recipient, bool default_value -) { +bool& CRM::assign_or_get_commands_units(CountryInstance* country, CountryInstance const* recipient, bool default_value) { decltype(command_units)::iterator it = command_units.find({ country, recipient }); if (it == command_units.end()) { it = command_units.insert({ { country, recipient }, default_value }).first; @@ -211,9 +181,7 @@ bool& CRM::assign_or_get_commands_units( // return it.value(); } -bool CRM::set_commands_units( // - CountryInstance* country, CountryInstance const* recipient, bool value -) { +bool CRM::set_commands_units(CountryInstance* country, CountryInstance const* recipient, bool value) { decltype(command_units)::iterator it = command_units.find({ country, recipient }); if (it == command_units.end()) { it = command_units.insert({ { country, recipient }, value }).first; @@ -227,9 +195,7 @@ decltype(CRM::command_units)::values_container_type const& CRM::get_commands_uni return command_units.values_container(); } -bool CRM::get_has_vision( // - CountryInstance const* country, CountryInstance const* recipient -) const { +bool CRM::get_has_vision(CountryInstance const* country, CountryInstance const* recipient) const { decltype(vision)::const_iterator it = vision.find({ country, recipient }); if (it == vision.end()) { return {}; @@ -237,9 +203,7 @@ bool CRM::get_has_vision( // return it->second; } -bool& CRM::assign_or_get_has_vision( // - CountryInstance* country, CountryInstance const* recipient, bool default_value -) { +bool& CRM::assign_or_get_has_vision(CountryInstance* country, CountryInstance const* recipient, bool default_value) { decltype(vision)::iterator it = vision.find({ country, recipient }); if (it == vision.end()) { it = vision.insert({ { country, recipient }, default_value }).first; @@ -247,9 +211,7 @@ bool& CRM::assign_or_get_has_vision( // return it.value(); } -bool CRM::set_has_vision( // - CountryInstance* country, CountryInstance const* recipient, bool value -) { +bool CRM::set_has_vision(CountryInstance* country, CountryInstance const* recipient, bool value) { decltype(vision)::iterator it = vision.find({ country, recipient }); if (it == vision.end()) { it = vision.insert({ { country, recipient }, value }).first; @@ -263,9 +225,7 @@ decltype(CRM::vision)::values_container_type const& CRM::get_has_vision_values() return vision.values_container(); } -OpinionType CRM::get_country_opinion( // - CountryInstance const* country, CountryInstance const* recipient -) const { +OpinionType CRM::get_country_opinion(CountryInstance const* country, CountryInstance const* recipient) const { decltype(opinions)::const_iterator it = opinions.find({ country, recipient }); if (it == opinions.end()) { return {}; @@ -273,8 +233,8 @@ OpinionType CRM::get_country_opinion( // return it->second; } -OpinionType& CRM::assign_or_get_country_opinion( // - CountryInstance* country, CountryInstance const* recipient, OpinionType default_value +OpinionType& CRM::assign_or_get_country_opinion( + CountryInstance* country, CountryInstance const* recipient, OpinionType default_value ) { decltype(opinions)::iterator it = opinions.find({ country, recipient }); if (it == opinions.end()) { @@ -283,9 +243,7 @@ OpinionType& CRM::assign_or_get_country_opinion( // return it.value(); } -bool CRM::set_country_opinion( // - CountryInstance* country, CountryInstance const* recipient, OpinionType value -) { +bool CRM::set_country_opinion(CountryInstance* country, CountryInstance const* recipient, OpinionType value) { decltype(opinions)::iterator it = opinions.find({ country, recipient }); if (it == opinions.end()) { it = opinions.insert({ { country, recipient }, value }).first; @@ -299,9 +257,7 @@ decltype(CRM::opinions)::values_container_type const& CRM::get_country_opinion_v return opinions.values_container(); } -influence_value_type CRM::get_influence_with( // - CountryInstance const* country, CountryInstance const* recipient -) const { +influence_value_type CRM::get_influence_with(CountryInstance const* country, CountryInstance const* recipient) const { decltype(influence)::const_iterator it = influence.find({ country, recipient }); if (it == influence.end()) { return {}; @@ -333,8 +289,8 @@ decltype(CRM::influence)::values_container_type const& CRM::get_influence_with_v return influence.values_container(); } -influence_priority_value_type CRM::get_influence_priority_with( // - CountryInstance const* country, CountryInstance const* recipient +influence_priority_value_type CRM::get_influence_priority_with( + CountryInstance const* country, CountryInstance const* recipient ) const { decltype(influence_priority)::const_iterator it = influence_priority.find({ country, recipient }); if (it == influence_priority.end()) { @@ -369,9 +325,7 @@ decltype(CRM::influence_priority)::values_container_type const& CRM::get_influen return influence_priority.values_container(); } -std::optional CRM::get_discredited_date( // - CountryInstance const* country, CountryInstance const* recipient -) const { +std::optional CRM::get_discredited_date(CountryInstance const* country, CountryInstance const* recipient) const { decltype(discredits)::const_iterator it = discredits.find({ country, recipient }); if (it == discredits.end()) { return {}; @@ -379,9 +333,7 @@ std::optional CRM::get_discredited_date( // return it->second; } -Date& CRM::assign_or_get_discredited_date( // - CountryInstance* country, CountryInstance const* recipient, Date default_value -) { +Date& CRM::assign_or_get_discredited_date(CountryInstance* country, CountryInstance const* recipient, Date default_value) { decltype(discredits)::iterator it = discredits.find({ country, recipient }); if (it == discredits.end()) { it = discredits.insert({ { country, recipient }, default_value }).first; @@ -389,9 +341,7 @@ Date& CRM::assign_or_get_discredited_date( // return it.value(); } -bool CRM::set_discredited_date( // - CountryInstance* country, CountryInstance const* recipient, Date value -) { +bool CRM::set_discredited_date(CountryInstance* country, CountryInstance const* recipient, Date value) { decltype(discredits)::iterator it = discredits.find({ country, recipient }); if (it == discredits.end()) { it = discredits.insert({ { country, recipient }, value }).first; @@ -405,9 +355,7 @@ decltype(CRM::discredits.values_container()) CRM::get_discredited_date_values() return discredits.values_container(); } -std::optional CRM::get_embassy_banned_date( // - CountryInstance const* country, CountryInstance const* recipient -) const { +std::optional CRM::get_embassy_banned_date(CountryInstance const* country, CountryInstance const* recipient) const { decltype(embassy_bans)::const_iterator it = embassy_bans.find({ country, recipient }); if (it == embassy_bans.end()) { return {}; @@ -415,9 +363,7 @@ std::optional CRM::get_embassy_banned_date( // return it->second; } -Date& CRM::assign_or_get_embassy_banned_date( // - CountryInstance* country, CountryInstance const* recipient, Date default_value -) { +Date& CRM::assign_or_get_embassy_banned_date(CountryInstance* country, CountryInstance const* recipient, Date default_value) { decltype(embassy_bans)::iterator it = embassy_bans.find({ country, recipient }); if (it == embassy_bans.end()) { it = embassy_bans.insert({ { country, recipient }, default_value }).first; @@ -425,9 +371,7 @@ Date& CRM::assign_or_get_embassy_banned_date( // return it.value(); } -bool CRM::set_embassy_banned_date( // - CountryInstance* country, CountryInstance const* recipient, Date value -) { +bool CRM::set_embassy_banned_date(CountryInstance* country, CountryInstance const* recipient, Date value) { decltype(embassy_bans)::iterator it = embassy_bans.find({ country, recipient }); if (it == embassy_bans.end()) { it = embassy_bans.insert({ { country, recipient }, value }).first; diff --git a/src/openvic-simulation/diplomacy/CountryRelation.hpp b/src/openvic-simulation/diplomacy/CountryRelation.hpp index a60b56ef2..26d6aabc8 100644 --- a/src/openvic-simulation/diplomacy/CountryRelation.hpp +++ b/src/openvic-simulation/diplomacy/CountryRelation.hpp @@ -24,10 +24,8 @@ namespace OpenVic { using base_type::base_type; inline constexpr auto operator<=>(UnorderedCountryInstancePair const& rhs) const { - const uintptr_t left1 = std::bit_cast(first), // - left2 = std::bit_cast(second), // - right1 = std::bit_cast(rhs.first), // - right2 = std::bit_cast(rhs.second); + const uintptr_t left1 = std::bit_cast(first), left2 = std::bit_cast(second), + right1 = std::bit_cast(rhs.first), right2 = std::bit_cast(rhs.second); using ordering = decltype(three_way_compare(std::tie(left1, left2), std::tie(right1, right2))); @@ -51,10 +49,8 @@ namespace OpenVic { } inline constexpr bool operator==(UnorderedCountryInstancePair const& rhs) const { - const uintptr_t left1 = std::bit_cast(first), // - left2 = std::bit_cast(second), // - right1 = std::bit_cast(rhs.first), // - right2 = std::bit_cast(rhs.second); + const uintptr_t left1 = std::bit_cast(first), left2 = std::bit_cast(second), + right1 = std::bit_cast(rhs.first), right2 = std::bit_cast(rhs.second); auto tied = std::tie(left1, left2); return tied == std::tie(right1, right2) || tied == std::tie(right2, right1); @@ -66,8 +62,7 @@ namespace std { template<> struct hash { size_t operator()(OpenVic::CountryInstancePair const& pair) const { - const uintptr_t first = std::bit_cast(pair.first), // - second = std::bit_cast(pair.second); + const uintptr_t first = std::bit_cast(pair.first), second = std::bit_cast(pair.second); std::size_t seed1 = 0; OpenVic::hash_combine(seed1, first); @@ -80,8 +75,7 @@ namespace std { template<> struct hash { size_t operator()(OpenVic::UnorderedCountryInstancePair const& pair) const { - const uintptr_t first = std::bit_cast(pair.first), // - second = std::bit_cast(pair.second); + const uintptr_t first = std::bit_cast(pair.first), second = std::bit_cast(pair.second); std::size_t seed1 = 0; OpenVic::hash_combine(seed1, first); @@ -172,8 +166,8 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& operator+=( // - influence_value_type& lhs, influence_value_type const& rhs + friend inline constexpr influence_value_type& operator+=( + influence_value_type& lhs, influence_value_type const& rhs ) { return lhs += rhs.value; } @@ -184,8 +178,8 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& operator-=( // - influence_value_type& lhs, influence_value_type const& rhs + friend inline constexpr influence_value_type& operator-=( + influence_value_type& lhs, influence_value_type const& rhs ) { return lhs -= rhs.value; } @@ -196,8 +190,8 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& operator*=( // - influence_value_type& lhs, influence_value_type const& rhs + friend inline constexpr influence_value_type& operator*=( + influence_value_type& lhs, influence_value_type const& rhs ) { return lhs *= rhs.value; } @@ -208,8 +202,8 @@ namespace OpenVic { return lhs; } - friend inline constexpr influence_value_type& operator/=( // - influence_value_type& lhs, influence_value_type const& rhs + friend inline constexpr influence_value_type& operator/=( + influence_value_type& lhs, influence_value_type const& rhs ) { return lhs /= rhs.value; } @@ -232,7 +226,7 @@ namespace OpenVic { }; enum class OpinionType : int8_t { - Hostile = -2, // + Hostile = -2, Opposed, Neutral, Cordial, @@ -280,9 +274,7 @@ public: \ decltype(discredits.values_container()) get_discredited_date_values() const; std::optional get_embassy_banned_date(CountryInstance const* country, CountryInstance const* recipient) const; - Date& assign_or_get_embassy_banned_date( // - CountryInstance* country, CountryInstance const* recipient, Date default_value - ); + Date& assign_or_get_embassy_banned_date(CountryInstance* country, CountryInstance const* recipient, Date default_value); bool set_embassy_banned_date(CountryInstance* country, CountryInstance const* recipient, Date value); decltype(embassy_bans.values_container()) get_embassy_banned_date_values() const; @@ -307,7 +299,7 @@ constexpr OpenVic::CountryRelationManager::OpinionType& operator++(OpenVic::Coun using underlying_type = std::underlying_type_t; type = static_cast(static_cast(type) + 1); type = static_cast(type) > - static_cast(OpenVic::CountryRelationManager::OpinionType::Sphere) // + static_cast(OpenVic::CountryRelationManager::OpinionType::Sphere) ? OpenVic::CountryRelationManager::OpinionType::Sphere : type; return type; @@ -323,7 +315,7 @@ constexpr OpenVic::CountryRelationManager::OpinionType& operator--(OpenVic::Coun using underlying_type = std::underlying_type_t; type = static_cast(static_cast(type) - 1); type = static_cast(type) < - static_cast(OpenVic::CountryRelationManager::OpinionType::Hostile) // + static_cast(OpenVic::CountryRelationManager::OpinionType::Hostile) ? OpenVic::CountryRelationManager::OpinionType::Hostile : type; return type; diff --git a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp index 58b5ac75a..0f89e7ff2 100644 --- a/src/openvic-simulation/diplomacy/DiplomaticAction.cpp +++ b/src/openvic-simulation/diplomacy/DiplomaticAction.cpp @@ -55,8 +55,8 @@ DiplomaticActionTickCache DiplomaticActionManager::create_diplomatic_action_tick type->visit([&](auto type) { CountryRelationManager::influence_value_type* influence = nullptr; if (type.influence_cost != 0) { - influence = &result.argument.instance_manager.get_country_relation_manager().assign_or_get_influence_with( // - result.argument.sender, result.argument.receiver + influence = &result.argument.instance_manager.get_country_relation_manager().assign_or_get_influence_with( + result.argument.sender, result.argument.receiver ); if (*influence < type.influence_cost) { return; @@ -86,9 +86,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // - arg.sender, arg.receiver, true - ); + arg.instance_manager.get_country_relation_manager().set_country_alliance(arg.sender, arg.receiver, true); }, } ); @@ -97,9 +95,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_country_alliance( // - arg.sender, arg.receiver, false - ); + arg.instance_manager.get_country_relation_manager().set_country_alliance(arg.sender, arg.receiver, false); }, } ); @@ -122,22 +118,22 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // - arg.sender, arg.receiver, true - ); + arg.instance_manager.get_country_relation_manager().set_has_military_access_to( + arg.sender, arg.receiver, true + ); }, } ); - result &= add_diplomatic_action( // - "give_military_access", - { - .commit = - [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_military_access_to( // - arg.sender, arg.receiver, true - ); - }, - } + result &= add_diplomatic_action( + "give_military_access", + { + .commit = + [](Argument& arg) { + arg.instance_manager.get_country_relation_manager().set_has_military_access_to( + arg.sender, arg.receiver, true + ); + }, + } ); result &= add_diplomatic_action( "increase_relations", @@ -174,9 +170,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // - arg.sender, arg.receiver, true - ); + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to(arg.sender, arg.receiver, true); }, } ); @@ -185,9 +179,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_war_subsidies_to( // - arg.sender, arg.receiver, false - ); + arg.instance_manager.get_country_relation_manager().set_war_subsidies_to(arg.sender, arg.receiver, false); }, } ); @@ -196,9 +188,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_at_war_with( // - arg.sender, arg.receiver, true - ); + arg.instance_manager.get_country_relation_manager().set_at_war_with(arg.sender, arg.receiver, true); }, } ); @@ -213,9 +203,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( // - arg.sender, arg.receiver - ) = true; + arg.instance_manager.get_country_relation_manager().assign_or_get_commands_units( + arg.sender, arg.receiver + ) = true; }, } ); @@ -225,9 +215,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 25, .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_discredited_date( // - arg.sender, arg.receiver, arg.instance_manager.get_today() + 180 - ); // TODO: implement defines.diplomacy.DISCREDIT_DAYS + arg.instance_manager.get_country_relation_manager().set_discredited_date( + arg.sender, arg.receiver, arg.instance_manager.get_today() + 180 + ); // TODO: implement defines.diplomacy.DISCREDIT_DAYS }, } ); @@ -244,9 +234,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 65, .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( // - arg.sender, arg.receiver, arg.instance_manager.get_today() + Timespan::from_years(1) - ); // TODO: implement defines.diplomacy.BANEMBASSY_DAYS + arg.instance_manager.get_country_relation_manager().set_embassy_banned_date( + arg.sender, arg.receiver, arg.instance_manager.get_today() + Timespan::from_years(1) + ); // TODO: implement defines.diplomacy.BANEMBASSY_DAYS }, } ); @@ -256,9 +246,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 50, .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - )++; + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( + arg.sender, arg.receiver + )++; }, .allowed = [](Argument const& arg) { @@ -272,9 +262,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 50, .commit = [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - std::any_cast(arg.context_data), arg.receiver - ); + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( + std::any_cast(arg.context_data), arg.receiver + ); }, .allowed = [](Argument const& arg) { @@ -288,9 +278,9 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 100, .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - ) = CountryRelationManager::OpinionType::Sphere; + arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( + arg.sender, arg.receiver + ) = CountryRelationManager::OpinionType::Sphere; }, .allowed = [](Argument const& arg) { @@ -304,12 +294,12 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 100, .commit = [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - std::any_cast(arg.context_data), arg.receiver - ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // - arg.sender, arg.receiver - ) -= 10; + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( + std::any_cast(arg.context_data), arg.receiver + ); + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) -= 10; }, .allowed = [](Argument const& arg) { @@ -323,12 +313,12 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { .influence_cost = 100, .commit = [](Argument& arg) { - --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( // - arg.sender, arg.receiver - ); - arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( // - arg.sender, arg.receiver - ) -= 10; + --arg.instance_manager.get_country_relation_manager().assign_or_get_country_opinion( + arg.sender, arg.receiver + ); + arg.instance_manager.get_country_relation_manager().assign_or_get_country_relation( + arg.sender, arg.receiver + ) -= 10; // TODO: implement REMOVEFROMSPHERE_PRESTIGE_COST and REMOVEFROMSPHERE_INFAMY_COST }, .allowed = @@ -348,9 +338,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // - arg.sender, arg.receiver, true - ); + arg.instance_manager.get_country_relation_manager().set_has_vision(arg.sender, arg.receiver, true); }, } ); @@ -359,9 +347,7 @@ bool DiplomaticActionManager::setup_diplomatic_actions() { { .commit = [](Argument& arg) { - arg.instance_manager.get_country_relation_manager().set_has_vision( // - arg.sender, arg.receiver, false - ); + arg.instance_manager.get_country_relation_manager().set_has_vision(arg.sender, arg.receiver, false); }, } ); diff --git a/src/openvic-simulation/misc/SoundEffect.cpp b/src/openvic-simulation/misc/SoundEffect.cpp index b856f51fd..903f9275e 100644 --- a/src/openvic-simulation/misc/SoundEffect.cpp +++ b/src/openvic-simulation/misc/SoundEffect.cpp @@ -5,10 +5,8 @@ using namespace OpenVic; using namespace OpenVic::NodeTools; -SoundEffect::SoundEffect( // - std::string_view new_identifier, std::filesystem::path&& new_file, fixed_point_t new_volume -) - : HasIdentifier { new_identifier }, file { std::move(new_file) }, volume { new_volume } {} +SoundEffect::SoundEffect(std::string_view new_identifier, std::filesystem::path&& new_file, fixed_point_t new_volume) : + HasIdentifier { new_identifier }, file { std::move(new_file) }, volume { new_volume } {} bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::string_view sfx_identifier, ast::NodeCPtr root) { std::filesystem::path file {}; @@ -22,14 +20,10 @@ bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::s }; fixed_point_t volume = 1; - bool ret = expect_dictionary_keys( - "file", - ONE_EXACTLY, - expect_string(file_callback), // - "volume", - ZERO_OR_ONE, - expect_fixed_point(assign_variable_callback(volume)) // - )(root); + bool ret = + expect_dictionary_keys("file", ONE_EXACTLY, expect_string(file_callback), "volume", ZERO_OR_ONE, expect_fixed_point(assign_variable_callback(volume)))( + root + ); if (sfx_identifier.empty()) { spdlog::error_s("Invalid sound identifier - empty!"); @@ -44,9 +38,7 @@ bool SoundEffectManager::_load_sound_define(Dataloader const& dataloader, std::s } bool SoundEffectManager::load_sound_defines_file(Dataloader const& dataloader, ast::NodeCPtr root) { - return expect_dictionary_reserve_length(sound_effects, // - [this, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { - return _load_sound_define(dataloader, key, value); - } - )(root); + return expect_dictionary_reserve_length(sound_effects, [this, &dataloader](std::string_view key, ast::NodeCPtr value) -> bool { + return _load_sound_define(dataloader, key, value); + })(root); } diff --git a/src/openvic-simulation/modifier/ModifierSum.hpp b/src/openvic-simulation/modifier/ModifierSum.hpp index 474c82bf6..724c45adc 100644 --- a/src/openvic-simulation/modifier/ModifierSum.hpp +++ b/src/openvic-simulation/modifier/ModifierSum.hpp @@ -49,7 +49,6 @@ namespace OpenVic { modifier { nullptr }, multiplier { fixed_point_t::_0 }, source { static_cast>(nullptr) }, excluded_targets {} {} - // constexpr modifier_entry_t( Modifier const& new_modifier, fixed_point_t new_multiplier, diff --git a/src/openvic-simulation/pathfinding/AStarPathing.cpp b/src/openvic-simulation/pathfinding/AStarPathing.cpp index 2df8f1544..bbe9e255b 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.cpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.cpp @@ -41,7 +41,7 @@ bool AStarPathing::_solve(search_iterator begin_point, search_iterator end_point // Find point closer to end_point, or same distance to end_point but closer to begin_point. if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // + (last_closest_point.value().abs_f_score >= p.value().abs_f_score && last_closest_point.value().g_score > p.value().g_score)) { last_closest_point = p; } diff --git a/src/openvic-simulation/pathfinding/AStarPathing.hpp b/src/openvic-simulation/pathfinding/AStarPathing.hpp index 0c27fec2c..997e03613 100644 --- a/src/openvic-simulation/pathfinding/AStarPathing.hpp +++ b/src/openvic-simulation/pathfinding/AStarPathing.hpp @@ -53,8 +53,8 @@ namespace OpenVic { }; protected: - virtual bool _solve( // - search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path + virtual bool _solve( + search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path ) override; }; diff --git a/src/openvic-simulation/pathfinding/FringePathing.cpp b/src/openvic-simulation/pathfinding/FringePathing.cpp index 93b212448..5bf5e3237 100644 --- a/src/openvic-simulation/pathfinding/FringePathing.cpp +++ b/src/openvic-simulation/pathfinding/FringePathing.cpp @@ -57,7 +57,7 @@ bool FringePathing::_solve(search_iterator begin_point, search_iterator end_poin // Find point closer to end_point, or same distance to end_point but closer to begin_point. if (last_closest_point == search.end() || last_closest_point.value().abs_f_score > p.value().abs_f_score || - (last_closest_point.value().abs_f_score >= p.value().abs_f_score && // + (last_closest_point.value().abs_f_score >= p.value().abs_f_score && last_closest_point.value().g_score > p.value().g_score)) { last_closest_point = p; } diff --git a/src/openvic-simulation/pathfinding/FringePathing.hpp b/src/openvic-simulation/pathfinding/FringePathing.hpp index 625c8dcfa..bf77a412a 100644 --- a/src/openvic-simulation/pathfinding/FringePathing.hpp +++ b/src/openvic-simulation/pathfinding/FringePathing.hpp @@ -40,8 +40,8 @@ namespace OpenVic { }; protected: - virtual bool _solve( // - search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path + virtual bool _solve( + search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path ) override; }; } diff --git a/src/openvic-simulation/pathfinding/PathingBase.hpp b/src/openvic-simulation/pathfinding/PathingBase.hpp index 50d29c7d0..a352207e5 100644 --- a/src/openvic-simulation/pathfinding/PathingBase.hpp +++ b/src/openvic-simulation/pathfinding/PathingBase.hpp @@ -26,7 +26,7 @@ namespace OpenVic { using search_container_type = std::vector; using search_map_type = tsl::ordered_map< search_key_type, - search_value_type, // + search_value_type, std::hash, std::equal_to, search_allocator_type, @@ -77,9 +77,7 @@ namespace OpenVic { return fp::sqrt(fixed_point_t { from_it.value().point->position.distance_squared(end_it.value().point->position) }); } - virtual bool _solve( // - search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path - ) = 0; + virtual bool _solve(search_iterator begin_point, search_iterator end_point, uint64_t pass, bool allow_partial_path) = 0; void _on_point_invalidated(search_key_type id) { search_const_iterator it = search.find(id); @@ -174,8 +172,8 @@ namespace OpenVic { return path; } - memory::vector get_point_path( // - PointMap::points_key_type from_id, PointMap::points_key_type to_id, bool allow_partial_path = false + memory::vector get_point_path( + PointMap::points_key_type from_id, PointMap::points_key_type to_id, bool allow_partial_path = false ) { OV_ERR_FAIL_COND_V(point_map == nullptr, memory::vector()); @@ -208,8 +206,8 @@ namespace OpenVic { }); } - memory::vector get_id_path( // - PointMap::points_key_type from_id, PointMap::points_key_type to_id, bool allow_partial_path = false + memory::vector get_id_path( + PointMap::points_key_type from_id, PointMap::points_key_type to_id, bool allow_partial_path = false ) { OV_ERR_FAIL_COND_V(point_map == nullptr, memory::vector()); diff --git a/src/openvic-simulation/pathfinding/PointMap.hpp b/src/openvic-simulation/pathfinding/PointMap.hpp index ff32cc5c9..efceab1d6 100644 --- a/src/openvic-simulation/pathfinding/PointMap.hpp +++ b/src/openvic-simulation/pathfinding/PointMap.hpp @@ -27,7 +27,7 @@ namespace OpenVic { using points_container_type = std::vector; using points_map_type = tsl::ordered_map< points_key_type, - points_value_type, // + points_value_type, std::hash, std::equal_to, points_allocator_type, @@ -39,7 +39,7 @@ namespace OpenVic { std::pair key; enum class Direction : uint8_t { - NONE = 0, // + NONE = 0, FORWARD = 1, BACKWARD = 2, BIDIRECTIONAL = FORWARD | BACKWARD @@ -91,7 +91,7 @@ namespace OpenVic { foonathan::memory::std_allocator>; using neighbors_container_type = std::vector; using neighbors_type = tsl::ordered_set< - neighbor_point_id_type, // + neighbor_point_id_type, std::hash, std::equal_to, neighbors_allocator_type, diff --git a/src/openvic-simulation/population/Pop.cpp b/src/openvic-simulation/population/Pop.cpp index 5007f3239..020d5db15 100644 --- a/src/openvic-simulation/population/Pop.cpp +++ b/src/openvic-simulation/population/Pop.cpp @@ -270,9 +270,11 @@ void Pop::update_gamestate( !is_culture_status_allowed(owner->get_allowed_regiment_cultures(), culture_status)) { max_supported_regiments = 0; } else { - max_supported_regiments = ( - type_safe::get(size) / (type_safe::get(military_defines.get_pop_size_per_regiment()) * pop_size_per_regiment_multiplier) // - ).floor() + 1; + max_supported_regiments = + (type_safe::get(size) / + (type_safe::get(military_defines.get_pop_size_per_regiment()) * pop_size_per_regiment_multiplier)) + .floor() + + 1; } } diff --git a/src/openvic-simulation/population/PopSum.hpp b/src/openvic-simulation/population/PopSum.hpp index 8bfe0aba8..a9580ee3e 100644 --- a/src/openvic-simulation/population/PopSum.hpp +++ b/src/openvic-simulation/population/PopSum.hpp @@ -32,15 +32,11 @@ namespace OpenVic { using ov_return_by_value = void; - friend inline constexpr fixed_point_t operator*( // - const SelfT lhs, const std::same_as auto rhs - ) { + friend inline constexpr fixed_point_t operator*(const SelfT lhs, const std::same_as auto rhs) { return type_safe::get(lhs) * rhs; } - friend inline constexpr fixed_point_t operator*( // - const std::same_as auto lhs, const SelfT rhs - ) { + friend inline constexpr fixed_point_t operator*(const std::same_as auto lhs, const SelfT rhs) { return lhs * type_safe::get(rhs); } @@ -49,15 +45,11 @@ namespace OpenVic { return lhs; } - friend inline constexpr fixed_point_t operator/( // - const SelfT lhs, const std::same_as auto rhs - ) { + friend inline constexpr fixed_point_t operator/(const SelfT lhs, const std::same_as auto rhs) { return type_safe::get(lhs) / rhs; } - friend inline constexpr fixed_point_t operator/( // - const std::same_as auto lhs, const SelfT rhs - ) { + friend inline constexpr fixed_point_t operator/(const std::same_as auto lhs, const SelfT rhs) { return lhs / type_safe::get(rhs); } diff --git a/src/openvic-simulation/scripts/ConditionalWeight.cpp b/src/openvic-simulation/scripts/ConditionalWeight.cpp index a11f526db..9caf3b6b5 100644 --- a/src/openvic-simulation/scripts/ConditionalWeight.cpp +++ b/src/openvic-simulation/scripts/ConditionalWeight.cpp @@ -10,10 +10,7 @@ using enum conditional_weight_type_t; template ConditionalWeight::ConditionalWeight( scope_type_t new_initial_scope, scope_type_t new_this_scope, scope_type_t new_from_scope -) : - initial_scope { new_initial_scope }, // - this_scope { new_this_scope }, // - from_scope { new_from_scope } {} +) : initial_scope { new_initial_scope }, this_scope { new_this_scope }, from_scope { new_from_scope } {} template static NodeCallback auto expect_modifier( diff --git a/src/openvic-simulation/utility/Logger.hpp b/src/openvic-simulation/utility/Logger.hpp index 26114a65b..1466a09a0 100644 --- a/src/openvic-simulation/utility/Logger.hpp +++ b/src/openvic-simulation/utility/Logger.hpp @@ -52,9 +52,8 @@ namespace spdlog { template log_s(level::level_enum level, format_string_t fmt, Args&&... args) -> log_s; template - log_s( // - std::shared_ptr const& logger, level::level_enum level, format_string_t fmt, Args&&... args - ) -> log_s; + log_s(std::shared_ptr const& logger, level::level_enum level, format_string_t fmt, Args&&... args) + -> log_s; template struct log_s { diff --git a/tests/src/core/DualAdjacent.cpp b/tests/src/core/DualAdjacent.cpp index 7c39f74f8..cf4059a07 100644 --- a/tests/src/core/DualAdjacent.cpp +++ b/tests/src/core/DualAdjacent.cpp @@ -18,9 +18,7 @@ using namespace OpenVic; namespace snitch { template - [[nodiscard]] inline static constexpr bool append( // - snitch::small_string_span ss, std::array array - ) noexcept { + [[nodiscard]] inline static constexpr bool append(snitch::small_string_span ss, std::array array) noexcept { if (array.empty()) { return append(ss, "{}"); } @@ -32,9 +30,7 @@ namespace snitch { } template - [[nodiscard]] inline static constexpr bool append( // - snitch::small_string_span ss, std::vector vector - ) noexcept { + [[nodiscard]] inline static constexpr bool append(snitch::small_string_span ss, std::vector vector) noexcept { if (vector.empty()) { return append(ss, "{}"); } @@ -146,9 +142,7 @@ TEST_CASE("remove_if_dual_adjacent", "[algorithm][dual-adjacent][remove_if_dual_ CHECK(remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), callback_none) == vector_down.end()); CHECK(remove_if_dual_adjacent(vector_spread.begin(), vector_spread.end(), callback_none) == vector_spread.end()); - CHECK( // - remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 1)) == vector_up.end() - ); + CHECK(remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 1)) == vector_up.end()); CHECK( remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 9)) == vector_down.end() ); @@ -157,8 +151,8 @@ TEST_CASE("remove_if_dual_adjacent", "[algorithm][dual-adjacent][remove_if_dual_ vector_spread.end() ); - CHECK( // - remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 9)) == vector_up.end() - 1 + CHECK( + remove_if_dual_adjacent(vector_up.begin(), vector_up.end(), std::bind_front(callback_bind, 9)) == vector_up.end() - 1 ); CHECK( remove_if_dual_adjacent(vector_down.begin(), vector_down.end(), std::bind_front(callback_bind, 1)) == diff --git a/tests/src/core/object/Approx.hpp b/tests/src/core/object/Approx.hpp index 95e9b4063..d2b802342 100644 --- a/tests/src/core/object/Approx.hpp +++ b/tests/src/core/object/Approx.hpp @@ -19,9 +19,7 @@ namespace OpenVic::testing { struct approx { constexpr approx(double value) : - _epsilon(static_cast(std::numeric_limits::epsilon()) * 100), // - _scale(1.0), // - _value(value) {} + _epsilon(static_cast(std::numeric_limits::epsilon()) * 100), _scale(1.0), _value(value) {} constexpr approx operator()(double value) const { approx approx(value); diff --git a/tests/src/core/object/Colour.hpp b/tests/src/core/object/Colour.hpp index 8e2a525dd..8dc3c2a33 100644 --- a/tests/src/core/object/Colour.hpp +++ b/tests/src/core/object/Colour.hpp @@ -9,8 +9,8 @@ namespace snitch { template - [[nodiscard]] inline static constexpr bool append( // - snitch::small_string_span ss, OpenVic::basic_colour_t const& s + [[nodiscard]] inline static constexpr bool append( + snitch::small_string_span ss, OpenVic::basic_colour_t const& s ) noexcept { if constexpr (std::decay_t::colour_traits::has_alpha) { return append(ss, "(", (int64_t)s.red, ",", (int64_t)s.green, ",", (int64_t)s.blue, ",", (int64_t)s.alpha, ")"); diff --git a/tests/src/core/object/Vector2.cpp b/tests/src/core/object/Vector2.cpp index b05f13625..a37992d1e 100644 --- a/tests/src/core/object/Vector2.cpp +++ b/tests/src/core/object/Vector2.cpp @@ -145,8 +145,8 @@ TEST_CASE("fvec2_t Operators", "[vec2_t][fvec2_t][fvec2_t-operators]") { CONSTEXPR_CHECK( decimal1 - decimal2 == testing::approx_vec2 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON) // + (1.1_a).epsilon(testing::INACCURATE_EPSILON), + (1.5_a).epsilon(testing::INACCURATE_EPSILON), } ); CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec2 { 0.25, 1.375 }); @@ -154,8 +154,8 @@ TEST_CASE("fvec2_t Operators", "[vec2_t][fvec2_t][fvec2_t-operators]") { CONSTEXPR_CHECK( decimal1 * decimal2 == testing::approx_vec2 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON) // + (2.76_a).epsilon(testing::INACCURATE_EPSILON), + (16.66_a).epsilon(testing::INACCURATE_EPSILON), } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec2 { 0.375, 0.1875 }); diff --git a/tests/src/core/object/Vector3.cpp b/tests/src/core/object/Vector3.cpp index 355805d53..8c9759453 100644 --- a/tests/src/core/object/Vector3.cpp +++ b/tests/src/core/object/Vector3.cpp @@ -117,7 +117,7 @@ TEST_CASE("dvec3_t Length methods", "[vec3_t][dvec3_t][dvec3_t-length]") { TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; - static constexpr fixed_point_t _7_80 = // + static constexpr fixed_point_t _7_80 = fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _1_20 = fixed_point_t::_0_20 * 6; @@ -140,9 +140,9 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { CONSTEXPR_CHECK( decimal1 - decimal2 == testing::approx_vec3 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON), // - (2.2_a).epsilon(testing::INACCURATE_EPSILON) // + (1.1_a).epsilon(testing::INACCURATE_EPSILON), + (1.5_a).epsilon(testing::INACCURATE_EPSILON), + (2.2_a).epsilon(testing::INACCURATE_EPSILON), } ); CONSTEXPR_CHECK(power1 - power2 == testing::approx_vec3(0.25, 1.375, 0.375)); @@ -150,9 +150,9 @@ TEST_CASE("fvec3_t Operators", "[vec3_t][fvec3_t][fvec3_t-operators]") { CONSTEXPR_CHECK( decimal1 * decimal2 == testing::approx_vec3 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON), // - (43.68_a).epsilon(testing::INACCURATE_EPSILON) // + (2.76_a).epsilon(testing::INACCURATE_EPSILON), + (16.66_a).epsilon(testing::INACCURATE_EPSILON), + (43.68_a).epsilon(testing::INACCURATE_EPSILON), } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec3(0.375, 0.1875, 0.15625)); diff --git a/tests/src/core/object/Vector4.cpp b/tests/src/core/object/Vector4.cpp index 0747b654f..fcae26d54 100644 --- a/tests/src/core/object/Vector4.cpp +++ b/tests/src/core/object/Vector4.cpp @@ -117,7 +117,7 @@ TEST_CASE("dvec4_t Length methods", "[vec4_t][dvec4_t][dvec4_t-length]") { TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { static constexpr fixed_point_t _2_30 = fixed_point_t::_2 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _4_90 = fixed_point_t::_4 + fixed_point_t::_0_50 + fixed_point_t::_0_20 * 2; - static constexpr fixed_point_t _7_80 = // + static constexpr fixed_point_t _7_80 = fixed_point_t::_4 + fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_50 + fixed_point_t::_0_20 + fixed_point_t::_0_10; static constexpr fixed_point_t _3_20 = fixed_point_t::_2 + fixed_point_t::_1 + fixed_point_t::_0_20; @@ -142,10 +142,10 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK( decimal1 - decimal2 == testing::approx_vec4 { - (1.1_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON), // - (2.2_a).epsilon(testing::INACCURATE_EPSILON), // - (1.5_a).epsilon(testing::INACCURATE_EPSILON) // + (1.1_a).epsilon(testing::INACCURATE_EPSILON), + (1.5_a).epsilon(testing::INACCURATE_EPSILON), + (2.2_a).epsilon(testing::INACCURATE_EPSILON), + (1.5_a).epsilon(testing::INACCURATE_EPSILON), } ); @@ -154,10 +154,10 @@ TEST_CASE("fvec4_t Operators", "[vec4_t][fvec4_t][fvec4_t-operators]") { CONSTEXPR_CHECK( decimal1 * decimal2 == testing::approx_vec4 { - (2.76_a).epsilon(testing::INACCURATE_EPSILON), // - (16.66_a).epsilon(testing::INACCURATE_EPSILON), // - (43.68_a).epsilon(testing::INACCURATE_EPSILON), // - (5.44_a).epsilon(testing::INACCURATE_EPSILON) // + (2.76_a).epsilon(testing::INACCURATE_EPSILON), + (16.66_a).epsilon(testing::INACCURATE_EPSILON), + (43.68_a).epsilon(testing::INACCURATE_EPSILON), + (5.44_a).epsilon(testing::INACCURATE_EPSILON), } ); CONSTEXPR_CHECK(power1 * power2 == testing::approx_vec4(0.375, 0.1875, 0.15625, 0.09375)); diff --git a/tests/src/core/string/StringLiteral.cpp b/tests/src/core/string/StringLiteral.cpp index 2f2a6dfd9..a0aa874f8 100644 --- a/tests/src/core/string/StringLiteral.cpp +++ b/tests/src/core/string/StringLiteral.cpp @@ -20,8 +20,8 @@ using namespace std::string_view_literals; namespace snitch { template - [[nodiscard]] inline static constexpr bool append( // - snitch::small_string_span ss, OpenVic::string_literal const& s + [[nodiscard]] inline static constexpr bool append( + snitch::small_string_span ss, OpenVic::string_literal const& s ) noexcept { return append(ss, s.as_string_view()); } diff --git a/tests/src/dataloader/NodeTools.cpp b/tests/src/dataloader/NodeTools.cpp index 5d769ce07..ad44251f6 100644 --- a/tests/src/dataloader/NodeTools.cpp +++ b/tests/src/dataloader/NodeTools.cpp @@ -203,21 +203,13 @@ struct Ast : ovdl::SymbolIntern { }; TEST_CASE("NodeTools AST get_type_name", "[NodeTools][NodeTools-ast-get_type_name]") { - CONSTEXPR_CHECK( // - ast::get_type_name(ovdl::v2script::ast::NodeKind::FileTree) == "ovdl::v2script::ast::FileTree"sv - ); + CONSTEXPR_CHECK(ast::get_type_name(ovdl::v2script::ast::NodeKind::FileTree) == "ovdl::v2script::ast::FileTree"sv); CONSTEXPR_CHECK( ast::get_type_name(ovdl::v2script::ast::NodeKind::IdentifierValue) == "ovdl::v2script::ast::IdentifierValue"sv ); - CONSTEXPR_CHECK( // - ast::get_type_name(ovdl::v2script::ast::NodeKind::StringValue) == "ovdl::v2script::ast::StringValue"sv - ); - CONSTEXPR_CHECK( // - ast::get_type_name(ovdl::v2script::ast::NodeKind::ListValue) == "ovdl::v2script::ast::ListValue"sv - ); - CONSTEXPR_CHECK( // - ast::get_type_name(ovdl::v2script::ast::NodeKind::NullValue) == "ovdl::v2script::ast::NullValue"sv - ); + CONSTEXPR_CHECK(ast::get_type_name(ovdl::v2script::ast::NodeKind::StringValue) == "ovdl::v2script::ast::StringValue"sv); + CONSTEXPR_CHECK(ast::get_type_name(ovdl::v2script::ast::NodeKind::ListValue) == "ovdl::v2script::ast::ListValue"sv); + CONSTEXPR_CHECK(ast::get_type_name(ovdl::v2script::ast::NodeKind::NullValue) == "ovdl::v2script::ast::NullValue"sv); CONSTEXPR_CHECK( ast::get_type_name(ovdl::v2script::ast::NodeKind::EventStatement) == "ovdl::v2script::ast::EventStatement"sv ); diff --git a/tests/src/types/Signal.cpp b/tests/src/types/Signal.cpp index da92adf83..11d070471 100644 --- a/tests/src/types/Signal.cpp +++ b/tests/src/types/Signal.cpp @@ -49,7 +49,6 @@ struct test_struct { void func_cv(int& sum, int i) const volatile { sum += i; } - // void unique_func(int& sum, int i) const { sum += i + 1; @@ -411,7 +410,6 @@ TEMPLATE_LIST_TEST_CASE("signal Disconnect methods", "[signal][signal-disconnect // TODO: Add windows linker option /OPT:NOICF? signal.connect(&test_struct::unique_func, &p1); signal.connect(&test_struct::unique_func, &p2); - // signal(sum, 1); CHECK(sum == 6); CHECK(signal.disconnect(&test_struct::unique_func, &p2) == 1); @@ -429,7 +427,6 @@ TEMPLATE_LIST_TEST_CASE("signal Disconnect methods", "[signal][signal-disconnect // TODO: Add windows linker option /OPT:NOICF? signal.connect(&test_struct::unique_func, p1); signal.connect(&test_struct::unique_func, p2); - // signal(sum, 1); CHECK(sum == 6); CHECK(signal.disconnect(&test_struct::unique_func, p2) == 1);