aboutsummaryrefslogtreecommitdiff
path: root/src/server/game/Loot/LootItemStorage.cpp
blob: c0362ea093b4e4eb7a67509078892abb618b8dd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "DatabaseEnv.h"
#include "Item.h"
#include "ItemTemplate.h"
#include "Log.h"
#include "Loot.h"
#include "LootItemStorage.h"
#include "LootMgr.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "StringConvert.h"
#include "Util.h"
#include <sstream>
#include <unordered_map>

namespace
{
    std::unordered_map<uint64, StoredLootContainer> _lootItemStore;
}

StoredLootItem::StoredLootItem(LootItem const& lootItem) : ItemId(lootItem.itemid), Count(lootItem.count), ItemIndex(lootItem.LootListId), FollowRules(lootItem.follow_loot_rules),
FFA(lootItem.freeforall), Blocked(lootItem.is_blocked), Counted(lootItem.is_counted), UnderThreshold(lootItem.is_underthreshold),
NeedsQuest(lootItem.needs_quest), RandomBonusListId(lootItem.randomBonusListId), Context(lootItem.context), BonusListIDs(lootItem.BonusListIDs)
{
}

LootItemStorage* LootItemStorage::instance()
{
    static LootItemStorage instance;
    return &instance;
}

std::shared_mutex* LootItemStorage::GetLock()
{
    static std::shared_mutex _lock;
    return &_lock;
}

void LootItemStorage::LoadStorageFromDB()
{
    uint32 oldMSTime = getMSTime();
    _lootItemStore.clear();
    uint32 count = 0;

    CharacterDatabaseTransaction trans = CharacterDatabaseTransaction(nullptr);
    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_ITEMS);
    PreparedQueryResult result = CharacterDatabase.Query(stmt);
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint64 key = fields[0].GetUInt64();
            StoredLootContainer& storedContainer = _lootItemStore.try_emplace(key, key).first->second;

            LootItem lootItem;
            lootItem.type = static_cast<LootItemType>(fields[1].GetInt8());
            lootItem.itemid = fields[2].GetUInt32();
            lootItem.count = fields[3].GetUInt32();
            lootItem.LootListId = fields[4].GetUInt32();
            lootItem.follow_loot_rules = fields[5].GetBool();
            lootItem.freeforall = fields[6].GetBool();
            lootItem.is_blocked = fields[7].GetBool();
            lootItem.is_counted = fields[8].GetBool();
            lootItem.is_underthreshold = fields[9].GetBool();
            lootItem.needs_quest = fields[10].GetBool();
            lootItem.randomBonusListId = fields[11].GetUInt32();
            lootItem.context = ItemContext(fields[12].GetUInt8());
            for (std::string_view bonusList : Trinity::Tokenize(fields[13].GetStringView(), ' ', false))
                if (Optional<int32> bonusListID = Trinity::StringTo<int32>(bonusList))
                    lootItem.BonusListIDs.push_back(*bonusListID);

            storedContainer.AddLootItem(lootItem, trans);

            ++count;
        } while (result->NextRow());

        TC_LOG_INFO("server.loading", ">> Loaded {} stored item loots in {} ms", count, GetMSTimeDiffToNow(oldMSTime));
    }
    else
        TC_LOG_INFO("server.loading", ">> Loaded 0 stored item loots");

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_MONEY);
    result = CharacterDatabase.Query(stmt);
    if (result)
    {
        count = 0;
        do
        {
            Field* fields = result->Fetch();

            uint64 key = fields[0].GetUInt64();
            StoredLootContainer& storedContainer = _lootItemStore.try_emplace(key, key).first->second;
            storedContainer.AddMoney(fields[1].GetUInt32(), trans);

            ++count;
        } while (result->NextRow());

        TC_LOG_INFO("server.loading", ">> Loaded {} stored item money in {} ms", count, GetMSTimeDiffToNow(oldMSTime));
    }
    else
        TC_LOG_INFO("server.loading", ">> Loaded 0 stored item money");
}

