Make loot accurate to the loot drop rates during live. (#216)

* loot fix (broken)

* Fixed loot

* Update SlashCommandHandler.cpp

* Remove debug command

* Roll loot command

* Remove debug log

* Added const references
When this commit is applied it adds const references to the loot system avoid some unnecessary copies.

Co-authored-by: wincent <wincent.holm@gmail.com>
Co-authored-by: Avery <averysumner@gmail.com>
This commit is contained in:
Jett 2021-12-20 10:25:45 +00:00 committed by GitHub
parent f7858ab183
commit 0531365cb5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 450 additions and 378 deletions

View File

@ -57,6 +57,6 @@ std::vector<CDLootMatrix> CDLootMatrixTable::Query(std::function<bool(CDLootMatr
} }
//! Gets all the entries in the table //! Gets all the entries in the table
std::vector<CDLootMatrix> CDLootMatrixTable::GetEntries(void) const { const std::vector<CDLootMatrix>& CDLootMatrixTable::GetEntries(void) const {
return this->entries; return this->entries;
} }

View File

@ -50,7 +50,7 @@ public:
/*! /*!
\return The entries \return The entries
*/ */
std::vector<CDLootMatrix> GetEntries(void) const; const std::vector<CDLootMatrix>& GetEntries(void) const;
}; };

View File

@ -54,6 +54,6 @@ std::vector<CDLootTable> CDLootTableTable::Query(std::function<bool(CDLootTable)
} }
//! Gets all the entries in the table //! Gets all the entries in the table
std::vector<CDLootTable> CDLootTableTable::GetEntries(void) const { const std::vector<CDLootTable>& CDLootTableTable::GetEntries(void) const {
return this->entries; return this->entries;
} }

View File

@ -46,7 +46,7 @@ public:
/*! /*!
\return The entries \return The entries
*/ */
std::vector<CDLootTable> GetEntries(void) const; const std::vector<CDLootTable>& GetEntries(void) const;
}; };

View File

@ -52,6 +52,6 @@ std::vector<CDRarityTable> CDRarityTableTable::Query(std::function<bool(CDRarity
} }
//! Gets all the entries in the table //! Gets all the entries in the table
std::vector<CDRarityTable> CDRarityTableTable::GetEntries(void) const { const std::vector<CDRarityTable>& CDRarityTableTable::GetEntries(void) const {
return this->entries; return this->entries;
} }

View File

@ -66,7 +66,7 @@ public:
/*! /*!
\return The entries \return The entries
*/ */
std::vector<CDRarityTable> GetEntries(void) const; const std::vector<CDRarityTable>& GetEntries(void) const;
}; };

View File

@ -783,12 +783,12 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType
if (member == nullptr) continue; if (member == nullptr) continue;
Loot::DropLoot(member, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins()); LootGenerator::Instance().DropLoot(member, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins());
} }
} }
else else
{ {
Loot::DropLoot(owner, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins()); LootGenerator::Instance().DropLoot(owner, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins());
} }
} }
} }
@ -815,7 +815,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType
coinsTotal -= coinsToLoose; coinsTotal -= coinsToLoose;
Loot::DropLoot(m_Parent, m_Parent, -1, coinsToLoose, coinsToLoose); LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLoose, coinsToLoose);
} }
character->SetCoins(coinsTotal); character->SetCoins(coinsTotal);

View File

@ -392,7 +392,7 @@ void RacingControlComponent::HandleMessageBoxResponse(Entity *player,
// Calculate the score, different loot depending on player count // Calculate the score, different loot depending on player count
const auto score = m_LoadedPlayers * 10 + data->finished; const auto score = m_LoadedPlayers * 10 + data->finished;
Loot::GiveActivityLoot(player, m_Parent, m_ActivityID, score); LootGenerator::Instance().GiveActivityLoot(player, m_Parent, m_ActivityID, score);
// Giving rewards // Giving rewards
GameMessages::SendNotifyRacingClient( GameMessages::SendNotifyRacingClient(

View File

@ -452,7 +452,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) {
missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId);
} }
Loot::DropActivityLoot(builder, m_Parent, m_ActivityId, 1); LootGenerator::Instance().DropActivityLoot(builder, m_Parent, m_ActivityId, 1);
} }
m_Builder = LWOOBJID_EMPTY; m_Builder = LWOOBJID_EMPTY;

View File

@ -524,7 +524,7 @@ void ActivityInstance::RewardParticipant(Entity* participant) {
maxCoins = currencyTable[0].maxvalue; maxCoins = currencyTable[0].maxvalue;
} }
Loot::DropLoot(participant, m_Parent, activityRewards[0].LootMatrixIndex, minCoins, maxCoins); LootGenerator::Instance().DropLoot(participant, m_Parent, activityRewards[0].LootMatrixIndex, minCoins, maxCoins);
} }
} }

View File

