diff options
author | Shauren <shauren.trinity@gmail.com> | 2020-01-02 14:19:35 +0100 |
---|---|---|
committer | Shauren <shauren.trinity@gmail.com> | 2022-10-04 00:19:38 +0200 |
commit | 9b924522d0549dd67b10e2cbdfc20297dd21e182 (patch) | |
tree | f0fcdf96902b7c497c1bc65db83621a8dfadf43a /src/server/game/Instances | |
parent | a131542855d23022714a97640be1c8d68a741c31 (diff) |
Core/Instances: Delete InstanceSaveMgr and replace most of its uses with new InstanceLockMgr
Diffstat (limited to 'src/server/game/Instances')
-rw-r--r-- | src/server/game/Instances/InstanceLockMgr.cpp | 8 | ||||
-rw-r--r-- | src/server/game/Instances/InstanceLockMgr.h | 7 | ||||
-rw-r--r-- | src/server/game/Instances/InstanceSaveMgr.cpp | 736 | ||||
-rw-r--r-- | src/server/game/Instances/InstanceSaveMgr.h | 245 | ||||
-rw-r--r-- | src/server/game/Instances/InstanceScript.cpp | 15 | ||||
-rw-r--r-- | src/server/game/Instances/InstanceScript.h | 2 |
6 files changed, 27 insertions, 986 deletions
diff --git a/src/server/game/Instances/InstanceLockMgr.cpp b/src/server/game/Instances/InstanceLockMgr.cpp index 007d994133a..94cfd09706c 100644 --- a/src/server/game/Instances/InstanceLockMgr.cpp +++ b/src/server/game/Instances/InstanceLockMgr.cpp @@ -414,10 +414,12 @@ void InstanceLockMgr::OnSharedInstanceLockDataDelete(uint32 instanceId) TC_LOG_DEBUG("instance.locks", "Deleting instance %u as it is no longer referenced by any player", instanceId); } -void InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended) +std::pair<InstanceResetTimePoint, InstanceResetTimePoint> InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, + MapDb2Entries const& entries, bool extended) { if (InstanceLock* instanceLock = FindActiveInstanceLock(playerGuid, entries, true, false)) { + InstanceResetTimePoint oldExpiryTime = instanceLock->GetEffectiveExpiryTime(); instanceLock->SetExtended(extended); CharacterDatabase.PExecute("UPDATE character_instance_lock SET extended = %d WHERE guid = " UI64FMTD " AND mapId = %u AND lockId = %d", extended ? 1 : 0, @@ -429,7 +431,11 @@ void InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& pla entries.Map->ID, entries.Map->MapName[sWorld->GetDefaultDbcLocale()], uint32(entries.MapDifficulty->DifficultyID), sDifficultyStore.AssertEntry(entries.MapDifficulty->DifficultyID)->Name[sWorld->GetDefaultDbcLocale()], playerGuid.ToString().c_str(), extended ? "now" : "no longer"); + + return { oldExpiryTime, instanceLock->GetEffectiveExpiryTime() }; } + + return { InstanceResetTimePoint::min(), InstanceResetTimePoint::min() }; } #include "Config.h" diff --git a/src/server/game/Instances/InstanceLockMgr.h b/src/server/game/Instances/InstanceLockMgr.h index faf0bd584f6..45394451878 100644 --- a/src/server/game/Instances/InstanceLockMgr.h +++ b/src/server/game/Instances/InstanceLockMgr.h @@ -38,6 +38,7 @@ * `difficulty` tinyint(3) unsigned, * `data` text, ALWAYS FILLED (also might not match instance data for instanceId based locks) * `completedEncountersMask` int(10) unsigned, ALWAYS FILLED (also might not match instance data for instanceId based locks) + * `entranceWorldSafeLocId` int(10) unsigned, ALWAYS FILLED (also might not match instance data for instanceId based locks) * `expiryTime` bigint(20) unsigned, * `extended` tinyint(1) unsigned, * PRIMARY KEY (`guid`,`mapId`,`lockId`), @@ -46,6 +47,7 @@ * `instanceId` int(10) unsigned NOT NULL, * `data` text, FILLED ONLY FOR ID BASED LOCKS * `completedEncountersMask` int(10) unsigned, FILLED ONLY FOR ID BASED LOCKS + * `entranceWorldSafeLocId` int(10) unsigned, FILLED ONLY FOR ID BASED LOCKS * PRIMARY KEY (`instanceId`) */ @@ -73,6 +75,7 @@ struct InstanceLockData std::string Data; uint32 CompletedEncountersMask = 0; + uint32 EntranceWorldSafeLocId = 0; }; class TC_GAME_API InstanceLock @@ -185,6 +188,7 @@ struct InstanceLockUpdateEvent DungeonEncounterEntry const* CompletedEncounter; }; +// TOTALLY NOT THREADSAFE YET class TC_GAME_API InstanceLockMgr { public: @@ -252,8 +256,9 @@ public: @param playerGuid Guid of player whose lock is extended @param entries Map.db2 + MapDifficulty.db2 data for instance @param extended New instance lock extension state + @return pair<OldExpirationTime, NewExpirationTime> */ - void UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended); + std::pair<InstanceResetTimePoint, InstanceResetTimePoint> UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended); static InstanceLockMgr& Instance(); diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp deleted file mode 100644 index b566b4f0cf6..00000000000 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ /dev/null @@ -1,736 +0,0 @@ -/* - * 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 "InstanceSaveMgr.h" -#include "Common.h" -#include "Config.h" -#include "DatabaseEnv.h" -#include "DB2Stores.h" -#include "GameTime.h" -#include "GridNotifiers.h" -#include "GridStates.h" -#include "Group.h" -#include "InstanceScenario.h" -#include "InstanceScript.h" -#include "Log.h" -#include "Map.h" -#include "MapManager.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "Timer.h" -#include "World.h" - -uint16 InstanceSaveManager::ResetTimeDelay[] = {3600, 900, 300, 60}; - -InstanceSaveManager::~InstanceSaveManager() -{ -} - -InstanceSaveManager* InstanceSaveManager::instance() -{ - static InstanceSaveManager instance; - return &instance; -} - -void InstanceSaveManager::Unload() -{ - lock_instLists = true; - for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - { - InstanceSave* save = itr->second; - - for (InstanceSave::PlayerListType::iterator itr2 = save->m_playerList.begin(), next = itr2; itr2 != save->m_playerList.end(); itr2 = next) - { - ++next; - (*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficultyID(), true); - } - - for (InstanceSave::GroupListType::iterator itr2 = save->m_groupList.begin(), next = itr2; itr2 != save->m_groupList.end(); itr2 = next) - { - ++next; - (*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficultyID(), true); - } - - delete save; - } -} - -/* -- adding instance into manager -- called from InstanceMap::Add, _LoadBoundInstances, LoadGroups -*/ -InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, time_t resetTime, uint32 entranceId, bool canReset, bool load) -{ - if (InstanceSave* old_save = GetInstanceSave(instanceId)) - return old_save; - - MapEntry const* entry = sMapStore.LookupEntry(mapId); - if (!entry) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: wrong mapid = %d, instanceid = %d!", mapId, instanceId); - return nullptr; - } - - if (instanceId == 0) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, wrong instanceid = %d!", mapId, instanceId); - return nullptr; - } - - DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(difficulty); - if (!difficultyEntry || difficultyEntry->InstanceType != entry->InstanceType) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d, wrong dificalty %u!", mapId, instanceId, static_cast<uint32>(difficulty)); - return nullptr; - } - - if (entranceId && !sObjectMgr->GetWorldSafeLoc(entranceId)) - { - TC_LOG_WARN("misc", "InstanceSaveManager::AddInstanceSave: invalid entranceId = %d defined for instance save with mapid = %d, instanceid = %d!", entranceId, mapId, instanceId); - entranceId = 0; - } - - if (!resetTime) - { - // initialize reset time - // for normal instances if no creatures are killed the instance will reset in two hours - if (entry->IsRaid() || difficulty > DIFFICULTY_NORMAL) - resetTime = GetResetTimeFor(mapId, difficulty); - else - { - resetTime = GameTime::GetGameTime() + 2 * HOUR; - // normally this will be removed soon after in InstanceMap::Add, prevent error - ScheduleReset(true, resetTime, InstResetEvent(0, mapId, difficulty, instanceId)); - } - } - - TC_LOG_DEBUG("maps", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d", mapId, instanceId); - - InstanceSave* save = new InstanceSave(mapId, instanceId, difficulty, entranceId, resetTime, canReset); - if (!load) - save->SaveToDB(); - - m_instanceSaveById[instanceId] = save; - return save; -} - -InstanceSave* InstanceSaveManager::GetInstanceSave(uint32 InstanceId) -{ - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - return itr != m_instanceSaveById.end() ? itr->second : nullptr; -} - -void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid) -{ - CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_SCENARIO_INSTANCE_CRITERIA_FOR_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - CharacterDatabase.CommitTransaction(trans); - // Respawn times should be deleted only when the map gets unloaded -} - -void InstanceSaveManager::RemoveInstanceSave(uint32 InstanceId) -{ - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - if (itr != m_instanceSaveById.end()) - { - // save the resettime for normal instances only when they get unloaded - if (time_t resettime = itr->second->GetResetTimeForDB()) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_RESETTIME); - - stmt->setInt64(0, resettime); - stmt->setUInt32(1, InstanceId); - - CharacterDatabase.Execute(stmt); - } - - itr->second->SetToDelete(true); - m_instanceSaveById.erase(itr); - } -} - -void InstanceSaveManager::UnloadInstanceSave(uint32 InstanceId) -{ - if (InstanceSave* save = GetInstanceSave(InstanceId)) - save->UnloadIfEmpty(); -} - -InstanceSave::InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, uint32 entranceId, time_t resetTime, bool canReset) -: m_resetTime(resetTime), m_instanceid(InstanceId), m_mapid(MapId), - m_difficulty(difficulty), m_entranceId(entranceId), m_canReset(canReset), m_toDelete(false) { } - -InstanceSave::~InstanceSave() -{ - // the players and groups must be unbound before deleting the save - ASSERT(m_playerList.empty() && m_groupList.empty()); -} - -/* - Called from AddInstanceSave -*/ -void InstanceSave::SaveToDB() -{ - // save instance data too - std::string data; - uint32 completedEncounters = 0; - - Map* map = sMapMgr->FindMap(GetMapId(), m_instanceid); - if (map) - { - ASSERT(map->IsDungeon()); - if (InstanceScript* instanceScript = ((InstanceMap*)map)->GetInstanceScript()) - { - data = instanceScript->GetSaveData(); - completedEncounters = instanceScript->GetCompletedEncounterMask(); - m_entranceId = instanceScript->GetEntranceLocation(); - } - - if (InstanceScenario* scenario = map->ToInstanceMap()->GetInstanceScenario()) - scenario->SaveToDB(); - } - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_INSTANCE_SAVE); - stmt->setUInt32(0, m_instanceid); - stmt->setUInt16(1, GetMapId()); - stmt->setUInt64(2, uint64(GetResetTimeForDB())); - stmt->setUInt8(3, uint8(GetDifficultyID())); - stmt->setUInt32(4, completedEncounters); - stmt->setString(5, data); - stmt->setUInt32(6, m_entranceId); - CharacterDatabase.Execute(stmt); -} - -time_t InstanceSave::GetResetTimeForDB() -{ - // only save the reset time for normal instances - MapEntry const* entry = sMapStore.LookupEntry(GetMapId()); - if (!entry || entry->IsRaid() || GetDifficultyID() == DIFFICULTY_HEROIC) - return 0; - else - return GetResetTime(); -} - -MapEntry const* InstanceSave::GetMapEntry() -{ - return sMapStore.LookupEntry(m_mapid); -} - -void InstanceSave::DeleteFromDB() -{ - InstanceSaveManager::DeleteInstanceFromDB(GetInstanceId()); -} - -/* true if the instance save is still valid */ -bool InstanceSave::UnloadIfEmpty() -{ - if (m_playerList.empty() && m_groupList.empty()) - { - // don't remove the save if there are still players inside the map - if (Map* map = sMapMgr->FindMap(GetMapId(), GetInstanceId())) - if (map->HavePlayers()) - return true; - - if (!sInstanceSaveMgr->lock_instLists) - sInstanceSaveMgr->RemoveInstanceSave(GetInstanceId()); - - return false; - } - else - return true; -} - -void InstanceSaveManager::LoadInstances() -{ - uint32 oldMSTime = getMSTime(); - - // Delete expired instances (Instance related spawns are removed in the following cleanup queries) - CharacterDatabase.DirectExecute("DELETE i FROM instance i LEFT JOIN instance_reset ir ON mapid = map AND i.difficulty = ir.difficulty " - "WHERE (i.resettime > 0 AND i.resettime < UNIX_TIMESTAMP()) OR (ir.resettime IS NOT NULL AND ir.resettime < UNIX_TIMESTAMP())"); - - // Delete invalid character_instance and group_instance references - CharacterDatabase.DirectExecute("DELETE ci.* FROM character_instance AS ci LEFT JOIN characters AS c ON ci.guid = c.guid WHERE c.guid IS NULL"); - CharacterDatabase.DirectExecute("DELETE gi.* FROM group_instance AS gi LEFT JOIN `groups` AS g ON gi.guid = g.guid WHERE g.guid IS NULL"); - - // Delete invalid instance references - CharacterDatabase.DirectExecute("DELETE i.* FROM instance AS i LEFT JOIN character_instance AS ci ON i.id = ci.instance LEFT JOIN group_instance AS gi ON i.id = gi.instance WHERE ci.guid IS NULL AND gi.guid IS NULL"); - - // Delete invalid references to instance - CharacterDatabase.DirectExecute("DELETE FROM respawn WHERE instanceId > 0 AND instanceId NOT IN (SELECT id FROM instance)"); - CharacterDatabase.DirectExecute("DELETE tmp.* FROM character_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL"); - CharacterDatabase.DirectExecute("DELETE tmp.* FROM group_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL"); - - // Clean invalid references to instance - CharacterDatabase.DirectExecute("UPDATE corpse SET instanceId = 0 WHERE instanceId > 0 AND instanceId NOT IN (SELECT id FROM instance)"); - CharacterDatabase.DirectExecute("UPDATE characters AS tmp LEFT JOIN instance ON tmp.instance_id = instance.id SET tmp.instance_id = 0 WHERE tmp.instance_id > 0 AND instance.id IS NULL"); - - // Initialize instance id storage (Needs to be done after the trash has been clean out) - sMapMgr->InitInstanceIds(); - - // Load reset times and clean expired instances - sInstanceSaveMgr->LoadResetTimes(); - - TC_LOG_INFO("server.loading", ">> Loaded instances in %u ms", GetMSTimeDiffToNow(oldMSTime)); - -} - -void InstanceSaveManager::LoadResetTimes() -{ - time_t now = GameTime::GetGameTime(); - time_t today = (now / DAY) * DAY; - - // NOTE: Use DirectPExecute for tables that will be queried later - - // get the current reset times for normal instances (these may need to be updated) - // these are only kept in memory for InstanceSaves that are loaded later - // resettime = 0 in the DB for raid/heroic instances so those are skipped - typedef std::pair<uint32 /*PAIR32(map, difficulty)*/, time_t> ResetTimeMapDiffType; - typedef std::map<uint32, ResetTimeMapDiffType> InstResetTimeMapDiffType; - InstResetTimeMapDiffType instResetTime; - - // index instance ids by map/difficulty pairs for fast reset warning send - typedef std::multimap<uint32 /*PAIR32(map, difficulty)*/, uint32 /*instanceid*/ > ResetTimeMapDiffInstances; - typedef std::pair<ResetTimeMapDiffInstances::const_iterator, ResetTimeMapDiffInstances::const_iterator> ResetTimeMapDiffInstancesBounds; - ResetTimeMapDiffInstances mapDiffResetInstances; - - if (QueryResult result = CharacterDatabase.Query("SELECT id, map, difficulty, resettime FROM instance ORDER BY id ASC")) - { - do - { - Field* fields = result->Fetch(); - - uint32 instanceId = fields[0].GetUInt32(); - - // Mark instance id as being used - sMapMgr->RegisterInstanceId(instanceId); - - if (time_t resettime = time_t(fields[3].GetUInt64())) - { - uint32 mapid = fields[1].GetUInt16(); - uint32 difficulty = fields[2].GetUInt8(); - - instResetTime[instanceId] = ResetTimeMapDiffType(MAKE_PAIR32(mapid, difficulty), resettime); - mapDiffResetInstances.insert(ResetTimeMapDiffInstances::value_type(MAKE_PAIR32(mapid, difficulty), instanceId)); - } - } - while (result->NextRow()); - - // schedule the reset times - for (InstResetTimeMapDiffType::iterator itr = instResetTime.begin(); itr != instResetTime.end(); ++itr) - if (itr->second.second > now) - ScheduleReset(true, itr->second.second, InstResetEvent(0, PAIR32_LOPART(itr->second.first), Difficulty(PAIR32_HIPART(itr->second.first)), itr->first)); - } - - // load the global respawn times for raid/heroic instances - uint32 resetHour = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR); - if (QueryResult result = CharacterDatabase.Query("SELECT mapid, difficulty, resettime FROM instance_reset")) - { - do - { - Field* fields = result->Fetch(); - uint32 mapid = fields[0].GetUInt16(); - Difficulty difficulty = Difficulty(fields[1].GetUInt8()); - uint64 oldresettime = fields[2].GetUInt64(); - - MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mapid, difficulty); - if (!mapDiff) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::LoadResetTimes: invalid mapid(%u)/difficulty(%u) pair in instance_reset!", mapid, static_cast<uint32>(difficulty)); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - continue; - } - - // update the reset time if the hour in the configs changes - uint64 newresettime = GetLocalHourTimestamp(oldresettime, resetHour, false); - if (oldresettime != newresettime) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt64(0, uint64(newresettime)); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - } - - InitializeResetTimeFor(mapid, difficulty, newresettime); - } while (result->NextRow()); - } - - // calculate new global reset times for expired instances and those that have never been reset yet - // add the global reset times to the priority queue - for (auto& mapDifficultyPair : sDB2Manager.GetMapDifficulties()) - { - uint32 mapid = mapDifficultyPair.first; - - for (auto& difficultyPair : mapDifficultyPair.second) - { - Difficulty difficulty = Difficulty(difficultyPair.first); - MapDifficultyEntry const* mapDiff = difficultyPair.second; - if (!mapDiff->GetRaidDuration()) - continue; - - // the reset_delay must be at least one day - uint32 period = uint32(((mapDiff->GetRaidDuration() * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); - if (period < DAY) - period = DAY; - - time_t t = GetResetTimeFor(mapid, difficulty); - if (!t) - { - // initialize the reset time - t = GetLocalHourTimestamp(today + period, resetHour); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - stmt->setInt64(2, t); - CharacterDatabase.DirectExecute(stmt); - } - - if (t < now) - { - // assume that expired instances have already been cleaned - // calculate the next reset time - time_t day = (t / DAY) * DAY; - t = GetLocalHourTimestamp(day + ((today - day) / period + 1) * period, resetHour); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - stmt->setInt64(0, t); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - } - - InitializeResetTimeFor(mapid, difficulty, t); - - // schedule the global reset/warning - uint8 type; - for (type = 1; type < 4; ++type) - if (t - ResetTimeDelay[type - 1] > now) - break; - - ScheduleReset(true, t - ResetTimeDelay[type - 1], InstResetEvent(type, mapid, difficulty, 0)); - - ResetTimeMapDiffInstancesBounds range = mapDiffResetInstances.equal_range(MAKE_PAIR32(mapid, difficulty)); - for (; range.first != range.second; ++range.first) - ScheduleReset(true, t - ResetTimeDelay[type - 1], InstResetEvent(type, mapid, difficulty, range.first->second)); - } - } -} - -time_t InstanceSaveManager::GetSubsequentResetTime(uint32 mapid, Difficulty difficulty, time_t resetTime) const -{ - MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mapid, difficulty); - if (!mapDiff || !mapDiff->GetRaidDuration()) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::GetSubsequentResetTime: not valid difficulty or no reset delay for map %u", mapid); - return 0; - } - - time_t resetHour = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR); - time_t period = uint32(((mapDiff->GetRaidDuration() * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); - if (period < DAY) - period = DAY; - - return GetLocalHourTimestamp(((resetTime + MINUTE) / DAY * DAY) + period, resetHour); -} - -void InstanceSaveManager::SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) -{ - ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR64(mapid, d)); - ASSERT(itr != m_resetTimeByMapDifficulty.end()); - itr->second = t; -} - -void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event) -{ - if (!add) - { - // find the event in the queue and remove it - ResetTimeQueue::iterator itr; - std::pair<ResetTimeQueue::iterator, ResetTimeQueue::iterator> range; - range = m_resetTimeQueue.equal_range(time); - for (itr = range.first; itr != range.second; ++itr) - { - if (itr->second == event) - { - m_resetTimeQueue.erase(itr); - return; - } - } - - // in case the reset time changed (should happen very rarely), we search the whole queue - if (itr == range.second) - { - for (itr = m_resetTimeQueue.begin(); itr != m_resetTimeQueue.end(); ++itr) - { - if (itr->second == event) - { - m_resetTimeQueue.erase(itr); - return; - } - } - - if (itr == m_resetTimeQueue.end()) - TC_LOG_ERROR("misc", "InstanceSaveManager::ScheduleReset: cannot cancel the reset, the event(%d, %d, %d) was not found!", event.type, event.mapid, event.instanceId); - } - } - else - m_resetTimeQueue.insert(std::pair<time_t, InstResetEvent>(time, event)); -} - -void InstanceSaveManager::ForceGlobalReset(uint32 mapId, Difficulty difficulty) -{ - if (!sDB2Manager.GetDownscaledMapDifficultyData(mapId, difficulty)) - return; - // remove currently scheduled reset times - ScheduleReset(false, 0, InstResetEvent(1, mapId, difficulty, 0)); - ScheduleReset(false, 0, InstResetEvent(4, mapId, difficulty, 0)); - // force global reset on the instance - _ResetOrWarnAll(mapId, difficulty, false, GameTime::GetGameTime()); -} - -void InstanceSaveManager::Update() -{ - time_t now = GameTime::GetGameTime(); - time_t t; - - while (!m_resetTimeQueue.empty()) - { - t = m_resetTimeQueue.begin()->first; - if (t >= now) - break; - - InstResetEvent &event = m_resetTimeQueue.begin()->second; - if (event.type == 0) - { - // for individual normal instances, max creature respawn + X hours - _ResetInstance(event.mapid, event.instanceId); - m_resetTimeQueue.erase(m_resetTimeQueue.begin()); - } - else - { - // global reset/warning for a certain map - time_t resetTime = GetResetTimeFor(event.mapid, event.difficulty); - _ResetOrWarnAll(event.mapid, event.difficulty, event.type != 4, resetTime); - if (event.type != 4) - { - // schedule the next warning/reset - ++event.type; - ScheduleReset(true, resetTime - ResetTimeDelay[event.type-1], event); - } - m_resetTimeQueue.erase(m_resetTimeQueue.begin()); - } - } -} - -void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator &itr) -{ - // unbind all players bound to the instance - // do not allow UnbindInstance to automatically unload the InstanceSaves - lock_instLists = true; - - bool shouldDelete = true; - InstanceSave::PlayerListType &pList = itr->second->m_playerList; - std::vector<Player*> temp; // list of expired binds that should be unbound - for (Player* player : pList) - { - if (InstancePlayerBind* bind = player->GetBoundInstance(itr->second->GetMapId(), itr->second->GetDifficultyID())) - { - ASSERT(bind->save == itr->second); - if (bind->perm && bind->extendState) // permanent and not already expired - { - // actual promotion in DB already happened in caller - bind->extendState = bind->extendState == EXTEND_STATE_EXTENDED ? EXTEND_STATE_NORMAL : EXTEND_STATE_EXPIRED; - shouldDelete = false; - continue; - } - } - temp.push_back(player); - } - for (Player* player : temp) - { - player->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficultyID(), true); - } - - InstanceSave::GroupListType &gList = itr->second->m_groupList; - while (!gList.empty()) - { - Group* group = *(gList.begin()); - group->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficultyID(), true); - } - - if (shouldDelete) - { - delete itr->second; - itr = m_instanceSaveById.erase(itr); - } - else - ++itr; - - lock_instLists = false; -} - -void InstanceSaveManager::_ResetInstance(uint32 mapid, uint32 instanceId) -{ - TC_LOG_DEBUG("maps", "InstanceSaveMgr::_ResetInstance %u, %u", mapid, instanceId); - MapEntry const* map = sMapStore.LookupEntry(mapid); - if (!map->IsDungeon()) - return; - - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(instanceId); - if (itr != m_instanceSaveById.end()) - _ResetSave(itr); - - DeleteInstanceFromDB(instanceId); // even if save not loaded - - Map* iMap = sMapMgr->FindMap(mapid, instanceId); - if (iMap) - { - ((InstanceMap*)iMap)->Reset(INSTANCE_RESET_RESPAWN_DELAY); - iMap->DeleteRespawnTimes(); - iMap->DeleteCorpseData(); - } - else - Map::DeleteRespawnTimesInDB(mapid, instanceId); - - // Free up the instance id and allow it to be reused - sMapMgr->FreeInstanceId(instanceId); -} - -void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime) -{ - // global reset for all instances of the given map - MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); - if (!mapEntry->Instanceable()) - return; - TC_LOG_DEBUG("misc", "InstanceSaveManager::ResetOrWarnAll: Processing map %s (%u) on difficulty %u (warn? %u)", mapEntry->MapName[sWorld->GetDefaultDbcLocale()], mapid, static_cast<uint32>(difficulty), warn); - - time_t now = GameTime::GetGameTime(); - - if (!warn) - { - // calculate the next reset time - time_t next_reset = GetSubsequentResetTime(mapid, difficulty, resetTime); - if (!next_reset) - return; - - // delete/promote instance binds from the DB, even if not loaded - CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_CHAR_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EXPIRE_CHAR_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - CharacterDatabase.CommitTransaction(trans); - - // promote loaded binds to instances of the given map - for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end();) - { - if (itr->second->GetMapId() == mapid && itr->second->GetDifficultyID() == difficulty) - _ResetSave(itr); - else - ++itr; - } - - SetResetTimeFor(mapid, difficulty, next_reset); - ScheduleReset(true, time_t(next_reset-3600), InstResetEvent(1, mapid, difficulty, 0)); - - // Update it in the DB - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - - stmt->setUInt64(0, uint64(next_reset)); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - - CharacterDatabase.Execute(stmt); - } - - // note: this isn't fast but it's meant to be executed very rarely - if (mapEntry->IsDungeon()) - { - sMapMgr->DoForAllMapsWithMapId(mapid, [=](Map* map) - { - if (warn) - { - uint32 timeLeft; - if (now >= resetTime) - timeLeft = 0; - else - timeLeft = uint32(resetTime - now); - - ((InstanceMap*)map)->SendResetWarnings(timeLeft); - } - else - ((InstanceMap*)map)->Reset(INSTANCE_RESET_GLOBAL); - }); - } - - /// @todo delete creature/gameobject respawn times even if the maps are not loaded -} - -uint32 InstanceSaveManager::GetNumBoundPlayersTotal() const -{ - uint32 ret = 0; - for (InstanceSaveHashMap::const_iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - ret += itr->second->GetPlayerCount(); - - return ret; -} - -uint32 InstanceSaveManager::GetNumBoundGroupsTotal() const -{ - uint32 ret = 0; - for (InstanceSaveHashMap::const_iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - ret += itr->second->GetGroupCount(); - - return ret; -} diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h deleted file mode 100644 index 6b5ac5c562f..00000000000 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ /dev/null @@ -1,245 +0,0 @@ -/* - * 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/>. - */ - -#ifndef _INSTANCESAVEMGR_H -#define _INSTANCESAVEMGR_H - -#include <list> -#include <map> -#include <mutex> -#include <unordered_map> - -#include "Define.h" -#include "DBCEnums.h" -#include "ObjectDefines.h" - -struct InstanceTemplate; -struct MapEntry; -class Player; -class Group; - -/* - Holds the information necessary for creating a new map for an existing instance - Is referenced in three cases: - - player-instance binds for solo players (not in group) - - player-instance binds for permanent heroic/raid saves - - group-instance binds (both solo and permanent) cache the player binds for the group leader -*/ -class TC_GAME_API InstanceSave -{ - friend class InstanceSaveManager; - public: - /* Created either when: - - any new instance is being generated - - the first time a player bound to InstanceId logs in - - when a group bound to the instance is loaded */ - InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, uint32 entranceId, time_t resetTime, bool canReset); - - /* Unloaded when m_playerList and m_groupList become empty - or when the instance is reset */ - ~InstanceSave(); - - InstanceSave(InstanceSave const& right) = delete; - InstanceSave(InstanceSave&& right) = delete; - InstanceSave& operator=(InstanceSave const& right) = delete; - InstanceSave& operator=(InstanceSave&& right) = delete; - - uint32 GetPlayerCount() const { return uint32(m_playerList.size()); } - uint32 GetGroupCount() const { return uint32(m_groupList.size()); } - - /* A map corresponding to the InstanceId/MapId does not always exist. - InstanceSave objects may be created on player logon but the maps are - created and loaded only when a player actually enters the instance. */ - uint32 GetInstanceId() const { return m_instanceid; } - uint32 GetMapId() const { return m_mapid; } - - /* Saved when the instance is generated for the first time */ - void SaveToDB(); - /* When the instance is being reset (permanently deleted) */ - void DeleteFromDB(); - - /* for normal instances this corresponds to max(creature respawn time) + X hours - for raid/heroic instances this caches the global respawn time for the map */ - time_t GetResetTime() const { return m_resetTime; } - void SetResetTime(time_t resetTime) { m_resetTime = resetTime; } - time_t GetResetTimeForDB(); - - uint32 GetEntranceLocation() const { return m_entranceId; } - void SetEntranceLocation(uint32 entranceId) { m_entranceId = entranceId; } - - MapEntry const* GetMapEntry(); - - /* online players bound to the instance (perm/solo) - does not include the members of the group unless they have permanent saves */ - void AddPlayer(Player* player) - { - std::lock_guard<std::mutex> lock(_playerListLock); - m_playerList.push_back(player); - } - - bool RemovePlayer(Player* player) - { - _playerListLock.lock(); - m_playerList.remove(player); - bool isStillValid = UnloadIfEmpty(); - _playerListLock.unlock(); - - //delete here if needed, after releasing the lock - if (m_toDelete) - delete this; - - return isStillValid; - } - /* all groups bound to the instance */ - void AddGroup(Group* group) { m_groupList.push_back(group); } - bool RemoveGroup(Group* group) - { - m_groupList.remove(group); - bool isStillValid = UnloadIfEmpty(); - if (m_toDelete) - delete this; - return isStillValid; - } - - /* instances cannot be reset (except at the global reset time) - if there are players permanently bound to it - this is cached for the case when those players are offline */ - bool CanReset() const { return m_canReset; } - void SetCanReset(bool canReset) { m_canReset = canReset; } - - /* currently it is possible to omit this information from this structure - but that would depend on a lot of things that can easily change in future */ - Difficulty GetDifficultyID() const { return m_difficulty; } - - /* used to flag the InstanceSave as to be deleted, so the caller can delete it */ - void SetToDelete(bool toDelete) - { - m_toDelete = toDelete; - } - - typedef std::list<Player*> PlayerListType; - typedef std::list<Group*> GroupListType; - private: - bool UnloadIfEmpty(); - /* the only reason the instSave-object links are kept is because - the object-instSave links need to be broken at reset time */ - /// @todo: Check if maybe it's enough to just store the number of players/groups - PlayerListType m_playerList; - GroupListType m_groupList; - time_t m_resetTime; - uint32 m_instanceid; - uint32 m_mapid; - Difficulty m_difficulty; - uint32 m_entranceId; - bool m_canReset; - bool m_toDelete; - - std::mutex _playerListLock; -}; - -typedef std::unordered_map<uint64 /*PAIR64(map, difficulty)*/, time_t /*resetTime*/> ResetTimeByMapDifficultyMap; - -class TC_GAME_API InstanceSaveManager -{ - friend class InstanceSave; - - private: - InstanceSaveManager() : lock_instLists(false) { }; - ~InstanceSaveManager(); - - public: - typedef std::unordered_map<uint32 /*InstanceId*/, InstanceSave*> InstanceSaveHashMap; - - static InstanceSaveManager* instance(); - - void Unload(); - - /* resetTime is a global propery of each (raid/heroic) map - all instances of that map reset at the same time */ - struct InstResetEvent - { - uint8 type; - Difficulty difficulty:8; - uint32 mapid; - uint32 instanceId; - - InstResetEvent() : type(0), difficulty(DIFFICULTY_NORMAL), mapid(0), instanceId(0) { } - InstResetEvent(uint8 t, uint32 _mapid, Difficulty d, uint32 _instanceid) - : type(t), difficulty(d), mapid(_mapid), instanceId(_instanceid) { } - bool operator==(InstResetEvent const& e) const { return e.instanceId == instanceId; } - }; - typedef std::multimap<time_t /*resetTime*/, InstResetEvent> ResetTimeQueue; - - void LoadInstances(); - - void LoadResetTimes(); - time_t GetResetTimeFor(uint32 mapid, Difficulty d) const - { - ResetTimeByMapDifficultyMap::const_iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR64(mapid, d)); - return itr != m_resetTimeByMapDifficulty.end() ? itr->second : 0; - } - time_t GetSubsequentResetTime(uint32 mapid, Difficulty difficulty, time_t resetTime) const; - - // Use this on startup when initializing reset times - void InitializeResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - m_resetTimeByMapDifficulty[MAKE_PAIR64(mapid, d)] = t; - } - - // Use this only when updating existing reset times - void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t); - - ResetTimeByMapDifficultyMap const& GetResetTimeMap() const - { - return m_resetTimeByMapDifficulty; - } - void ScheduleReset(bool add, time_t time, InstResetEvent event); - void ForceGlobalReset(uint32 mapId, Difficulty difficulty); - - void Update(); - - InstanceSave* AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, time_t resetTime, uint32 entranceId, - bool canReset, bool load = false); - void RemoveInstanceSave(uint32 InstanceId); - void UnloadInstanceSave(uint32 InstanceId); - static void DeleteInstanceFromDB(uint32 instanceid); - - InstanceSave* GetInstanceSave(uint32 InstanceId); - - /* statistics */ - uint32 GetNumInstanceSaves() const { return uint32(m_instanceSaveById.size()); } - uint32 GetNumBoundPlayersTotal() const; - uint32 GetNumBoundGroupsTotal() const; - - protected: - static uint16 ResetTimeDelay[]; - - private: - void _ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime); - void _ResetInstance(uint32 mapid, uint32 instanceId); - void _ResetSave(InstanceSaveHashMap::iterator &itr); - // used during global instance resets - bool lock_instLists; - // fast lookup by instance id - InstanceSaveHashMap m_instanceSaveById; - // fast lookup for reset times (always use existed functions for access/set) - ResetTimeByMapDifficultyMap m_resetTimeByMapDifficulty; - ResetTimeQueue m_resetTimeQueue; -}; - -#define sInstanceSaveMgr InstanceSaveManager::instance() -#endif diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index 358ce8d60c0..159eb82b89e 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -451,7 +451,7 @@ bool InstanceScript::SetBossState(uint32 id, EncounterState state) bossInfo->state = state; SaveToDB(); - if (state == DONE) + if (state == DONE && dungeonEncounter) instance->UpdateInstanceLock(dungeonEncounter, { id, state }); } @@ -779,11 +779,20 @@ bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player con return false; } +bool InstanceScript::IsEncounterCompleted(uint32 dungeonEncounterId) const +{ + for (std::size_t i = 0; i < bosses.size(); ++i) + for (std::size_t j = 0; j < bosses[i].DungeonEncounters.size(); ++j) + if (bosses[i].DungeonEncounters[j] && bosses[i].DungeonEncounters[j]->ID == dungeonEncounterId) + return bosses[i].state == DONE; + + return false; +} + void InstanceScript::SetEntranceLocation(uint32 worldSafeLocationId) { _entranceId = worldSafeLocationId; - if (_temporaryEntranceId) - _temporaryEntranceId = 0; + _temporaryEntranceId = 0; } void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= nullptr*/, uint8 priority) diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index 8e34702361b..77c8886628d 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -273,6 +273,8 @@ class TC_GAME_API InstanceScript : public ZoneScript // Returns completed encounters mask for packets uint32 GetCompletedEncounterMask() const { return completedEncounters; } + bool IsEncounterCompleted(uint32 dungeonEncounterId) const; + uint32 GetEncounterCount() const { return uint32(bosses.size()); } // Sets the entrance location (WorldSafeLoc) id |