bool LootItemStorage::LoadStoredLoot(Item* item, Player* player)
{
    StoredLootContainer const* container = nullptr;

    // read
    {
        std::shared_lock<std::shared_mutex> lock(*GetLock());

        auto itr = _lootItemStore.find(item->GetGUID().GetCounter());
        if (itr == _lootItemStore.end())
            return false;

        container = &itr->second;
    }

    // container is never null at this point
    Loot* loot = new Loot(player->GetMap(), item->GetGUID(), LOOT_ITEM, nullptr);
    loot->gold = container->GetMoney();

    if (LootTemplate const* lt = LootTemplates_Item.GetLootFor(item->GetEntry()))
    {
        for (auto const& storedItemPair : container->GetLootItems())
        {
            LootItem li;
            li.itemid = storedItemPair.first;
            li.count = storedItemPair.second.Count;
            li.LootListId = storedItemPair.second.ItemIndex;
            li.follow_loot_rules = storedItemPair.second.FollowRules;
            li.freeforall = storedItemPair.second.FFA;
            li.is_blocked = storedItemPair.second.Blocked;
            li.is_counted = storedItemPair.second.Counted;
            li.is_underthreshold = storedItemPair.second.UnderThreshold;
            li.needs_quest = storedItemPair.second.NeedsQuest;
            li.randomBonusListId = storedItemPair.second.RandomBonusListId;
            li.context = storedItemPair.second.Context;
            li.BonusListIDs = storedItemPair.second.BonusListIDs;

            // Copy the extra loot conditions from the item in the loot template
            lt->CopyConditions(&li);

            // If container item is in a bag, add that player as an allowed looter
            if (item->GetBagSlot())
                li.AddAllowedLooter(player);

            // Finally add the LootItem to the container
            loot->items.push_back(li);

            // Increment unlooted count
            ++loot->unlootedCount;
        }
    }

    if (!loot->items.empty())
    {
        std::sort(loot->items.begin(), loot->items.end(), [](LootItem const& left, LootItem const& right) { return left.LootListId < right.LootListId; });

        uint32 lootListId = 0;
        // add dummy loot items to ensure items are indexable by their LootListId
        while (loot->items.size() <= loot->items.back().LootListId)
        {
            if (loot->items[lootListId].LootListId != lootListId)
            {
                auto li = loot->items.emplace(loot->items.begin() + lootListId);
                li->LootListId = lootListId;
                li->is_looted = true;
            }

            ++lootListId;
        }
    }

    // Mark the item if it has loot so it won't be generated again on open
    item->m_loot.reset(loot);
    item->m_lootGenerated = true;
    return true;
}

void LootItemStorage::RemoveStoredMoneyForContainer(uint64 containerId)
{
    // write
    std::unique_lock<std::shared_mutex> lock(*GetLock());

    auto itr = _lootItemStore.find(containerId);
    if (itr == _lootItemStore.end())
        return;

    itr->second.RemoveMoney();
}

void LootItemStorage::RemoveStoredLootForContainer(uint64 containerId)
{
    // write
    {
        std::unique_lock<std::shared_mutex> lock(*GetLock());
        _lootItemStore.erase(containerId);
    }

    CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS);
    stmt->setUInt64(0, containerId);
    trans->Append(stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY);
    stmt->setUInt64(0, containerId);
    trans->Append(stmt);

    CharacterDatabase.CommitTransaction(trans);
}

void LootItemStorage::RemoveStoredLootItemForContainer(uint64 containerId, LootItemType type, uint32 itemId, uint32 count, uint32 itemIndex)
{
    // write
    std::unique_lock<std::shared_mutex> lock(*GetLock());

    auto itr = _lootItemStore.find(containerId);
    if (itr == _lootItemStore.end())
        return;

    itr->second.RemoveItem(type, itemId, count, itemIndex);
}