@ -333,14 +333,14 @@ bool Item::UseNonEquip()
{ {
std::unordered_map<LOT, int32_t> result {}; std::unordered_map<LOT, int32_t> result {};
Loot::CalculateLootMatrix(pack.LootMatrixIndex, entityParent, result); result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex);
if (!inventory->GetComponent()->HasSpaceForLoot(result)) if (!inventory->GetComponent()->HasSpaceForLoot(result))
{ {
return false; return false;
} }
Loot::GiveLoot(inventory->GetComponent()->GetParent(), result); LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result);
} }
inventory->GetComponent()->RemoveItem(lot, 1); inventory->GetComponent()->RemoveItem(lot, 1);

View File

@ -1,82 +1,344 @@
#include "Loot.h"
#include "GameMessages.h"
#include "CDClientManager.h"
#include "CDLootMatrixTable.h"
#include "CDLootTableTable.h"
#include "SimplePhysicsComponent.h"
#include "ControllablePhysicsComponent.h"
#include "DestroyableComponent.h"
#include "MissionComponent.h"
#include "CharacterComponent.h"
#include "TeamManager.h"
#include <algorithm> #include <algorithm>
std::vector<CDLootTable> Loot::GetLootOfRarity(const std::vector<CDLootTable> &lootTable, uint32_t rarity) { #include "Loot.h"
std::vector<CDLootTable> refinedLoot;
for (auto loot : lootTable) { #include "CDComponentsRegistryTable.h"
CDItemComponent item = Inventory::FindItemComponent(loot.itemid); #include "CDItemComponentTable.h"
if (item.rarity == rarity) { #include "CDLootMatrixTable.h"
refinedLoot.push_back(loot); #include "CDLootTableTable.h"
} #include "CDRarityTableTable.h"
else if (item.rarity == 0) { #include "Character.h"
refinedLoot.push_back(loot); // powerups #include "Entity.h"
} #include "GameMessages.h"
#include "GeneralUtils.h"
#include "InventoryComponent.h"
#include "MissionComponent.h"
LootGenerator::LootGenerator() {
CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable");
CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry");
CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent");
CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable<CDLootMatrixTable>("LootMatrix");
CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable<CDRarityTableTable>("RarityTable");
// ==============================
// Cache Item Rarities
// ==============================
std::vector<uint32_t> uniqueItems;
for (const CDLootTable& loot : lootTableTable->GetEntries()) {
uniqueItems.push_back(loot.itemid);
} }
return refinedLoot; // filter out duplicates
std::sort(uniqueItems.begin(), uniqueItems.end());
uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end());
for (const uint32_t itemID : uniqueItems) {
uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM);
const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID);
m_ItemRarities.insert({itemID, item.rarity});
}
// ==============================
// Cache Rarity Tables
// ==============================
std::vector<uint32_t> uniqueRarityIndices;
for (const CDRarityTable& rarity : rarityTableTable->GetEntries()) {
uniqueRarityIndices.push_back(rarity.RarityTableIndex);
}
// filter out duplicates
std::sort(uniqueRarityIndices.begin(), uniqueRarityIndices.end());
uniqueRarityIndices.erase(std::unique(uniqueRarityIndices.begin(), uniqueRarityIndices.end()), uniqueRarityIndices.end());
for (const uint32_t index : uniqueRarityIndices) {
std::vector<CDRarityTable> table = rarityTableTable->Query([index](const CDRarityTable& entry) { return entry.RarityTableIndex == index; });
RarityTable rarityTable;
for (const CDRarityTable& entry : table) {
RarityTableEntry rarity{entry.rarity, entry.randmax};
rarityTable.push_back(rarity);
}
// sort in descending order based on randMax
std::sort(rarityTable.begin(), rarityTable.end(), [](const RarityTableEntry& x, const RarityTableEntry& y) { return x.randMax > y.randMax; });
m_RarityTables.insert({index, rarityTable});
}
// ==============================
// Cache Loot Matrices
// ==============================
std::vector<uint32_t> uniqueMatrixIndices;
for (const CDLootMatrix& matrix : lootMatrixTable->GetEntries()) {
uniqueMatrixIndices.push_back(matrix.LootMatrixIndex);
}
// filter out duplicates
std::sort(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end());
uniqueMatrixIndices.erase(std::unique(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()), uniqueMatrixIndices.end());
for (const uint32_t index : uniqueMatrixIndices) {
std::vector<CDLootMatrix> matrix = lootMatrixTable->Query([index](const CDLootMatrix& entry) { return entry.LootMatrixIndex == index; });
LootMatrix lootMatrix;
for (const CDLootMatrix& entry : matrix) {
LootMatrixEntry matrixEntry{entry.LootTableIndex, entry.RarityTableIndex, entry.percent, entry.minToDrop, entry.maxToDrop};
lootMatrix.push_back(matrixEntry);
}
m_LootMatrices.insert({index, lootMatrix});
}
// ==============================
// Cache Loot Tables
// ==============================
std::vector<uint32_t> uniqueTableIndices;
for (const CDLootTable& entry : lootTableTable->GetEntries()) {
uniqueTableIndices.push_back(entry.LootTableIndex);
}
// filter out duplicates
std::sort(uniqueTableIndices.begin(), uniqueTableIndices.end());
uniqueTableIndices.erase(std::unique(uniqueTableIndices.begin(), uniqueTableIndices.end()), uniqueTableIndices.end());
for (const uint32_t index : uniqueTableIndices) {
std::vector<CDLootTable> entries = lootTableTable->Query([index](const CDLootTable& entry) { return entry.LootTableIndex == index; });
LootTable lootTable;
for (const CDLootTable& entry : entries) {
LootTableEntry tableEntry{(LOT)entry.itemid, entry.MissionDrop};
lootTable.push_back(tableEntry);
}
// sort by item rarity descending
std::sort(lootTable.begin(), lootTable.end(), [&](const LootTableEntry& x, const LootTableEntry& y) {
return m_ItemRarities[x.itemID] > m_ItemRarities[y.itemID];
});
m_LootTables.insert({index, lootTable});
}
} }
void Loot::GiveLoot(Entity* user, uint32_t lootMatrixID) { std::unordered_map<LOT, int32_t> LootGenerator::RollLootMatrix(Entity* player, uint32_t matrixIndex) {
user = user->GetOwner(); // If the owner is overwritten, we collect that here auto* missionComponent = player->GetComponent<MissionComponent>();
std::unordered_map<LOT, int32_t> result {}; std::unordered_map<LOT, int32_t> drops;
CalculateLootMatrix(lootMatrixID, user, result); const LootMatrix& matrix = m_LootMatrices[matrixIndex];
GiveLoot(user, result); for (const LootMatrixEntry& entry : matrix) {
if (GeneralUtils::GenerateRandomNumber<float>(0, 1) < entry.percent) {
const LootTable& lootTable = m_LootTables[entry.lootTableIndex];
const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex];
uint32_t dropCount = GeneralUtils::GenerateRandomNumber<uint32_t>(entry.minDrop, entry.maxDrop);
for (uint32_t i = 0; i < dropCount; ++i) {
uint32_t maxRarity = 1;
float rarityRoll = GeneralUtils::GenerateRandomNumber<float>(0, 1);
for (const RarityTableEntry& rarity : rarityTable) {
if (rarity.randMax >= rarityRoll) {
maxRarity = rarity.rarity;
} else {
break;
}
}
bool rarityFound = false;
std::vector<LootTableEntry> possibleDrops;
for (const LootTableEntry& loot : lootTable) {
uint32_t rarity = m_ItemRarities[loot.itemID];
if (rarity == maxRarity) {
possibleDrops.push_back(loot);
rarityFound = true;
} else if (rarity < maxRarity && !rarityFound) {
possibleDrops.push_back(loot);
maxRarity = rarity;
}
}
if (possibleDrops.size() > 0) {
LootTableEntry drop = possibleDrops[GeneralUtils::GenerateRandomNumber<uint32_t>(0, possibleDrops.size() - 1)];
// filter out uneeded mission items
if (drop.isMissionDrop && !missionComponent->RequiresItem(drop.itemID))
continue;
// convert faction token proxy
if (drop.itemID == 13763) {
if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE)
drop.itemID = 8318; // "Assembly Token"
else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE)
drop.itemID = 8321; // "Venture League Token"
else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE)
drop.itemID = 8319; // "Sentinels Token"
else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE)
drop.itemID = 8320; // "Paradox Token"
}
if (drop.itemID == 13763) {
continue;
} // check if we aren't in faction
if (drops.find(drop.itemID) == drops.end()) {
drops.insert({drop.itemID, 1});
} else {
++drops[drop.itemID];
}
}
}
}
}
return drops;
} }
void Loot::DropLoot(Entity* user, Entity* killedObject, uint32_t lootMatrixID, uint32_t minCoins, uint32_t maxCoins) { std::unordered_map<LOT, int32_t> LootGenerator::RollLootMatrix(uint32_t matrixIndex) {
user = user->GetOwner(); // If the owner is overwritten, we collect that here std::unordered_map<LOT, int32_t> drops;
auto* inventoryComponent = user->GetComponent<InventoryComponent>(); const LootMatrix& matrix = m_LootMatrices[matrixIndex];
if (inventoryComponent == nullptr) { for (const LootMatrixEntry& entry : matrix) {
if (GeneralUtils::GenerateRandomNumber<float>(0, 1) < entry.percent) {
const LootTable& lootTable = m_LootTables[entry.lootTableIndex];
const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex];
uint32_t dropCount = GeneralUtils::GenerateRandomNumber<uint32_t>(entry.minDrop, entry.maxDrop);
for (uint32_t i = 0; i < dropCount; ++i) {
uint32_t maxRarity = 1;
float rarityRoll = GeneralUtils::GenerateRandomNumber<float>(0, 1);
for (const RarityTableEntry& rarity : rarityTable) {
if (rarity.randMax >= rarityRoll) {
maxRarity = rarity.rarity;
} else {
break;
}
}
bool rarityFound = false;
std::vector<LootTableEntry> possibleDrops;
for (const LootTableEntry& loot : lootTable) {
uint32_t rarity = m_ItemRarities[loot.itemID];
if (rarity == maxRarity) {
possibleDrops.push_back(loot);
rarityFound = true;
} else if (rarity < maxRarity && !rarityFound) {
possibleDrops.push_back(loot);
maxRarity = rarity;
}
}
if (possibleDrops.size() > 0) {
const LootTableEntry& drop = possibleDrops[GeneralUtils::GenerateRandomNumber<uint32_t>(0, possibleDrops.size() - 1)];
if (drops.find(drop.itemID) == drops.end()) {
drops.insert({drop.itemID, 1});
} else {
++drops[drop.itemID];
}
}
}
}
}
return drops;
}
void LootGenerator::GiveLoot(Entity* player, uint32_t matrixIndex) {
player = player->GetOwner(); // If the owner is overwritten, we collect that here
std::unordered_map<LOT, int32_t> result = RollLootMatrix(player, matrixIndex);
GiveLoot(player, result);
}
void LootGenerator::GiveLoot(Entity* player, std::unordered_map<LOT, int32_t>& result) {
player = player->GetOwner(); // if the owner is overwritten, we collect that here
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
if (!inventoryComponent)
return; return;
}
std::unordered_map<LOT, int32_t> result {};
CalculateLootMatrix(lootMatrixID, user, result);
DropLoot(user, killedObject, result, minCoins, maxCoins);
}
void Loot::GiveLoot(Entity* user, std::unordered_map<LOT, int32_t>& result) {
user = user->GetOwner(); // If the owner is overwritten, we collect that here
auto* inventoryComponent = user->GetComponent<InventoryComponent>();
if (inventoryComponent == nullptr) {
return;
}
for (const auto& pair : result) { for (const auto& pair : result) {
inventoryComponent->AddItem(pair.first, pair.second); inventoryComponent->AddItem(pair.first, pair.second);
} }
} }
void Loot::DropLoot(Entity* user, Entity* killedObject, std::unordered_map<LOT, int32_t>& result, uint32_t minCoins, uint32_t maxCoins) { void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) {
user = user->GetOwner(); // If the owner is overwritten, we collect that here CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards");
std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); });
auto* inventoryComponent = user->GetComponent<InventoryComponent>(); const CDActivityRewards* selectedReward = nullptr;
for (const auto& activityReward : activityRewards) {
if (inventoryComponent == nullptr) { if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) {
return; selectedReward = &activityReward;
} }
}
if (!selectedReward)
return;
uint32_t minCoins = 0;
uint32_t maxCoins = 0;
CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable");
std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); });
if (currencyTable.size() > 0) {
minCoins = currencyTable[0].minvalue;
maxCoins = currencyTable[0].maxvalue;
}
GiveLoot(player, selectedReward->LootMatrixIndex);
uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber<float>(0, 1) * (maxCoins - minCoins));
auto* character = player->GetCharacter();
character->SetCoins(character->GetCoins() + coins);
}
void LootGenerator::DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins) {
player = player->GetOwner(); // if the owner is overwritten, we collect that here
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
if (!inventoryComponent)
return;
std::unordered_map<LOT, int32_t> result = RollLootMatrix(player, matrixIndex);
DropLoot(player, killedObject, result, minCoins, maxCoins);
}
void LootGenerator::DropLoot(Entity* player, Entity* killedObject, std::unordered_map<LOT, int32_t>& result, uint32_t minCoins, uint32_t maxCoins) {
player = player->GetOwner(); // if the owner is overwritten, we collect that here
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
if (!inventoryComponent)
return;
const auto spawnPosition = killedObject->GetPosition(); const auto spawnPosition = killedObject->GetPosition();
@ -84,31 +346,27 @@ void Loot::DropLoot(Entity* user, Entity* killedObject, std::unordered_map<LOT,
for (const auto& pair : result) { for (const auto& pair : result) {
for (int i = 0; i < pair.second; ++i) { for (int i = 0; i < pair.second; ++i) {
GameMessages::SendDropClientLoot(user, source, pair.first, 0, spawnPosition, 1); GameMessages::SendDropClientLoot(player, source, pair.first, 0, spawnPosition, 1);
} }
} }
uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber<float>(0, 1) * (maxCoins - minCoins)); uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber<float>(0, 1) * (maxCoins - minCoins));
GameMessages::SendDropClientLoot(user, source, LOT_NULL, coins, spawnPosition); GameMessages::SendDropClientLoot(player, source, LOT_NULL, coins, spawnPosition);
} }
void Loot::DropActivityLoot(Entity* user, Entity* source, uint32_t activityID, int32_t rating) void LootGenerator::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) {
{
CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards"); CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards");
std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); });
const CDActivityRewards* selectedReward = nullptr; const CDActivityRewards* selectedReward = nullptr;
for (const auto& activityReward : activityRewards) for (const auto& activityReward : activityRewards) {
{ if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) {
if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating))
{
selectedReward = &activityReward; selectedReward = &activityReward;
} }
} }
if (selectedReward == nullptr) if (selectedReward == nullptr) {
{
return; return;
} }
@ -116,269 +374,12 @@ void Loot::DropActivityLoot(Entity* user, Entity* source, uint32_t activityID, i
uint32_t maxCoins = 0; uint32_t maxCoins = 0;
CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable"); CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable");
std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); });
if (currencyTable.size() > 0) { if (currencyTable.size() > 0) {
minCoins = currencyTable[0].minvalue; minCoins = currencyTable[0].minvalue;
maxCoins = currencyTable[0].maxvalue; maxCoins = currencyTable[0].maxvalue;
} }
Loot::DropLoot(user, source, selectedReward->LootMatrixIndex, minCoins, maxCoins); DropLoot(player, source, selectedReward->LootMatrixIndex, minCoins, maxCoins);
}
void Loot::GiveActivityLoot(Entity* user, Entity* source, uint32_t activityID, int32_t rating)
{
CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards");
std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) { return (entry.objectTemplate == activityID); });
const CDActivityRewards* selectedReward = nullptr;
for (const auto& activityReward : activityRewards)
{
if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating))
{
selectedReward = &activityReward;
}
}
if (selectedReward == nullptr)
{
return;
}
uint32_t minCoins = 0;
uint32_t maxCoins = 0;
CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable");
std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); });
if (currencyTable.size() > 0) {
minCoins = currencyTable[0].minvalue;
maxCoins = currencyTable[0].maxvalue;
}
Loot::GiveLoot(user, selectedReward->LootMatrixIndex);
uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber<float>(0, 1) * (maxCoins - minCoins));
auto* charactert = user->GetCharacter();
charactert->SetCoins(charactert->GetCoins() + coins);
}
void Loot::CalculateLootMatrix(uint32_t lootMatrixID, Entity* user, std::unordered_map<LOT, int32_t>& result)
{
user = user->GetOwner();
auto* missionComponent = user->GetComponent<MissionComponent>();
// Get our loot for this LOT's lootMatrixID:
CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable<CDLootMatrixTable>("LootMatrix");
CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable");
CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable<CDRarityTableTable>("RarityTable");
std::vector<CDLootMatrix> lootMatrix = lootMatrixTable->Query([lootMatrixID](CDLootMatrix entry) { return (entry.LootMatrixIndex == lootMatrixID); });
// Now, loop through each entry
for (uint32_t i = 0; i < lootMatrix.size(); ++i) {
// Now, determine whether or not we should drop this
float chanceToDrop = 1.0 - lootMatrix[i].percent;
float shouldDrop = GeneralUtils::GenerateRandomNumber<float>(0, 1);
const auto rarityTableIndex = lootMatrix[i].RarityTableIndex;
std::vector<CDRarityTable> rarityTable = rarityTableTable->Query([rarityTableIndex](CDRarityTable entry) { return (entry.RarityTableIndex == rarityTableIndex); });
std::sort(rarityTable.begin(), rarityTable.end());
if (shouldDrop < chanceToDrop) {
// We are not able to drop this item, so continue
continue;
}
// If we reached here, we are able to drop the item
uint32_t minToDrop = lootMatrix[i].minToDrop;
uint32_t maxToDrop = lootMatrix[i].maxToDrop;
// Now determine the number we will drop of items from this table
uint32_t numToDrop = GeneralUtils::GenerateRandomNumber<uint32_t>(minToDrop, maxToDrop);
// Now, query the loot matrix index
const auto lootTableIndex = lootMatrix[i].LootTableIndex;
std::vector<CDLootTable> lootTable = lootTableTable->Query([lootTableIndex](CDLootTable entry) { return (entry.LootTableIndex == lootTableIndex); });
// Now randomize these entries
if (lootTable.size() > 1) {
std::shuffle(std::begin(lootTable), std::end(lootTable), Game::randomEngine);
}
uint32_t addedItems = 0;
if (lootTable.empty()) continue;
while (addedItems < numToDrop) {
addedItems++;
float rarityRoll = GeneralUtils::GenerateRandomNumber<float>(0, 1);
// im sorry
uint32_t highestRarity = 1; // LOOT_COMMON
float highestRandMax = 0.0f;
for (const auto& rarity : rarityTable) {
if (rarityRoll > rarity.randmax && rarity.randmax > highestRandMax) {
highestRandMax = rarity.randmax;
highestRarity = rarity.rarity + 1;
}
}
std::vector<CDLootTable> refinedLoot;
if (lootTable.size() == 1)
{
refinedLoot = lootTable;
}
else
{
refinedLoot = GetLootOfRarity(lootTable, highestRarity);
bool continueLoop = false;
while (refinedLoot.empty())
{
if (highestRarity == 1)
{
continueLoop = true;
break;
}
highestRarity -= 1;
refinedLoot = GetLootOfRarity(lootTable, highestRarity);
if (!refinedLoot.empty())
{
break;
}
}
if (continueLoop) continue;
}
int randomTable = GeneralUtils::GenerateRandomNumber<int>(0, refinedLoot.size() - 1);
const auto& selectedTable = refinedLoot[randomTable];
uint32_t itemLOT = selectedTable.itemid;
bool isMissionItem = selectedTable.MissionDrop;
if (isMissionItem && missionComponent != nullptr)
{
// TODO: this executes a query in a hot path, might be worth refactoring away
if (!missionComponent->RequiresItem(itemLOT))
{
continue;
}
}
if (lootTable.size() > numToDrop)
{
for (size_t i = 0; i < lootTable.size(); i++)
{
if (lootTable[i].id == selectedTable.id)
{
lootTable.erase(lootTable.begin() + i);
break;
}
}
}
const auto& it = result.find(itemLOT);
if (it != result.end()) {
it->second++;
}
else {
result.emplace(itemLOT, 1);
}
}
}
int32_t tokenCount = 0;
const auto& tokens = result.find(13763);
if (tokens != result.end()) {
tokenCount = tokens->second;
result.erase(tokens);
}
if (tokenCount == 0 || user == nullptr) {
return;
}
if (missionComponent == nullptr) {
return;
}
LOT tokenId = -1;
if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) // "Join Assembly!"
{
tokenId = 8318; // "Assembly Token"
}
if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) // "Join Venture League!"
{
tokenId = 8321; // "Venture League Token"
}
if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) // "Join The Sentinels!"
{
tokenId = 8319; // "Sentinels Token"
}
if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) // "Join Paradox!"
{
tokenId = 8320; // "Paradox Token"
}
if (tokenId != -1)
{
result.emplace(tokenId, tokenCount);
}
}
void Loot::DropItem(Entity* user, Entity* sourceObject, LOT item, int32_t currency, int32_t count, bool useTeam, bool freeForAll)
{
if (sourceObject == nullptr)
{
return;
}
const auto sourceID = sourceObject->GetObjectID();
const auto sourcePosition = sourceObject->GetPosition();
// If useTeam, drop the item once for each team member.
auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID());
if (team != nullptr && useTeam)
{
for (const auto& memberID : team->members)
{
// Get the team member from its ID.
auto* member = EntityManager::Instance()->GetEntity(memberID);
if (member == nullptr)
{
continue;
}
// Drop the item.
GameMessages::SendDropClientLoot(member, sourceID, item, currency, sourcePosition, count);
}
return;
}
GameMessages::SendDropClientLoot(user, sourceID, item, currency, sourcePosition, count);
} }

