From dc29f5962dd43a652fd5549ce6ed154b7f0fbbaf Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 8 Feb 2024 21:40:43 -0800 Subject: [PATCH 1/5] Move CDClientManager to be a namespace (#1431) Tested that worlds still load data as expected. Had no use being a singleton anyways. --- dDatabase/CDClientDatabase/CDClientManager.h | 5 +-- .../CDClientTables/CDLootTableTable.cpp | 4 +- dGame/Entity.cpp | 22 +++++------ dGame/LeaderboardManager.cpp | 2 +- dGame/dBehaviors/Behavior.cpp | 10 ++--- dGame/dBehaviors/OverTimeBehavior.cpp | 2 +- dGame/dComponents/ActivityComponent.cpp | 10 ++--- dGame/dComponents/BaseCombatAIComponent.cpp | 4 +- dGame/dComponents/BuffComponent.cpp | 2 +- dGame/dComponents/CharacterComponent.cpp | 2 +- dGame/dComponents/DestroyableComponent.cpp | 4 +- dGame/dComponents/InventoryComponent.cpp | 18 ++++----- .../dComponents/LevelProgressionComponent.cpp | 2 +- dGame/dComponents/MissionComponent.cpp | 10 ++--- dGame/dComponents/MissionOfferComponent.cpp | 4 +- dGame/dComponents/MovementAIComponent.cpp | 4 +- dGame/dComponents/PetComponent.cpp | 2 +- dGame/dComponents/PhantomPhysicsComponent.cpp | 8 ++-- .../dComponents/PropertyEntranceComponent.cpp | 2 +- dGame/dComponents/RacingControlComponent.cpp | 2 +- dGame/dComponents/RailActivatorComponent.cpp | 2 +- dGame/dComponents/RenderComponent.cpp | 4 +- dGame/dComponents/SkillComponent.cpp | 2 +- dGame/dComponents/VendorComponent.cpp | 12 +++--- dGame/dGameMessages/GameMessageHandler.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 16 ++++---- dGame/dGameMessages/PropertyDataMessage.cpp | 2 +- dGame/dInventory/Inventory.cpp | 6 +-- dGame/dInventory/Item.cpp | 10 ++--- dGame/dInventory/ItemSet.cpp | 4 +- dGame/dMission/Mission.cpp | 10 ++--- dGame/dMission/MissionPrerequisites.cpp | 2 +- dGame/dUtilities/Loot.cpp | 38 +++++++++---------- dGame/dUtilities/SlashCommandHandler.cpp | 4 +- dMasterServer/InstanceManager.cpp | 4 +- dMasterServer/MasterServer.cpp | 11 ------ .../02_server/Map/General/QbEnemyStunner.cpp | 4 +- .../FireFirstSkillonStartup.cpp | 4 +- dWorldServer/PerformanceManager.cpp | 2 +- dWorldServer/WorldServer.cpp | 2 +- dZoneManager/Level.cpp | 2 +- dZoneManager/Zone.cpp | 2 +- dZoneManager/dZoneManager.cpp | 4 +- tests/dGameTests/GameDependencies.h | 2 +- 44 files changed, 128 insertions(+), 142 deletions(-) diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index ae628a36..21a6e3cd 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -9,10 +9,7 @@ /** * Initialize the CDClient tables so they are all loaded into memory. */ -class CDClientManager : public Singleton { -public: - CDClientManager() = default; - +namespace CDClientManager { void LoadValuesFromDatabase(); void LoadValuesFromDefaults(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index a90f8108..7d04db13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -6,8 +6,8 @@ // Sort the tables by their rarity so the highest rarity items are first. void SortTable(LootTableEntries& table) { - auto* componentsRegistryTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); + auto* componentsRegistryTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); // We modify the table in place so the outer loop keeps track of what is sorted // and the inner loop finds the highest rarity item and swaps it with the current position // of the outer loop. diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 50ef5df2..84bdca21 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -215,7 +215,7 @@ void Entity::Initialize() { } // Get the registry table - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); /** * Special case for BBB models. They have components not corresponding to the registry. @@ -369,7 +369,7 @@ void Entity::Initialize() { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); bool isSmashable = GetVarAs(u"is_smashable") != 0; @@ -404,7 +404,7 @@ void Entity::Initialize() { uint32_t npcMinLevel = destCompData[0].level; uint32_t currencyIndex = destCompData[0].CurrencyIndex; - CDCurrencyTableTable* currencyTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTable = CDClientManager::GetTable(); std::vector currencyValues = currencyTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == currencyIndex && entry.npcminlevel == npcMinLevel); }); if (currencyValues.size() > 0) { @@ -489,7 +489,7 @@ void Entity::Initialize() { * This is a bit of a mess */ - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; @@ -538,7 +538,7 @@ void Entity::Initialize() { // ZoneControl script if (m_TemplateID == 2365) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const auto zoneID = Game::zoneManager->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); @@ -561,7 +561,7 @@ void Entity::Initialize() { if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD) > 0) { auto* quickBuildComponent = AddComponent(); - CDRebuildComponentTable* rebCompTable = CDClientManager::Instance().GetTable(); + CDRebuildComponentTable* rebCompTable = CDClientManager::GetTable(); std::vector rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == quickBuildComponentID); }); if (rebCompData.size() > 0) { @@ -685,7 +685,7 @@ void Entity::Initialize() { int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { - CDMovementAIComponentTable* moveAITable = CDClientManager::Instance().GetTable(); + CDMovementAIComponentTable* moveAITable = CDClientManager::GetTable(); std::vector moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); if (moveAIComp.size() > 0) { @@ -749,7 +749,7 @@ void Entity::Initialize() { int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { - CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance().GetTable(); + CDProximityMonitorComponentTable* proxCompTable = CDClientManager::GetTable(); std::vector proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); @@ -1665,7 +1665,7 @@ void Entity::PickupItem(const LWOOBJID& objectID) { auto* characterComponent = GetComponent(); if (!inv || !characterComponent) return; - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); auto& droppedLoot = characterComponent->GetDroppedLoot(); @@ -1678,10 +1678,10 @@ void Entity::PickupItem(const LWOOBJID& objectID) { const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { - CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 1fd49d26..ba9055a7 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -402,7 +402,7 @@ Leaderboard::Type LeaderboardManager::GetLeaderboardType(const GameID gameID) { auto lookup = leaderboardCache.find(gameID); if (lookup != leaderboardCache.end()) return lookup->second; - auto* activitiesTable = CDClientManager::Instance().GetTable(); + auto* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([gameID](const CDActivities& entry) { return entry.ActivityID == gameID; }); diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index c70b34c7..64bb03f5 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -82,7 +82,7 @@ CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { if (BehaviorParameterTable == nullptr) { - BehaviorParameterTable = CDClientManager::Instance().GetTable(); + BehaviorParameterTable = CDClientManager::GetTable(); } const auto pair = Cache.find(behaviorId); @@ -297,7 +297,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; // Find behavior template by its behavior id. Default to 0. @@ -405,7 +405,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID } Behavior::Behavior(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); CDBehaviorTemplate templateInDatabase{}; @@ -448,7 +448,7 @@ Behavior::Behavior(const uint32_t behaviorId) { float Behavior::GetFloat(const std::string& name, const float defaultValue) const { // Get the behavior parameter entry and return its value. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } @@ -476,7 +476,7 @@ Behavior* Behavior::GetAction(float value) const { std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); if (BehaviorParameterTable) { templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index bdef2eb6..f66a5253 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -41,7 +41,7 @@ void OverTimeBehavior::Load() { m_Action = GetInt("action"); // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; m_Delay = GetFloat("delay"); diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index 60a95952..376251d2 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -46,7 +46,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo if (destroyableComponent) { // First lookup the loot matrix id for this component id. - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) {return (entry.LootMatrixIndex == destroyableComponent->GetLootMatrixID()); }); uint32_t startingLMI = 0; @@ -70,7 +70,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo } } void ActivityComponent::LoadActivityData(const int32_t activityId) { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([activityId](CDActivities entry) {return (entry.ActivityID == activityId); }); bool soloRacing = Game::config->GetValue("solo_racing") == "1"; @@ -106,7 +106,7 @@ void ActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti } void ActivityComponent::ReloadConfig() { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([this](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (auto activity : activities) { auto mapID = m_ActivityInfo.instanceMapID; @@ -545,14 +545,14 @@ void ActivityInstance::RewardParticipant(Entity* participant) { } // First, get the activity data - auto* activityRewardsTable = CDClientManager::Instance().GetTable(); + auto* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([this](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); }); if (!activityRewards.empty()) { uint32_t minCoins = 0; uint32_t maxCoins = 0; - auto* currencyTableTable = CDClientManager::Instance().GetTable(); + auto* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == activityRewards[0].CurrencyIndex && entry.npcminlevel == 1); }); if (!currencyTable.empty()) { diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 21909d5f..17183409 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -107,10 +107,10 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): int32_t collisionGroup = (COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_ENEMY); - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 10ac4ebb..cdf1d5bc 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -164,7 +164,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) { if (parameter.name == "overtime") { - auto* behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto* behaviorTemplateTable = CDClientManager::GetTable(); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; stacks = static_cast(parameter.values[1]); diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 61b744f1..e4e2ba4b 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -770,7 +770,7 @@ void CharacterComponent::AwardClaimCodes() { auto rewardCodes = Database::Get()->GetRewardCodesByAccountID(user->GetAccountID()); if (rewardCodes.empty()) return; - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); for (auto const rewardCode : rewardCodes) { LOG_DEBUG("Processing RewardCode %i", rewardCode); const uint32_t rewardCodeIndex = rewardCode >> 6; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index fd89da4d..68271f26 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -81,7 +81,7 @@ DestroyableComponent::~DestroyableComponent() { } void DestroyableComponent::Reinitialize(LOT templateID) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); @@ -92,7 +92,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (componentID > 0) { diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 97c1198b..591e0505 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -55,10 +55,10 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do return; } - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); - auto* inventoryComponentTable = CDClientManager::Instance().GetTable(); + auto* inventoryComponentTable = CDClientManager::GetTable(); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); auto slot = 0u; @@ -909,11 +909,11 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -924,11 +924,11 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { } void InventoryComponent::UnequipScripts(Item* unequippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -1280,7 +1280,7 @@ bool InventoryComponent::IsTransferInventory(eInventoryType type) { } uint32_t InventoryComponent::FindSkill(const LOT lot) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); @@ -1298,8 +1298,8 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) { std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; - auto* table = CDClientManager::Instance().GetTable(); - auto* behaviors = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); + auto* behaviors = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 3a18b19c..d271f97b 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -44,7 +44,7 @@ void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool } void LevelProgressionComponent::HandleLevelUp() { - auto* rewardsTable = CDClientManager::Instance().GetTable(); + auto* rewardsTable = CDClientManager::GetTable(); const auto& rewards = rewardsTable->GetByLevelID(m_Level); bool rewardingItem = rewards.size() > 0; diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 7219589a..151fcf2f 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -266,7 +266,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missions = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -320,8 +320,8 @@ const std::vector MissionComponent::LookForAchievements(eMissionTaskTy return acceptedAchievements; #else - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { return entry.taskType == static_cast(type); @@ -407,8 +407,8 @@ const std::vector& MissionComponent::QueryAchievements(eMissionTaskTyp } // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); std::vector result; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 25d4a739..7f26ed72 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -40,7 +40,7 @@ bool OfferedMission::GetAcceptsMission() const { //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); @@ -48,7 +48,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot const uint32_t componentId = value; // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance().GetTable(); + auto* missionNpcComponentTable = CDClientManager::GetTable(); auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 1332fd07..8377031a 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -244,8 +244,8 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { return it->second; } - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0c377ac7..1af65b4e 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -71,7 +71,7 @@ std::map PetComponent::petFlags = { }; PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Component{ parentEntity } { - m_PetInfo = CDClientManager::Instance().GetTable()->GetByID(componentId); // TODO: Make reference when safe + m_PetInfo = CDClientManager::GetTable()->GetByID(componentId); // TODO: Make reference when safe m_ComponentId = componentId; m_Interaction = LWOOBJID_EMPTY; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 217a02fb..b3021415 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -143,10 +143,10 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon */ if (!m_HasCreatedPhysics) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; @@ -260,10 +260,10 @@ void PhantomPhysicsComponent::CreatePhysics() { y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); } else { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 2bb6ea30..ab3bb5da 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -18,7 +18,7 @@ PropertyEntranceComponent::PropertyEntranceComponent(Entity* parent, uint32_t componentID) : Component(parent) { this->propertyQueries = {}; - auto table = CDClientManager::Instance().GetTable(); + auto table = CDClientManager::GetTable(); const auto& entry = table->GetByID(componentID); this->m_MapID = entry.mapID; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 824e7f36..f3772aad 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -53,7 +53,7 @@ RacingControlComponent::RacingControlComponent(Entity* parent) if (Game::zoneManager->CheckIfAccessibleZone((worldID / 10) * 10)) m_MainWorld = (worldID / 10) * 10; m_ActivityID = 42; - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.instanceMapID == worldID); }); for (CDActivities activity : activities) m_ActivityID = activity.ActivityID; } diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index e0eb035a..f269da49 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -13,7 +13,7 @@ RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance().GetTable()->GetEntryByID(componentID);; + const auto tableData = CDClientManager::GetTable()->GetEntryByID(componentID);; m_Path = parent->GetVar(u"rail_path"); m_PathDirection = parent->GetVar(u"rail_path_direction"); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 449fbc4d..d5866917 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -27,7 +27,7 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo if (!result.eof()) { auto animationGroupIDs = std::string(result.getStringField("animationGroupIDs", "")); if (!animationGroupIDs.empty()) { - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { int32_t groupIdInt; @@ -165,7 +165,7 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* renderComponent = self->GetComponent(); if (!renderComponent) return returnlength; - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); if (animationGroup.FoundData()) { diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index b65c7d21..c43813c1 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -234,7 +234,7 @@ bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LW // if it's not in the cache look it up and cache it if (pair == m_skillBehaviorCache.end()) { - auto skillTable = CDClientManager::Instance().GetTable(); + auto skillTable = CDClientManager::GetTable(); behaviorId = skillTable->GetSkillByID(skillId).behaviorID; m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); } else { diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index dfea33df..afa3d013 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -41,14 +41,14 @@ void VendorComponent::RefreshInventory(bool isCreation) { return; } - auto* lootMatrixTable = CDClientManager::Instance().GetTable(); + auto* lootMatrixTable = CDClientManager::GetTable(); const auto& lootMatrices = lootMatrixTable->GetMatrix(m_LootMatrixID); if (lootMatrices.empty()) return; - auto* lootTableTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* lootTableTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); for (const auto& lootMatrix : lootMatrices) { auto vendorItems = lootTableTable->GetTable(lootMatrix.LootTableIndex); @@ -101,10 +101,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { } void VendorComponent::SetupConstants() { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); - auto* vendorComponentTable = CDClientManager::Instance().GetTable(); + auto* vendorComponentTable = CDClientManager::GetTable(); std::vector vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); if (vendorComps.empty()) return; auto vendorData = vendorComps.at(0); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 07df3c60..64790e31 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -290,7 +290,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index a81fec70..8b4d1f05 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -1116,7 +1116,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, // Currency and powerups should not sync if (team != nullptr && currency == 0) { - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); const CDObjects& object = objectsTable->GetByID(item); @@ -4686,8 +4686,8 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti return; } - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4778,8 +4778,8 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4828,8 +4828,8 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -5041,7 +5041,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (emoteID == 0) return; std::string sAnimationName = "deaded"; //Default name in case we fail to get the emote - CDEmoteTableTable* emotes = CDClientManager::Instance().GetTable(); + CDEmoteTableTable* emotes = CDClientManager::GetTable(); if (emotes) { CDEmoteTable* emote = emotes->GetEmote(emoteID); if (emote) sAnimationName = emote->animationName; diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 29bc8ea9..ab7fe9c3 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -103,7 +103,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance().GetTable()->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::GetTable()->GetByMapID(mapID); TemplateID = propertyTemplate.id; ZoneId = propertyTemplate.mapID; diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 4475f77b..35222bea 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -275,9 +275,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { } const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); - auto* itemComponents = CDClientManager::Instance().GetTable(); + auto* itemComponents = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); @@ -293,7 +293,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { } bool Inventory::IsValidItem(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4a13cd92..55b0a2d0 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -247,7 +247,7 @@ bool Item::IsEquipped() const { } bool Item::Consume() { - auto* skillsTable = CDClientManager::Instance().GetTable(); + auto* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([this](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); @@ -313,12 +313,12 @@ void Item::UseNonEquip(Item* item) { bool success = false; auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance().GetTable(); + auto* packCompTable = CDClientManager::GetTable(); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast(packageComponentId); }); auto success = !packages.empty(); @@ -396,7 +396,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } void Item::DisassembleModel(uint32_t numToDismantle) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); @@ -481,7 +481,7 @@ void Item::DisassembleModel(uint32_t numToDismantle) { currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - auto* brickIDTable = CDClientManager::Instance().GetTable(); + auto* brickIDTable = CDClientManager::GetTable(); // Second iteration actually distributes the bricks for (const auto& [part, count] : parts) { diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 3364b63b..54db9e9c 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -129,7 +129,7 @@ void ItemSet::OnEquip(const LOT lot) { auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -161,7 +161,7 @@ void ItemSet::OnUnEquip(const LOT lot) { const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 40ab0688..4ed80bf3 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -41,7 +41,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_State = eMissionState::UNKNOWN; - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto* mis = missionsTable->GetPtrByMissionID(missionId); info = *mis; @@ -52,7 +52,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { return; } - auto* tasksTable = CDClientManager::Instance().GetTable(); + auto* tasksTable = CDClientManager::GetTable(); auto tasks = tasksTable->GetByMissionID(missionId); @@ -180,7 +180,7 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -190,7 +190,7 @@ bool Mission::IsValidMission(const uint32_t missionId) { } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -334,7 +334,7 @@ void Mission::Complete(const bool yieldRewards) { missionComponent->Progress(eMissionTaskType::RACING, info.id, static_cast(eRacingTaskParam::COMPLETE_TRACK_TASKS)); - auto* missionEmailTable = CDClientManager::Instance().GetTable(); + auto* missionEmailTable = CDClientManager::GetTable(); const auto missionId = GetMissionId(); diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 89d547fd..b5b81160 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -161,7 +161,7 @@ bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::uno return index->second->Execute(missions); } - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); }); diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 25c81e74..b2f96ac3 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -28,11 +28,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { return; } CachedMatrices.insert(matrixIndex); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -47,11 +47,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { } std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); auto* missionComponent = player->GetComponent(); std::unordered_map drops; @@ -134,11 +134,11 @@ std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t m } std::unordered_map Loot::RollLootMatrix(uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); std::unordered_map drops; const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -216,7 +216,7 @@ void Loot::GiveLoot(Entity* player, std::unordered_map& result, eL } void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -232,7 +232,7 @@ void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { @@ -286,7 +286,7 @@ void Loot::DropLoot(Entity* player, Entity* killedObject, std::unordered_map(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -303,7 +303,7 @@ void Loot::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 0b5133ff..ef12c396 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1899,7 +1899,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setrewardcode" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); auto id = cdrewardCodes->GetCodeID(args[0]); if (id != -1) Database::Get()->InsertRewardCode(user->GetAccountID(), id); @@ -1960,7 +1960,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::entityManager->SerializeEntity(closest); - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto& info = table->GetByID(closest->GetLOT()); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a5a6d8dc..a46ed81a 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -322,7 +322,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) { } int InstanceManager::GetSoftCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -335,7 +335,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { } int InstanceManager::GetHardCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f15bb9a9..749b4130 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -177,17 +177,6 @@ int main(int argc, char** argv) { // Run migrations should any need to be run. MigrationRunner::RunSQLiteMigrations(); - //Get CDClient initial information - try { - CDClientManager::Instance(); - } catch (CppSQLite3Exception& e) { - LOG("Failed to initialize CDServer SQLite Database"); - LOG("May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. if (argc > 1 && diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 8291f409..2238c410 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -17,12 +17,12 @@ void QbEnemyStunner::OnQuickBuildComplete(Entity* self, Entity* target) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); std::map skillBehaviorMap; // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); diff --git a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp index 389f3621..0220711d 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -11,12 +11,12 @@ void FireFirstSkillonStartup::OnStartup(Entity* self) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); // Should parent entity be null, make the originator self. diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 248be54a..052d075b 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -70,7 +70,7 @@ std::map PerformanceManager::m_Profiles = { void PerformanceManager::SelectProfile(LWOMAPID mapID) { // Try to get it from zoneTable - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); if (zone) { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 550fc7ee..6df5d0da 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -180,7 +180,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - CDClientManager::Instance().LoadValuesFromDatabase(); + CDClientManager::LoadValuesFromDatabase(); Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 0a46dc89..2606b46f 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -208,7 +208,7 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); - CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance().GetTable(); + CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; gating.major = 1; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 3f306c05..42ce1215 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -154,7 +154,7 @@ void Zone::LoadZoneIntoMemory() { std::string Zone::GetFilePathForZoneID() { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { std::string toReturn = "maps/" + zone->zoneName; diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 3aa35485..09baabed 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -29,7 +29,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { LOT zoneControlTemplate = 2365; - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); @@ -208,7 +208,7 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { bool dZoneManager::CheckIfAccessibleZone(LWOMAPID zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 11c320ba..5d9c99bf 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -36,7 +36,7 @@ protected: Game::entityManager = new EntityManager(); // Create a CDClientManager instance and load from defaults - CDClientManager::Instance().LoadValuesFromDefaults(); + CDClientManager::LoadValuesFromDefaults(); } void TearDownDependencies() { From d2aeebcd46d1b5fbc9177a53915fda898faee1da Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 9 Feb 2024 05:37:58 -0800 Subject: [PATCH 2/5] chore: Move database storage containers to be translation unit local to allow for safe references (#1434) * Move CDClientManager to be a namespace Tested that worlds still load data as expected. Had no use being a singleton anyways. * Move cdclient data storage to tu local containers Allows some data from these containers to be saved on object by reference instead of always needing to copy. iteration 2 - move all unnamed namespace containers to a singular spot - use macro for template specialization and variable declaration - use templates to allow for as little copy paste of types and functions as possible * remember to use typename! compiler believes T::StorageType is accessing a member, not a type. * Update CDClientManager.cpp * move to cpp? --- .../CDClientDatabase/CDClientManager.cpp | 50 +++++++++++++++++++ dDatabase/CDClientDatabase/CDClientManager.h | 34 ++++++++++--- .../CDClientTables/CDActivitiesTable.cpp | 8 +-- .../CDClientTables/CDActivitiesTable.h | 7 +-- .../CDClientTables/CDActivityRewardsTable.cpp | 8 +-- .../CDClientTables/CDActivityRewardsTable.h | 8 +-- .../CDClientTables/CDAnimationsTable.cpp | 31 +++++++----- .../CDClientTables/CDAnimationsTable.h | 20 +++----- .../CDBehaviorParameterTable.cpp | 21 +++++--- .../CDClientTables/CDBehaviorParameterTable.h | 10 ++-- .../CDBehaviorTemplateTable.cpp | 29 ++++------- .../CDClientTables/CDBehaviorTemplateTable.h | 12 +---- .../CDClientTables/CDBrickIDTableTable.cpp | 13 ++--- .../CDClientTables/CDBrickIDTableTable.h | 7 +-- .../CDComponentsRegistryTable.cpp | 22 ++++---- .../CDComponentsRegistryTable.h | 5 +- .../CDClientTables/CDCurrencyTableTable.cpp | 13 ++--- .../CDClientTables/CDCurrencyTableTable.h | 7 +-- .../CDDestructibleComponentTable.cpp | 13 ++--- .../CDDestructibleComponentTable.h | 7 +-- .../CDClientTables/CDEmoteTable.cpp | 2 + .../CDClientTables/CDEmoteTable.h | 5 +- .../CDClientTables/CDFeatureGatingTable.cpp | 14 +++--- .../CDClientTables/CDFeatureGatingTable.h | 7 +-- .../CDInventoryComponentTable.cpp | 13 ++--- .../CDInventoryComponentTable.h | 7 +-- .../CDClientTables/CDItemComponentTable.cpp | 14 +++--- .../CDClientTables/CDItemComponentTable.h | 5 +- .../CDClientTables/CDItemSetSkillsTable.cpp | 14 ++---- .../CDClientTables/CDItemSetSkillsTable.h | 7 +-- .../CDClientTables/CDItemSetsTable.cpp | 12 ++--- .../CDClientTables/CDItemSetsTable.h | 7 +-- .../CDLevelProgressionLookupTable.cpp | 12 ++--- .../CDLevelProgressionLookupTable.h | 7 +-- .../CDClientTables/CDLootMatrixTable.cpp | 14 +++--- .../CDClientTables/CDLootMatrixTable.h | 3 +- .../CDClientTables/CDLootTableTable.cpp | 18 ++++--- .../CDClientTables/CDLootTableTable.h | 3 +- .../CDClientTables/CDMissionEmailTable.cpp | 15 ++---- .../CDClientTables/CDMissionEmailTable.h | 7 +-- .../CDMissionNPCComponentTable.cpp | 13 ++--- .../CDMissionNPCComponentTable.h | 9 +--- .../CDClientTables/CDMissionTasksTable.cpp | 15 +++--- .../CDClientTables/CDMissionTasksTable.h | 8 ++- .../CDClientTables/CDMissionsTable.cpp | 15 +++--- .../CDClientTables/CDMissionsTable.h | 8 +-- .../CDMovementAIComponentTable.cpp | 12 ++--- .../CDMovementAIComponentTable.h | 8 +-- .../CDClientTables/CDObjectSkillsTable.cpp | 11 ++-- .../CDClientTables/CDObjectSkillsTable.h | 9 +--- .../CDClientTables/CDObjectsTable.cpp | 16 ++++-- .../CDClientTables/CDObjectsTable.h | 6 +-- .../CDPackageComponentTable.cpp | 14 ++---- .../CDClientTables/CDPackageComponentTable.h | 7 +-- .../CDClientTables/CDPetComponentTable.cpp | 11 ++-- .../CDClientTables/CDPetComponentTable.h | 5 +- .../CDPhysicsComponentTable.cpp | 8 +-- .../CDClientTables/CDPhysicsComponentTable.h | 5 +- .../CDPropertyEntranceComponentTable.cpp | 12 +++-- .../CDPropertyEntranceComponentTable.h | 8 +-- .../CDPropertyTemplateTable.cpp | 11 ++-- .../CDClientTables/CDPropertyTemplateTable.h | 6 +-- .../CDProximityMonitorComponentTable.cpp | 12 ++--- .../CDProximityMonitorComponentTable.h | 7 +-- .../CDRailActivatorComponent.cpp | 9 ++-- .../CDClientTables/CDRailActivatorComponent.h | 5 +- .../CDClientTables/CDRarityTableTable.cpp | 5 +- .../CDClientTables/CDRarityTableTable.h | 8 ++- .../CDRebuildComponentTable.cpp | 12 ++--- .../CDClientTables/CDRebuildComponentTable.h | 7 +-- .../CDClientTables/CDRewardCodesTable.cpp | 9 ++-- .../CDClientTables/CDRewardCodesTable.h | 6 +-- .../CDClientTables/CDRewardsTable.cpp | 5 +- .../CDClientTables/CDRewardsTable.h | 6 +-- .../CDClientTables/CDScriptComponentTable.cpp | 12 +++-- .../CDClientTables/CDScriptComponentTable.h | 6 +-- .../CDClientTables/CDSkillBehaviorTable.cpp | 16 +++--- .../CDClientTables/CDSkillBehaviorTable.h | 6 +-- .../CDClientDatabase/CDClientTables/CDTable.h | 28 ++++++----- .../CDClientTables/CDVendorComponentTable.cpp | 13 ++--- .../CDClientTables/CDVendorComponentTable.h | 7 +-- .../CDClientTables/CDZoneTableTable.cpp | 4 +- .../CDClientTables/CDZoneTableTable.h | 5 +- dGame/dComponents/RenderComponent.cpp | 7 ++- 84 files changed, 394 insertions(+), 529 deletions(-) diff --git a/dDatabase/CDClientDatabase/CDClientManager.cpp b/dDatabase/CDClientDatabase/CDClientManager.cpp index f270d849..0e05c0b8 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientDatabase/CDClientManager.cpp @@ -39,6 +39,7 @@ #include "CDFeatureGatingTable.h" #include "CDRailActivatorComponent.h" #include "CDRewardCodesTable.h" +#include "CDPetComponentTable.h" #include @@ -61,6 +62,55 @@ public: } }; +// Using a macro to reduce repetitive code and issues from copy and paste. +// As a note, ## in a macro is used to concatenate two tokens together. + +#define SPECIALIZE_TABLE_STORAGE(table) \ + template<> typename table::StorageType& CDClientManager::GetEntriesMutable() { return table##Entries; }; + +#define DEFINE_TABLE_STORAGE(table) namespace { table::StorageType table##Entries; }; SPECIALIZE_TABLE_STORAGE(table) + +DEFINE_TABLE_STORAGE(CDActivityRewardsTable); +DEFINE_TABLE_STORAGE(CDActivitiesTable); +DEFINE_TABLE_STORAGE(CDAnimationsTable); +DEFINE_TABLE_STORAGE(CDBehaviorParameterTable); +DEFINE_TABLE_STORAGE(CDBehaviorTemplateTable); +DEFINE_TABLE_STORAGE(CDBrickIDTableTable); +DEFINE_TABLE_STORAGE(CDComponentsRegistryTable); +DEFINE_TABLE_STORAGE(CDCurrencyTableTable); +DEFINE_TABLE_STORAGE(CDDestructibleComponentTable); +DEFINE_TABLE_STORAGE(CDEmoteTableTable); +DEFINE_TABLE_STORAGE(CDFeatureGatingTable); +DEFINE_TABLE_STORAGE(CDInventoryComponentTable); +DEFINE_TABLE_STORAGE(CDItemComponentTable); +DEFINE_TABLE_STORAGE(CDItemSetSkillsTable); +DEFINE_TABLE_STORAGE(CDItemSetsTable); +DEFINE_TABLE_STORAGE(CDLevelProgressionLookupTable); +DEFINE_TABLE_STORAGE(CDLootMatrixTable); +DEFINE_TABLE_STORAGE(CDLootTableTable); +DEFINE_TABLE_STORAGE(CDMissionEmailTable); +DEFINE_TABLE_STORAGE(CDMissionNPCComponentTable); +DEFINE_TABLE_STORAGE(CDMissionTasksTable); +DEFINE_TABLE_STORAGE(CDMissionsTable); +DEFINE_TABLE_STORAGE(CDMovementAIComponentTable); +DEFINE_TABLE_STORAGE(CDObjectSkillsTable); +DEFINE_TABLE_STORAGE(CDObjectsTable); +DEFINE_TABLE_STORAGE(CDPhysicsComponentTable); +DEFINE_TABLE_STORAGE(CDPackageComponentTable); +DEFINE_TABLE_STORAGE(CDPetComponentTable); +DEFINE_TABLE_STORAGE(CDProximityMonitorComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyEntranceComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyTemplateTable); +DEFINE_TABLE_STORAGE(CDRailActivatorComponentTable); +DEFINE_TABLE_STORAGE(CDRarityTableTable); +DEFINE_TABLE_STORAGE(CDRebuildComponentTable); +DEFINE_TABLE_STORAGE(CDRewardCodesTable); +DEFINE_TABLE_STORAGE(CDRewardsTable); +DEFINE_TABLE_STORAGE(CDScriptComponentTable); +DEFINE_TABLE_STORAGE(CDSkillBehaviorTable); +DEFINE_TABLE_STORAGE(CDVendorComponentTable); +DEFINE_TABLE_STORAGE(CDZoneTableTable); + void CDClientManager::LoadValuesFromDatabase() { if (!CDClientDatabase::isConnected) throw CDClientConnectionException(); diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index 21a6e3cd..c1c4443d 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -1,8 +1,5 @@ -#pragma once - -#include "CDTable.h" - -#include "Singleton.h" +#ifndef __CDCLIENTMANAGER__H__ +#define __CDCLIENTMANAGER__H__ #define UNUSED_TABLE(v) @@ -20,7 +17,28 @@ namespace CDClientManager { * @return A pointer to the requested table. */ template - T* GetTable() { - return &T::Instance(); - } + T* GetTable(); + + /** + * Fetch a table from CDClient + * Note: Calling this function without a template specialization in CDClientManager.cpp will cause a linker error. + * + * @tparam Table type to fetch + * @return A pointer to the requested table. + */ + template + typename T::StorageType& GetEntriesMutable(); }; + + +// These are included after the CDClientManager namespace declaration as CDTable as of Jan 29 2024 relies on CDClientManager in Templated code. +#include "CDTable.h" + +#include "Singleton.h" + +template +T* CDClientManager::GetTable() { + return &T::Instance(); +}; + +#endif //!__CDCLIENTMANAGER__H__ diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp index 998c4095..19111490 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp @@ -1,5 +1,6 @@ #include "CDActivitiesTable.h" + void CDActivitiesTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -13,7 +14,8 @@ void CDActivitiesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Activities"); @@ -39,7 +41,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { entry.noTeamLootOnDeath = tableData.getIntField("noTeamLootOnDeath", -1); entry.optionalPercentage = tableData.getFloatField("optionalPercentage", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -48,7 +50,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { std::vector CDActivitiesTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h index 75fc602e..3e1d4c37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h @@ -25,15 +25,10 @@ struct CDActivities { float optionalPercentage; }; -class CDActivitiesTable : public CDTable { -private: - std::vector entries; - +class CDActivitiesTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const { return this->entries; } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp index 7795a177..abe0c50c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp @@ -1,5 +1,6 @@ #include "CDActivityRewardsTable.h" + void CDActivityRewardsTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -14,7 +15,8 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); @@ -28,7 +30,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { entry.ChallengeRating = tableData.getIntField("ChallengeRating", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -37,7 +39,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { std::vector CDActivityRewardsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h index 40ab17e7..8d07a718 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h @@ -13,15 +13,9 @@ struct CDActivityRewards { std::string description; //!< The description }; -class CDActivityRewardsTable : public CDTable { -private: - std::vector entries; - +class CDActivityRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - std::vector GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp index 7244ddee..cf461fc9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp @@ -5,6 +5,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + auto& animations = GetEntriesMutable(); while (!tableData.eof()) { std::string animation_type = tableData.getStringField("animation_type", ""); DluAssert(!animation_type.empty()); @@ -24,7 +25,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } @@ -35,6 +36,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { auto tableData = queryToCache.execQuery(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (tableData.eof()) return false; + auto& animations = GetEntriesMutable(); do { std::string animation_type = tableData.getStringField("animation_type", ""); @@ -55,7 +57,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } while (!tableData.eof()); @@ -68,15 +70,17 @@ void CDAnimationsTable::CacheAnimations(const CDAnimationKey animationKey) { auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Animations WHERE animationGroupID = ? and animation_type = ?"); query.bind(1, static_cast(animationKey.second)); query.bind(2, animationKey.first.c_str()); + auto& animations = GetEntriesMutable(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (!CacheData(query)) { - this->animations[animationKey]; + animations[animationKey]; } } void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { - auto animationEntryCached = this->animations.find(CDAnimationKey("", animationGroupID)); - if (animationEntryCached != this->animations.end()) { + auto& animations = GetEntriesMutable(); + auto animationEntryCached = animations.find(CDAnimationKey("", animationGroupID)); + if (animationEntryCached != animations.end()) { return; } @@ -85,28 +89,29 @@ void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { // Cache the query so we don't run the query again. CacheData(query); - this->animations[CDAnimationKey("", animationGroupID)]; + animations[CDAnimationKey("", animationGroupID)]; } -CDAnimationLookupResult CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { +std::optional CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { + auto& animations = GetEntriesMutable(); CDAnimationKey animationKey(animationType, animationGroupID); - auto animationEntryCached = this->animations.find(animationKey); - if (animationEntryCached == this->animations.end()) { + auto animationEntryCached = animations.find(animationKey); + if (animationEntryCached == animations.end()) { this->CacheAnimations(animationKey); } - auto animationEntry = this->animations.find(animationKey); + auto animationEntry = animations.find(animationKey); // If we have only one animation, return it regardless of the chance to play. if (animationEntry->second.size() == 1) { - return CDAnimationLookupResult(animationEntry->second.front()); + return animationEntry->second.front(); } auto randomAnimation = GeneralUtils::GenerateRandomNumber(0, 1); for (auto& animationEntry : animationEntry->second) { randomAnimation -= animationEntry.chance_to_play; // This is how the client gets the random animation. - if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return CDAnimationLookupResult(animationEntry); + if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return animationEntry; } - return CDAnimationLookupResult(); + return std::nullopt; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h index 1b6280ca..643ef98f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h @@ -2,6 +2,11 @@ #include "CDTable.h" #include +#include + +typedef int32_t AnimationGroupID; +typedef std::string AnimationID; +typedef std::pair CDAnimationKey; struct CDAnimation { // uint32_t animationGroupID; @@ -20,12 +25,7 @@ struct CDAnimation { UNUSED_COLUMN(float blendTime;) //!< The blend time }; -typedef LookupResult CDAnimationLookupResult; - -class CDAnimationsTable : public CDTable { - typedef int32_t AnimationGroupID; - typedef std::string AnimationID; - typedef std::pair CDAnimationKey; +class CDAnimationsTable : public CDTable>> { public: void LoadValuesFromDatabase(); /** @@ -38,7 +38,7 @@ public: * @param animationGroupID The animationGroupID to lookup * @return CDAnimationLookupResult */ - [[nodiscard]] CDAnimationLookupResult GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); + [[nodiscard]] std::optional GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); /** * Cache a full AnimationGroup by its ID. @@ -58,10 +58,4 @@ private: * @return false */ bool CacheData(CppSQLite3Statement& queryToCache); - - /** - * Each animation is key'd by its animationName and its animationGroupID. Each - * animation has a possible list of animations. This is because there can be animations have a percent chance to play so one is selected at random. - */ - std::map> animations; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp index 708bec4c..57187c7c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp @@ -1,6 +1,10 @@ #include "CDBehaviorParameterTable.h" #include "GeneralUtils.h" +namespace { + std::unordered_map m_ParametersList; +}; + uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { uint64_t key = behaviorID; key <<= 31U; @@ -11,6 +15,7 @@ uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { void CDBehaviorParameterTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { uint32_t behaviorID = tableData.getIntField("behaviorID", -1); auto candidateStringToAdd = std::string(tableData.getStringField("parameterID", "")); @@ -24,7 +29,7 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { uint64_t hash = GetKey(behaviorID, parameterId); float value = tableData.getFloatField("value", -1.0f); - m_Entries.insert(std::make_pair(hash, value)); + entries.insert(std::make_pair(hash, value)); tableData.nextRow(); } @@ -32,22 +37,24 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { } float CDBehaviorParameterTable::GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue) { - auto parameterID = this->m_ParametersList.find(name); - if (parameterID == this->m_ParametersList.end()) return defaultValue; + auto parameterID = m_ParametersList.find(name); + if (parameterID == m_ParametersList.end()) return defaultValue; auto hash = GetKey(behaviorID, parameterID->second); // Search for specific parameter - auto it = m_Entries.find(hash); - return it != m_Entries.end() ? it->second : defaultValue; + auto& entries = GetEntriesMutable(); + auto it = entries.find(hash); + return it != entries.end() ? it->second : defaultValue; } std::map CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { + auto& entries = GetEntriesMutable(); uint64_t hashBase = behaviorID; std::map returnInfo; for (auto& [parameterString, parameterId] : m_ParametersList) { uint64_t hash = GetKey(hashBase, parameterId); - auto infoCandidate = m_Entries.find(hash); - if (infoCandidate != m_Entries.end()) { + auto infoCandidate = entries.find(hash); + if (infoCandidate != entries.end()) { returnInfo.insert(std::make_pair(parameterString, infoCandidate->second)); } } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h index 3daa3aa3..ba6ad6c1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h @@ -5,12 +5,10 @@ #include #include -class CDBehaviorParameterTable : public CDTable { -private: - typedef uint64_t BehaviorParameterHash; - typedef float BehaviorParameterValue; - std::unordered_map m_Entries; - std::unordered_map m_ParametersList; +typedef uint64_t BehaviorParameterHash; +typedef float BehaviorParameterValue; + +class CDBehaviorParameterTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp index a67398a9..983156e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDBehaviorTemplateTable.h" +namespace { + std::unordered_set m_EffectHandles; +}; + void CDBehaviorTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -13,11 +17,9 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); - // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDBehaviorTemplate entry; entry.behaviorID = tableData.getIntField("behaviorID", -1); @@ -31,30 +33,17 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; } - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + entries.insert(std::make_pair(entry.behaviorID, entry)); tableData.nextRow(); } tableData.finalize(); } -std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; -} - -const std::vector& CDBehaviorTemplateTable::GetEntries() const { - return this->entries; -} - const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { + auto& entries = GetEntriesMutable(); + auto entry = entries.find(behaviorID); + if (entry == entries.end()) { CDBehaviorTemplate entryToReturn; entryToReturn.behaviorID = 0; entryToReturn.effectHandle = m_EffectHandles.end(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h index cbc494a2..367f5f0a 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h @@ -12,19 +12,9 @@ struct CDBehaviorTemplate { std::unordered_set::iterator effectHandle; //!< The effect handle }; - -class CDBehaviorTemplateTable : public CDTable { -private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; +class CDBehaviorTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - // Queries the table with a custom "where" clause - std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp index abc917b5..c2714396 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp @@ -14,7 +14,8 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BrickIDTable"); @@ -23,7 +24,7 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { entry.NDObjectID = tableData.getIntField("NDObjectID", -1); entry.LEGOBrickID = tableData.getIntField("LEGOBrickID", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,15 +32,9 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { } std::vector CDBrickIDTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDBrickIDTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h index 1a9f9a94..9a2c2523 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h @@ -16,14 +16,9 @@ struct CDBrickIDTable { //! BrickIDTable table -class CDBrickIDTableTable : public CDTable { -private: - std::vector entries; - +class CDBrickIDTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp index 3cf7ac62..4944c13b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp @@ -4,14 +4,15 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDComponentsRegistry entry; entry.id = tableData.getIntField("id", -1); entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); - this->mappedEntries.insert_or_assign(entry.id, 0); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(entry.id, 0); tableData.nextRow(); } @@ -20,10 +21,11 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { } int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { - auto exists = mappedEntries.find(id); - if (exists != mappedEntries.end()) { - auto iter = mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == mappedEntries.end() ? defaultValue : iter->second; + auto& entries = GetEntriesMutable(); + auto exists = entries.find(id); + if (exists != entries.end()) { + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); + return iter == entries.end() ? defaultValue : iter->second; } // Now get the data. Get all components of this entity so we dont do a query for each component @@ -38,14 +40,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponent entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); tableData.nextRow(); } - mappedEntries.insert_or_assign(id, 0); + entries.insert_or_assign(id, 0); - auto iter = this->mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == this->mappedEntries.end() ? defaultValue : iter->second; + return iter == entries.end() ? defaultValue : iter->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h index 45da7614..2165f907 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h @@ -13,10 +13,7 @@ struct CDComponentsRegistry { }; -class CDComponentsRegistryTable : public CDTable { -private: - std::unordered_map mappedEntries; //id, component_type, component_id - +class CDComponentsRegistryTable : public CDTable> { public: void LoadValuesFromDatabase(); int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp index deb2b168..19ac7da0 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp @@ -15,7 +15,8 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); @@ -27,7 +28,7 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { entry.maxvalue = tableData.getIntField("maxvalue", -1); entry.id = tableData.getIntField("id", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,15 +36,9 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { } std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDCurrencyTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h index 9c68c277..1cd6c142 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h @@ -18,14 +18,9 @@ struct CDCurrencyTable { }; //! CurrencyTable table -class CDCurrencyTableTable : public CDTable { -private: - std::vector entries; - +class CDCurrencyTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp index 4939a50e..b1a6f699 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp @@ -13,7 +13,8 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); @@ -34,7 +35,7 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { entry.isSmashable = tableData.getIntField("isSmashable", -1) == 1 ? true : false; entry.difficultyLevel = tableData.getIntField("difficultyLevel", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -42,15 +43,9 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { } std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDDestructibleComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h index 0871d9ea..3319907b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h @@ -20,14 +20,9 @@ struct CDDestructibleComponent { int32_t difficultyLevel; //!< ??? }; -class CDDestructibleComponentTable : public CDTable { -private: - std::vector entries; - +class CDDestructibleComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp index a7f39705..28052819 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp @@ -2,6 +2,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDEmoteTable entry; entry.ID = tableData.getIntField("id", -1); @@ -21,6 +22,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { } CDEmoteTable* CDEmoteTableTable::GetEmote(int32_t id) { + auto& entries = GetEntriesMutable(); auto itr = entries.find(id); return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h index 360cfc38..ff0b28d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h @@ -26,10 +26,7 @@ struct CDEmoteTable { std::string gateVersion; }; -class CDEmoteTableTable : public CDTable { -private: - std::map entries; - +class CDEmoteTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Returns an emote by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp index 1a146bf1..407efff7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp @@ -14,7 +14,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); @@ -26,7 +27,7 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { entry.minor = tableData.getIntField("minor", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,7 +36,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { std::vector CDFeatureGatingTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + auto& entries = GetEntriesMutable(); + std::vector data = cpplinq::from(entries) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -43,6 +45,7 @@ std::vector CDFeatureGatingTable::Query(std::function= entry) { return true; @@ -51,8 +54,3 @@ bool CDFeatureGatingTable::FeatureUnlocked(const CDFeatureGating& feature) const return false; } - -const std::vector& CDFeatureGatingTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h index 5df202e3..65f33395 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h @@ -17,10 +17,7 @@ struct CDFeatureGating { } }; -class CDFeatureGatingTable : public CDTable { -private: - std::vector entries; - +class CDFeatureGatingTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -28,6 +25,4 @@ public: std::vector Query(std::function predicate); bool FeatureUnlocked(const CDFeatureGating& feature) const; - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp index 1a21a899..8cf3d8da 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp @@ -14,7 +14,8 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); @@ -25,7 +26,7 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { entry.count = tableData.getIntField("count", -1); entry.equip = tableData.getIntField("equip", -1) == 1 ? true : false; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,15 +34,9 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { } std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDInventoryComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h index 1f5a525d..361e1a90 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h @@ -10,14 +10,9 @@ struct CDInventoryComponent { bool equip; //!< Whether or not to equip the item }; -class CDInventoryComponentTable : public CDTable { -private: - std::vector entries; - +class CDInventoryComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp index 9f7609e9..0d8b1ad9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp @@ -17,6 +17,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDItemComponent entry; entry.id = tableData.getIntField("id", -1); @@ -62,7 +63,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -70,8 +71,9 @@ void CDItemComponentTable::LoadValuesFromDatabase() { } const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skillID) { - const auto& it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(skillID); + if (it != entries.end()) { return it->second; } @@ -129,12 +131,12 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skill entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - const auto& it2 = this->entries.find(skillID); - if (it2 != this->entries.end()) { + const auto& it2 = entries.find(skillID); + if (it2 != entries.end()) { return it2->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h index 014c9801..60a3e412 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h @@ -49,10 +49,7 @@ struct CDItemComponent { float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; -class CDItemComponentTable : public CDTable { -private: - std::map entries; - +class CDItemComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp index 0376bad4..79bd69ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); @@ -24,7 +25,7 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { entry.SkillID = tableData.getIntField("SkillID", -1); entry.SkillCastType = tableData.getIntField("SkillCastType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,22 +33,17 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { } std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDItemSetSkillsTable::GetEntries() const { - return this->entries; -} - std::vector CDItemSetSkillsTable::GetBySkillID(uint32_t SkillSetID) { std::vector toReturn; - for (CDItemSetSkills entry : this->entries) { + for (const auto& entry : GetEntries()) { if (entry.SkillSetID == SkillSetID) toReturn.push_back(entry); if (entry.SkillSetID > SkillSetID) return toReturn; //stop seeking in the db if it's not needed. } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h index ee5fda05..78e708ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h @@ -9,16 +9,11 @@ struct CDItemSetSkills { uint32_t SkillCastType; //!< The skill cast type }; -class CDItemSetSkillsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - const std::vector& GetEntries() const; - std::vector GetBySkillID(uint32_t SkillSetID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp index f3859ae2..77b3b1e7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); @@ -36,7 +37,7 @@ void CDItemSetsTable::LoadValuesFromDatabase() { entry.kitID = tableData.getIntField("kitID", -1); entry.priority = tableData.getFloatField("priority", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -45,14 +46,9 @@ void CDItemSetsTable::LoadValuesFromDatabase() { std::vector CDItemSetsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDItemSetsTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h index 77cc0c35..45b91590 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h @@ -21,15 +21,10 @@ struct CDItemSets { float priority; //!< The priority }; -class CDItemSetsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp index 930f3a85..284cf484 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp @@ -14,7 +14,8 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); @@ -24,7 +25,7 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { entry.requiredUScore = tableData.getIntField("requiredUScore", -1); entry.BehaviorEffect = tableData.getStringField("BehaviorEffect", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,14 +34,9 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDLevelProgressionLookupTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h index fa1bb4cc..050d910e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h @@ -9,15 +9,10 @@ struct CDLevelProgressionLookup { std::string BehaviorEffect; //!< The behavior effect attached to this }; -class CDLevelProgressionLookupTable : public CDTable { -private: - std::vector entries; - +class CDLevelProgressionLookupTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp index 36bebb69..cd8ae5c4 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp @@ -25,7 +25,8 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); @@ -33,14 +34,15 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { CDLootMatrix entry; uint32_t lootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries[lootMatrixIndex].push_back(ReadRow(tableData)); + entries[lootMatrixIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } } const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { - auto itr = this->entries.find(matrixId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(matrixId); + if (itr != entries.end()) { return itr->second; } @@ -49,10 +51,10 @@ const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { auto tableData = query.execQuery(); while (!tableData.eof()) { - this->entries[matrixId].push_back(ReadRow(tableData)); + entries[matrixId].push_back(ReadRow(tableData)); tableData.nextRow(); } - return this->entries[matrixId]; + return entries[matrixId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h index c7157e07..b0ce7e0f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h @@ -16,7 +16,7 @@ struct CDLootMatrix { typedef uint32_t LootMatrixIndex; typedef std::vector LootMatrixEntries; -class CDLootMatrixTable : public CDTable { +class CDLootMatrixTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -24,6 +24,5 @@ public: const LootMatrixEntries& GetMatrix(uint32_t matrixId); private: CDLootMatrix ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index 7d04db13..d5e9d4dc 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -49,7 +49,8 @@ void CDLootTableTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); @@ -57,17 +58,18 @@ void CDLootTableTable::LoadValuesFromDatabase() { CDLootTable entry; uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); - this->entries[lootTableIndex].push_back(ReadRow(tableData)); + entries[lootTableIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } - for (auto& [id, table] : this->entries) { + for (auto& [id, table] : entries) { SortTable(table); } } const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { - auto itr = this->entries.find(tableId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(tableId); + if (itr != entries.end()) { return itr->second; } @@ -77,10 +79,10 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { while (!tableData.eof()) { CDLootTable entry; - this->entries[tableId].push_back(ReadRow(tableData)); + entries[tableId].push_back(ReadRow(tableData)); tableData.nextRow(); } - SortTable(this->entries[tableId]); + SortTable(entries[tableId]); - return this->entries[tableId]; + return entries[tableId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h index e432d621..416bd87a 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h @@ -13,10 +13,9 @@ struct CDLootTable { typedef uint32_t LootTableIndex; typedef std::vector LootTableEntries; -class CDLootTableTable : public CDTable { +class CDLootTableTable : public CDTable> { private: CDLootTable ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp index c7e884c2..1123bfec 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp @@ -1,7 +1,7 @@ #include "CDMissionEmailTable.h" -void CDMissionEmailTable::LoadValuesFromDatabase() { +void CDMissionEmailTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); @@ -14,7 +14,8 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); @@ -29,7 +30,7 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { entry.locStatus = tableData.getIntField("locStatus", -1); entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,15 +39,9 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionEmailTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h index 06c15e71..ac2dba81 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h @@ -15,14 +15,9 @@ struct CDMissionEmail { }; -class CDMissionEmailTable : public CDTable { -private: - std::vector entries; - +class CDMissionEmailTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp index 87d2bd61..efe284d4 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp @@ -14,7 +14,8 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); @@ -26,7 +27,7 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionNPCComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h index 8c4b790d..1eba2fad 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h @@ -11,17 +11,10 @@ struct CDMissionNPCComponent { std::string gate_version; //!< The gate version }; -class CDMissionNPCComponentTable : public CDTable { -private: - std::vector entries; - +class CDMissionNPCComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp index b2cb9e21..c5b6620f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp @@ -14,7 +14,8 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); @@ -34,7 +35,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -43,7 +44,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { std::vector CDMissionTasksTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -53,7 +54,8 @@ std::vector CDMissionTasksTable::Query(std::function CDMissionTasksTable::GetByMissionID(uint32_t missionID) { std::vector tasks; - for (auto& entry : this->entries) { + // TODO: this should not be linear(?) and also shouldnt need to be a pointer + for (auto& entry : GetEntriesMutable()) { if (entry.id == missionID) { tasks.push_back(&entry); } @@ -62,7 +64,6 @@ std::vector CDMissionTasksTable::GetByMissionID(uint32_t missio return tasks; } -const std::vector& CDMissionTasksTable::GetEntries() const { - return this->entries; +const typename CDMissionTasksTable::StorageType& CDMissionTasksTable::GetEntries() const { + return CDTable::GetEntries(); } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h index 420dbfbe..97553359 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h @@ -19,10 +19,7 @@ struct CDMissionTasks { UNUSED(std::string gate_version); //!< ??? }; -class CDMissionTasksTable : public CDTable { -private: - std::vector entries; - +class CDMissionTasksTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause @@ -30,6 +27,7 @@ public: std::vector GetByMissionID(uint32_t missionID); - const std::vector& GetEntries() const; + // TODO: Remove this and replace it with a proper lookup function. + const CDTable::StorageType& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp index bc9eb76c..8862b1db 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp @@ -16,7 +16,8 @@ void CDMissionsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); @@ -75,7 +76,7 @@ void CDMissionsTable::LoadValuesFromDatabase() { UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -86,19 +87,15 @@ void CDMissionsTable::LoadValuesFromDatabase() { std::vector CDMissionsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; -} - const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { return const_cast(&entry); } @@ -108,7 +105,7 @@ const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { } const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { found = true; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h index de4b21c3..6ba7b19e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h @@ -60,18 +60,12 @@ struct CDMissions { int32_t reward_bankinventory; //!< The amount of bank space this mission rewards }; -class CDMissionsTable : public CDTable { -private: - std::vector entries; - +class CDMissionsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - // Gets all the entries in the table - const std::vector& GetEntries() const; - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp index be1c3d96..48964a59 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp @@ -14,7 +14,8 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); @@ -29,7 +30,7 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.attachedPath = tableData.getStringField("attachedPath", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,14 +39,9 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { std::vector CDMovementAIComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDMovementAIComponentTable::GetEntries(void) const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h index 8b415f3a..34d01e3d 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h @@ -14,15 +14,9 @@ struct CDMovementAIComponent { std::string attachedPath; }; -class CDMovementAIComponentTable : public CDTable { -private: - std::vector entries; - +class CDMovementAIComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp index 958c6cc8..9933fe7f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp @@ -14,7 +14,8 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); @@ -25,7 +26,7 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { entry.castOnType = tableData.getIntField("castOnType", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,13 +35,9 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { std::vector CDObjectSkillsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDObjectSkillsTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h index 0b88fb6f..a2a8d440 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h @@ -10,17 +10,10 @@ struct CDObjectSkills { uint32_t AICombatWeight; //!< ??? }; -class CDObjectSkillsTable : public CDTable { -private: - std::vector entries; - +class CDObjectSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp index 3282e14c..d1f6771e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp @@ -1,5 +1,9 @@ #include "CDObjectsTable.h" +namespace { + CDObjects m_default; +}; + void CDObjectsTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -14,6 +18,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDObjects entry; entry.id = tableData.getIntField("id", -1); @@ -31,7 +36,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -41,8 +46,9 @@ void CDObjectsTable::LoadValuesFromDatabase() { } const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { - const auto& it = this->entries.find(LOT); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(LOT); + if (it != entries.end()) { return it->second; } @@ -51,7 +57,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { auto tableData = query.execQuery(); if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); + entries.insert(std::make_pair(LOT, m_default)); return m_default; } @@ -73,7 +79,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h index 2ef47727..add21c8f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h @@ -20,11 +20,7 @@ struct CDObjects { UNUSED(uint32_t HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; -class CDObjectsTable : public CDTable { -private: - std::map entries; - CDObjects m_default; - +class CDObjectsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp index 8038c779..da100026 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp @@ -13,8 +13,8 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); @@ -24,7 +24,7 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.packageType = tableData.getIntField("packageType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,15 +34,9 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDPackageComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDPackageComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h index cc8b0636..ad7003df 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h @@ -9,14 +9,9 @@ struct CDPackageComponent { uint32_t packageType; }; -class CDPackageComponentTable : public CDTable { -private: - std::vector entries; - +class CDPackageComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp index c3dd5d50..f3371ecb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp @@ -23,10 +23,12 @@ namespace { void CDPetComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PetComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { const uint32_t componentID = tableData.getIntField("id", defaultEntry.id); - auto& entry = m_Entries[componentID]; + auto& entry = entries[componentID]; + entry.id = componentID; UNUSED_COLUMN(entry.minTameUpdateTime = tableData.getFloatField("minTameUpdateTime", defaultEntry.minTameUpdateTime)); UNUSED_COLUMN(entry.maxTameUpdateTime = tableData.getFloatField("maxTameUpdateTime", defaultEntry.maxTameUpdateTime)); @@ -48,12 +50,13 @@ void CDPetComponentTable::LoadValuesFromDatabase() { } void CDPetComponentTable::LoadValuesFromDefaults() { - m_Entries.insert(std::make_pair(defaultEntry.id, defaultEntry)); + GetEntriesMutable().insert(std::make_pair(defaultEntry.id, defaultEntry)); } CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) { - auto itr = m_Entries.find(componentID); - if (itr == m_Entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + if (itr == entries.end()) { LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID); return defaultEntry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h index fa54e457..42890253 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h @@ -21,7 +21,7 @@ struct CDPetComponent { UNUSED_COLUMN(std::string buffIDs;) }; -class CDPetComponentTable : public CDTable { +class CDPetComponentTable : public CDTable> { public: /** @@ -39,7 +39,4 @@ public: * @returns A reference to the corresponding table, or the default if one could not be found */ CDPetComponent& GetByID(const uint32_t componentID); - -private: - std::map m_Entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp index ebc5327b..34671f3c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp @@ -2,6 +2,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDPhysicsComponent entry; entry.id = tableData.getIntField("id", -1); @@ -21,7 +22,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { UNUSED(entry->friction = tableData.getFloatField("friction")); UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,7 +30,8 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { } CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { - auto itr = m_entries.find(componentID); - return itr != m_entries.end() ? &itr->second : nullptr; + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h index 5ed33cc9..f0a62139 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h @@ -21,13 +21,10 @@ struct CDPhysicsComponent { UNUSED(std::string gravityVolumeAsset); }; -class CDPhysicsComponentTable : public CDTable { +class CDPhysicsComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static const std::string GetTableName() { return "PhysicsComponent"; }; CDPhysicsComponent* GetByID(uint32_t componentID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp index c1532c86..dfb591d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyEntranceComponentTable.h" +namespace { + CDPropertyEntranceComponent defaultEntry{}; +}; + void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); while (!tableData.eof()) { @@ -24,7 +29,7 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableData.getStringField("groupType", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,11 +37,10 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } return defaultEntry; } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h index 5c7d0965..f687b881 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h @@ -9,15 +9,9 @@ struct CDPropertyEntranceComponent { std::string groupType; }; -class CDPropertyEntranceComponentTable : public CDTable { +class CDPropertyEntranceComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause CDPropertyEntranceComponent GetByID(uint32_t id); - - // Gets all the entries in the table - [[nodiscard]] const std::vector& GetEntries() const { return entries; } -private: - std::vector entries{}; - CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp index 4a1d666e..4046b6fa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyTemplateTable.h" +namespace { + CDPropertyTemplate defaultEntry{}; +}; + void CDPropertyTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); while (!tableData.eof()) { @@ -23,7 +28,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableData.getStringField("spawnName", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,7 +36,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.mapID == mapID) return entry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h index 7261bdf9..e0c6c485 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h @@ -8,13 +8,9 @@ struct CDPropertyTemplate { std::string spawnName; }; -class CDPropertyTemplateTable : public CDTable { +class CDPropertyTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "PropertyTemplate"; }; CDPropertyTemplate GetByMapID(uint32_t mapID); -private: - std::vector entries{}; - CDPropertyTemplate defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp index 6edd00b2..279d6408 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp @@ -14,7 +14,8 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ProximityMonitorComponent"); @@ -25,7 +26,7 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { entry.LoadOnClient = tableData.getIntField("LoadOnClient", -1); entry.LoadOnServer = tableData.getIntField("LoadOnServer", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,14 +35,9 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { std::vector CDProximityMonitorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDProximityMonitorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h index 861c900e..af2c385e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h @@ -10,14 +10,9 @@ struct CDProximityMonitorComponent { bool LoadOnServer; }; -class CDProximityMonitorComponentTable : public CDTable { -private: - std::vector entries; - +class CDProximityMonitorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); //! Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp index 34ec5826..72a26beb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp @@ -3,6 +3,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRailActivatorComponent entry; @@ -36,7 +37,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { entry.showNameBillboard = tableData.getIntField("ShowNameBillboard", 0); - m_Entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -44,7 +45,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } @@ -52,10 +53,6 @@ CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) return {}; } -const std::vector& CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; -} - std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { const auto split = GeneralUtils::SplitString(str, ':'); if (split.size() == 2) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h index d06b2d36..d9a94d37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h @@ -20,13 +20,10 @@ struct CDRailActivatorComponent { bool showNameBillboard; }; -class CDRailActivatorComponentTable : public CDTable { +class CDRailActivatorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "RailActivatorComponent"; }; [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] const std::vector& GetEntries() const; private: static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp index 6f086e34..def27339 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp @@ -14,7 +14,8 @@ void CDRarityTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable order by randmax desc;"); @@ -30,5 +31,5 @@ void CDRarityTableTable::LoadValuesFromDatabase() { } const std::vector& CDRarityTableTable::GetRarityTable(uint32_t id) { - return entries[id]; + return GetEntriesMutable()[id]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h index 1248350b..006ac986 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h @@ -6,15 +6,13 @@ struct CDRarityTable { float randmax; uint32_t rarity; + + typedef uint32_t Index; }; typedef std::vector RarityTable; -class CDRarityTableTable : public CDTable { -private: - typedef uint32_t RarityTableIndex; - std::unordered_map> entries; - +class CDRarityTableTable : public CDTable>> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp index 30534936..8a07db88 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp @@ -14,7 +14,8 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); @@ -31,7 +32,7 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { entry.post_imagination_cost = tableData.getIntField("post_imagination_cost", -1); entry.time_before_smash = tableData.getFloatField("time_before_smash", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -40,14 +41,9 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { std::vector CDRebuildComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDRebuildComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h index aed71905..0eeb62ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h @@ -16,15 +16,10 @@ struct CDRebuildComponent { float time_before_smash; //!< The time before smash }; -class CDRebuildComponentTable : public CDTable { -private: - std::vector entries; - +class CDRebuildComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp index 4dab9ee9..8ade60a9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp @@ -14,7 +14,8 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RewardCodes"); @@ -26,20 +27,20 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } } LOT CDRewardCodesTable::GetAttachmentLOT(uint32_t rewardCodeId) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (rewardCodeId == entry.id) return entry.attachmentLOT; } return LOT_NULL; } uint32_t CDRewardCodesTable::GetCodeID(std::string code) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (code == entry.code) return entry.id; } return -1; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h index 1010a572..aa64c3bb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h @@ -13,13 +13,9 @@ struct CDRewardCode { }; -class CDRewardCodesTable : public CDTable { -private: - std::vector entries; - +class CDRewardCodesTable : public CDTable> { public: void LoadValuesFromDatabase(); - const std::vector& GetEntries() const; LOT GetAttachmentLOT(uint32_t rewardCodeId) const; uint32_t GetCodeID(std::string code) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp index 27c2344a..4539e417 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp @@ -2,6 +2,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRewards entry; entry.id = tableData.getIntField("id", -1); @@ -11,7 +12,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { entry.value = tableData.getIntField("value", -1); entry.count = tableData.getIntField("count", -1); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -20,7 +21,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { std::vector result{}; - for (const auto& e : m_entries) { + for (const auto& e : GetEntries()) { if (e.second.levelID == levelID) result.push_back(e.second); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h index 9c24397b..cec787cf 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h @@ -11,13 +11,9 @@ struct CDRewards { int32_t count; }; -class CDRewardsTable : public CDTable { +class CDRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "Rewards"; }; std::vector GetByLevelID(uint32_t levelID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp index a2fe0514..02e3e29c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDScriptComponentTable.h" +namespace { + CDScriptComponent m_ToReturnWhenNoneFound; +}; + void CDScriptComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -15,13 +19,14 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDScriptComponent entry; entry.id = tableData.getIntField("id", -1); entry.script_name = tableData.getStringField("script_name", ""); entry.client_script_name = tableData.getStringField("client_script_name", ""); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,8 +34,9 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { } const CDScriptComponent& CDScriptComponentTable::GetByID(uint32_t id) { - std::map::iterator it = this->entries.find(id); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(id); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h index 56296776..96c1b5a5 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h @@ -9,11 +9,7 @@ struct CDScriptComponent { std::string client_script_name; //!< The client script name }; -class CDScriptComponentTable : public CDTable { -private: - std::map entries; - CDScriptComponent m_ToReturnWhenNoneFound; - +class CDScriptComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by scriptID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp index 51ed7de3..0df67884 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp @@ -1,8 +1,10 @@ #include "CDSkillBehaviorTable.h" -void CDSkillBehaviorTable::LoadValuesFromDatabase() { - m_empty = CDSkillBehavior(); +namespace { + CDSkillBehavior m_empty = CDSkillBehavior(); +}; +void CDSkillBehaviorTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); @@ -14,8 +16,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + auto& entries = GetEntriesMutable(); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); @@ -41,7 +42,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.cancelType = tableData.getIntField("cancelType", -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); + entries.insert(std::make_pair(entry.skillID, entry)); //this->entries.push_back(entry); tableData.nextRow(); } @@ -50,8 +51,9 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { } const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(uint32_t skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(skillID); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h index 0c970be6..19225d19 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h @@ -25,11 +25,7 @@ struct CDSkillBehavior { UNUSED(uint32_t cancelType); //!< The cancel type (?) }; -class CDSkillBehaviorTable : public CDTable { -private: - std::map entries; - CDSkillBehavior m_empty; - +class CDSkillBehaviorTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h index ab965127..4e896dbb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h @@ -1,6 +1,7 @@ #pragma once #include "CDClientDatabase.h" +#include "CDClientManager.h" #include "Singleton.h" #include "DluAssert.h" @@ -27,22 +28,23 @@ #define UNUSED_ENTRY(v, x) #pragma warning (disable : 4244) //Disable double to float conversion warnings -#pragma warning (disable : 4715) //Disable "not all control paths return a value" +// #pragma warning (disable : 4715) //Disable "not all control paths return a value" -template +template class CDTable : public Singleton
{ +public: + typedef Storage StorageType; + protected: virtual ~CDTable() = default; -}; -template -class LookupResult { - typedef std::pair DataType; -public: - LookupResult() { m_data.first = T(); m_data.second = false; }; - LookupResult(T& data) { m_data.first = data; m_data.second = true; }; - inline const T& Data() { return m_data.first; }; - inline const bool& FoundData() { return m_data.second; }; -private: - DataType m_data; + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] StorageType& GetEntriesMutable() const { + return CDClientManager::GetEntriesMutable
(); + } + + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] const StorageType& GetEntries() const { + return GetEntriesMutable(); + } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp index 990d0b32..f639a7e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp @@ -14,7 +14,8 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM VendorComponent"); @@ -26,7 +27,7 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { entry.refreshTimeSeconds = tableData.getFloatField("refreshTimeSeconds", -1.0f); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDVendorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDVendorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h index 133ce78f..cbed2d13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h @@ -11,15 +11,10 @@ struct CDVendorComponent { uint32_t LootMatrixIndex; //!< LootMatrixIndex of the vendor's items }; -class CDVendorComponentTable : public CDTable { -private: - std::vector entries; - +class CDVendorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp index b599c37f..6aaeb854 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp @@ -15,6 +15,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDZoneTable entry; entry.zoneID = tableData.getIntField("zoneID", -1); @@ -45,7 +46,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); entry.mountsAllowed = tableData.getIntField("mountsAllowed", -1) == 1 ? true : false; - this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); + entries.insert(std::make_pair(entry.zoneID, entry)); tableData.nextRow(); } @@ -54,6 +55,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(uint32_t zoneID) { + auto& m_Entries = GetEntries(); const auto& iter = m_Entries.find(zoneID); if (iter != m_Entries.end()) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h index 5f5970ae..b1e8b1ba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h @@ -33,10 +33,7 @@ struct CDZoneTable { bool mountsAllowed; //!< Whether or not mounts are allowed }; -class CDZoneTableTable : public CDTable { -private: - std::map m_Entries; - +class CDZoneTableTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index d5866917..d3c74f78 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -168,10 +168,9 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); - if (animationGroup.FoundData()) { - auto data = animationGroup.Data(); - renderComponent->SetLastAnimationName(data.animation_name); - returnlength = data.animation_length; + if (animationGroup) { + renderComponent->SetLastAnimationName(animationGroup->animation_name); + returnlength = animationGroup->animation_length; } } if (sendAnimation) GameMessages::SendPlayAnimation(self, GeneralUtils::ASCIIToUTF16(animation), priority, scale); From 62b670d283cf078d42b04f391d49b1c6c30f8e30 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:15:28 -0800 Subject: [PATCH 3/5] remove sha512, move md5 to thirdparty (#1443) title. Tested that Auth runs and I can login still. --- CMakeLists.txt | 3 +- dCommon/CMakeLists.txt | 7 -- dCommon/SHA512.cpp | 154 ---------------------------- dCommon/SHA512.h | 68 ------------ dNet/AuthPackets.cpp | 1 - thirdparty/CMakeLists.txt | 2 + thirdparty/MD5/CMakeLists.txt | 6 ++ {dCommon => thirdparty/MD5}/MD5.cpp | 0 {dCommon => thirdparty/MD5}/MD5.h | 0 9 files changed, 10 insertions(+), 231 deletions(-) delete mode 100644 dCommon/SHA512.cpp delete mode 100644 dCommon/SHA512.h create mode 100644 thirdparty/MD5/CMakeLists.txt rename {dCommon => thirdparty/MD5}/MD5.cpp (100%) rename {dCommon => thirdparty/MD5}/MD5.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b6a775e..e085bfe7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -245,6 +245,7 @@ set(INCLUDED_DIRECTORIES "thirdparty/SQLite" "thirdparty/cpplinq" "thirdparty/cpp-httplib" + "thirdparty/MD5" "tests" "tests/dCommonTests" @@ -320,7 +321,7 @@ add_subdirectory(dPhysics) add_subdirectory(dServer) # Create a list of common libraries shared between all binaries -set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum") +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum" "MD5") # Add platform specific common libraries if(UNIX) diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 32f24028..c5fff63a 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -8,11 +8,9 @@ set(DCOMMON_SOURCES "Game.cpp" "GeneralUtils.cpp" "LDFFormat.cpp" - "MD5.cpp" "Metrics.cpp" "NiPoint3.cpp" "NiQuaternion.cpp" - "SHA512.cpp" "Demangler.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" @@ -68,8 +66,3 @@ else () endif () target_link_libraries(dCommon ZLIB::ZLIB) - -# Disable deprecation warnings on MD5.cpp and SHA512.cpp for Apple Clang -if (APPLE) - set_source_files_properties("MD5.cpp" "SHA512.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") -endif() diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp deleted file mode 100644 index e3c2d9f7..00000000 --- a/dCommon/SHA512.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Source: http://www.zedwood.com/article/cpp-sha512-function - -#include "SHA512.h" - -#include -#include - -const unsigned long long SHA512::sha512_k[80] = //ULL = uint64 -{ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; - -void SHA512::transform(const unsigned char* message, unsigned int block_nb) { - uint64 w[80]; - uint64 wv[8]; - uint64 t1, t2; - const unsigned char* sub_block; - int i, j; - for (i = 0; i < (int)block_nb; i++) { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) { - SHA2_PACK64(&sub_block[j << 3], &w[j]); - } - for (j = 16; j < 80; j++) { - w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; - } - for (j = 0; j < 8; j++) { - wv[j] = m_h[j]; - } - for (j = 0; j < 80; j++) { - t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha512_k[j] + w[j]; - t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) { - m_h[j] += wv[j]; - } - - } -} - -void SHA512::init() { - m_h[0] = 0x6a09e667f3bcc908ULL; - m_h[1] = 0xbb67ae8584caa73bULL; - m_h[2] = 0x3c6ef372fe94f82bULL; - m_h[3] = 0xa54ff53a5f1d36f1ULL; - m_h[4] = 0x510e527fade682d1ULL; - m_h[5] = 0x9b05688c2b3e6c1fULL; - m_h[6] = 0x1f83d9abfb41bd6bULL; - m_h[7] = 0x5be0cd19137e2179ULL; - m_len = 0; - m_tot_len = 0; -} - -void SHA512::update(const unsigned char* message, unsigned int len) { - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char* shifted_message; - tmp_len = SHA384_512_BLOCK_SIZE - m_len; - rem_len = len < tmp_len ? len : tmp_len; - memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA384_512_BLOCK_SIZE) { - m_len += len; - return; - } - new_len = len - rem_len; - block_nb = new_len / SHA384_512_BLOCK_SIZE; - shifted_message = message + rem_len; - transform(m_block, 1); - transform(shifted_message, block_nb); - rem_len = new_len % SHA384_512_BLOCK_SIZE; - memcpy(m_block, &shifted_message[block_nb << 7], rem_len); - m_len = rem_len; - m_tot_len += (block_nb + 1) << 7; -} - -void SHA512::final(unsigned char* digest) { - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) - < (m_len % SHA384_512_BLOCK_SIZE)); - len_b = (m_tot_len + m_len) << 3; - pm_len = block_nb << 7; - memset(m_block + m_len, 0, pm_len - m_len); - m_block[m_len] = 0x80; - SHA2_UNPACK32(len_b, m_block + pm_len - 4); - transform(m_block, block_nb); - for (i = 0; i < 8; i++) { - SHA2_UNPACK64(m_h[i], &digest[i << 3]); - } -} - -std::string sha512(std::string input) { - unsigned char digest[SHA512::DIGEST_SIZE]; - memset(digest, 0, SHA512::DIGEST_SIZE); - class SHA512 ctx; - ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); - ctx.final(digest); - - char buf[2 * SHA512::DIGEST_SIZE + 1]; - buf[2 * SHA512::DIGEST_SIZE] = 0; - for (int i = 0; i < SHA512::DIGEST_SIZE; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - - return std::string(buf); -} diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h deleted file mode 100644 index 512fa645..00000000 --- a/dCommon/SHA512.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -// C++ -#include - -class SHA512 { -protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; - - const static uint64 sha512_k[]; - static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); - -public: - void init(); - void update(const unsigned char* message, unsigned int len); - void final(unsigned char* digest); - static const unsigned int DIGEST_SIZE = (512 / 8); - -protected: - void transform(const unsigned char* message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; - uint64 m_h[8]; -}; - -std::string sha512(std::string input); - -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) -#define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA512_F1(x) (SHA2_ROTR(x, 28) ^ SHA2_ROTR(x, 34) ^ SHA2_ROTR(x, 39)) -#define SHA512_F2(x) (SHA2_ROTR(x, 14) ^ SHA2_ROTR(x, 18) ^ SHA2_ROTR(x, 41)) -#define SHA512_F3(x) (SHA2_ROTR(x, 1) ^ SHA2_ROTR(x, 8) ^ SHA2_SHFR(x, 7)) -#define SHA512_F4(x) (SHA2_ROTR(x, 19) ^ SHA2_ROTR(x, 61) ^ SHA2_SHFR(x, 6)) -#define SHA2_UNPACK32(x, str) \ -{ \ -*((str) + 3) = (uint8) ((x) ); \ -*((str) + 2) = (uint8) ((x) >> 8); \ -*((str) + 1) = (uint8) ((x) >> 16); \ -*((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_UNPACK64(x, str) \ -{ \ -*((str) + 7) = (uint8) ((x) ); \ -*((str) + 6) = (uint8) ((x) >> 8); \ -*((str) + 5) = (uint8) ((x) >> 16); \ -*((str) + 4) = (uint8) ((x) >> 24); \ -*((str) + 3) = (uint8) ((x) >> 32); \ -*((str) + 2) = (uint8) ((x) >> 40); \ -*((str) + 1) = (uint8) ((x) >> 48); \ -*((str) + 0) = (uint8) ((x) >> 56); \ -} -#define SHA2_PACK64(str, x) \ -{ \ -*(x) = ((uint64) *((str) + 7) ) \ -| ((uint64) *((str) + 6) << 8) \ -| ((uint64) *((str) + 5) << 16) \ -| ((uint64) *((str) + 4) << 24) \ -| ((uint64) *((str) + 3) << 32) \ -| ((uint64) *((str) + 2) << 40) \ -| ((uint64) *((str) + 1) << 48) \ -| ((uint64) *((str) + 0) << 56); \ -} diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 2597c576..9982f89e 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -7,7 +7,6 @@ #include "Database.h" #include "ZoneInstanceManager.h" #include "MD5.h" -#include "SHA512.h" #include "GeneralUtils.h" #include diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 11d278c0..40c81544 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -57,3 +57,5 @@ if(UNIX AND NOT APPLE) include_directories(${backtrace_SOURCE_DIR}) endif() endif() + +add_subdirectory(MD5) diff --git a/thirdparty/MD5/CMakeLists.txt b/thirdparty/MD5/CMakeLists.txt new file mode 100644 index 00000000..755b4519 --- /dev/null +++ b/thirdparty/MD5/CMakeLists.txt @@ -0,0 +1,6 @@ +add_library(MD5 "MD5.cpp") + +# Disable deprecation warnings on MD5.cpp for Apple Clang +if (APPLE) + set_source_files_properties("MD5.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") +endif() diff --git a/dCommon/MD5.cpp b/thirdparty/MD5/MD5.cpp similarity index 100% rename from dCommon/MD5.cpp rename to thirdparty/MD5/MD5.cpp diff --git a/dCommon/MD5.h b/thirdparty/MD5/MD5.h similarity index 100% rename from dCommon/MD5.h rename to thirdparty/MD5/MD5.h From 0c1ee0513d1d3fb19709da8c9bb2513290639259 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 10 Feb 2024 05:05:25 -0600 Subject: [PATCH 4/5] refactor: Change TryParse implementation (#1442) * Changed how the TryParse function works (and also did some general cleanup along the way) * Update noexcept attributes (verified these are correct) * Add fp overload for MacOS functionality * resolving some feedback * Split out unrelated changes to CleanupRoundup branch * Update in response to feedback * the consequences of emo's member variable renaming request * Revert "the consequences of emo's member variable renaming request" This reverts commit bf318caeda34f4439c1769fd7d5b77d341f7f646. * Fully revert renaming attempt * Revert "the consequences of emo's member variable renaming request" This reverts commit bf318caeda34f4439c1769fd7d5b77d341f7f646. Fully revert renaming attempt * Created ClientVersion.h and moved the client version defaults to it * Fix partial parsing and MacOS floating point errors * attempting fix to MacOS compiler error * syntax pass (should be the last commit unless the CI fails) * ah, wait, forgot to uncomment the preprocessor statements for MacOS. THIS should be the last commit pending CI * Okay, one last thing I noticed: We were including C headers here. Now they're C++ headers. Pinky swear this is it! * typo and I am OCD. please let this be the last * hash is usally but not always noexcept, so the specifier should go * Address MOST of the feedback * address the claim codes issue --- dAuthServer/AuthServer.cpp | 8 +- dChatServer/ChatServer.cpp | 9 +- dChatServer/PlayerContainer.cpp | 6 +- dCommon/GeneralUtils.cpp | 4 - dCommon/GeneralUtils.h | 184 ++++---- dCommon/LDFFormat.cpp | 38 +- dCommon/dClient/CMakeLists.txt | 2 +- dCommon/dClient/ClientVersion.h | 12 + dGame/Entity.cpp | 6 +- dGame/Entity.h | 10 +- dGame/dComponents/ActivityComponent.cpp | 3 +- dGame/dComponents/QuickBuildComponent.cpp | 9 +- dGame/dComponents/QuickBuildComponent.h | 2 +- dGame/dComponents/RenderComponent.cpp | 10 +- dGame/dComponents/TriggerComponent.cpp | 59 ++- dGame/dInventory/Item.cpp | 8 +- dGame/dInventory/ItemSet.cpp | 6 +- dGame/dMission/MissionTask.cpp | 12 +- .../BehaviorMessageBase.cpp | 7 +- dGame/dUtilities/Preconditions.cpp | 6 +- dGame/dUtilities/SlashCommandHandler.cpp | 400 +++++++++--------- dMasterServer/InstanceManager.cpp | 3 +- dMasterServer/InstanceManager.h | 2 +- dMasterServer/MasterServer.cpp | 3 +- dNet/AuthPackets.cpp | 23 +- dPhysics/dpWorld.cpp | 10 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 14 +- dScripts/02_server/Map/AM/AmSkullkinTower.cpp | 9 +- .../Map/AM/AmTemplateSkillVolume.cpp | 9 +- dScripts/ChooseYourDestinationNsToNt.cpp | 10 +- dScripts/ai/FV/FvBrickPuzzleServer.cpp | 16 +- dWorldServer/WorldServer.cpp | 3 +- dZoneManager/Level.cpp | 13 +- 33 files changed, 463 insertions(+), 453 deletions(-) create mode 100644 dCommon/dClient/ClientVersion.h diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 5593f0e1..476e1a68 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -82,11 +82,11 @@ int main(int argc, char** argv) { Game::randomEngine = std::mt19937(time(0)); //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("auth_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + + //LU client is hardcoded to use this for auth port, so I'm making it the default. + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("auth_server_port")).value_or(1001); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index d04cbd01..44957042 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -99,18 +99,15 @@ int main(int argc, char** argv) { masterPort = masterInfo->port; } //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1501; std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("chat_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("chat_server_port")).value_or(1501); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; Game::server = new dServer(ourIP, ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::lastSignal); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::randomEngine = std::mt19937(time(0)); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 95bafd8b..7d8d7d97 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -15,8 +15,10 @@ #include "dConfig.h" void PlayerContainer::Initialize() { - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends"), m_MaxNumberOfBestFriends); - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends"), m_MaxNumberOfFriends); + m_MaxNumberOfBestFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends")).value_or(m_MaxNumberOfBestFriends); + m_MaxNumberOfFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } PlayerContainer::~PlayerContainer() { diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index b45165fa..78cf4f48 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -319,7 +319,3 @@ std::vector GeneralUtils::GetSqlFileNamesFromFolder(const std::stri return sortedFiles; } - -bool GeneralUtils::TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst) { - return TryParse(x.c_str(), dst.x) && TryParse(y.c_str(), dst.y) && TryParse(z.c_str(), dst.z); -} diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 37291ab8..15659912 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -1,17 +1,20 @@ #pragma once // C++ -#include +#include +#include #include -#include +#include #include -#include +#include +#include #include #include #include #include "BitStream.h" #include "NiPoint3.h" +#include "dPlatforms.h" #include "Game.h" #include "Logger.h" @@ -123,90 +126,125 @@ namespace GeneralUtils { std::vector GetSqlFileNamesFromFolder(const std::string& folder); + // Concept constraining to enum types template - T Parse(const char* value); - - template <> - inline bool Parse(const char* value) { - return std::stoi(value); - } - - template <> - inline int32_t Parse(const char* value) { - return std::stoi(value); - } - - template <> - inline int64_t Parse(const char* value) { - return std::stoll(value); - } - - template <> - inline float Parse(const char* value) { - return std::stof(value); - } - - template <> - inline double Parse(const char* value) { - return std::stod(value); - } - - template <> - inline uint16_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint32_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint64_t Parse(const char* value) { - return std::stoull(value); - } - - template <> - inline eInventoryType Parse(const char* value) { - return static_cast(std::stoul(value)); - } - - template <> - inline eReplicaComponentType Parse(const char* value) { - return static_cast(std::stoul(value)); - } + concept Enum = std::is_enum_v; + // Concept constraining to numeric types template - bool TryParse(const char* value, T& dst) { - try { - dst = Parse(value); + concept Numeric = std::integral || Enum || std::floating_point; - return true; - } catch (...) { - return false; + // Concept trickery to enable parsing underlying numeric types + template + struct numeric_parse { using type = T; }; + + // If an enum, present an alias to its underlying type for parsing + template requires Enum + struct numeric_parse { using type = std::underlying_type_t; }; + + // If a boolean, present an alias to an intermediate integral type for parsing + template requires std::same_as + struct numeric_parse { using type = uint32_t; }; + + // Shorthand type alias + template + using numeric_parse_t = numeric_parse::type; + + /** + * For numeric values: Parses a string_view and returns an optional variable depending on the result. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) { + numeric_parse_t result; + + const char* const strEnd = str.data() + str.size(); + const auto [parseEnd, ec] = std::from_chars(str.data(), strEnd, result); + const bool isParsed = parseEnd == strEnd && ec == std::errc{}; + + return isParsed ? static_cast(result) : std::optional{}; + } + +#ifdef DARKFLAME_PLATFORM_MACOS + + // Anonymous namespace containing MacOS floating-point parse function specializations + namespace { + template + [[nodiscard]] T Parse(const std::string_view str, size_t* parseNum); + + template <> + [[nodiscard]] float Parse(const std::string_view str, size_t* parseNum) { + return std::stof(std::string{ str }, parseNum); + } + + template <> + [[nodiscard]] double Parse(const std::string_view str, size_t* parseNum) { + return std::stod(std::string{ str }, parseNum); + } + + template <> + [[nodiscard]] long double Parse(const std::string_view str, size_t* parseNum) { + return std::stold(std::string{ str }, parseNum); } } + /** + * For floating-point values: Parses a string_view and returns an optional variable depending on the result. + * Note that this function overload is only included for MacOS, as from_chars will fulfill its purpose otherwise. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept try { + size_t parseNum; + const T result = Parse(str, &parseNum); + const bool isParsed = str.length() == parseNum; + + return isParsed ? result : std::optional{}; + } catch (...) { + return std::nullopt; + } + +#endif + + /** + * The TryParse overload for handling NiPoint3 by passing 3 seperate string references + * @param strX The string representing the X coordinate + * @param strY The string representing the Y coordinate + * @param strZ The string representing the Z coordinate + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ template - T Parse(const std::string& value) { - return Parse(value.c_str()); + [[nodiscard]] std::optional TryParse(const std::string& strX, const std::string& strY, const std::string& strZ) { + const auto x = TryParse(strX); + if (!x) return std::nullopt; + + const auto y = TryParse(strY); + if (!y) return std::nullopt; + + const auto z = TryParse(strZ); + return z ? std::make_optional(x.value(), y.value(), z.value()) : std::nullopt; + } + + /** + * The TryParse overload for handling NiPoint3 by passingn a reference to a vector of three strings + * @param str The string vector representing the X, Y, and Xcoordinates + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ + template + [[nodiscard]] std::optional TryParse(const std::vector& str) { + return (str.size() == 3) ? TryParse(str[0], str[1], str[2]) : std::nullopt; } template - bool TryParse(const std::string& value, T& dst) { - return TryParse(value.c_str(), dst); - } - - bool TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst); - - template std::u16string to_u16string(T value) { return GeneralUtils::ASCIIToUTF16(std::to_string(value)); } // From boost::hash_combine template - void hash_combine(std::size_t& s, const T& v) { + constexpr void hash_combine(std::size_t& s, const T& v) { std::hash h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } @@ -239,10 +277,8 @@ namespace GeneralUtils { * @param entry Enum entry to cast * @returns The enum entry's value in its underlying type */ - template - inline constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) { - static_assert(std::is_enum_v, "Not an enum"); - + template + constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) noexcept { return static_cast>(entry); } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 67f6a630..da28ae6e 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -61,33 +61,33 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_S32: { - int32_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_FLOAT: { - float data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_DOUBLE: { - double data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } @@ -100,10 +100,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = 0; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -118,10 +120,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = false; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -129,22 +133,22 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_U64: { - uint64_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_OBJID: { - LWOOBJID data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } diff --git a/dCommon/dClient/CMakeLists.txt b/dCommon/dClient/CMakeLists.txt index 69bb1712..017a22a5 100644 --- a/dCommon/dClient/CMakeLists.txt +++ b/dCommon/dClient/CMakeLists.txt @@ -1,6 +1,6 @@ set(DCOMMON_DCLIENT_SOURCES + "AssetManager.cpp" "PackIndex.cpp" "Pack.cpp" - "AssetManager.cpp" PARENT_SCOPE ) diff --git a/dCommon/dClient/ClientVersion.h b/dCommon/dClient/ClientVersion.h new file mode 100644 index 00000000..393103ab --- /dev/null +++ b/dCommon/dClient/ClientVersion.h @@ -0,0 +1,12 @@ +#ifndef __CLIENTVERSION_H__ +#define __CLIENTVERSION_H__ + +#include + +namespace ClientVersion { + constexpr uint16_t major = 1; + constexpr uint16_t current = 10; + constexpr uint16_t minor = 64; +} + +#endif // !__CLIENTVERSION_H__ diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 84bdca21..16169887 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -452,10 +452,10 @@ void Entity::Initialize() { if (!setFaction.empty()) { // TODO also split on space here however we do not have a general util for splitting on multiple characters yet. std::vector factionsToAdd = GeneralUtils::SplitString(setFaction, ';'); - int32_t factionToAdd; for (const auto faction : factionsToAdd) { - if (GeneralUtils::TryParse(faction, factionToAdd)) { - comp->AddFaction(factionToAdd, true); + const auto factionToAdd = GeneralUtils::TryParse(faction); + if (factionToAdd) { + comp->AddFaction(factionToAdd.value(), true); } } } diff --git a/dGame/Entity.h b/dGame/Entity.h index eb6eb956..6546e458 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -395,14 +395,8 @@ const T& Entity::GetVar(const std::u16string& name) const { template T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); - - T value; - - if (!GeneralUtils::TryParse(data, value)) { - return LDFData::Default; - } - - return value; + + return GeneralUtils::TryParse(data).value_or(LDFData::Default); } template diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index 376251d2..49ca4faf 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -83,7 +83,8 @@ void ActivityComponent::LoadActivityData(const int32_t activityId) { if (m_ActivityInfo.instanceMapID == -1) { const auto& transferOverride = m_Parent->GetVarAsString(u"transferZoneID"); if (!transferOverride.empty()) { - GeneralUtils::TryParse(transferOverride, m_ActivityInfo.instanceMapID); + m_ActivityInfo.instanceMapID = + GeneralUtils::TryParse(transferOverride).value_or(m_ActivityInfo.instanceMapID); } } } diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index 1e745d8a..2514f194 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -33,10 +33,9 @@ QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { // Should a setting that has the build activator position exist, fetch that setting here and parse it for position. // It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F) auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F); - if (positionAsVector.size() == 3 && - GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && - GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { + const auto activatorPositionValid = GeneralUtils::TryParse(positionAsVector); + if (positionAsVector.size() == 3 && activatorPositionValid) { + m_ActivatorPosition = activatorPositionValid.value(); } else { LOG("Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); @@ -328,7 +327,7 @@ float QuickBuildComponent::GetTimeBeforeSmash() { return m_TimeBeforeSmash; } -eQuickBuildState QuickBuildComponent::GetState() { +eQuickBuildState QuickBuildComponent::GetState() const noexcept { return m_State; } diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index d989bc51..d9cc4190 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -173,7 +173,7 @@ public: * Returns the current quickbuild state * @return the current quickbuild state */ - eQuickBuildState GetState(); + [[nodiscard]] eQuickBuildState GetState() const noexcept; /** * Returns the player that is currently building this quickbuild diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index d3c74f78..118e4847 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -30,13 +30,15 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { - int32_t groupIdInt; - if (!GeneralUtils::TryParse(groupId, groupIdInt)) { + const auto groupIdInt = GeneralUtils::TryParse(groupId); + + if (!groupIdInt) { LOG("bad animation group Id %s", groupId.c_str()); continue; } - m_animationGroupIds.push_back(groupIdInt); - animationsTable->CacheAnimationGroup(groupIdInt); + + m_animationGroupIds.push_back(groupIdInt.value()); + animationsTable->CacheAnimationGroup(groupIdInt.value()); } } } diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index bb297dbc..5d4415f8 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -21,10 +21,8 @@ TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo std::vector tokens = GeneralUtils::SplitString(triggerInfo, ':'); - uint32_t sceneID; - GeneralUtils::TryParse(tokens.at(0), sceneID); - uint32_t triggerID; - GeneralUtils::TryParse(tokens.at(1), triggerID); + const auto sceneID = GeneralUtils::TryParse(tokens.at(0)).value_or(0); + const auto triggerID = GeneralUtils::TryParse(tokens.at(1)).value_or(0); m_Trigger = Game::zoneManager->GetZone()->GetTrigger(sceneID, triggerID); @@ -190,9 +188,8 @@ void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { } void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args){ - uint32_t killType; - GeneralUtils::TryParse(args, killType); - targetEntity->Smash(m_Parent->GetObjectID(), static_cast(killType)); + const eKillType killType = GeneralUtils::TryParse(args).value_or(eKillType::VIOLENT); + targetEntity->Smash(m_Parent->GetObjectID(), killType); } void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ @@ -216,9 +213,8 @@ void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - auto position = targetEntity->GetPosition(); - NiPoint3 offset = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); + NiPoint3 position = targetEntity->GetPosition(); + const NiPoint3 offset = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); position += offset; targetEntity->SetPosition(position); @@ -227,8 +223,7 @@ void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - NiPoint3 vector = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); + const NiPoint3 vector = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); targetEntity->SetRotation(rotation); @@ -245,8 +240,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorSetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(1); - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); + const NiPoint3 direction = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); phantomPhysicsComponent->SetDirection(direction); Game::entityManager->SerializeEntity(m_Parent); @@ -259,8 +253,8 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) LOG_DEBUG("Phantom Physics component not found!"); return; } - float forceMultiplier; - GeneralUtils::TryParse(args, forceMultiplier); + const float forceMultiplier = GeneralUtils::TryParse(args).value_or(1.0f); + phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(forceMultiplier); @@ -279,11 +273,10 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray){ if (argArray.size() != 2) { - LOG_DEBUG("Not ehought variables!"); + LOG_DEBUG("Not enough variables!"); return; } - float time = 0.0; - GeneralUtils::TryParse(argArray.at(1), time); + const float time = GeneralUtils::TryParse(argArray.at(1)).value_or(0.0f); m_Parent->AddTimer(argArray.at(0), time); } @@ -299,7 +292,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector= 2) { - GeneralUtils::TryParse(argArray.at(1), leadIn); + leadIn = GeneralUtils::TryParse(argArray.at(1)).value_or(leadIn); if (argArray.size() >= 3 && argArray.at(2) == "wait") { wait = eEndBehavior::WAIT; if (argArray.size() >= 4 && argArray.at(3) == "unlock") { @@ -344,12 +337,16 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector argArray) { if (argArray.size() < 3) return; - int32_t effectID = 0; - if (!GeneralUtils::TryParse(argArray.at(1), effectID)) return; + const auto effectID = GeneralUtils::TryParse(argArray.at(1)); + if (!effectID) return; std::u16string effectType = GeneralUtils::UTF8ToUTF16(argArray.at(2)); + float priority = 1; - if (argArray.size() == 4) GeneralUtils::TryParse(argArray.at(3), priority); - GameMessages::SendPlayFXEffect(targetEntity, effectID, effectType, argArray.at(0), LWOOBJID_EMPTY, priority); + if (argArray.size() == 4) { + priority = GeneralUtils::TryParse(argArray.at(3)).value_or(priority); + } + + GameMessages::SendPlayFXEffect(targetEntity, effectID.value(), effectType, argArray.at(0), LWOOBJID_EMPTY, priority); } void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ @@ -358,8 +355,7 @@ void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ LOG_DEBUG("Skill component not found!"); return; } - uint32_t skillId; - GeneralUtils::TryParse(args, skillId); + const uint32_t skillId = GeneralUtils::TryParse(args).value_or(0); skillComponent->CastSkill(skillId, targetEntity->GetObjectID()); } @@ -381,17 +377,16 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v phantomPhysicsComponent->SetEffectType(effectType); phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); + const NiPoint3 direction = + GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4)).value_or(NiPoint3Constant::ZERO); + phantomPhysicsComponent->SetDirection(direction); } if (argArray.size() > 5) { - uint32_t min; - GeneralUtils::TryParse(argArray.at(6), min); + const uint32_t min = GeneralUtils::TryParse(argArray.at(6)).value_or(0); phantomPhysicsComponent->SetMin(min); - uint32_t max; - GeneralUtils::TryParse(argArray.at(7), max); + const uint32_t max = GeneralUtils::TryParse(argArray.at(7)).value_or(0); phantomPhysicsComponent->SetMax(max); } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 55b0a2d0..d3f15315 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -468,14 +468,14 @@ void Item::DisassembleModel(uint32_t numToDismantle) { // First iteration gets the count std::map parts; while (currentBrick) { - auto* designID = currentBrick->Attribute("designID"); + const char* const designID = currentBrick->Attribute("designID"); if (designID) { - uint32_t designId; - if (!GeneralUtils::TryParse(designID, designId)) { + const auto designId = GeneralUtils::TryParse(designID); + if (!designId) { LOG("Failed to parse designID %s", designID); continue; } - parts[designId]++; + parts[designId.value()]++; } currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 54db9e9c..1d086786 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -87,10 +87,8 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { m_Items = {}; while (std::getline(stream, token, ',')) { - int32_t value; - if (GeneralUtils::TryParse(token, value)) { - m_Items.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) m_Items.push_back(validToken.value()); } m_Equipped = {}; diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 604276ec..2fe9bc9f 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -27,19 +27,15 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) std::string token; while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - parameters.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) parameters.push_back(parameter.value()); } stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - targets.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) targets.push_back(parameter.value()); } } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index cc817cd7..0aad74dd 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -5,7 +5,7 @@ #include "dCommonVars.h" BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { - behaviorId = GetBehaviorIdFromArgument(arguments); + this->behaviorId = GetBehaviorIdFromArgument(arguments); } int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { @@ -13,12 +13,13 @@ int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) auto* behaviorIDValue = arguments->Get(key); if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { - GeneralUtils::TryParse(behaviorIDValue->GetValue(), behaviorId); + this->behaviorId = + GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(this->behaviorId); } else if (arguments->Get(key) && arguments->Get(key)->GetValueType() != eAmf::Undefined) { throw std::invalid_argument("Unable to find behavior ID"); } - return behaviorId; + return this->behaviorId; } int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 12059b5b..bd855962 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -40,10 +40,8 @@ Precondition::Precondition(const uint32_t condition) { std::string token; while (std::getline(stream, token, ',')) { - uint32_t value; - if (GeneralUtils::TryParse(token, value)) { - this->values.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) this->values.push_back(validToken.value()); } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index ef12c396..169426ab 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -113,13 +113,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { if (args.size() != 1) return; - uint32_t level_intermed = 0; + const auto level_intermed = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], level_intermed)) { + if (!level_intermed) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } - eGameMasterLevel level = static_cast(level_intermed); + eGameMasterLevel level = static_cast(level_intermed.value()); #ifndef DEVELOPER_SERVER if (user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER) { @@ -378,26 +378,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "resetmission" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t missionId; - if (!GeneralUtils::TryParse(args[0], missionId)) { + const auto missionId = GeneralUtils::TryParse(args[0]); + if (!missionId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission ID."); return; } auto* missionComponent = entity->GetComponent(); if (!missionComponent) return; - missionComponent->ResetMission(missionId); + missionComponent->ResetMission(missionId.value()); } // Log command to database Database::Get()->InsertSlashCommandUsage(entity->GetObjectID(), chatCommand); if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { // could break characters so only allow if GM > 0 - int32_t minifigItemId; - if (!GeneralUtils::TryParse(args[1], minifigItemId)) { + const auto minifigItemIdExists = GeneralUtils::TryParse(args[1]); + if (!minifigItemIdExists) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid Minifig Item Id ID."); return; } + const int32_t minifigItemId = minifigItemIdExists.value(); Game::entityManager->DestructEntity(entity, sysAddr); auto* charComp = entity->GetComponent(); std::string lowerName = args[0]; @@ -457,14 +458,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t emoteID; + const auto emoteID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], emoteID)) { + if (!emoteID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } - entity->GetCharacter()->UnlockEmote(emoteID); + entity->GetCharacter()->UnlockEmote(emoteID.value()); } if (chatCommand == "force-save" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -486,19 +487,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - float boost; - - if (!GeneralUtils::TryParse(args[0], boost)) { + const auto boostOptional = GeneralUtils::TryParse(args[0]); + if (!boostOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } + const float boost = boostOptional.value(); auto* controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); - // speedboost possesables + // speedboost possessables auto possessor = entity->GetComponent(); if (possessor) { auto possessedID = possessor->GetPossessable(); @@ -527,14 +528,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t scheme; + const auto scheme = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], scheme)) { + if (!scheme) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } - GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme.value())); ChatPackets::SendSystemMessage(sysAddr, u"Switched control scheme."); return; @@ -574,29 +575,28 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { - uint32_t size; - - if (!GeneralUtils::TryParse(args.at(0), size)) { + const auto sizeOptional = GeneralUtils::TryParse(args[0]); + if (!sizeOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } + const uint32_t size = sizeOptional.value(); eInventoryType selectedInventory = eInventoryType::ITEMS; // a possible inventory was provided if we got more than 1 argument if (args.size() >= 2) { - selectedInventory = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args.at(1), selectedInventory)) { + selectedInventory = GeneralUtils::TryParse(args.at(1)).value_or(eInventoryType::INVALID); + if (selectedInventory == eInventoryType::INVALID) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); + return; + } else { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args.at(1).begin(), args.at(1).end(), args.at(1).begin(), ::toupper); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args.at(1)) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) selectedInventory = static_cast(index); } } - if (selectedInventory == eInventoryType::INVALID) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); - return; - } ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory " + GeneralUtils::ASCIIToUTF16(args.at(1)) + @@ -643,48 +643,48 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->AcceptMission(missionID, true); + if (comp) comp->AcceptMission(missionID.value(), true); return; } if (chatCommand == "completemission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->CompleteMission(missionID, true); + if (comp) comp->CompleteMission(missionID.value(), true); return; } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, true); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), true); } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { - int32_t flagId; - std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) { + const auto flagId = GeneralUtils::TryParse(args.at(1)); + std::string onOffFlag = args.at(0); + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -692,28 +692,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag type."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), onOffFlag == "on"); } if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, false); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), false); } if (chatCommand == "playeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - int32_t effectID = 0; + const auto effectID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], effectID)) { - return; - } + if (!effectID) return; // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway - GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); + GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID.value(), GeneralUtils::ASCIIToUTF16(args.at(1)), args.at(2)); } if (chatCommand == "stopeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { @@ -775,34 +773,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmadditem" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 1) { - uint32_t itemLOT; + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, 1, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), 1, eLootSourceType::MODERATION); } else if (args.size() == 2) { - uint32_t itemLOT; - - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - uint32_t count; - - if (!GeneralUtils::TryParse(args[1], count)) { + const auto count = GeneralUtils::TryParse(args.at(1)); + if (!count) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, count, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), count.value(), eLootSourceType::MODERATION); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } @@ -822,9 +818,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit receiverID = playerInfo->id; - LOT lot; + const auto lot = GeneralUtils::TryParse(args.at(1)); - if (!GeneralUtils::TryParse(args[1], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -837,7 +833,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit mailInsert.subject = "Lost item"; mailInsert.body = "This is a replacement item for one you lost."; mailInsert.itemID = LWOOBJID_EMPTY; - mailInsert.itemLOT = lot; + mailInsert.itemLOT = lot.value(); mailInsert.itemSubkey = LWOOBJID_EMPTY; mailInsert.itemCount = 1; Database::Get()->InsertNewMail(mailInsert); @@ -871,46 +867,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit NiPoint3 pos{}; if (args.size() == 3) { - float x, y, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) { + const auto y = GeneralUtils::TryParse(args.at(1)); + if (!y) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) { + const auto z = GeneralUtils::TryParse(args.at(2)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x.value()); + pos.SetY(y.value()); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else if (args.size() == 2) { - float x, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) { + const auto z = GeneralUtils::TryParse(args.at(1)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); + pos.SetX(x.value()); pos.SetY(0.0f); - pos.SetZ(z); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); @@ -970,10 +967,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit float speedScale = 1.0f; if (args.size() >= 1) { - float tempScaleStore; + const auto tempScaleStore = GeneralUtils::TryParse(args.at(0)); - if (GeneralUtils::TryParse(args[0], tempScaleStore)) { - speedScale = tempScaleStore; + if (tempScaleStore) { + speedScale = tempScaleStore.value(); } else { ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); } @@ -1025,16 +1022,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit time_t expire = 1; // Default to indefinate mute if (args.size() >= 2) { - uint32_t days = 0; - uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) { + const auto days = GeneralUtils::TryParse(args[1]); + if (!days) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } + std::optional hours; if (args.size() >= 3) { - if (!GeneralUtils::TryParse(args[2], hours)) { + hours = GeneralUtils::TryParse(args[2]); + if (!hours) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1042,8 +1040,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } expire = time(NULL); - expire += 24 * 60 * 60 * days; - expire += 60 * 60 * hours; + expire += 24 * 60 * 60 * days.value(); + expire += 60 * 60 * hours.value_or(0); } if (accountId != 0) Database::Get()->UpdateAccountUnmuteTime(accountId, expire); @@ -1143,14 +1141,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t celebration; + const auto celebration = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], celebration)) { + if (!celebration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } - GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); + GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration.value()); } if (chatCommand == "buffmed" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -1204,15 +1202,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; - uint32_t lot; + const auto lot = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.pos = comp->GetPosition(); info.rot = comp->GetRotation(); info.spawner = nullptr; @@ -1233,28 +1231,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; - LOT lot{}; - uint32_t numberToSpawn{}; - float radiusToSpawnWithin{}; - - if (!GeneralUtils::TryParse(args[0], lot)) { + const auto lot = GeneralUtils::TryParse(args[0]); + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } - if (!GeneralUtils::TryParse(args[1], numberToSpawn) && numberToSpawn > 0) { + const auto numberToSpawnOptional = GeneralUtils::TryParse(args[1]); + if (!numberToSpawnOptional && numberToSpawnOptional.value() > 0) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid number of enemies to spawn."); return; } + uint32_t numberToSpawn = numberToSpawnOptional.value(); // Must spawn within a radius of at least 0.0f - if (!GeneralUtils::TryParse(args[2], radiusToSpawnWithin) && radiusToSpawnWithin < 0.0f) { + const auto radiusToSpawnWithinOptional = GeneralUtils::TryParse(args[2]); + if (!radiusToSpawnWithinOptional && radiusToSpawnWithinOptional.value() < 0.0f) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid radius to spawn within."); return; } + const float radiusToSpawnWithin = radiusToSpawnWithinOptional.value(); EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.spawner = nullptr; info.spawnerID = entity->GetObjectID(); info.spawnerNodeID = 0; @@ -1281,12 +1280,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t uscore; - - if (!GeneralUtils::TryParse(args[0], uscore)) { + const auto uscoreOptional = GeneralUtils::TryParse(args[0]); + if (!uscoreOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } + const int32_t uscore = uscoreOptional.value(); CharacterComponent* character = entity->GetComponent(); if (character) character->SetUScore(character->GetUScore() + uscore); @@ -1294,9 +1293,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eLootSourceType lootType = eLootSourceType::MODERATION; - int32_t type; - if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { - lootType = static_cast(type); + if (args.size() >= 2) { + const auto type = GeneralUtils::TryParse(args[1]); + lootType = type.value_or(lootType); } GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); @@ -1322,14 +1321,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity = requestedPlayer->GetOwner(); } - uint32_t requestedLevel; + const auto requestedLevelOptional = GeneralUtils::TryParse(args[0]); uint32_t oldLevel; - // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) { + // first check the level is valid + if (!requestedLevelOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } + uint32_t requestedLevel = requestedLevelOptional.value(); // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); @@ -1402,27 +1402,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "freemoney" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) && args.size() == 1) { - int64_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(ch->GetCoins() + money, eLootSourceType::MODERATION); + ch->SetCoins(ch->GetCoins() + money.value(), eLootSourceType::MODERATION); } if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(money, eLootSourceType::MODERATION); + ch->SetCoins(money.value(), eLootSourceType::MODERATION); } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. @@ -1435,17 +1435,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsGMImmune(state.value()); return; } @@ -1453,53 +1450,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "attackimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsImmune(state.value()); return; } if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* buffComponent = entity->GetComponent(); - int32_t id = 0; - int32_t duration = 0; - - if (!GeneralUtils::TryParse(args[0], id)) { + const auto id = GeneralUtils::TryParse(args[0]); + if (!id) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) { + const auto duration = GeneralUtils::TryParse(args[1]); + if (!duration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) { - buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); - } - + if (buffComponent) buffComponent->ApplyBuff(id.value(), duration.value(), entity->GetObjectID()); return; } if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Requesting map change..."); - uint32_t reqZone; LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) { + const auto reqZoneOptional = GeneralUtils::TryParse(args[0]); + if (!reqZoneOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } + const LWOMAPID reqZone = reqZoneOptional.value(); if (args.size() > 1) { auto index = 1; @@ -1510,9 +1501,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); - return; + if (args.size() > index) { + const auto cloneIdOptional = GeneralUtils::TryParse(args[index]); + if (!cloneIdOptional) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); + return; + } + cloneId = cloneIdOptional.value(); } } @@ -1550,23 +1545,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "createprivate" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - uint32_t zone; - - if (!GeneralUtils::TryParse(args[0], zone)) { + const auto zone = GeneralUtils::TryParse(args[0]); + if (!zone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - uint32_t clone; - - if (!GeneralUtils::TryParse(args[1], clone)) { + const auto clone = GeneralUtils::TryParse(args[1]); + if (!clone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } const auto& password = args[2]; - ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone, clone, password); + ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone.value(), clone.value(), password); ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16("Sent request for private zone with password: " + password)); @@ -1593,14 +1586,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 1) { - float time; + const auto time = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], time)) { + if (!time) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); return; } else { GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - entity->AddCallbackTimer(time, [vehicle]() { + entity->AddCallbackTimer(time.value(), [vehicle]() { if (!vehicle) return; GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); }); @@ -1676,20 +1669,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "reforge" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - LOT baseItem; - LOT reforgedItem; + const auto baseItem = GeneralUtils::TryParse(args[0]); + if (!baseItem) return; - if (!GeneralUtils::TryParse(args[0], baseItem)) return; - if (!GeneralUtils::TryParse(args[1], reforgedItem)) return; + const auto reforgedItem = GeneralUtils::TryParse(args[1]); + if (!reforgedItem) return; auto* inventoryComponent = entity->GetComponent(); - - if (inventoryComponent == nullptr) return; + if (!inventoryComponent) return; std::vector data{}; - data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); + data.push_back(new LDFData(u"reforgedLOT", reforgedItem.value())); - inventoryComponent->AddItem(baseItem, 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); + inventoryComponent->AddItem(baseItem.value(), 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); } if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { @@ -1743,8 +1735,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit VanityUtilities::SpawnVanity(); dpWorld::Reload(); auto entities = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (auto entity : entities) { - auto* scriptedActivityComponent = entity->GetComponent(); + for (const auto* const entity : entities) { + auto* const scriptedActivityComponent = entity->GetComponent(); if (!scriptedActivityComponent) continue; scriptedActivityComponent->ReloadConfig(); @@ -1755,19 +1747,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "rollloot" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR && args.size() >= 3) { - uint32_t lootMatrixIndex = 0; - uint32_t targetLot = 0; - uint32_t loops = 1; + const auto lootMatrixIndex = GeneralUtils::TryParse(args[0]); + if (!lootMatrixIndex) return; - if (!GeneralUtils::TryParse(args[0], lootMatrixIndex)) return; - if (!GeneralUtils::TryParse(args[1], targetLot)) return; - if (!GeneralUtils::TryParse(args[2], loops)) return; + const auto targetLot = GeneralUtils::TryParse(args[1]); + if (!targetLot) return; + + const auto loops = GeneralUtils::TryParse(args[2]); + if (!loops) return; uint64_t totalRuns = 0; for (uint32_t i = 0; i < loops; i++) { while (true) { - auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex); + auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex.value()); totalRuns += 1; bool doBreak = false; for (const auto& kv : lootRoll) { @@ -1780,26 +1773,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } std::u16string message = u"Ran loot drops looking for " - + GeneralUtils::to_u16string(targetLot) + + GeneralUtils::to_u16string(targetLot.value()) + u", " - + GeneralUtils::to_u16string(loops) + + GeneralUtils::to_u16string(loops.value()) + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string(static_cast(totalRuns) / loops); + + GeneralUtils::to_u16string(static_cast(totalRuns) / loops.value()); ChatPackets::SendSystemMessage(sysAddr, message); } if (chatCommand == "deleteinven" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { eInventoryType inventoryType = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args[0], inventoryType)) { + + const auto inventoryTypeOptional = GeneralUtils::TryParse(args[0]); + if (!inventoryTypeOptional) { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args[0].begin(), args[0].end(), args[0].begin(), ::toupper); LOG("looking for inventory %s", args[0].c_str()); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args[0]) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) inventoryType = static_cast(index); } + } else { + inventoryType = inventoryTypeOptional.value(); } if (inventoryType == eInventoryType::INVALID || inventoryType >= NUMBER_OF_INVENTORIES) { @@ -1821,32 +1818,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "castskill" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* skillComponent = entity->GetComponent(); if (skillComponent) { - uint32_t skillId; + const auto skillId = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], skillId)) { + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill ID."); return; } else { - skillComponent->CastSkill(skillId, entity->GetObjectID(), entity->GetObjectID()); + skillComponent->CastSkill(skillId.value(), entity->GetObjectID(), entity->GetObjectID()); ChatPackets::SendSystemMessage(sysAddr, u"Cast skill"); } } } if (chatCommand == "setskillslot" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - uint32_t skillId; - int slot; - auto* inventoryComponent = entity->GetComponent(); + auto* const inventoryComponent = entity->GetComponent(); if (inventoryComponent) { - if (!GeneralUtils::TryParse(args[0], slot)) { + const auto slot = GeneralUtils::TryParse(args[0]); + if (!slot) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting slot."); return; } else { - if (!GeneralUtils::TryParse(args[1], skillId)) { + const auto skillId = GeneralUtils::TryParse(args[1]); + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill."); return; } else { - if (inventoryComponent->SetSkill(slot, skillId)) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); + if (inventoryComponent->SetSkill(slot.value(), skillId.value())) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); else ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot failed"); } } @@ -1856,13 +1853,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->SetFaction(faction); + destroyableComponent->SetFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Set faction and updated enemies list"); } } @@ -1871,13 +1868,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->AddFaction(faction); + destroyableComponent->AddFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Added faction and updated enemies list"); } } @@ -1908,13 +1905,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "inspect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; - eReplicaComponentType component; - std::u16string ldf; bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) { + auto component = GeneralUtils::TryParse(args[0]); + if (!component) { component = eReplicaComponentType::INVALID; ldf = GeneralUtils::UTF8ToUTF16(args[0]); @@ -1926,7 +1922,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto closestDistance = 0.0f; - const auto candidates = Game::entityManager->GetEntitiesByComponent(component); + const auto candidates = Game::entityManager->GetEntitiesByComponent(component.value()); for (auto* candidate : candidates) { if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { @@ -1937,7 +1933,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit continue; } - if (closest == nullptr) { + if (!closest) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1954,9 +1950,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (closest == nullptr) { - return; - } + if (!closest) return; Game::entityManager->SerializeEntity(closest); @@ -1982,20 +1976,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() >= 2) { if (args[1] == "-m" && args.size() >= 3) { - auto* movingPlatformComponent = closest->GetComponent(); + auto* const movingPlatformComponent = closest->GetComponent(); - int32_t value = 0; + const auto mValue = GeneralUtils::TryParse(args[2]); - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { - return; - } + if (!movingPlatformComponent || !mValue) return; movingPlatformComponent->SetSerialized(true); - if (value == -1) { + if (mValue == -1) { movingPlatformComponent->StopPathing(); } else { - movingPlatformComponent->GotoWaypoint(value); + movingPlatformComponent->GotoWaypoint(mValue.value()); } Game::entityManager->SerializeEntity(closest); @@ -2036,13 +2028,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 3) { - int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) { - return; - } + const auto faction = GeneralUtils::TryParse(args[2]); + if (!faction) return; destuctable->SetFaction(-1); - destuctable->AddFaction(faction, true); + destuctable->AddFaction(faction.value(), true); } } else if (args[1] == "-cf") { auto* destuctable = entity->GetComponent(); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a46ed81a..9ae9930c 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -17,7 +17,8 @@ InstanceManager::InstanceManager(Logger* logger, const std::string& externalIP) { mLogger = logger; mExternalIP = externalIP; - GeneralUtils::TryParse(Game::config->GetValue("world_port_start"), m_LastPort); + m_LastPort = + GeneralUtils::TryParse(Game::config->GetValue("world_port_start")).value_or(m_LastPort); m_LastInstanceID = LWOINSTANCEID_INVALID; } diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index b9f1ec5a..1fc4af43 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -134,7 +134,7 @@ private: Logger* mLogger; std::string mExternalIP; std::vector m_Instances; - unsigned short m_LastPort = 3000; + uint16_t m_LastPort = 3000; LWOINSTANCEID m_LastInstanceID; /** diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 749b4130..1fade06e 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -89,9 +89,8 @@ int main(int argc, char** argv) { if (!dConfig::Exists("worldconfig.ini")) LOG("Could not find worldconfig.ini, using default settings"); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); LOG("Using net version %i", clientNetVersion); diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 9982f89e..25ccc902 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -8,6 +8,7 @@ #include "ZoneInstanceManager.h" #include "MD5.h" #include "GeneralUtils.h" +#include "ClientVersion.h" #include @@ -38,10 +39,9 @@ void AuthPackets::LoadClaimCodes() { auto rcstring = Game::config->GetValue("rewardcodes"); auto codestrings = GeneralUtils::SplitString(rcstring, ','); for(auto const &codestring: codestrings){ - uint32_t code = -1; - if(GeneralUtils::TryParse(codestring, code) && code != -1){ - claimCodes.push_back(code); - } + const auto code = GeneralUtils::TryParse(codestring); + + if (code && code.value() != -1) claimCodes.push_back(code.value()); } } @@ -73,9 +73,8 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c RakNet::BitStream bitStream; BitStreamUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::VERSION_CONFIRM); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); bitStream.Write(clientNetVersion); bitStream.Write(861228100); @@ -242,12 +241,12 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd loginResponse.Write(LUString(Game::config->GetValue("event_7"))); loginResponse.Write(LUString(Game::config->GetValue("event_8"))); - uint16_t version_major = 1; - uint16_t version_current = 10; - uint16_t version_minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), version_major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), version_current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), version_minor); + const uint16_t version_major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + const uint16_t version_current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + const uint16_t version_minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); loginResponse.Write(version_major); loginResponse.Write(version_current); diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 4ed54858..c9bc742a 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -26,9 +26,15 @@ namespace { void dpWorld::Initialize(unsigned int zoneID, bool generateNewNavMesh) { const auto physSpTilecount = Game::config->GetValue("phys_sp_tilecount"); - if (!physSpTilecount.empty()) GeneralUtils::TryParse(physSpTilecount, phys_sp_tilecount); + if (!physSpTilecount.empty()) { + phys_sp_tilecount = GeneralUtils::TryParse(physSpTilecount).value_or(phys_sp_tilecount); + } + const auto physSpTilesize = Game::config->GetValue("phys_sp_tilesize"); - if (!physSpTilesize.empty()) GeneralUtils::TryParse(physSpTilesize, phys_sp_tilesize); + if (!physSpTilesize.empty()) { + phys_sp_tilesize = GeneralUtils::TryParse(physSpTilesize).value_or(phys_sp_tilesize); + } + const auto physSpatialPartitioning = Game::config->GetValue("phys_spatial_partitioning"); if (!physSpatialPartitioning.empty()) phys_spatial_partitioning = physSpatialPartitioning == "1"; diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 60b750cf..357187ef 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -33,14 +33,12 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -70,11 +68,9 @@ void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { } void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { - auto* quickBuildComponent = self->GetComponent(); + const auto* const quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr) { - return; - } + if (!quickBuildComponent) return; if (timerName == "reset" && quickBuildComponent->GetState() == eQuickBuildState::OPEN) { self->Smash(self->GetObjectID(), eKillType::SILENT); diff --git a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp index 0c0f7515..1eaad3c9 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp @@ -144,13 +144,10 @@ void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { ); for (const auto& mission : missions) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(mission); + if (!missionID) continue; - if (!GeneralUtils::TryParse(mission, missionID)) { - continue; - } - - missionIDs.push_back(missionID); + missionIDs.push_back(missionID.value()); } } diff --git a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp index 3acc9063..82f1481a 100644 --- a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp +++ b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp @@ -12,12 +12,9 @@ void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, cons const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); for (const auto& missionIDStr : missionIDs) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(missionIDStr); + if (!missionID) continue; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) { - continue; - } - - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + missionComponent->ForceProgressTaskType(missionID.value(), 1, 1, false); } } diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index f9ca0a79..b736883c 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -41,11 +41,9 @@ void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { if (button != -1) { const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); - - int32_t newMap = 0; - if (!GeneralUtils::TryParse(newMapStr, newMap)) { - return; - } + const auto newMap = GeneralUtils::TryParse(newMapStr); + + if (!newMap) return; std::u16string strText = u""; @@ -56,7 +54,7 @@ void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sen } self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap.value())); GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); } else { diff --git a/dScripts/ai/FV/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp index e1f1ac88..f8601e3f 100644 --- a/dScripts/ai/FV/FvBrickPuzzleServer.cpp +++ b/dScripts/ai/FV/FvBrickPuzzleServer.cpp @@ -7,10 +7,8 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; if (pipeNum != 1) { self->AddTimer("reset", 30); @@ -20,14 +18,12 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -37,7 +33,7 @@ void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { samePipeSpawners[0]->Deactivate(); } - if (killer != nullptr && killer->IsPlayer()) { + if (killer && killer->IsPlayer()) { const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); const auto nextPipeSpawners = Game::zoneManager->GetSpawnersByName(nextPipe); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6df5d0da..bb879dbd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -208,8 +208,7 @@ int main(int argc, char** argv) { UserManager::Instance()->Initialize(); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::lastSignal, zoneID); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 2606b46f..9524d908 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -14,6 +14,7 @@ #include "CDFeatureGatingTable.h" #include "CDClientManager.h" #include "AssetManager.h" +#include "ClientVersion.h" #include "dConfig.h" Level::Level(Zone* parentZone, const std::string& filepath) { @@ -211,12 +212,12 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; - gating.major = 1; - gating.current = 10; - gating.minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), gating.major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), gating.current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), gating.minor); + gating.major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + gating.current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + gating.minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); const auto zoneControlObject = Game::zoneManager->GetZoneControlObject(); DluAssert(zoneControlObject != nullptr); From 29666a1ff768ed01f581f783b12c2499cf82c839 Mon Sep 17 00:00:00 2001 From: jadebenn Date: Sat, 10 Feb 2024 13:44:40 -0600 Subject: [PATCH 5/5] chore: General cleanup roundup (#1444) * Moved unrelated changes out of the TryParse PR branch * const correctness and cstdint type usage * removing a few "== nullptr" * amf constexpr, const-correctness, and attrib tagging * update to account for feedback * Fixing accidentally included header and hopefully fixing the MacOS issue too * try reordering the amf3 specializations to fix the MacOS issue again * Amf3 template class member func instantiation fix * try including only on macos * Using if constexpr rather than specialization * Trying a different solution for the instantiation problem * Remove #include "dPlatforms.h" --- dChatServer/PlayerContainer.cpp | 9 - dChatServer/PlayerContainer.h | 7 +- dCommon/Amf3.h | 164 ++++++++++-------- dCommon/LDFFormat.h | 2 +- dCommon/dEnums/dCommonVars.h | 90 +++++----- dGame/dComponents/QuickBuildComponent.cpp | 66 ++++--- dGame/dComponents/QuickBuildComponent.h | 70 ++++---- .../AddStripMessage.cpp | 2 +- .../ControlBehaviorMessages/AddStripMessage.h | 2 +- .../BehaviorMessageBase.cpp | 14 +- .../BehaviorMessageBase.h | 12 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 8 +- 12 files changed, 218 insertions(+), 228 deletions(-) diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 7d8d7d97..dbbaeb9e 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -10,7 +10,6 @@ #include "Database.h" #include "eConnectionType.h" #include "eChatInternalMessageType.h" -#include "eGameMasterLevel.h" #include "ChatPackets.h" #include "dConfig.h" @@ -21,14 +20,6 @@ void PlayerContainer::Initialize() { GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } -PlayerContainer::~PlayerContainer() { - m_Players.clear(); -} - -PlayerData::PlayerData() { - gmLevel = eGameMasterLevel::CIVILIAN; -} - TeamData::TeamData() { lootFlag = Game::config->GetValue("default_team_loot") == "0" ? 0 : 1; } diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index f34b1e54..3f2d783a 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -10,7 +10,7 @@ enum class eGameMasterLevel : uint8_t; struct IgnoreData { - IgnoreData(const std::string& name, const LWOOBJID& id) : playerName(name), playerId(id) {} + IgnoreData(const std::string& name, const LWOOBJID& id) : playerName{ name }, playerId{ id } {} inline bool operator==(const std::string& other) const noexcept { return playerName == other; } @@ -24,7 +24,6 @@ struct IgnoreData { }; struct PlayerData { - PlayerData(); operator bool() const noexcept { return playerID != LWOOBJID_EMPTY; } @@ -45,7 +44,7 @@ struct PlayerData { std::string playerName; std::vector friends; std::vector ignoredPlayers; - eGameMasterLevel gmLevel; + eGameMasterLevel gmLevel = static_cast(0); // CIVILLIAN bool isFTP = false; }; @@ -61,8 +60,6 @@ struct TeamData { class PlayerContainer { public: - ~PlayerContainer(); - void Initialize(); void InsertPlayer(Packet* packet); void RemovePlayer(Packet* packet); diff --git a/dCommon/Amf3.h b/dCommon/Amf3.h index 967313c7..dbafba1f 100644 --- a/dCommon/Amf3.h +++ b/dCommon/Amf3.h @@ -31,54 +31,68 @@ enum class eAmf : uint8_t { class AMFBaseValue { public: - virtual eAmf GetValueType() { return eAmf::Undefined; }; - AMFBaseValue() {}; - virtual ~AMFBaseValue() {}; + [[nodiscard]] constexpr virtual eAmf GetValueType() const noexcept { return eAmf::Undefined; } + constexpr AMFBaseValue() noexcept = default; + constexpr virtual ~AMFBaseValue() noexcept = default; }; -template +// AMFValue template class instantiations +template class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(ValueType value) { SetValue(value); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const ValueType value) { m_Data = value; } + virtual ~AMFValue() override = default; - eAmf GetValueType() override { return eAmf::Undefined; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override; + + [[nodiscard]] const ValueType& GetValue() const { return m_Data; } + void SetValue(const ValueType value) { m_Data = value; } - const ValueType& GetValue() { return data; }; - void SetValue(ValueType value) { data = value; }; protected: - ValueType data; + ValueType m_Data; }; +// Explicit template class instantiations +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; + +// AMFValue template class member function instantiations +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Null; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return m_Data ? eAmf::True : eAmf::False; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::String; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Double; } + +template +[[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Undefined; } + // As a string this is much easier to write and read from a BitStream. -template<> +template <> class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(const char* value) { SetValue(std::string(value)); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const char* value) { m_Data = value; } + virtual ~AMFValue() override = default; - eAmf GetValueType() override { return eAmf::String; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::String; } - const std::string& GetValue() { return data; }; - void SetValue(std::string value) { data = value; }; + [[nodiscard]] const std::string& GetValue() const { return m_Data; } + void SetValue(const std::string& value) { m_Data = value; } protected: - std::string data; + std::string m_Data; }; -typedef AMFValue AMFNullValue; -typedef AMFValue AMFBoolValue; -typedef AMFValue AMFIntValue; -typedef AMFValue AMFStringValue; -typedef AMFValue AMFDoubleValue; - -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Null; }; -template<> inline eAmf AMFValue::GetValueType() { return this->data ? eAmf::True : eAmf::False; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::String; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; }; +using AMFNullValue = AMFValue; +using AMFBoolValue = AMFValue; +using AMFIntValue = AMFValue; +using AMFStringValue = AMFValue; +using AMFDoubleValue = AMFValue; /** * The AMFArrayValue object holds 2 types of lists: @@ -89,12 +103,11 @@ template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; } * and are not to be deleted by a caller. */ class AMFArrayValue : public AMFBaseValue { - - typedef std::unordered_map AMFAssociative; - typedef std::vector AMFDense; + using AMFAssociative = std::unordered_map; + using AMFDense = std::vector; public: - eAmf GetValueType() override { return eAmf::Array; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; } ~AMFArrayValue() override { for (auto valueToDelete : GetDense()) { @@ -109,17 +122,17 @@ public: valueToDelete.second = nullptr; } } - }; + } /** * Returns the Associative portion of the object */ - inline AMFAssociative& GetAssociative() { return this->associative; }; + [[nodiscard]] inline AMFAssociative& GetAssociative() noexcept { return this->associative; } /** * Returns the dense portion of the object */ - inline AMFDense& GetDense() { return this->dense; }; + [[nodiscard]] inline AMFDense& GetDense() noexcept { return this->dense; } /** * Inserts an AMFValue into the associative portion with the given key. @@ -135,8 +148,8 @@ public: * @return The inserted element if the type matched, * or nullptr if a key existed and was not the same type */ - template - std::pair*, bool> Insert(const std::string& key, ValueType value) { + template + [[maybe_unused]] std::pair*, bool> Insert(const std::string& key, const ValueType value) { auto element = associative.find(key); AMFValue* val = nullptr; bool found = true; @@ -148,10 +161,10 @@ public: found = false; } return std::make_pair(val, found); - }; + } // Associates an array with a string key - std::pair Insert(const std::string& key) { + [[maybe_unused]] std::pair Insert(const std::string& key) { auto element = associative.find(key); AMFArrayValue* val = nullptr; bool found = true; @@ -163,10 +176,10 @@ public: found = false; } return std::make_pair(val, found); - }; + } // Associates an array with an integer key - std::pair Insert(const uint32_t& index) { + [[maybe_unused]] std::pair Insert(const size_t index) { AMFArrayValue* val = nullptr; bool inserted = false; if (index >= dense.size()) { @@ -176,7 +189,7 @@ public: inserted = true; } return std::make_pair(dynamic_cast(dense.at(index)), inserted); - }; + } /** * @brief Inserts an AMFValue into the AMFArray key'd by index. @@ -188,8 +201,8 @@ public: * @return The inserted element, or nullptr if the type did not match * what was at the index. */ - template - std::pair*, bool> Insert(const uint32_t& index, ValueType value) { + template + [[maybe_unused]] std::pair*, bool> Insert(const size_t index, const ValueType value) { AMFValue* val = nullptr; bool inserted = false; if (index >= this->dense.size()) { @@ -199,7 +212,7 @@ public: inserted = true; } return std::make_pair(dynamic_cast*>(this->dense.at(index)), inserted); - }; + } /** * Inserts an AMFValue into the associative portion with the given key. @@ -210,7 +223,7 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const std::string& key, AMFBaseValue* value) { + void Insert(const std::string& key, AMFBaseValue* const value) { auto element = associative.find(key); if (element != associative.end() && element->second) { delete element->second; @@ -218,7 +231,7 @@ public: } else { associative.insert(std::make_pair(key, value)); } - }; + } /** * Inserts an AMFValue into the associative portion with the given index. @@ -229,7 +242,7 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const uint32_t index, AMFBaseValue* value) { + void Insert(const size_t index, AMFBaseValue* const value) { if (index < dense.size()) { AMFDense::iterator itr = dense.begin() + index; if (*itr) delete dense.at(index); @@ -237,7 +250,7 @@ public: dense.resize(index + 1); } dense.at(index) = value; - }; + } /** * Pushes an AMFValue into the back of the dense portion. @@ -249,10 +262,10 @@ public: * * @return The inserted pointer, or nullptr should the key already be in use. */ - template - inline AMFValue* Push(ValueType value) { + template + [[maybe_unused]] inline AMFValue* Push(const ValueType value) { return Insert(this->dense.size(), value).first; - }; + } /** * Removes the key from the associative portion @@ -261,7 +274,7 @@ public: * * @param key The key to remove from the associative portion */ - void Remove(const std::string& key, bool deleteValue = true) { + void Remove(const std::string& key, const bool deleteValue = true) { AMFAssociative::iterator it = this->associative.find(key); if (it != this->associative.end()) { if (deleteValue) delete it->second; @@ -272,7 +285,7 @@ public: /** * Pops the last element in the dense portion, deleting it in the process. */ - void Remove(const uint32_t index) { + void Remove(const size_t index) { if (!this->dense.empty() && index < this->dense.size()) { auto itr = this->dense.begin() + index; if (*itr) delete (*itr); @@ -284,29 +297,29 @@ public: if (!this->dense.empty()) Remove(this->dense.size() - 1); } - AMFArrayValue* GetArray(const std::string& key) { + [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) { AMFAssociative::const_iterator it = this->associative.find(key); if (it != this->associative.end()) { return dynamic_cast(it->second); } return nullptr; - }; + } - AMFArrayValue* GetArray(const uint32_t index) { + [[nodiscard]] AMFArrayValue* GetArray(const size_t index) { return index >= this->dense.size() ? nullptr : dynamic_cast(this->dense.at(index)); - }; + } - inline AMFArrayValue* InsertArray(const std::string& key) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) { return static_cast(Insert(key).first); - }; + } - inline AMFArrayValue* InsertArray(const uint32_t index) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const size_t index) { return static_cast(Insert(index).first); - }; + } - inline AMFArrayValue* PushArray() { + [[maybe_unused]] inline AMFArrayValue* PushArray() { return static_cast(Insert(this->dense.size()).first); - }; + } /** * Gets an AMFValue by the key from the associative portion and converts it @@ -318,18 +331,18 @@ public: * @return The AMFValue */ template - AMFValue* Get(const std::string& key) const { + [[nodiscard]] AMFValue* Get(const std::string& key) const { AMFAssociative::const_iterator it = this->associative.find(key); return it != this->associative.end() ? dynamic_cast*>(it->second) : nullptr; - }; + } // Get from the array but dont cast it - AMFBaseValue* Get(const std::string& key) const { + [[nodiscard]] AMFBaseValue* Get(const std::string& key) const { AMFAssociative::const_iterator it = this->associative.find(key); return it != this->associative.end() ? it->second : nullptr; - }; + } /** * @brief Get an AMFValue object at a position in the dense portion. @@ -341,16 +354,17 @@ public: * @return The casted object, or nullptr. */ template - AMFValue* Get(uint32_t index) const { + [[nodiscard]] AMFValue* Get(const size_t index) const { return index < this->dense.size() ? dynamic_cast*>(this->dense.at(index)) : nullptr; - }; + } // Get from the dense but dont cast it - AMFBaseValue* Get(const uint32_t index) const { + [[nodiscard]] AMFBaseValue* Get(const size_t index) const { return index < this->dense.size() ? this->dense.at(index) : nullptr; - }; + } + private: /** * The associative portion. These values are key'd with strings to an AMFValue. diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 7bcc91a2..3a4f2ea7 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -162,7 +162,7 @@ public: return new LDFData(key, value); } - inline static T Default = {}; + inline static const T Default = {}; }; // LDF Types diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f4f8fdfb..d871e267 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -39,86 +39,84 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); //=========== TYPEDEFS ========== -typedef int32_t LOT; //!< A LOT -typedef int64_t LWOOBJID; //!< An object ID (should be unsigned actually but ok) -typedef int32_t TSkillID; //!< A skill ID -typedef uint32_t LWOCLONEID; //!< Used for Clone IDs -typedef uint16_t LWOMAPID; //!< Used for Map IDs -typedef uint16_t LWOINSTANCEID; //!< Used for Instance IDs -typedef uint32_t PROPERTYCLONELIST; //!< Used for Property Clone IDs -typedef uint32_t StripId; +using LOT = int32_t; //!< A LOT +using LWOOBJID = int64_t; //!< An object ID (should be unsigned actually but ok) +using TSkillID = int32_t; //!< A skill ID +using LWOCLONEID = uint32_t; //!< Used for Clone IDs +using LWOMAPID = uint16_t; //!< Used for Map IDs +using LWOINSTANCEID = uint16_t; //!< Used for Instance IDs +using PROPERTYCLONELIST = uint32_t; //!< Used for Property Clone IDs +using StripId = uint32_t; -const LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID -const LOT LOT_NULL = -1; //!< A null LOT -const int32_t LOOTTYPE_NONE = 0; //!< No loot type available -const float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority -const uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size -const uint32_t LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID -const uint16_t LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID -const uint16_t LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID -const uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID +constexpr LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID +constexpr LOT LOT_NULL = -1; //!< A null LOT +constexpr int32_t LOOTTYPE_NONE = 0; //!< No loot type available +constexpr float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority +constexpr uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size +constexpr LWOCLONEID LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID +constexpr LWOINSTANCEID LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID +constexpr LWOMAPID LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID +constexpr uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID -const float PI = 3.14159f; +constexpr float PI = 3.14159f; //============ STRUCTS ============== struct LWOSCENEID { public: - LWOSCENEID() { m_sceneID = -1; m_layerID = 0; } - LWOSCENEID(int sceneID) { m_sceneID = sceneID; m_layerID = 0; } - LWOSCENEID(int sceneID, unsigned int layerID) { m_sceneID = sceneID; m_layerID = layerID; } + constexpr LWOSCENEID() noexcept { m_sceneID = -1; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID) noexcept { m_sceneID = sceneID; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID, uint32_t layerID) noexcept { m_sceneID = sceneID; m_layerID = layerID; } - LWOSCENEID& operator=(const LWOSCENEID& rhs) { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } - LWOSCENEID& operator=(const int rhs) { m_sceneID = rhs; m_layerID = 0; return *this; } + constexpr LWOSCENEID& operator=(const LWOSCENEID& rhs) noexcept { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } + constexpr LWOSCENEID& operator=(const int32_t rhs) noexcept { m_sceneID = rhs; m_layerID = 0; return *this; } - bool operator<(const LWOSCENEID& rhs) const { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } - bool operator<(const int rhs) const { return m_sceneID < rhs; } + constexpr bool operator<(const LWOSCENEID& rhs) const noexcept { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } + constexpr bool operator<(const int32_t rhs) const noexcept { return m_sceneID < rhs; } - bool operator==(const LWOSCENEID& rhs) const { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } - bool operator==(const int rhs) const { return m_sceneID == rhs; } + constexpr bool operator==(const LWOSCENEID& rhs) const noexcept { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } + constexpr bool operator==(const int32_t rhs) const noexcept { return m_sceneID == rhs; } - const int GetSceneID() const { return m_sceneID; } - const unsigned int GetLayerID() const { return m_layerID; } + constexpr int32_t GetSceneID() const noexcept { return m_sceneID; } + constexpr uint32_t GetLayerID() const noexcept { return m_layerID; } - void SetSceneID(const int sceneID) { m_sceneID = sceneID; } - void SetLayerID(const unsigned int layerID) { m_layerID = layerID; } + constexpr void SetSceneID(const int32_t sceneID) noexcept { m_sceneID = sceneID; } + constexpr void SetLayerID(const uint32_t layerID) noexcept { m_layerID = layerID; } private: - int m_sceneID; - unsigned int m_layerID; + int32_t m_sceneID; + uint32_t m_layerID; }; struct LWOZONEID { public: - const LWOMAPID& GetMapID() const { return m_MapID; } - const LWOINSTANCEID& GetInstanceID() const { return m_InstanceID; } - const LWOCLONEID& GetCloneID() const { return m_CloneID; } + constexpr const LWOMAPID& GetMapID() const noexcept { return m_MapID; } + constexpr const LWOINSTANCEID& GetInstanceID() const noexcept { return m_InstanceID; } + constexpr const LWOCLONEID& GetCloneID() const noexcept { return m_CloneID; } //In order: def constr, constr, assign op - LWOZONEID() { m_MapID = LWOMAPID_INVALID; m_InstanceID = LWOINSTANCEID_INVALID; m_CloneID = LWOCLONEID_INVALID; } - LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } - LWOZONEID(const LWOZONEID& replacement) { *this = replacement; } + constexpr LWOZONEID() noexcept = default; + constexpr LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) noexcept { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } + constexpr LWOZONEID(const LWOZONEID& replacement) noexcept { *this = replacement; } private: - LWOMAPID m_MapID; //1000 for VE, 1100 for AG, etc... - LWOINSTANCEID m_InstanceID; //Instances host the same world, but on a different dWorld process. - LWOCLONEID m_CloneID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. + LWOMAPID m_MapID = LWOMAPID_INVALID; //1000 for VE, 1100 for AG, etc... + LWOINSTANCEID m_InstanceID = LWOINSTANCEID_INVALID; //Instances host the same world, but on a different dWorld process. + LWOCLONEID m_CloneID = LWOCLONEID_INVALID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. }; -const LWOSCENEID LWOSCENEID_INVALID = -1; +constexpr LWOSCENEID LWOSCENEID_INVALID = -1; struct LWONameValue { uint32_t length = 0; //!< The length of the name std::u16string name; //!< The name - LWONameValue(void) {} + LWONameValue() = default; LWONameValue(const std::u16string& name) { this->name = name; this->length = static_cast(name.length()); } - - ~LWONameValue(void) {} }; struct FriendData { diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index 2514f194..6cef87d3 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -23,7 +23,7 @@ #include "CppScripts.h" -QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { +QuickBuildComponent::QuickBuildComponent(Entity* const entity) : Component{ entity } { std::u16string checkPreconditions = entity->GetVar(u"CheckPrecondition"); if (!checkPreconditions.empty()) { @@ -283,47 +283,47 @@ void QuickBuildComponent::DespawnActivator() { } } -Entity* QuickBuildComponent::GetActivator() { +Entity* QuickBuildComponent::GetActivator() const { return Game::entityManager->GetEntity(m_ActivatorId); } -NiPoint3 QuickBuildComponent::GetActivatorPosition() { +NiPoint3 QuickBuildComponent::GetActivatorPosition() const noexcept { return m_ActivatorPosition; } -float QuickBuildComponent::GetResetTime() { +float QuickBuildComponent::GetResetTime() const noexcept { return m_ResetTime; } -float QuickBuildComponent::GetCompleteTime() { +float QuickBuildComponent::GetCompleteTime() const noexcept { return m_CompleteTime; } -int QuickBuildComponent::GetTakeImagination() { +int32_t QuickBuildComponent::GetTakeImagination() const noexcept { return m_TakeImagination; } -bool QuickBuildComponent::GetInterruptible() { +bool QuickBuildComponent::GetInterruptible() const noexcept { return m_Interruptible; } -bool QuickBuildComponent::GetSelfActivator() { +bool QuickBuildComponent::GetSelfActivator() const noexcept { return m_SelfActivator; } -std::vector QuickBuildComponent::GetCustomModules() { +std::vector QuickBuildComponent::GetCustomModules() const noexcept { return m_CustomModules; } -int QuickBuildComponent::GetActivityId() { +int32_t QuickBuildComponent::GetActivityId() const noexcept { return m_ActivityId; } -int QuickBuildComponent::GetPostImaginationCost() { +int32_t QuickBuildComponent::GetPostImaginationCost() const noexcept { return m_PostImaginationCost; } -float QuickBuildComponent::GetTimeBeforeSmash() { +float QuickBuildComponent::GetTimeBeforeSmash() const noexcept { return m_TimeBeforeSmash; } @@ -332,24 +332,24 @@ eQuickBuildState QuickBuildComponent::GetState() const noexcept { } Entity* QuickBuildComponent::GetBuilder() const { - auto* builder = Game::entityManager->GetEntity(m_Builder); + auto* const builder = Game::entityManager->GetEntity(m_Builder); return builder; } -bool QuickBuildComponent::GetRepositionPlayer() const { +bool QuickBuildComponent::GetRepositionPlayer() const noexcept { return m_RepositionPlayer; } -void QuickBuildComponent::SetActivatorPosition(NiPoint3 value) { +void QuickBuildComponent::SetActivatorPosition(const NiPoint3& value) noexcept { m_ActivatorPosition = value; } -void QuickBuildComponent::SetResetTime(float value) { +void QuickBuildComponent::SetResetTime(const float value) noexcept { m_ResetTime = value; } -void QuickBuildComponent::SetCompleteTime(float value) { +void QuickBuildComponent::SetCompleteTime(const float value) noexcept { if (value < 0) { m_CompleteTime = 4.5f; } else { @@ -357,31 +357,31 @@ void QuickBuildComponent::SetCompleteTime(float value) { } } -void QuickBuildComponent::SetTakeImagination(int value) { +void QuickBuildComponent::SetTakeImagination(const int32_t value) noexcept { m_TakeImagination = value; } -void QuickBuildComponent::SetInterruptible(bool value) { +void QuickBuildComponent::SetInterruptible(const bool value) noexcept { m_Interruptible = value; } -void QuickBuildComponent::SetSelfActivator(bool value) { +void QuickBuildComponent::SetSelfActivator(const bool value) noexcept { m_SelfActivator = value; } -void QuickBuildComponent::SetCustomModules(std::vector value) { +void QuickBuildComponent::SetCustomModules(const std::vector& value) noexcept { m_CustomModules = value; } -void QuickBuildComponent::SetActivityId(int value) { +void QuickBuildComponent::SetActivityId(const int32_t value) noexcept { m_ActivityId = value; } -void QuickBuildComponent::SetPostImaginationCost(int value) { +void QuickBuildComponent::SetPostImaginationCost(const int32_t value) noexcept { m_PostImaginationCost = value; } -void QuickBuildComponent::SetTimeBeforeSmash(float value) { +void QuickBuildComponent::SetTimeBeforeSmash(const float value) noexcept { if (value < 0) { m_TimeBeforeSmash = 10.0f; } else { @@ -389,11 +389,11 @@ void QuickBuildComponent::SetTimeBeforeSmash(float value) { } } -void QuickBuildComponent::SetRepositionPlayer(bool value) { +void QuickBuildComponent::SetRepositionPlayer(const bool value) noexcept { m_RepositionPlayer = value; } -void QuickBuildComponent::StartQuickBuild(Entity* user) { +void QuickBuildComponent::StartQuickBuild(Entity* const user) { if (m_State == eQuickBuildState::OPEN || m_State == eQuickBuildState::COMPLETED || m_State == eQuickBuildState::INCOMPLETE) { m_Builder = user->GetObjectID(); @@ -426,10 +426,8 @@ void QuickBuildComponent::StartQuickBuild(Entity* user) { } } -void QuickBuildComponent::CompleteQuickBuild(Entity* user) { - if (user == nullptr) { - return; - } +void QuickBuildComponent::CompleteQuickBuild(Entity* const user) { + if (!user) return; auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { @@ -518,7 +516,7 @@ void QuickBuildComponent::CompleteQuickBuild(Entity* user) { RenderComponent::PlayAnimation(user, u"rebuild-celebrate", 1.09f); } -void QuickBuildComponent::ResetQuickBuild(bool failed) { +void QuickBuildComponent::ResetQuickBuild(const bool failed) { Entity* builder = GetBuilder(); if (m_State == eQuickBuildState::BUILDING && builder) { @@ -553,7 +551,7 @@ void QuickBuildComponent::ResetQuickBuild(bool failed) { } } -void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason failReason, bool skipChecks) { +void QuickBuildComponent::CancelQuickBuild(Entity* const entity, const eQuickBuildFailReason failReason, const bool skipChecks) { if (m_State != eQuickBuildState::COMPLETED || skipChecks) { m_Builder = LWOOBJID_EMPTY; @@ -581,9 +579,7 @@ void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason Game::entityManager->SerializeEntity(m_Parent); } - if (entity == nullptr) { - return; - } + if (!entity) return; CharacterComponent* characterComponent = entity->GetComponent(); if (characterComponent) { diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index d9cc4190..556264a8 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -24,7 +24,7 @@ class QuickBuildComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD; - QuickBuildComponent(Entity* entity); + QuickBuildComponent(Entity* const entity); ~QuickBuildComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; @@ -50,124 +50,124 @@ public: * Returns the entity that acts as the activator for this quickbuild * @return the entity that acts as the activator for this quickbuild */ - Entity* GetActivator(); + [[nodiscard]] Entity* GetActivator() const; /** * Returns the spawn position of the activator for this quickbuild, if any * @return the spawn position of the activator for this quickbuild, if any */ - NiPoint3 GetActivatorPosition(); + [[nodiscard]] NiPoint3 GetActivatorPosition() const noexcept; /** * Sets the spawn position for the activator of this quickbuild * @param value the spawn position to set for the activator */ - void SetActivatorPosition(NiPoint3 value); + void SetActivatorPosition(const NiPoint3& value) noexcept; /** * Returns the time it takes for the quickbuild to reset after being built * @return the time it takes for the quickbuild to reset after being built */ - float GetResetTime(); + [[nodiscard]] float GetResetTime() const noexcept; /** * Sets the time it takes for the quickbuild to reset after being built * @param value the reset time to set */ - void SetResetTime(float value); + void SetResetTime(const float value) noexcept; /** * Returns the time it takes to complete the quickbuild * @return the time it takes to complete the quickbuild */ - float GetCompleteTime(); + [[nodiscard]] float GetCompleteTime() const noexcept; /** * Sets the time it takes to complete the quickbuild * @param value the completion time to set */ - void SetCompleteTime(float value); + void SetCompleteTime(const float value) noexcept; /** * Returns the imagination that's taken when completing the quickbuild * @return the imagination that's taken when completing the quickbuild */ - int GetTakeImagination(); + [[nodiscard]] int32_t GetTakeImagination() const noexcept; /** * Sets the imagination that's taken when completing the quickbuild * @param value the imagination deduction to set */ - void SetTakeImagination(int value); + void SetTakeImagination(const int32_t value) noexcept; /** * Returns if the quickbuild can be interrupted, currently unused * @return if the quickbuild can be interrupted */ - bool GetInterruptible(); + [[nodiscard]] bool GetInterruptible() const noexcept; /** * Sets whether or not the quickbuild can be interrupted, currently unused * @param value true if the quickbuild may be interrupted, false otherwise */ - void SetInterruptible(bool value); + void SetInterruptible(const bool value) noexcept; /** * Returns whether or not this entity contains a built-in activator * @return whether or not this entity contains a built-in activator */ - bool GetSelfActivator(); + [[nodiscard]] bool GetSelfActivator() const noexcept; /** * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on * each new quickbuild. * @param value whether or not this entity contains a built-in activator */ - void SetSelfActivator(bool value); + void SetSelfActivator(const bool value) noexcept; /** * Currently unused */ - std::vector GetCustomModules(); + [[nodiscard]] std::vector GetCustomModules() const noexcept; /** * Currently unused */ - void SetCustomModules(std::vector value); + void SetCustomModules(const std::vector& value) noexcept; /** * Returns the activity ID for participating in this quickbuild * @return the activity ID for participating in this quickbuild */ - int GetActivityId(); + [[nodiscard]] int32_t GetActivityId() const noexcept; /** * Sets the activity ID for participating in this quickbuild * @param value the activity ID to set */ - void SetActivityId(int value); + void SetActivityId(const int32_t value) noexcept; /** * Currently unused */ - int GetPostImaginationCost(); + [[nodiscard]] int32_t GetPostImaginationCost() const noexcept; /** * Currently unused */ - void SetPostImaginationCost(int value); + void SetPostImaginationCost(const int32_t value) noexcept; /** * Returns the time it takes for an incomplete quickbuild to be smashed automatically * @return the time it takes for an incomplete quickbuild to be smashed automatically */ - float GetTimeBeforeSmash(); + [[nodiscard]] float GetTimeBeforeSmash() const noexcept; /** * Sets the time it takes for an incomplete quickbuild to be smashed automatically * @param value the time to set */ - void SetTimeBeforeSmash(float value); + void SetTimeBeforeSmash(const float value) noexcept; /** * Returns the current quickbuild state @@ -179,19 +179,19 @@ public: * Returns the player that is currently building this quickbuild * @return the player that is currently building this quickbuild */ - Entity* GetBuilder() const; + [[nodiscard]] Entity* GetBuilder() const; /** * Returns whether or not the player is repositioned when initiating the quickbuild * @return whether or not the player is repositioned when initiating the quickbuild */ - bool GetRepositionPlayer() const; + [[nodiscard]] bool GetRepositionPlayer() const noexcept; /** * Sets whether or not the player is repositioned when initiating the quickbuild * @param value whether or not the player is repositioned when initiating the quickbuild */ - void SetRepositionPlayer(bool value); + void SetRepositionPlayer(const bool value) noexcept; /** * Adds a callback that is called when the quickbuild is completed @@ -209,7 +209,7 @@ public: * Resets the quickbuild * @param failed whether or not the player failed to complete the quickbuild, triggers an extra animation */ - void ResetQuickBuild(bool failed); + void ResetQuickBuild(const bool failed); /** * Cancels the quickbuild if it wasn't completed @@ -217,7 +217,7 @@ public: * @param failReason the reason the quickbuild was cancelled * @param skipChecks whether or not to skip the check for the quickbuild not being completed */ - void CancelQuickBuild(Entity* builder, eQuickBuildFailReason failReason, bool skipChecks = false); + void CancelQuickBuild(Entity* const builder, const eQuickBuildFailReason failReason, const bool skipChecks = false); private: /** * Whether or not the quickbuild state has been changed since we last serialized it. @@ -287,7 +287,7 @@ private: /** * The imagination that's deducted when completing the quickbuild */ - int m_TakeImagination = 0; + int32_t m_TakeImagination = 0; /** * Currently unused @@ -302,17 +302,17 @@ private: /** * Currently unused */ - std::vector m_CustomModules{}; + std::vector m_CustomModules{}; /** * The activity ID that players partake in when doing this quickbuild */ - int m_ActivityId = 0; + int32_t m_ActivityId = 0; /** * Currently unused */ - int m_PostImaginationCost = 0; + int32_t m_PostImaginationCost = 0; /** * The time it takes for the quickbuild to reset when it's not completed yet @@ -327,7 +327,7 @@ private: /** * The amount of imagination that was drained when building this quickbuild */ - int m_DrainedImagination = 0; + int32_t m_DrainedImagination = 0; /** * Whether to reposition the player or not when building @@ -337,7 +337,7 @@ private: /** * Currently unused */ - float m_SoftTimer = 0; + int32_t m_SoftTimer = 0; /** * The ID of the entity that's currently building the quickbuild @@ -353,13 +353,13 @@ private: * Starts the quickbuild for a certain entity * @param user the entity to start the quickbuild */ - void StartQuickBuild(Entity* user); + void StartQuickBuild(Entity* const user); /** * Completes the quickbuild for an entity, dropping loot and despawning the activator * @param user the entity that completed the quickbuild */ - void CompleteQuickBuild(Entity* user); + void CompleteQuickBuild(Entity* const user); }; #endif // QUICKBUILDCOMPONENT_H diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index 6f0741dd..ac6e8db7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -2,7 +2,7 @@ #include "Action.h" -AddStripMessage::AddStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { +AddStripMessage::AddStripMessage(AMFArrayValue* const arguments) : BehaviorMessageBase{ arguments } { actionContext = ActionContext(arguments); position = StripUiPosition(arguments); diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index 5cceb510..2e2bf9a0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -18,7 +18,7 @@ class AMFArrayValue; */ class AddStripMessage : public BehaviorMessageBase { public: - AddStripMessage(AMFArrayValue* arguments); + AddStripMessage(AMFArrayValue* const arguments); StripUiPosition GetPosition() const { return position; }; ActionContext GetActionContext() const { return actionContext; }; std::vector GetActionsToAdd() const; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index 0aad74dd..a49a8aeb 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -8,9 +8,9 @@ BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { this->behaviorId = GetBehaviorIdFromArgument(arguments); } -int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { - const auto* key = "BehaviorID"; - auto* behaviorIDValue = arguments->Get(key); +int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* const arguments) { + const char* const key = "BehaviorID"; + const auto* const behaviorIDValue = arguments->Get(key); if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { this->behaviorId = @@ -22,11 +22,9 @@ int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) return this->behaviorId; } -int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { - auto* actionIndexAmf = arguments->Get(keyName); - if (!actionIndexAmf) { - throw std::invalid_argument("Unable to find actionIndex"); - } +int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName) const { + const auto* const actionIndexAmf = arguments->Get(keyName); + if (!actionIndexAmf) throw std::invalid_argument("Unable to find actionIndex"); return static_cast(actionIndexAmf->GetValue()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h index 8a841d7f..f55fde8e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -15,13 +15,13 @@ enum class BehaviorState : uint32_t; */ class BehaviorMessageBase { public: - static inline int32_t DefaultBehaviorId = -1; - const int32_t GetBehaviorId() const { return behaviorId; }; - bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; - BehaviorMessageBase(AMFArrayValue* arguments); + static constexpr int32_t DefaultBehaviorId = -1; + [[nodiscard]] int32_t GetBehaviorId() const { return behaviorId; }; + [[nodiscard]] bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; + BehaviorMessageBase(AMFArrayValue* const arguments); protected: - int32_t GetBehaviorIdFromArgument(AMFArrayValue* arguments); - int32_t GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName = "actionIndex"); + [[nodiscard]] int32_t GetBehaviorIdFromArgument(AMFArrayValue* const arguments); + [[nodiscard]] int32_t GetActionIndexFromArgument(AMFArrayValue* const arguments, const std::string& keyName = "actionIndex") const; int32_t behaviorId = DefaultBehaviorId; }; diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 357187ef..e88ec468 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -12,16 +12,12 @@ void AmDropshipComputer::OnStartup(Entity* self) { void AmDropshipComputer::OnUse(Entity* self, Entity* user) { auto* quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) { - return; - } + if (!quickBuildComponent || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) return; auto* missionComponent = user->GetComponent(); auto* inventoryComponent = user->GetComponent(); - if (missionComponent == nullptr || inventoryComponent == nullptr) { - return; - } + if (!missionComponent || !inventoryComponent) return; if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == eMissionState::COMPLETE) { return;