void LootItemStorage::AddNewStoredLoot(uint64 containerId, Loot* loot, Player* player)
{
    // Saves the money and item loot associated with an openable item to the DB
    if (loot->isLooted()) // no money and no loot
        return;

    // read
    {
        std::shared_lock<std::shared_mutex> lock(*GetLock());

        auto itr = _lootItemStore.find(containerId);
        if (itr != _lootItemStore.end())
        {
            TC_LOG_ERROR("misc", "Trying to store item loot by player: {} for container id: {} that is already in storage!", player->GetGUID().ToString(), containerId);
            return;
        }
    }

    StoredLootContainer container(containerId);

    CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
    if (loot->gold)
        container.AddMoney(loot->gold, trans);

    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS);
    stmt->setUInt64(0, containerId);
    trans->Append(stmt);

    for (LootItem const& li : loot->items)
    {
        // Conditions are not checked when loot is generated, it is checked when loot is sent to a player.
        // For items that are lootable, loot is saved to the DB immediately, that means that loot can be
        // saved to the DB that the player never should have gotten. This check prevents that, so that only
        // items that the player should get in loot are in the DB.
        // IE: Horde items are not saved to the DB for Ally players.
        if (!li.AllowedForPlayer(player, loot))
            continue;

        // Don't save currency tokens
        ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(li.itemid);
        if (!itemTemplate || itemTemplate->IsCurrencyToken())
            continue;

        container.AddLootItem(li, trans);
    }

    CharacterDatabase.CommitTransaction(trans);

    // write
    {
        std::unique_lock<std::shared_mutex> lock(*GetLock());
        _lootItemStore.emplace(containerId, std::move(container));
    }
}

void StoredLootContainer::AddLootItem(LootItem const& lootItem, CharacterDatabaseTransaction trans)
{
    _lootItems.emplace(std::piecewise_construct, std::forward_as_tuple(lootItem.itemid), std::forward_as_tuple(lootItem));
    if (!trans)
        return;

    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_ITEMS);

    // container_id, item_type, item_id, item_count, item_index, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix
    stmt->setUInt64(0, _containerId);
    stmt->setInt8(1, AsUnderlyingType(lootItem.type));
    stmt->setUInt32(2, lootItem.itemid);
    stmt->setUInt32(3, lootItem.count);
    stmt->setUInt32(4, lootItem.LootListId);
    stmt->setBool(5, lootItem.follow_loot_rules);
    stmt->setBool(6, lootItem.freeforall);
    stmt->setBool(7, lootItem.is_blocked);
    stmt->setBool(8, lootItem.is_counted);
    stmt->setBool(9, lootItem.is_underthreshold);
    stmt->setBool(10, lootItem.needs_quest);
    stmt->setInt32(11, lootItem.randomBonusListId);
    stmt->setUInt8(13, AsUnderlyingType(lootItem.context));
    std::ostringstream bonusListIDs;
    for (int32 bonusListID : lootItem.BonusListIDs)
        bonusListIDs << bonusListID << ' ';
    stmt->setString(13, bonusListIDs.str());
    trans->Append(stmt);
}

void StoredLootContainer::AddMoney(uint32 money, CharacterDatabaseTransaction trans)
{
    _money = money;
    if (!trans)
        return;

    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY);
    stmt->setUInt64(0, _containerId);
    trans->Append(stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_MONEY);
    stmt->setUInt64(0, _containerId);
    stmt->setUInt32(1, _money);
    trans->Append(stmt);
}

void StoredLootContainer::RemoveMoney()
{
    _money = 0;

    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY);
    stmt->setUInt64(0, _containerId);
    CharacterDatabase.Execute(stmt);
}

void StoredLootContainer::RemoveItem(LootItemType type, uint32 itemId, uint32 count, uint32 itemIndex)
{
    auto bounds = _lootItems.equal_range(itemId);
    for (auto itr = bounds.first; itr != bounds.second; ++itr)
    {
        if (itr->second.ItemIndex == itemIndex)
        {
            _lootItems.erase(itr);
            break;
        }
    }

    // Deletes a single item associated with an openable item from the DB
    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEM);
    stmt->setUInt64(0, _containerId);
    stmt->setInt8(1, AsUnderlyingType(type));
    stmt->setUInt32(2, itemId);
    stmt->setUInt32(3, count);
    stmt->setUInt32(4, itemIndex);
    CharacterDatabase.Execute(stmt);
}