View File

@ -1,31 +1,61 @@
#pragma once #pragma once
#include "dCommonVars.h" #include "dCommonVars.h"
#include <vector> #include <unordered_map>
#include "CDClientManager.h" #include "Singleton.h"
class Entity; class Entity;
struct RarityTableEntry {
uint32_t rarity;
float randMax;
};
typedef std::vector<RarityTableEntry> RarityTable;
struct LootMatrixEntry {
uint32_t lootTableIndex;
uint32_t rarityTableIndex;
float percent;
uint32_t minDrop;
uint32_t maxDrop;
};
typedef std::vector<LootMatrixEntry> LootMatrix;
struct LootTableEntry {
LOT itemID;
bool isMissionDrop;
};
typedef std::vector<LootTableEntry> LootTable;
// used for glue code with Entity and Player classes
namespace Loot { namespace Loot {
struct Info { struct Info {
LWOOBJID id; LWOOBJID id;
LOT lot; LOT lot;
uint32_t count; uint32_t count;
}; };
}
std::vector<CDLootTable> GetLootOfRarity(const std::vector<CDLootTable> &lootTable, uint32_t rarity);
void DropActivityLoot(Entity* user, Entity* source, uint32_t activityID, int32_t rating = 0); class LootGenerator : public Singleton<LootGenerator> {
public:
LootGenerator();
void GiveActivityLoot(Entity* user, Entity* source, uint32_t activityID, int32_t rating = 0); std::unordered_map<LOT, int32_t> RollLootMatrix(Entity* player, uint32_t matrixIndex);
std::unordered_map<LOT, int32_t> RollLootMatrix(uint32_t matrixIndex);
void GiveLoot(Entity* player, uint32_t matrixIndex);
void GiveLoot(Entity* player, std::unordered_map<LOT, int32_t>& result);
void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0);
void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins);
void DropLoot(Entity* player, Entity* killedObject, std::unordered_map<LOT, int32_t>& result, uint32_t minCoins, uint32_t maxCoins);
void DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0);
void CalculateLootMatrix(uint32_t lootMatrixID, Entity* user, std::unordered_map<LOT, int32_t>& result); private:
std::unordered_map<uint32_t, uint8_t> m_ItemRarities;
void GiveLoot(Entity* user, uint32_t lootMatrixID); std::unordered_map<uint32_t, RarityTable> m_RarityTables;
std::unordered_map<uint32_t, LootMatrix> m_LootMatrices;
void DropLoot(Entity* user, Entity* killedObject, uint32_t lootMatrixID, uint32_t minCoins, uint32_t maxCoins); std::unordered_map<uint32_t, LootTable> m_LootTables;
void GiveLoot(Entity* user, std::unordered_map<LOT, int32_t>& result);
void DropLoot(Entity* user, Entity* killedObject, std::unordered_map<LOT, int32_t>& result, uint32_t minCoins, uint32_t maxCoins);
void DropItem(Entity* user, Entity* sourceObject, LOT item, int32_t currency, int32_t count, bool useTeam = false, bool freeForAll = false);
}; };

View File

@ -1691,6 +1691,43 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit
return; return;
} }
if (chatCommand == "rollloot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && args.size() >= 3) {
uint32_t lootMatrixIndex = 0;
uint32_t targetLot = 0;
uint32_t loops = 1;
if (!GeneralUtils::TryParse(args[0], lootMatrixIndex)) return;
if (!GeneralUtils::TryParse(args[1], targetLot)) return;
if (!GeneralUtils::TryParse(args[2], loops)) return;
uint64_t totalRuns = 0;
for (uint32_t i = 0; i < loops; i++) {
while (true) {
auto lootRoll = LootGenerator::Instance().RollLootMatrix(lootMatrixIndex);
totalRuns += 1;
bool doBreak = false;
for (const auto& kv : lootRoll) {
if ((uint32_t)kv.first == targetLot) {
doBreak = true;
}
}
if (doBreak) break;
}
}
std::u16string message = u"Ran loot drops looking for "
+ GeneralUtils::to_u16string(targetLot)
+ u", "
+ GeneralUtils::to_u16string(loops)
+ u" times. It ran "
+ GeneralUtils::to_u16string(totalRuns)
+ u" times. Averaging out at "
+ GeneralUtils::to_u16string((float) totalRuns / loops);
ChatPackets::SendSystemMessage(sysAddr, message);
}
if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1)
{ {
Entity* closest = nullptr; Entity* closest = nullptr;

View File

@ -70,7 +70,7 @@ void ActivityManager::StopActivity(Entity *self, const LWOOBJID playerID, const
SetActivityValue(self, playerID, 1, value1); SetActivityValue(self, playerID, 1, value1);
SetActivityValue(self, playerID, 2, value2); SetActivityValue(self, playerID, 2, value2);
Loot::GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID)); LootGenerator::Instance().GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID));
// Save the new score to the leaderboard and show the leaderboard to the player // Save the new score to the leaderboard and show the leaderboard to the player
LeaderboardManager::SaveScore(playerID, gameID, score, value1); LeaderboardManager::SaveScore(playerID, gameID, score, value1);

View File

@ -8,7 +8,7 @@ void AgPicnicBlanket::OnUse(Entity *self, Entity *user) {
self->SetVar<bool>(u"active", true); self->SetVar<bool>(u"active", true);
auto lootTable = std::unordered_map<LOT, int32_t> {{935, 3}}; auto lootTable = std::unordered_map<LOT, int32_t> {{935, 3}};
Loot::DropLoot(user, self, lootTable, 0, 0); LootGenerator::Instance().DropLoot(user, self, lootTable, 0, 0);
self->AddCallbackTimer(5.0f, [self]() { self->AddCallbackTimer(5.0f, [self]() {
self->SetVar<bool>(u"active", false); self->SetVar<bool>(u"active", false);

View File

@ -25,7 +25,7 @@ void BaseInteractDropLootServer::BaseUse(Entity* self, Entity* user)
self->SetNetworkVar(u"bInUse", true); self->SetNetworkVar(u"bInUse", true);
Loot::DropLoot(user, self, lootMatrix, 0, 0); LootGenerator::Instance().DropLoot(user, self, lootMatrix, 0, 0);
self->AddCallbackTimer(cooldownTime, [this, self] () { self->AddCallbackTimer(cooldownTime, [this, self] () {
self->SetNetworkVar(u"bInUse", false); self->SetNetworkVar(u"bInUse", false);

View File

@ -41,7 +41,7 @@ BootyDigServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string
if (renderComponent != nullptr) if (renderComponent != nullptr)
renderComponent->PlayEffect(7730, u"cast", "bootyshine"); renderComponent->PlayEffect(7730, u"cast", "bootyshine");
Loot::DropLoot(player, self, 231, 75, 75); LootGenerator::Instance().DropLoot(player, self, 231, 75, 75);
} }
} }
} else if (args == "ChestDead") { } else if (args == "ChestDead") {

View File

@ -6,6 +6,7 @@
#include "MissionState.h" #include "MissionState.h"
#include "Game.h" #include "Game.h"
#include "dLogger.h" #include "dLogger.h"
#include "Loot.h"
class User; class User;
class Entity; class Entity;

View File

@ -10,7 +10,7 @@ void GrowingFlower::OnSkillEventFired(Entity *self, Entity *target, const std::s
const auto mission1 = self->GetVar<int32_t>(u"missionID"); const auto mission1 = self->GetVar<int32_t>(u"missionID");
const auto mission2 = self->GetVar<int32_t>(u"missionID2"); const auto mission2 = self->GetVar<int32_t>(u"missionID2");
Loot::DropActivityLoot(target, self, self->GetLOT(), 0); LootGenerator::Instance().DropActivityLoot(target, self, self->GetLOT(), 0);
auto* missionComponent = target->GetComponent<MissionComponent>(); auto* missionComponent = target->GetComponent<MissionComponent>();
if (missionComponent != nullptr) { if (missionComponent != nullptr) {

View File

@ -22,10 +22,10 @@ void MinigameTreasureChestServer::OnUse(Entity *self, Entity *user) {
for (const auto& teamMemberID : team->members) { for (const auto& teamMemberID : team->members) {
auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID); auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID);
if (teamMember != nullptr) if (teamMember != nullptr)
Loot::DropActivityLoot(teamMember, self, sac->GetActivityID(), CalculateActivityRating(self, teamMemberID)); LootGenerator::Instance().DropActivityLoot(teamMember, self, sac->GetActivityID(), CalculateActivityRating(self, teamMemberID));
} }
} else { } else {
Loot::DropActivityLoot(user, self, sac->GetActivityID(), CalculateActivityRating(self, user->GetObjectID())); LootGenerator::Instance().DropActivityLoot(user, self, sac->GetActivityID(), CalculateActivityRating(self, user->GetObjectID()));
} }
sac->PlayerRemove(user->GetObjectID()); sac->PlayerRemove(user->GetObjectID());

View File

@ -10,6 +10,6 @@ void NjDragonEmblemChestServer::OnUse(Entity *self, Entity *user) {
auto* destroyable = self->GetComponent<DestroyableComponent>(); auto* destroyable = self->GetComponent<DestroyableComponent>();
if (destroyable != nullptr) { if (destroyable != nullptr) {
Loot::DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0); LootGenerator::Instance().DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0);
} }
} }

View File

@ -423,7 +423,7 @@ void SGCannon::SpawnNewModel(Entity *self) {
if (lootMatrix != 0) { if (lootMatrix != 0) {
std::unordered_map<LOT, int32_t> toDrop = {}; std::unordered_map<LOT, int32_t> toDrop = {};
Loot::CalculateLootMatrix(lootMatrix, player, toDrop); toDrop = LootGenerator::Instance().RollLootMatrix(player, lootMatrix);
for (auto drop : toDrop) { for (auto drop : toDrop) {
rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first); rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first);
@ -581,7 +581,7 @@ void SGCannon::StopGame(Entity *self, bool cancel) {
); );
} }
Loot::GiveActivityLoot(player, self, GetGameID(self), self->GetVar<uint32_t>(TotalScoreVariable)); LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar<uint32_t>(TotalScoreVariable));
StopActivity(self, player->GetObjectID(), self->GetVar<uint32_t>(TotalScoreVariable), StopActivity(self, player->GetObjectID(), self->GetVar<uint32_t>(TotalScoreVariable),
self->GetVar<uint32_t>(MaxStreakVariable), percentage); self->GetVar<uint32_t>(MaxStreakVariable), percentage);

View File

@ -24,7 +24,7 @@ void ScriptedPowerupSpawner::OnTimerDone(Entity *self, std::string message) {
renderComponent->PlayEffect(0, u"cast", "N_cast"); renderComponent->PlayEffect(0, u"cast", "N_cast");
} }
Loot::DropItem(owner, self, itemLOT, 0, 1, true, true); LootGenerator::Instance().DropLoot(owner, self, itemLOT, 0, 1);
} }
// Increment the current cycle // Increment the current cycle

View File

@ -39,12 +39,12 @@ void TreasureChestDragonServer::OnUse(Entity* self, Entity* user)
if (memberObject == nullptr) continue; if (memberObject == nullptr) continue;
Loot::DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating); LootGenerator::Instance().DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating);
} }
} }
else else
{ {
Loot::DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating); LootGenerator::Instance().DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating);
} }
self->Smash(self->GetObjectID()); self->Smash(self->GetObjectID());

View File

@ -4,7 +4,7 @@
#include "GameMessages.h" #include "GameMessages.h"
void VeMissionConsole::OnUse(Entity *self, Entity *user) { void VeMissionConsole::OnUse(Entity *self, Entity *user) {
Loot::DropActivityLoot(user, self, 12551); LootGenerator::Instance().DropActivityLoot(user, self, 12551);
auto* inventoryComponent = user->GetComponent<InventoryComponent>(); auto* inventoryComponent = user->GetComponent<InventoryComponent>();
if (inventoryComponent != nullptr) { if (inventoryComponent != nullptr) {

View File

@ -24,7 +24,7 @@ void WishingWellServer::OnUse(Entity* self, Entity* user)
GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio); GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio);
} }
Loot::DropActivityLoot( LootGenerator::Instance().DropActivityLoot(
user, user,
self, self,
static_cast<uint32_t>(scriptedActivity->GetActivityID()), static_cast<uint32_t>(scriptedActivity->GetActivityID()),

View File

@ -187,6 +187,7 @@ int main(int argc, char** argv) {
ObjectIDManager::Instance()->Initialize(); ObjectIDManager::Instance()->Initialize();
UserManager::Instance()->Initialize(); UserManager::Instance()->Initialize();
LootGenerator::Instance();
Game::chatFilter = new dChatFilter("./res/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); Game::chatFilter = new dChatFilter("./res/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf"))));
Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, zoneID); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, zoneID);

View File

@ -11,6 +11,8 @@
#include "GeneralUtils.h" #include "GeneralUtils.h"
#include "Entity.h" #include "Entity.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "CDFeatureGatingTable.h"
#include "CDClientManager.h"
Level::Level(Zone* parentZone, const std::string& filepath) { Level::Level(Zone* parentZone, const std::string& filepath) {
m_ParentZone = parentZone; m_ParentZone = parentZone;