diff options
Diffstat (limited to 'src')
128 files changed, 1133 insertions, 817 deletions
diff --git a/src/common/Cryptography/TOTP.cpp b/src/common/Cryptography/TOTP.cpp index d1f66b99d5..937285bc97 100644 --- a/src/common/Cryptography/TOTP.cpp +++ b/src/common/Cryptography/TOTP.cpp @@ -1,9 +1,22 @@ /* - * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3 - * Copyright (C) 2021+ WarheadCore <https://github.com/WarheadCore> + * This file is part of the AzerothCore 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 Affero General Public License as published by the + * Free Software Foundation; either version 3 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 Affero 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 "TOTP.h" +#include "Timer.h" #include <openssl/evp.h> #include <openssl/hmac.h> @@ -34,7 +47,7 @@ static constexpr uint32 HMAC_RESULT_SIZE = 20; /*static*/ bool Acore::Crypto::TOTP::ValidateToken(Secret const& secret, uint32 token) { - time_t now = time(nullptr); + time_t now = GetEpochTime().count(); return ( (token == GenerateToken(secret, now - TOTP_INTERVAL)) || (token == GenerateToken(secret, now)) || diff --git a/src/common/Logging/AppenderFile.cpp b/src/common/Logging/AppenderFile.cpp index 493f9ff9c5..280b5e8bd5 100644 --- a/src/common/Logging/AppenderFile.cpp +++ b/src/common/Logging/AppenderFile.cpp @@ -19,7 +19,7 @@ #include "Log.h" #include "LogMessage.h" #include "StringConvert.h" -#include "Util.h" +#include "Timer.h" #include <algorithm> AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector<std::string_view> const& args) : @@ -127,7 +127,7 @@ FILE* AppenderFile::OpenFile(std::string const& filename, std::string const& mod CloseFile(); std::string newName(fullName); newName.push_back('.'); - newName.append(LogMessage::getTimeStr(time(nullptr))); + newName.append(LogMessage::getTimeStr(GetEpochTime())); std::replace(newName.begin(), newName.end(), ':', '-'); rename(fullName.c_str(), newName.c_str()); // no error handling... if we couldn't make a backup, just ignore } diff --git a/src/common/Logging/LogMessage.cpp b/src/common/Logging/LogMessage.cpp index 28f8e82ba5..56b6cb4750 100644 --- a/src/common/Logging/LogMessage.cpp +++ b/src/common/Logging/LogMessage.cpp @@ -20,18 +20,18 @@ #include "Timer.h" LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) - : level(_level), type(_type), text(std::forward<std::string>(_text)), mtime(time(nullptr)) + : level(_level), type(_type), text(std::forward<std::string>(_text)), mtime(GetEpochTime()) { } LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text, std::string&& _param1) - : level(_level), type(_type), text(std::forward<std::string>(_text)), param1(std::forward<std::string>(_param1)), mtime(time(nullptr)) + : level(_level), type(_type), text(std::forward<std::string>(_text)), param1(std::forward<std::string>(_param1)), mtime(GetEpochTime()) { } -std::string LogMessage::getTimeStr(time_t time) +std::string LogMessage::getTimeStr(Seconds time) { - return Acore::Time::TimeToTimestampStr(Seconds(time), "%Y-%m-%d %X"); + return Acore::Time::TimeToTimestampStr(time, "%Y-%m-%d %X"); } std::string LogMessage::getTimeStr() const diff --git a/src/common/Logging/LogMessage.h b/src/common/Logging/LogMessage.h index 55fe027039..11bbba53d8 100644 --- a/src/common/Logging/LogMessage.h +++ b/src/common/Logging/LogMessage.h @@ -19,8 +19,8 @@ #define LogMessage_h__ #include "Define.h" +#include "Duration.h" #include "LogCommon.h" -#include <ctime> #include <string> struct LogMessage @@ -31,7 +31,7 @@ struct LogMessage LogMessage(LogMessage const& /*other*/) = delete; LogMessage& operator=(LogMessage const& /*other*/) = delete; - static std::string getTimeStr(time_t time); + static std::string getTimeStr(Seconds time); std::string getTimeStr() const; LogLevel const level; @@ -39,7 +39,7 @@ struct LogMessage std::string const text; std::string prefix; std::string param1; - time_t mtime; + Seconds mtime; ///@ Returns size of the log message content in bytes uint32 Size() const diff --git a/src/common/Utilities/SFMTRand.cpp b/src/common/Utilities/SFMTRand.cpp index 21147145b2..fccd41aab8 100644 --- a/src/common/Utilities/SFMTRand.cpp +++ b/src/common/Utilities/SFMTRand.cpp @@ -16,8 +16,8 @@ */ #include "SFMTRand.h" +#include "Timer.h" #include <array> -#include <ctime> #include <functional> #include <random> @@ -69,7 +69,7 @@ SFMTRand::SFMTRand() } else { - sfmt_init_gen_rand(&_state, uint32(time(nullptr))); + sfmt_init_gen_rand(&_state, uint32(GetEpochTime().count())); } } diff --git a/src/common/Utilities/Timer.h b/src/common/Utilities/Timer.h index 5e2d190599..505b238276 100644 --- a/src/common/Utilities/Timer.h +++ b/src/common/Utilities/Timer.h @@ -76,7 +76,7 @@ inline TimePoint GetApplicationStartTime() { using namespace std::chrono; - static const steady_clock::time_point ApplicationStartTime = steady_clock::now(); + static const TimePoint ApplicationStartTime = steady_clock::now(); return ApplicationStartTime; } diff --git a/src/server/database/Logging/AppenderDB.cpp b/src/server/database/Logging/AppenderDB.cpp index d227416ac8..1bf9f08296 100644 --- a/src/server/database/Logging/AppenderDB.cpp +++ b/src/server/database/Logging/AppenderDB.cpp @@ -32,7 +32,7 @@ void AppenderDB::_write(LogMessage const* message) return; LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_LOG); - stmt->setUInt64(0, message->mtime); + stmt->setUInt64(0, message->mtime.count()); stmt->setUInt32(1, realmId); stmt->setString(2, message->type); stmt->setUInt8(3, uint8(message->level)); diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index bfad7890d4..325b35ea35 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -18,6 +18,7 @@ #include "ScriptedCreature.h" #include "Cell.h" #include "CellImpl.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "ObjectMgr.h" @@ -493,9 +494,10 @@ bool ScriptedAI::EnterEvadeIfOutOfCombatArea() if (me->IsInEvadeMode() || !me->IsInCombat()) return false; - if (_evadeCheckCooldown == time(nullptr)) + if (_evadeCheckCooldown == GameTime::GetGameTime().count()) return false; - _evadeCheckCooldown = time(nullptr); + + _evadeCheckCooldown = GameTime::GetGameTime().count(); if (!CheckEvadeIfOutOfCombatArea()) return false; diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index 469344f04e..cd57be9d66 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -29,6 +29,7 @@ #include "DatabaseEnv.h" #include "DisableMgr.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Guild.h" #include "GuildMgr.h" @@ -423,7 +424,7 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un birthday_tm.tm_year += birthday_login.nth_birthday; time_t birthday = mktime(&birthday_tm); - time_t now = sWorld->GetGameTime(); + time_t now = GameTime::GetGameTime().count(); return now <= birthday + DAY && now >= birthday; } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE: @@ -648,7 +649,7 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, PreparedQ continue; } - if (criteria->timeLimit && time_t(date + criteria->timeLimit) < time(nullptr)) + if (criteria->timeLimit && time_t(date + criteria->timeLimit) < GameTime::GetGameTime().count()) continue; CriteriaProgress& progress = m_criteriaProgress[id]; @@ -726,7 +727,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8 + 4 + 8); data << GetPlayer()->GetPackGUID(); data << uint32(achievement->ID); - data.AppendPackedTime(time(nullptr)); + data.AppendPackedTime(GameTime::GetGameTime().count()); data << uint32(0); GetPlayer()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true); } @@ -1002,13 +1003,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: { - time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); + Seconds nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); CriteriaProgress* progress = GetCriteriaProgress(achievementCriteria); if (!miscValue1) // Login case. { // reset if player missed one day. - if (progress && progress->date < (nextDailyResetTime - 2 * DAY)) + if (progress && Seconds(progress->date) < (nextDailyResetTime - 2_days)) SetCriteriaProgress(achievementCriteria, 0, PROGRESS_SET); continue; } @@ -1017,10 +1018,10 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui if (!progress) // 1st time. Start count. progressType = PROGRESS_SET; - else if (progress->date < (nextDailyResetTime - 2 * DAY)) + else if (Seconds(progress->date) < (nextDailyResetTime - 2_days)) // last progress is older than 2 days. Player missed 1 day => Retart count. progressType = PROGRESS_RESET; - else if (progress->date < (nextDailyResetTime - DAY)) + else if (Seconds(progress->date) < (nextDailyResetTime - 1_days)) // last progress is between 1 and 2 days. => 1st time of the day. progressType = PROGRESS_ACCUMULATE; else @@ -2075,7 +2076,7 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry, } progress->changed = true; - progress->date = time(nullptr); // set the date to the latest update. + progress->date = GameTime::GetGameTime().count(); // set the date to the latest update. uint32 timeElapsed = 0; bool timedCompleted = false; @@ -2198,7 +2199,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) SendAchievementEarned(achievement); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; - ca.date = time(nullptr); + ca.date = GameTime::GetGameTime().count(); ca.changed = true; sScriptMgr->OnAchievementComplete(GetPlayer(), achievement); @@ -2419,20 +2420,20 @@ bool AchievementGlobalMgr::IsRealmCompleted(AchievementEntry const* achievement) if (itr == m_allCompletedAchievements.end()) return false; - if (itr->second == std::chrono::system_clock::time_point::min()) + if (itr->second == SystemTimePoint::min()) return false; if (!sScriptMgr->IsRealmCompleted(this, achievement, itr->second)) return false; - if (itr->second == std::chrono::system_clock::time_point::max()) + if (itr->second == SystemTimePoint::max()) return true; // Allow completing the realm first kill for entire minute after first person did it // it may allow more than one group to achieve it (highly unlikely) // but apparently this is how blizz handles it as well if (achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL) - return (std::chrono::system_clock::now() - itr->second) > std::chrono::minutes(1); + return (GameTime::GetSystemTime() - itr->second) > 1min; sScriptMgr->SetRealmCompleted(achievement); @@ -2444,7 +2445,7 @@ void AchievementGlobalMgr::SetRealmCompleted(AchievementEntry const* achievement if (IsRealmCompleted(achievement)) return; - m_allCompletedAchievements[achievement->ID] = std::chrono::system_clock::now(); + m_allCompletedAchievements[achievement->ID] = GameTime::GetSystemTime(); } //========================================================== @@ -2771,7 +2772,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() for (uint32 i = 0; i < sAchievementStore.GetNumRows(); ++i) if (AchievementEntry const* achievement = sAchievementStore.LookupEntry(i)) if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) - m_allCompletedAchievements[achievement->ID] = std::chrono::system_clock::time_point::min(); + m_allCompletedAchievements[achievement->ID] = SystemTimePoint::min(); if (!result) { @@ -2799,7 +2800,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() continue; } else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) - m_allCompletedAchievements[achievementId] = std::chrono::system_clock::time_point::max(); + m_allCompletedAchievements[achievementId] = SystemTimePoint::max(); } while (result->NextRow()); LOG_INFO("server.loading", ">> Loaded %lu completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime)); diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index 8cd66c66d8..f385078a91 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -400,7 +400,7 @@ private: // store achievements by referenced achievement id to speed up lookup AchievementListByReferencedId m_AchievementListByReferencedId; - typedef std::unordered_map<uint32 /*achievementId*/, std::chrono::system_clock::time_point /*completionTime*/> AllCompletedAchievements; + typedef std::unordered_map<uint32 /*achievementId*/, SystemTimePoint /*completionTime*/> AllCompletedAchievements; AllCompletedAchievements m_allCompletedAchievements; AchievementRewards m_achievementRewards; diff --git a/src/server/game/Addons/AddonMgr.cpp b/src/server/game/Addons/AddonMgr.cpp index c24933cd13..a5267a886e 100644 --- a/src/server/game/Addons/AddonMgr.cpp +++ b/src/server/game/Addons/AddonMgr.cpp @@ -19,13 +19,11 @@ #include "DatabaseEnv.h" #include "Log.h" #include "Timer.h" - #include <list> #include <openssl/md5.h> namespace AddonMgr { - // Anonymous namespace ensures file scope of all the stuff inside it, even // if you add something more to this namespace somewhere else. namespace diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index 0f79d2fdca..fb924202f1 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -18,15 +18,16 @@ #include "AuctionHouseMgr.h" #include "AccountMgr.h" #include "AsyncAuctionListing.h" -#include "AvgDiffTracker.h" #include "Common.h" #include "DBCStores.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Item.h" #include "Logging/Log.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" +#include "UpdateTime.h" #include "World.h" #include "WorldPacket.h" #include <vector> @@ -345,7 +346,7 @@ void AuctionHouseMgr::SendAuctionSalePendingMail(AuctionEntry* auction, Characte uint32 deliveryDelay = sWorld->getIntConfig(CONFIG_MAIL_DELIVERY_DELAY); ByteBuffer timePacker; - timePacker.AppendPackedTime(time_t(time(nullptr) + deliveryDelay)); + timePacker.AppendPackedTime(GameTime::GetGameTime().count() + time_t(deliveryDelay)); if (sendMail) // can be changed in the hook MailDraft(auction->BuildAuctionMailSubject(AUCTION_SALE_PENDING), @@ -650,7 +651,7 @@ bool AuctionHouseObject::RemoveAuction(AuctionEntry* auction) void AuctionHouseObject::Update() { - time_t checkTime = sWorld->GetGameTime() + 60; + time_t checkTime = GameTime::GetGameTime().count() + 60; ///- Handle expired auctions // If storage is empty, no need to update. next == nullptr in this case. @@ -743,7 +744,7 @@ bool AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player } else { - time_t curTime = sWorld->GetGameTime(); + auto curTime = GameTime::GetGameTime(); int loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); int locdbc_idx = player->GetSession()->GetSessionDbcLocale(); @@ -754,7 +755,7 @@ bool AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player { if ((itrcounter++) % 100 == 0) // check condition every 100 iterations { - if (avgDiffTracker.getAverage() >= 30 || getMSTimeDiff(World::GetGameTimeMS(), getMSTime()) >= 10) // pussywizard: stop immediately if diff is high or waiting too long + if (sWorldUpdateTime.GetAverageUpdateTime() >= 30 || GetMSTimeDiff(GameTime::GetGameTimeMS(), GetTimeMS()) >= 10ms) // pussywizard: stop immediately if diff is high or waiting too long { return false; } @@ -763,7 +764,7 @@ bool AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player AuctionEntry* Aentry = itr->second; // Skip expired auctions - if (Aentry->expire_time < curTime) + if (Aentry->expire_time < curTime.count()) { continue; } @@ -948,7 +949,7 @@ bool AuctionEntry::BuildAuctionInfo(WorldPacket& data) const data << uint32(bid ? GetAuctionOutBid() : 0); // Minimal outbid data << uint32(buyout); // Auction->buyout - data << uint32((expire_time - time(nullptr)) * IN_MILLISECONDS); // time left + data << uint32((expire_time - GameTime::GetGameTime().count()) * IN_MILLISECONDS); // time left data << bidder; // auction->bidder current data << uint32(bid); // current bid return true; diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index aacc39bbc2..211c3dfcb0 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -20,6 +20,7 @@ #include "CellImpl.h" #include "CreatureTextMgr.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" @@ -86,7 +87,7 @@ void Battlefield::HandlePlayerEnterZone(Player* player, uint32 /*zone*/) else // No more vacant places { // TODO: Send a packet to announce it to player - m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + (player->IsGameMaster() ? 30 * MINUTE : 10); + m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = GameTime::GetGameTime().count() + (player->IsGameMaster() ? 30 * MINUTE : 10); InvitePlayerToQueue(player); } } @@ -176,7 +177,7 @@ bool Battlefield::Update(uint32 diff) // Kick players who chose not to accept invitation to the battle if (m_uiKickDontAcceptTimer <= diff) { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); for (int team = 0; team < 2; team++) for (PlayerTimerMap::iterator itr = m_InvitedPlayers[team].begin(); itr != m_InvitedPlayers[team].end(); ++itr) if (itr->second <= now) @@ -261,7 +262,7 @@ void Battlefield::InvitePlayersInZoneToWar() if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer) InvitePlayerToWar(player); else if (m_PlayersWillBeKick[player->GetTeamId()].count(player->GetGUID()) == 0)// Battlefield is full of players - m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10; + m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = GameTime::GetGameTime().count() + 10; } } } @@ -285,7 +286,7 @@ void Battlefield::InvitePlayerToWar(Player* player) if (player->getLevel() < m_MinLevel) { if (m_PlayersWillBeKick[player->GetTeamId()].count(player->GetGUID()) == 0) - m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10; + m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = GameTime::GetGameTime().count() + 10; return; } @@ -294,7 +295,7 @@ void Battlefield::InvitePlayerToWar(Player* player) return; m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID()); - m_InvitedPlayers[player->GetTeamId()][player->GetGUID()] = time(nullptr) + m_TimeForAcceptInvite; + m_InvitedPlayers[player->GetTeamId()][player->GetGUID()] = GameTime::GetGameTime().count() + m_TimeForAcceptInvite; player->GetSession()->SendBfInvitePlayerToWar(m_BattleId, m_ZoneId, m_TimeForAcceptInvite); } diff --git a/src/server/game/Battlefield/BattlefieldHandler.cpp b/src/server/game/Battlefield/BattlefieldHandler.cpp index 6108e3ab47..5fcbd2b2b8 100644 --- a/src/server/game/Battlefield/BattlefieldHandler.cpp +++ b/src/server/game/Battlefield/BattlefieldHandler.cpp @@ -17,6 +17,7 @@ #include "Battlefield.h" #include "BattlefieldMgr.h" +#include "GameTime.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" @@ -33,7 +34,7 @@ void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint3 WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 12); data << uint32(BattleId); data << uint32(ZoneId); - data << uint32((time(nullptr) + p_time)); + data << uint32((GameTime::GetGameTime().count() + p_time)); //Sending the packet to player SendPacket(&data); diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp index 08939dab59..c13bb08045 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp @@ -20,6 +20,7 @@ // TODO: Add proper implement of achievement #include "BattlefieldWG.h" +#include "GameTime.h" #include "MapMgr.h" #include "Opcodes.h" #include "Player.h" @@ -76,8 +77,9 @@ bool BattlefieldWG::SetupBattlefield() SetGraveyardNumber(BATTLEFIELD_WG_GRAVEYARD_MAX); // Load from db - if ((sWorld->getWorldState(BATTLEFIELD_WG_WORLD_STATE_ACTIVE) == 0) && (sWorld->getWorldState(BATTLEFIELD_WG_WORLD_STATE_DEFENDER) == 0) - && (sWorld->getWorldState(ClockWorldState[0]) == 0)) + if (!sWorld->getWorldState(BATTLEFIELD_WG_WORLD_STATE_ACTIVE) && + !sWorld->getWorldState(BATTLEFIELD_WG_WORLD_STATE_DEFENDER) && + !sWorld->getWorldState(ClockWorldState[0])) { sWorld->setWorldState(BATTLEFIELD_WG_WORLD_STATE_ACTIVE, uint64(false)); sWorld->setWorldState(BATTLEFIELD_WG_WORLD_STATE_DEFENDER, uint64(urand(0, 1))); @@ -889,7 +891,7 @@ void BattlefieldWG::FillInitialWorldStates(WorldPacket& data) data << uint32(BATTLEFIELD_WG_WORLD_STATE_SHOW_WORLDSTATE) << uint32(IsWarTime() ? 1 : 0); for (uint32 i = 0; i < 2; ++i) - data << ClockWorldState[i] << uint32(time(nullptr) + (m_Timer / 1000)); + data << ClockWorldState[i] << uint32(GameTime::GetGameTime().count() + (m_Timer / 1000)); data << uint32(BATTLEFIELD_WG_WORLD_STATE_VEHICLE_H) << uint32(GetData(BATTLEFIELD_WG_DATA_VEHICLE_H)); data << uint32(BATTLEFIELD_WG_WORLD_STATE_MAX_VEHICLE_H) << GetData(BATTLEFIELD_WG_DATA_MAX_VEHICLE_H); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 496dc3bed2..c03be4c81d 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -36,6 +36,7 @@ #include "Formulas.h" #include "GameEventMgr.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "Map.h" #include "MapMgr.h" #include "ObjectMgr.h" @@ -138,11 +139,11 @@ void BattlegroundMgr::Update(uint32 diff) { if (m_AutoDistributionTimeChecker < diff) { - if (time(nullptr) > m_NextAutoDistributionTime) + if (GameTime::GetGameTime() > m_NextAutoDistributionTime) { sArenaTeamMgr->DistributeArenaPoints(); - m_NextAutoDistributionTime = m_NextAutoDistributionTime + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld->getIntConfig(CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS); - sWorld->setWorldState(WS_ARENA_DISTRIBUTION_TIME, uint64(m_NextAutoDistributionTime)); + m_NextAutoDistributionTime = m_NextAutoDistributionTime + 1_days * sWorld->getIntConfig(CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS); + sWorld->setWorldState(WS_ARENA_DISTRIBUTION_TIME, m_NextAutoDistributionTime.count()); } m_AutoDistributionTimeChecker = 600000; // 10 minutes check } @@ -631,16 +632,21 @@ void BattlegroundMgr::InitAutomaticArenaPointDistribution() if (!sWorld->getBoolConfig(CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS)) return; - time_t wstime = time_t(sWorld->getWorldState(WS_ARENA_DISTRIBUTION_TIME)); - time_t curtime = time(nullptr); + Seconds wstime = Seconds(sWorld->getWorldState(WS_ARENA_DISTRIBUTION_TIME)); + Seconds curtime = GameTime::GetGameTime(); + LOG_INFO("server.loading", "Initializing Automatic Arena Point Distribution"); + if (wstime < curtime) { - m_NextAutoDistributionTime = curtime; // reset will be called in the next update + m_NextAutoDistributionTime = curtime; // reset will be called in the next update LOG_INFO("server.loading", "Next arena point distribution time in the past, reseting it now."); } else + { m_NextAutoDistributionTime = wstime; + } + LOG_INFO("server.loading", "Automatic Arena Point Distribution initialized."); } @@ -1012,10 +1018,10 @@ void BattlegroundMgr::InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, T if (bg->isArena() && bg->isRated()) bg->SetArenaTeamIdForTeam(ginfo->teamId, ginfo->ArenaTeamId); - ginfo->RemoveInviteTime = World::GetGameTimeMS() + INVITE_ACCEPT_WAIT_TIME; + ginfo->RemoveInviteTime = GameTime::GetGameTimeMS().count() + INVITE_ACCEPT_WAIT_TIME; // loop through the players - for (auto itr : ginfo->Players) + for (auto& itr : ginfo->Players) { // get the player Player* player = ObjectAccessor::FindConnectedPlayer(itr); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index 41c007ae4a..d650af31cf 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -32,8 +32,6 @@ typedef Battleground* (*bgRef)(Battleground*); typedef void(*bgMapRef)(WorldPacket*, Battleground::BattlegroundScoreMap::const_iterator); typedef void(*bgTypeRef)(WorldPacket*, Battleground::BattlegroundScoreMap::const_iterator, Battleground*); -#define BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY 86400 // how many seconds in day - struct CreateBattlegroundData { BattlegroundTypeId bgTypeId; @@ -155,7 +153,7 @@ private: bool m_ArenaTesting; bool m_Testing; uint32 m_lastClientVisibleInstanceId; - time_t m_NextAutoDistributionTime; + Seconds m_NextAutoDistributionTime; uint32 m_AutoDistributionTimeChecker; uint32 m_NextPeriodicQueueUpdateTime; BattleMastersMap mBattleMastersMap; diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index eaa7985177..bef951aca9 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -22,6 +22,7 @@ #include "BattlegroundSpamProtect.h" #include "Channel.h" #include "Chat.h" +#include "GameTime.h" #include "Group.h" #include "Language.h" #include "Log.h" @@ -138,7 +139,7 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, PvPDiffi ginfo->ArenaTeamId = arenateamid; ginfo->IsRated = isRated; ginfo->IsInvitedToBGInstanceGUID = 0; - ginfo->JoinTime = World::GetGameTimeMS(); + ginfo->JoinTime = GameTime::GetGameTimeMS().count(); ginfo->RemoveInviteTime = 0; ginfo->teamId = leader->GetTeamId(); ginfo->RealTeamID = leader->GetTeamId(true); @@ -205,7 +206,7 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, PvPDiffi void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo) { - uint32 timeInQueue = std::max<uint32>(1, getMSTimeDiff(ginfo->JoinTime, World::GetGameTimeMS())); + uint32 timeInQueue = std::max<uint32>(1, getMSTimeDiff(ginfo->JoinTime, GameTime::GetGameTimeMS().count())); // team_index: bg alliance - TEAM_ALLIANCE, bg horde - TEAM_HORDE, arena skirmish - TEAM_ALLIANCE, arena rated - TEAM_HORDE uint8 team_index; @@ -570,7 +571,7 @@ bool BattlegroundQueue::CheckPremadeMatch(BattlegroundBracketId bracket_id, uint // this happens if timer has expired or group size lowered uint32 premade_time = sWorld->getIntConfig(CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH); - uint32 time_before = World::GetGameTimeMS() >= premade_time ? World::GetGameTimeMS() - premade_time : 0; + uint32 time_before = GameTime::GetGameTimeMS().count() >= premade_time ? GameTime::GetGameTimeMS().count() - premade_time : 0; for (uint32 i = 0; i < BG_TEAMS_COUNT; i++) if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE + i].empty()) @@ -797,7 +798,7 @@ void BattlegroundQueue::BattlegroundQueueUpdate(uint32 diff, BattlegroundBracket { // pussywizard: everything inside this section is mine, do NOT destroy! - const uint32 currMSTime = World::GetGameTimeMS(); + const uint32 currMSTime = GameTime::GetGameTimeMS().count(); const uint32 discardTime = sBattlegroundMgr->GetRatingDiscardTimer(); const uint32 maxDefaultRatingDifference = (MaxPlayersPerTeam > 2 ? 300 : 200); const uint32 maxCountedMMR = 2500; diff --git a/src/server/game/Battlegrounds/BattlegroundSpamProtect.cpp b/src/server/game/Battlegrounds/BattlegroundSpamProtect.cpp index aef85048b8..2105960aa8 100644 --- a/src/server/game/Battlegrounds/BattlegroundSpamProtect.cpp +++ b/src/server/game/Battlegrounds/BattlegroundSpamProtect.cpp @@ -17,6 +17,7 @@ #include "BattlegroundSpamProtect.h" #include "Battleground.h" +#include "GameTime.h" #include "ObjectGuid.h" #include "Player.h" #include "World.h" @@ -27,7 +28,7 @@ namespace void AddTime(ObjectGuid guid) { - _players.insert_or_assign(guid, sWorld->GetGameTime()); + _players.insert_or_assign(guid, GameTime::GetGameTime().count()); } uint32 GetTime(ObjectGuid guid) @@ -44,7 +45,7 @@ namespace bool IsCorrectDelay(ObjectGuid guid) { // Skip if spam time < 30 secs (default) - return sWorld->GetGameTime() - GetTime(guid) >= sWorld->getIntConfig(CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_SPAM_DELAY); + return GameTime::GetGameTime().count() - GetTime(guid) >= sWorld->getIntConfig(CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_SPAM_DELAY); } } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 40898644d4..5af09724d3 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -19,6 +19,7 @@ #include "BattlegroundMgr.h" #include "Creature.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" @@ -66,7 +67,7 @@ void BattlegroundEY::PostUpdateImpl(uint32 diff) AddPoints(TEAM_ALLIANCE, BG_EY_TickPoints[_ownedPointsCount[TEAM_ALLIANCE] - 1]); if (_ownedPointsCount[TEAM_HORDE] > 0) AddPoints(TEAM_HORDE, BG_EY_TickPoints[_ownedPointsCount[TEAM_HORDE] - 1]); - _bgEvents.ScheduleEvent(BG_EY_EVENT_ADD_POINTS, BG_EY_FPOINTS_TICK_TIME - (World::GetGameTimeMS() % BG_EY_FPOINTS_TICK_TIME)); + _bgEvents.ScheduleEvent(BG_EY_EVENT_ADD_POINTS, BG_EY_FPOINTS_TICK_TIME - (GameTime::GetGameTimeMS().count() % BG_EY_FPOINTS_TICK_TIME)); break; case BG_EY_EVENT_FLAG_ON_GROUND: RespawnFlagAfterDrop(); @@ -76,7 +77,7 @@ void BattlegroundEY::PostUpdateImpl(uint32 diff) break; case BG_EY_EVENT_CHECK_CPOINTS: UpdatePointsState(); - _bgEvents.ScheduleEvent(BG_EY_EVENT_CHECK_CPOINTS, BG_EY_FPOINTS_CHECK_TIME - (World::GetGameTimeMS() % BG_EY_FPOINTS_CHECK_TIME)); + _bgEvents.ScheduleEvent(BG_EY_EVENT_CHECK_CPOINTS, BG_EY_FPOINTS_CHECK_TIME - (GameTime::GetGameTimeMS().count() % BG_EY_FPOINTS_CHECK_TIME)); break; } } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp index 3c9388c06b..71f5b8d051 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp @@ -19,6 +19,7 @@ #include "Battleground.h" #include "GameGraveyard.h" #include "GameObject.h" +#include "GameTime.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" @@ -139,7 +140,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) { // Check if creature respawn time is properly saved RespawnMap::iterator itr = respawnMap.find(catapult->GetGUID()); - if (itr == respawnMap.end() || time(nullptr) < itr->second) + if (itr == respawnMap.end() || GameTime::GetGameTime().count() < itr->second) continue; catapult->Relocate(BG_IC_DocksVehiclesCatapults[j].GetPositionX(), BG_IC_DocksVehiclesCatapults[j].GetPositionY(), BG_IC_DocksVehiclesCatapults[j].GetPositionZ(), BG_IC_DocksVehiclesCatapults[j].GetOrientation()); @@ -157,7 +158,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) { // Check if creature respawn time is properly saved RespawnMap::iterator itr = respawnMap.find(glaiveThrower->GetGUID()); - if (itr == respawnMap.end() || time(nullptr) < itr->second) + if (itr == respawnMap.end() || GameTime::GetGameTime().count() < itr->second) continue; glaiveThrower->Relocate(BG_IC_DocksVehiclesGlaives[j].GetPositionX(), BG_IC_DocksVehiclesGlaives[j].GetPositionY(), BG_IC_DocksVehiclesGlaives[j].GetPositionZ(), BG_IC_DocksVehiclesGlaives[j].GetOrientation()); @@ -186,7 +187,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) { // Check if creature respawn time is properly saved RespawnMap::iterator itr = respawnMap.find(siege->GetGUID()); - if (itr == respawnMap.end() || time(nullptr) < itr->second) + if (itr == respawnMap.end() || GameTime::GetGameTime().count() < itr->second) continue; siege->Relocate(BG_IC_WorkshopVehicles[4].GetPositionX(), BG_IC_WorkshopVehicles[4].GetPositionY(), BG_IC_WorkshopVehicles[4].GetPositionZ(), BG_IC_WorkshopVehicles[4].GetOrientation()); @@ -203,7 +204,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) { // Check if creature respawn time is properly saved RespawnMap::iterator itr = respawnMap.find(demolisher->GetGUID()); - if (itr == respawnMap.end() || time(nullptr) < itr->second) + if (itr == respawnMap.end() || GameTime::GetGameTime().count() < itr->second) continue; demolisher->Relocate(BG_IC_WorkshopVehicles[u].GetPositionX(), BG_IC_WorkshopVehicles[u].GetPositionY(), BG_IC_WorkshopVehicles[u].GetPositionZ(), BG_IC_WorkshopVehicles[u].GetOrientation()); @@ -532,7 +533,7 @@ void BattlegroundIC::HandleKillUnit(Creature* unit, Player* killer) // Xinef: Add to respawn list if (entry == NPC_DEMOLISHER || entry == NPC_SIEGE_ENGINE_H || entry == NPC_SIEGE_ENGINE_A || entry == NPC_GLAIVE_THROWER_A || entry == NPC_GLAIVE_THROWER_H || entry == NPC_CATAPULT) - respawnMap[unit->GetGUID()] = time(nullptr) + VEHICLE_RESPAWN_TIME; + respawnMap[unit->GetGUID()] = GameTime::GetGameTime().count() + VEHICLE_RESPAWN_TIME; } } @@ -890,7 +891,7 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* nodePoint, bool recapture) if (!siegeVehicle->IsVehicleInUse()) Unit::Kill(siegeEngine, siegeEngine); - respawnMap[siegeEngine->GetGUID()] = time(nullptr) + VEHICLE_RESPAWN_TIME; + respawnMap[siegeEngine->GetGUID()] = GameTime::GetGameTime().count() + VEHICLE_RESPAWN_TIME; } } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp index d812daa38d..91c76ef2e0 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp @@ -18,6 +18,7 @@ #include "BattlegroundSA.h" #include "GameGraveyard.h" #include "GameObject.h" +#include "GameTime.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" @@ -1087,11 +1088,11 @@ void BattlegroundSA::UpdateDemolisherSpawns() // Demolisher is not in list if (DemoliserRespawnList.find(i) == DemoliserRespawnList.end()) { - DemoliserRespawnList[i] = World::GetGameTimeMS() + 30000; + DemoliserRespawnList[i] = GameTime::GetGameTimeMS().count() + 30000; } else { - if (DemoliserRespawnList[i] < World::GetGameTimeMS()) + if (DemoliserRespawnList[i] < GameTime::GetGameTimeMS().count()) { Demolisher->Relocate(BG_SA_NpcSpawnlocs[i][0], BG_SA_NpcSpawnlocs[i][1], BG_SA_NpcSpawnlocs[i][2], BG_SA_NpcSpawnlocs[i][3]); diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 1cba49541e..a2192a447f 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -16,6 +16,7 @@ */ #include "CalendarMgr.h" +#include "GameTime.h" #include "GuildMgr.h" #include "Log.h" #include "ObjectAccessor.h" @@ -24,6 +25,9 @@ #include "QueryResult.h" #include <unordered_map> +CalendarInvite::CalendarInvite() : _inviteId(1), _eventId(0), _statusTime(GameTime::GetGameTime().count()), +_status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } + CalendarInvite::~CalendarInvite() { // Free _inviteId only if it's a real invite and not just a pre-invite or guild announcement @@ -358,7 +362,7 @@ uint64 CalendarMgr::GetFreeInviteId() void CalendarMgr::DeleteOldEvents() { - time_t oldEventsTime = time(nullptr) - CALENDAR_OLD_EVENTS_DELETION_TIME; + time_t oldEventsTime = GameTime::GetGameTime().count() - CALENDAR_OLD_EVENTS_DELETION_TIME; for (CalendarEventStore::const_iterator itr = _events.begin(); itr != _events.end();) { diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index e853a734ec..e633b1a310 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -147,8 +147,7 @@ public: _text = calendarInvite.GetText(); } - CalendarInvite() : _inviteId(1), _eventId(0), _statusTime(time(nullptr)), - _status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } + CalendarInvite(); CalendarInvite(uint64 inviteId, uint64 eventId, ObjectGuid invitee, ObjectGuid senderGUID, time_t statusTime, CalendarInviteStatus status, CalendarModerationRank rank, std::string text) : diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index d91951765e..de5f7401e8 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -20,6 +20,7 @@ #include "CharacterCache.h" #include "Chat.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "ObjectMgr.h" #include "Player.h" #include "SocialMgr.h" @@ -34,6 +35,7 @@ Channel::Channel(std::string const& name, uint32 channelId, uint32 channelDBId, _channelId(channelId), _channelDBId(channelDBId), _teamId(teamId), + _lastSpeakTime(0), _name(name), _password("") { @@ -95,7 +97,7 @@ Channel::Channel(std::string const& name, uint32 channelId, uint32 channelDBId, bool Channel::IsBanned(ObjectGuid guid) const { BannedContainer::const_iterator itr = bannedStore.find(guid); - return itr != bannedStore.end() && itr->second > time(nullptr); + return itr != bannedStore.end() && itr->second > GameTime::GetGameTime().count(); } void Channel::UpdateChannelInDB() const @@ -208,7 +210,6 @@ void Channel::JoinChannel(Player* player, std::string const& pass) PlayerInfo pinfo; pinfo.player = guid; pinfo.flags = MEMBER_FLAG_NONE; - pinfo.lastSpeakTime = 0; pinfo.plrPtr = player; playersStore[guid] = pinfo; @@ -428,8 +429,8 @@ void Channel::KickOrBan(Player const* player, std::string const& badname, bool b { if (!IsBanned(victim)) { - bannedStore[victim] = time(nullptr) + CHANNEL_BAN_DURATION; - AddChannelBanToDB(victim, time(nullptr) + CHANNEL_BAN_DURATION); + bannedStore[victim] = GameTime::GetGameTime().count() + CHANNEL_BAN_DURATION; + AddChannelBanToDB(victim, GameTime::GetGameTime().count() + CHANNEL_BAN_DURATION); if (notify) { @@ -811,9 +812,9 @@ void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) else if (playersStore.size() >= 10) speakDelay = 5; - if (!pinfo.IsAllowedToSpeak(speakDelay)) + if (!IsAllowedToSpeak(speakDelay)) { - std::string timeStr = secsToTimeString(pinfo.lastSpeakTime + speakDelay - sWorld->GetGameTime()); + std::string timeStr = secsToTimeString(_lastSpeakTime + speakDelay - GameTime::GetGameTime().count()); if (_channelRights.speakMessage.length() > 0) player->GetSession()->SendNotification("%s", _channelRights.speakMessage.c_str()); player->GetSession()->SendNotification("You must wait %s before speaking again.", timeStr.c_str()); @@ -830,6 +831,17 @@ void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) SendToAll(&data, pinfo.IsModerator() ? ObjectGuid::Empty : guid); } +bool Channel::IsAllowedToSpeak(uint32 speakDelay) +{ + if (_lastSpeakTime + speakDelay <= GameTime::GetGameTime().count()) + { + _lastSpeakTime = GameTime::GetGameTime().count(); + return true; + } + + return false; +} + void Channel::Invite(Player const* player, std::string const& newname) { ObjectGuid guid = player->GetGUID(); diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index 29edff3124..96a774e8dd 100644 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -150,7 +150,6 @@ class Channel { ObjectGuid player; uint8 flags; - uint64 lastSpeakTime; // pussywizard Player* plrPtr; // pussywizard [[nodiscard]] bool HasFlag(uint8 flag) const { return flags & flag; } @@ -175,16 +174,6 @@ class Channel if (state) flags |= MEMBER_FLAG_MUTED; else flags &= ~MEMBER_FLAG_MUTED; } - bool IsAllowedToSpeak(uint64 speakDelay) // pussywizard - { - if (lastSpeakTime + speakDelay <= static_cast<uint64>(sWorld->GetGameTime())) - { - lastSpeakTime = sWorld->GetGameTime(); - return true; - } - else - return false; - } private: bool _gmStatus = false; }; @@ -234,6 +223,7 @@ public: // pussywizard: void AddWatching(Player* p); void RemoveWatching(Player* p); + bool IsAllowedToSpeak(uint32 speakDelay); // pussywizard private: // initial packet data (notify type and channel name) @@ -339,6 +329,7 @@ private: uint32 _channelDBId; TeamId _teamId; ObjectGuid _ownerGUID; + uint32 _lastSpeakTime; std::string _name; std::string _password; ChannelRights _channelRights; diff --git a/src/server/game/DungeonFinding/LFG.cpp b/src/server/game/DungeonFinding/LFG.cpp index 2277a07840..b22ece0962 100644 --- a/src/server/game/DungeonFinding/LFG.cpp +++ b/src/server/game/DungeonFinding/LFG.cpp @@ -21,7 +21,6 @@ namespace lfg { - std::string ConcatenateDungeons(LfgDungeonSet const& dungeons) { std::string dungeonstr = ""; diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index 9b19cb369a..9eca8f0181 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -21,6 +21,7 @@ #include "DBCStores.h" #include "DisableMgr.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "Group.h" #include "GroupMgr.h" #include "InstanceSaveMgr.h" @@ -278,7 +279,7 @@ namespace lfg if (task == 0) { - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); // Remove obsolete role checks for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();) @@ -716,7 +717,7 @@ namespace lfg // Create new rolecheck LfgRoleCheck& roleCheck = RoleChecksStore[gguid]; roleCheck.roles.clear(); // pussywizard: NEW rolecheck, not old one with trash data >_> - roleCheck.cancelTime = time_t(time(nullptr)) + LFG_TIME_ROLECHECK; + roleCheck.cancelTime = time_t(GameTime::GetGameTime().count()) + LFG_TIME_ROLECHECK; roleCheck.state = LFG_ROLECHECK_INITIALITING; roleCheck.leader = guid; roleCheck.dungeons = dungeons; @@ -754,7 +755,7 @@ namespace lfg LfgRolesMap rolesMap; rolesMap[guid] = roles; LFGQueue& queue = GetQueue(guid); - queue.AddQueueData(guid, time(nullptr), dungeons, rolesMap); + queue.AddQueueData(guid, GameTime::GetGameTime().count(), dungeons, rolesMap); if (!isContinue) { @@ -964,8 +965,10 @@ namespace lfg m_raidBrowserUpdateTimer[team] = 0; } - if (getMSTimeDiff(World::GetGameTimeMS(), getMSTime()) > (70 * 7) / 5) // prevent lagging + if (GetMSTimeDiff(GameTime::GetGameTimeMS(), GetTimeMS()) > 98ms) // prevent lagging + { return; + } ObjectGuid guid, groupGuid, instanceGuid; uint8 level, Class, race, talents[3]; @@ -1444,7 +1447,7 @@ namespace lfg { SetState(gguid, LFG_STATE_QUEUED); LFGQueue& queue = GetQueue(gguid); - queue.AddQueueData(gguid, time_t(time(nullptr)), roleCheck.dungeons, roleCheck.roles); + queue.AddQueueData(gguid, time_t(GameTime::GetGameTime().count()), roleCheck.dungeons, roleCheck.roles); RoleChecksStore.erase(itRoleCheck); } else if (roleCheck.state != LFG_ROLECHECK_INITIALITING) @@ -1809,7 +1812,7 @@ namespace lfg bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS; proposal.state = LFG_PROPOSAL_SUCCESS; - time_t joinTime = time(nullptr); + time_t joinTime = GameTime::GetGameTime().count(); LFGQueue& queue = GetQueue(guid); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND); @@ -1987,7 +1990,7 @@ namespace lfg LfgPlayerBoot& boot = BootsStore[gguid]; boot.inProgress = true; - boot.cancelTime = time_t(time(nullptr)) + LFG_TIME_BOOT; + boot.cancelTime = time_t(GameTime::GetGameTime().count()) + LFG_TIME_BOOT; boot.reason = reason; boot.victim = victim; diff --git a/src/server/game/DungeonFinding/LFGQueue.cpp b/src/server/game/DungeonFinding/LFGQueue.cpp index 3ca1e11876..3f9fa46fe0 100644 --- a/src/server/game/DungeonFinding/LFGQueue.cpp +++ b/src/server/game/DungeonFinding/LFGQueue.cpp @@ -18,6 +18,7 @@ #include "LFGQueue.h" #include "Containers.h" #include "DBCStores.h" +#include "GameTime.h" #include "Group.h" #include "InstanceScript.h" #include "LFGMgr.h" @@ -29,6 +30,10 @@ namespace lfg { + LfgQueueData::LfgQueueData() : + joinTime(time_t(GameTime::GetGameTime().count())), lastRefreshTime(joinTime), tanks(LFG_TANKS_NEEDED), + healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) { } + void LFGQueue::AddToQueue(ObjectGuid guid, bool failedProposal) { LOG_DEBUG("lfg", "ADD AddToQueue: %s, failed proposal: %u", guid.ToString().c_str(), failedProposal ? 1 : 0); @@ -408,7 +413,7 @@ namespace lfg return LFG_COMPATIBILITY_PENDING; // Create a new proposal - proposal.cancelTime = time(nullptr) + LFG_TIME_PROPOSAL; + proposal.cancelTime = GameTime::GetGameTime().count() + LFG_TIME_PROPOSAL; proposal.state = LFG_PROPOSAL_INITIATING; proposal.leader.Clear(); proposal.dungeonId = Acore::Containers::SelectRandomContainerElement(proposalDungeons); @@ -464,7 +469,7 @@ namespace lfg void LFGQueue::UpdateQueueTimers(uint32 diff) { - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); bool sendQueueStatus = false; if (m_QueueStatusTimer > LFG_QUEUEUPDATE_INTERVAL) diff --git a/src/server/game/DungeonFinding/LFGQueue.h b/src/server/game/DungeonFinding/LFGQueue.h index efd144e804..0f5c1cab6d 100644 --- a/src/server/game/DungeonFinding/LFGQueue.h +++ b/src/server/game/DungeonFinding/LFGQueue.h @@ -41,8 +41,7 @@ namespace lfg /// Stores player or group queue info struct LfgQueueData { - LfgQueueData(): joinTime(time_t(time(nullptr))), lastRefreshTime(joinTime) - { } + LfgQueueData(); LfgQueueData(time_t _joinTime, LfgDungeonSet _dungeons, LfgRolesMap _roles): joinTime(_joinTime), lastRefreshTime(_joinTime), tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index 70c901f1b1..a3dba1f5de 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -19,6 +19,7 @@ #include "CharacterCache.h" #include "Common.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Log.h" #include "ObjectAccessor.h" #include "Opcodes.h" @@ -30,13 +31,9 @@ Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type { m_objectType |= TYPEMASK_CORPSE; m_objectTypeId = TYPEID_CORPSE; - m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_STATIONARY_POSITION | UPDATEFLAG_POSITION); - m_valuesCount = CORPSE_END; - - m_time = time(nullptr); - + m_time = GameTime::GetGameTime().count(); lootRecipient = nullptr; } @@ -195,3 +192,8 @@ bool Corpse::IsExpired(time_t t) const else return m_time < t - 3 * DAY; } + +void Corpse::ResetGhostTime() +{ + m_time = GameTime::GetGameTime().count(); +} diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 227580a117..acd852d2b1 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -66,7 +66,7 @@ public: [[nodiscard]] ObjectGuid GetOwnerGUID() const { return GetGuidValue(CORPSE_FIELD_OWNER); } [[nodiscard]] time_t const& GetGhostTime() const { return m_time; } - void ResetGhostTime() { m_time = time(nullptr); } + void ResetGhostTime(); [[nodiscard]] CorpseType GetType() const { return m_type; } [[nodiscard]] CellCoord const& GetCellCoord() const { return _cellCoord; } diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 272a93d722..b3efbac77d 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -25,6 +25,7 @@ #include "DatabaseEnv.h" #include "Formulas.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "GroupMgr.h" @@ -105,6 +106,9 @@ bool VendorItemData::RemoveItem(uint32 item_id) return found; } +VendorItemCount::VendorItemCount(uint32 _item, uint32 _count) + : itemId(_item), count(_count), lastIncrementTime(GameTime::GetGameTime().count()) { } + VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, uint32 extendedCost) const { for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i) @@ -165,7 +169,7 @@ bool AssistDelayEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) if (Unit* victim = ObjectAccessor::GetUnit(*m_owner, m_victim)) { // Initialize last damage timer if it doesn't exist - m_owner->SetLastDamagedTime(sWorld->GetGameTime() + MAX_AGGRO_RESET_TIME); + m_owner->SetLastDamagedTime(GameTime::GetGameTime().count() + MAX_AGGRO_RESET_TIME); while (!m_assistants.empty()) { @@ -329,7 +333,7 @@ void Creature::RemoveCorpse(bool setSpawnTime, bool skipVisibility) if (getDeathState() != CORPSE) return; - m_corpseRemoveTime = time(nullptr); + m_corpseRemoveTime = GameTime::GetGameTime().count(); setDeathState(DEAD); RemoveAllAuras(); if (!skipVisibility) // pussywizard @@ -342,7 +346,7 @@ void Creature::RemoveCorpse(bool setSpawnTime, bool skipVisibility) // Should get removed later, just keep "compatibility" with scripts if (setSpawnTime) { - m_respawnTime = time(nullptr) + respawnDelay; + m_respawnTime = GameTime::GetGameTime().count() + respawnDelay; //SaveRespawnTime(); } @@ -597,7 +601,7 @@ void Creature::Update(uint32 diff) break; case DEAD: { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (m_respawnTime <= now) { @@ -606,7 +610,7 @@ void Creature::Update(uint32 diff) if (!sConditionMgr->IsObjectMeetToConditions(this, conditions)) { // Creature should not respawn, reset respawn timer. Conditions will be checked again the next time it tries to respawn. - m_respawnTime = time(nullptr) + m_respawnDelay; + m_respawnTime = GameTime::GetGameTime().count() + m_respawnDelay; break; } @@ -649,7 +653,7 @@ void Creature::Update(uint32 diff) } else m_groupLootTimer -= diff; } - else if (m_corpseRemoveTime <= time(nullptr)) + else if (m_corpseRemoveTime <= GameTime::GetGameTime().count()) { RemoveCorpse(false); LOG_DEBUG("entities.unit", "Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY)); @@ -1756,7 +1760,7 @@ bool Creature::IsInvisibleDueToDespawn() const if (Unit::IsInvisibleDueToDespawn()) return true; - if (IsAlive() || m_corpseRemoveTime > time(nullptr)) + if (IsAlive() || m_corpseRemoveTime > GameTime::GetGameTime().count()) return false; return true; @@ -1825,8 +1829,8 @@ void Creature::setDeathState(DeathState s, bool despawn) { _lastDamagedTime.reset(); - m_corpseRemoveTime = time(nullptr) + m_corpseDelay; - m_respawnTime = time(nullptr) + m_respawnDelay + m_corpseDelay; + m_corpseRemoveTime = GameTime::GetGameTime().count() + m_corpseDelay; + m_respawnTime = GameTime::GetGameTime().count() + m_respawnDelay + m_corpseDelay; // always save boss respawn time at death to prevent crash cheating if (GetMap()->IsDungeon() || isWorldBoss() || GetCreatureTemplate()->rank >= CREATURE_ELITE_ELITE) @@ -1957,9 +1961,9 @@ void Creature::Respawn(bool force) //Re-initialize reactstate that could be altered by movementgenerators InitializeReactState(); - m_respawnedTime = sWorld->GetGameTime(); + m_respawnedTime = GameTime::GetGameTime().count(); } - m_respawnedTime = time(nullptr); + m_respawnedTime = GameTime::GetGameTime().count(); // xinef: relocate notifier, fixes npc appearing in corpse position after forced respawn (instead of spawn) m_last_notify_position.Relocate(-5000.0f, -5000.0f, -5000.0f, 0.0f); UpdateObjectVisibility(false); @@ -1982,7 +1986,7 @@ void Creature::ForcedDespawn(uint32 timeMSToDespawn, Seconds forceRespawnTimer) if (forceRespawnTimer > Seconds::zero()) { - m_respawnTime = time(nullptr) + forceRespawnTimer.count(); + m_respawnTime = GameTime::GetGameTime().count() + forceRespawnTimer.count(); m_respawnDelay = forceRespawnTimer.count(); } } @@ -2456,7 +2460,7 @@ bool Creature::CanCreatureAttack(Unit const* victim, bool skipDistCheck) const return false; // cannot attack if is during 5 second grace period, unless being attacked - if (m_respawnedTime && (sWorld->GetGameTime() - m_respawnedTime) < 5 && victim->getAttackers().empty()) + if (m_respawnedTime && (GameTime::GetGameTime().count() - m_respawnedTime) < 5 && victim->getAttackers().empty()) { return false; } @@ -2474,7 +2478,7 @@ bool Creature::CanCreatureAttack(Unit const* victim, bool skipDistCheck) const // pussywizard: don't check distance to home position if recently damaged (allow kiting away from spawnpoint!) // xinef: this should include taunt auras - if (!isWorldBoss() && (GetLastDamagedTime() > sWorld->GetGameTime() || HasAuraType(SPELL_AURA_MOD_TAUNT))) + if (!isWorldBoss() && (GetLastDamagedTime() > GameTime::GetGameTime().count() || HasAuraType(SPELL_AURA_MOD_TAUNT))) return true; } @@ -2626,7 +2630,7 @@ void Creature::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs { if (idSchoolMask & (1 << i)) { - m_ProhibitSchoolTime[i] = World::GetGameTimeMS() + unTimeMs; + m_ProhibitSchoolTime[i] = GameTime::GetGameTimeMS().count() + unTimeMs; } } } @@ -2637,7 +2641,7 @@ bool Creature::IsSpellProhibited(SpellSchoolMask idSchoolMask) const { if (idSchoolMask & (1 << i)) { - if (m_ProhibitSchoolTime[i] >= World::GetGameTimeMS()) + if (m_ProhibitSchoolTime[i] >= GameTime::GetGameTimeMS().count()) { return true; } @@ -2651,7 +2655,7 @@ void Creature::_AddCreatureSpellCooldown(uint32 spell_id, uint16 categoryId, uin { CreatureSpellCooldown spellCooldown; spellCooldown.category = categoryId; - spellCooldown.end = World::GetGameTimeMS() + end_time; + spellCooldown.end = GameTime::GetGameTimeMS().count() + end_time; m_CreatureSpellCooldowns[spell_id] = std::move(spellCooldown); } @@ -2697,13 +2701,13 @@ uint32 Creature::GetSpellCooldown(uint32 spell_id) const if (itr == m_CreatureSpellCooldowns.end()) return 0; - return itr->second.end > World::GetGameTimeMS() ? itr->second.end - World::GetGameTimeMS() : 0; + return itr->second.end > GameTime::GetGameTimeMS().count() ? itr->second.end - GameTime::GetGameTimeMS().count() : 0; } bool Creature::HasSpellCooldown(uint32 spell_id) const { CreatureSpellCooldowns::const_iterator itr = m_CreatureSpellCooldowns.find(spell_id); - return (itr != m_CreatureSpellCooldowns.end() && itr->second.end > World::GetGameTimeMS()); + return (itr != m_CreatureSpellCooldowns.end() && itr->second.end > GameTime::GetGameTimeMS().count()); } bool Creature::HasSpell(uint32 spellID) const @@ -2717,7 +2721,7 @@ bool Creature::HasSpell(uint32 spellID) const time_t Creature::GetRespawnTimeEx() const { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (m_respawnTime > now) return m_respawnTime; @@ -2783,7 +2787,7 @@ void Creature::AllLootRemovedFromCorpse() } } - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (m_corpseRemoveTime <= now) { return; @@ -2797,7 +2801,7 @@ void Creature::AllLootRemovedFromCorpse() // corpse skinnable, but without skinning flag, and then skinned, corpse will despawn next update if (loot.loot_type == LOOT_SKINNING) { - m_corpseRemoveTime = time(nullptr); + m_corpseRemoveTime = GameTime::GetGameTime().count(); } else { @@ -2856,7 +2860,7 @@ uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem) VendorItemCount* vCount = &*itr; - time_t ptime = time(nullptr); + time_t ptime = GameTime::GetGameTime().count(); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) { @@ -2895,7 +2899,7 @@ uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 us VendorItemCount* vCount = &*itr; - time_t ptime = time(nullptr); + time_t ptime = GameTime::GetGameTime().count(); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) { @@ -3063,7 +3067,7 @@ bool Creature::SetCanFly(bool enable, bool /*packetOnly*/ /* = false */) sScriptMgr->AnticheatSetCanFlybyServer(m_movedByPlayer->ToPlayer(), enable); if (!enable) - m_movedByPlayer->ToPlayer()->SetFallInformation(time(nullptr), m_movedByPlayer->ToPlayer()->GetPositionZ()); + m_movedByPlayer->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), m_movedByPlayer->ToPlayer()->GetPositionZ()); WorldPacket data(enable ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12); data << GetPackGUID(); @@ -3486,3 +3490,18 @@ uint32 Creature::GetRandomId(uint32 id1, uint32 id2, uint32 id3) } return id; } + +void Creature::SetPickPocketLootTime() +{ + lootPickPocketRestoreTime = GameTime::GetGameTime().count() + MINUTE + GetCorpseDelay() + GetRespawnTime(); +} + +bool Creature::CanGeneratePickPocketLoot() const +{ + return (lootPickPocketRestoreTime == 0 || lootPickPocketRestoreTime < GameTime::GetGameTime().count()); +} + +void Creature::SetRespawnTime(uint32 respawn) +{ + m_respawnTime = respawn ? GameTime::GetGameTime().count() + respawn : 0; +} diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index d94b2e4bd2..54e59a9bd3 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -219,8 +219,8 @@ public: [[nodiscard]] Group* GetLootRecipientGroup() const; [[nodiscard]] bool hasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } bool isTappedBy(Player const* player) const; // return true if the creature is tapped by the player or a member of his party. - [[nodiscard]] bool CanGeneratePickPocketLoot() const { return lootPickPocketRestoreTime == 0 || lootPickPocketRestoreTime < time(nullptr); } - void SetPickPocketLootTime() { lootPickPocketRestoreTime = time(nullptr) + MINUTE + GetCorpseDelay() + GetRespawnTime(); } + [[nodiscard]] bool CanGeneratePickPocketLoot() const; + void SetPickPocketLootTime(); void ResetPickPocketLootTime() { lootPickPocketRestoreTime = 0; } void SetLootRecipient (Unit* unit, bool withGroup = true); @@ -274,7 +274,7 @@ public: [[nodiscard]] time_t const& GetRespawnTime() const { return m_respawnTime; } [[nodiscard]] time_t GetRespawnTimeEx() const; - void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(nullptr) + respawn : 0; } + void SetRespawnTime(uint32 respawn); void Respawn(bool force = false); void SaveRespawnTime() override; diff --git a/src/server/game/Entities/Creature/CreatureData.h b/src/server/game/Entities/Creature/CreatureData.h index 9422647a19..18734e8ba1 100644 --- a/src/server/game/Entities/Creature/CreatureData.h +++ b/src/server/game/Entities/Creature/CreatureData.h @@ -485,8 +485,7 @@ struct VendorItemData struct VendorItemCount { - explicit VendorItemCount(uint32 _item, uint32 _count) - : itemId(_item), count(_count), lastIncrementTime(time(nullptr)) {} + explicit VendorItemCount(uint32 _item, uint32 _count); uint32 itemId; uint32 count; diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.cpp b/src/server/game/Entities/DynamicObject/DynamicObject.cpp index 0311024205..e896424579 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.cpp +++ b/src/server/game/Entities/DynamicObject/DynamicObject.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "ObjectAccessor.h" @@ -122,7 +123,7 @@ bool DynamicObject::CreateDynamicObject(ObjectGuid::LowType guidlow, Unit* caste SetByteValue(DYNAMICOBJECT_BYTES, 0, type); SetUInt32Value(DYNAMICOBJECT_SPELLID, spellId); SetFloatValue(DYNAMICOBJECT_RADIUS, radius); - SetUInt32Value(DYNAMICOBJECT_CASTTIME, World::GetGameTimeMS()); + SetUInt32Value(DYNAMICOBJECT_CASTTIME, GameTime::GetGameTimeMS().count()); if (IsWorldObject()) setActive(true); //must before add to map to be put in world container diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index 5c612dd5bd..4ac2add75a 100644 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -23,6 +23,7 @@ #include "DynamicTree.h" #include "GameObjectAI.h" #include "GameObjectModel.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" @@ -461,9 +462,9 @@ void GameObject::Update(uint32 diff) GameObjectTemplate const* goInfo = GetGOInfo(); // Bombs if (goInfo->trap.type == 2) - m_cooldownTime = World::GetGameTimeMS() + 10 * IN_MILLISECONDS; // Hardcoded tooltip value + m_cooldownTime = GameTime::GetGameTimeMS().count() + 10 * IN_MILLISECONDS; // Hardcoded tooltip value else if (GetOwner()) - m_cooldownTime = World::GetGameTimeMS() + goInfo->trap.startDelay * IN_MILLISECONDS; + m_cooldownTime = GameTime::GetGameTimeMS().count() + goInfo->trap.startDelay * IN_MILLISECONDS; m_lootState = GO_READY; break; @@ -471,7 +472,7 @@ void GameObject::Update(uint32 diff) case GAMEOBJECT_TYPE_FISHINGNODE: { // fishing code (bobber ready) - if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) + if (GameTime::GetGameTime().count() > m_respawnTime - FISHING_BOBBER_READY_TIME) { // splash bobber (bobber ready now) Unit* caster = GetOwner(); @@ -495,7 +496,7 @@ void GameObject::Update(uint32 diff) } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: { - if (World::GetGameTimeMS() < m_cooldownTime) + if (GameTime::GetGameTimeMS().count() < m_cooldownTime) return; GameObjectTemplate const* info = GetGOInfo(); if (info->summoningRitual.animSpell) @@ -568,7 +569,7 @@ void GameObject::Update(uint32 diff) { if (m_respawnTime > 0) // timer on { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (m_respawnTime <= now) // timer expired { ObjectGuid dbtableHighGuid = ObjectGuid::Create<HighGuid::GameObject>(GetEntry(), m_spawnId); @@ -644,7 +645,7 @@ void GameObject::Update(uint32 diff) GameObjectTemplate const* goInfo = GetGOInfo(); if (goInfo->type == GAMEOBJECT_TYPE_TRAP) { - if (World::GetGameTimeMS() < m_cooldownTime) + if (GameTime::GetGameTimeMS().count() < m_cooldownTime) break; // Type 2 - Bomb (will go away after casting it's spell) @@ -702,7 +703,7 @@ void GameObject::Update(uint32 diff) if (goInfo->trap.spellId) CastSpell(target, goInfo->trap.spellId); - m_cooldownTime = World::GetGameTimeMS() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds + m_cooldownTime = GameTime::GetGameTimeMS().count() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds if (goInfo->trap.type == 1) SetLootState(GO_JUST_DEACTIVATED); @@ -734,11 +735,11 @@ void GameObject::Update(uint32 diff) { case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: - if (GetGOInfo()->GetAutoCloseTime() && World::GetGameTimeMS() >= m_cooldownTime) + if (GetGOInfo()->GetAutoCloseTime() && GameTime::GetGameTimeMS().count() >= m_cooldownTime) ResetDoorOrButton(); break; case GAMEOBJECT_TYPE_GOOBER: - if (World::GetGameTimeMS() >= m_cooldownTime) + if (GameTime::GetGameTimeMS().count() >= m_cooldownTime) { RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); @@ -825,7 +826,7 @@ void GameObject::Update(uint32 diff) return; } - m_respawnTime = time(nullptr) + m_respawnDelayTime; + m_respawnTime = GameTime::GetGameTime().count() + m_respawnDelayTime; // if option not set then object will be saved at grid unload if (GetMap()->IsDungeon()) @@ -1092,7 +1093,7 @@ bool GameObject::LoadGameObjectFromDB(ObjectGuid::LowType spawnId, Map* map, boo m_respawnTime = GetMap()->GetGORespawnTime(m_spawnId); // ready to respawn - if (m_respawnTime && m_respawnTime <= time(nullptr)) + if (m_respawnTime && m_respawnTime <= GameTime::GetGameTime().count()) { m_respawnTime = 0; GetMap()->RemoveGORespawnTime(m_spawnId); @@ -1172,9 +1173,9 @@ Unit* GameObject::GetOwner() const void GameObject::SaveRespawnTime(uint32 forceDelay) { - if (m_goData && m_goData->dbData && (forceDelay || m_respawnTime > time(nullptr)) && m_spawnedByDefault) + if (m_goData && m_goData->dbData && (forceDelay || m_respawnTime > GameTime::GetGameTime().count()) && m_spawnedByDefault) { - time_t respawnTime = forceDelay ? time(nullptr) + forceDelay : m_respawnTime; + time_t respawnTime = forceDelay ? GameTime::GetGameTime().count() + forceDelay : m_respawnTime; GetMap()->SaveGORespawnTime(m_spawnId, respawnTime); } } @@ -1232,7 +1233,7 @@ bool GameObject::IsInvisibleDueToDespawn() const void GameObject::SetRespawnTime(int32 respawn) { - m_respawnTime = respawn > 0 ? time(nullptr) + respawn : 0; + m_respawnTime = respawn > 0 ? GameTime::GetGameTime().count() + respawn : 0; SetRespawnDelay(respawn); if (respawn && !m_spawnedByDefault) { @@ -1249,7 +1250,7 @@ void GameObject::Respawn() { if (m_spawnedByDefault && m_respawnTime > 0) { - m_respawnTime = time(nullptr); + m_respawnTime = GameTime::GetGameTime().count(); GetMap()->RemoveGORespawnTime(m_spawnId); } } @@ -1367,7 +1368,7 @@ void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = f SwitchDoorOrButton(true, alternative); SetLootState(GO_ACTIVATED, user); - m_cooldownTime = World::GetGameTimeMS() + time_to_restore; + m_cooldownTime = GameTime::GetGameTimeMS().count() + time_to_restore; } void GameObject::SetGoArtKit(uint8 kit) @@ -1430,10 +1431,10 @@ void GameObject::Use(Unit* user) // If cooldown data present in template if (uint32 cooldown = GetGOInfo()->GetCooldown()) { - if (World::GetGameTimeMS() < m_cooldownTime) + if (GameTime::GetGameTimeMS().count() < m_cooldownTime) return; - m_cooldownTime = World::GetGameTimeMS() + cooldown * IN_MILLISECONDS; + m_cooldownTime = GameTime::GetGameTimeMS().count() + cooldown * IN_MILLISECONDS; } switch (GetGoType()) @@ -1467,7 +1468,7 @@ void GameObject::Use(Unit* user) if (goInfo->trap.spellId) CastSpell(user, goInfo->trap.spellId); - m_cooldownTime = World::GetGameTimeMS() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds + m_cooldownTime = GameTime::GetGameTimeMS().count() + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)) * IN_MILLISECONDS; // template or 4 seconds if (goInfo->trap.type == 1) // Deactivate after trigger SetLootState(GO_JUST_DEACTIVATED); @@ -1634,7 +1635,7 @@ void GameObject::Use(Unit* user) if (info->goober.customAnim) SendCustomAnim(GetGoAnimProgress()); - m_cooldownTime = World::GetGameTimeMS() + info->GetAutoCloseTime(); + m_cooldownTime = GameTime::GetGameTimeMS().count() + info->GetAutoCloseTime(); // cast this spell later if provided spellId = info->goober.spellId; @@ -1806,7 +1807,7 @@ void GameObject::Use(Unit* user) if (!info->summoningRitual.animSpell) m_cooldownTime = 0; else // channel ready, maintain this - m_cooldownTime = World::GetGameTimeMS() + 5 * IN_MILLISECONDS; + m_cooldownTime = GameTime::GetGameTimeMS().count() + 5 * IN_MILLISECONDS; } return; @@ -2726,6 +2727,20 @@ void GameObject::UpdateModelPosition() } } +time_t GameObject::GetRespawnTimeEx() const +{ + time_t now = GameTime::GetGameTime().count(); + if (m_respawnTime > now) + return m_respawnTime; + else + return now; +} + +void GameObject::SetLootGenerationTime() +{ + m_lootGenerationTime = GameTime::GetGameTime().count(); +} + std::unordered_map<int, goEventFlag> GameObject::gameObjectToEventFlag = { }; class GameObjectModelOwnerImpl : public GameObjectModelOwnerBase diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index 6d4ce5f21f..4bd2aca7bd 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -821,14 +821,7 @@ public: [[nodiscard]] uint32 GetSpellId() const { return m_spellId;} [[nodiscard]] time_t GetRespawnTime() const { return m_respawnTime; } - [[nodiscard]] time_t GetRespawnTimeEx() const - { - time_t now = time(nullptr); - if (m_respawnTime > now) - return m_respawnTime; - else - return now; - } + [[nodiscard]] time_t GetRespawnTimeEx() const; void SetRespawnTime(int32 respawn); void SetRespawnDelay(int32 respawn); @@ -895,7 +888,7 @@ public: [[nodiscard]] bool HasLootRecipient() const { return m_lootRecipient || m_lootRecipientGroup; } uint32 m_groupLootTimer; // (msecs)timer used for group loot uint32 lootingGroupLowGUID; // used to find group which is looting - void SetLootGenerationTime() { m_lootGenerationTime = time(nullptr); } + void SetLootGenerationTime(); [[nodiscard]] uint32 GetLootGenerationTime() const { return m_lootGenerationTime; } [[nodiscard]] GameObject* GetLinkedTrap(); diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 4e5674f2c9..b11181afa8 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -19,6 +19,7 @@ #include "Common.h" #include "ConditionMgr.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "ItemEnchantmentMgr.h" #include "ObjectMgr.h" #include "Player.h" @@ -253,7 +254,7 @@ Item::Item() m_container = nullptr; m_lootGenerated = false; mb_in_trade = false; - m_lastPlayedTimeUpdate = time(nullptr); + m_lastPlayedTimeUpdate = GameTime::GetGameTime().count(); m_refundRecipient = 0; m_paidMoney = 0; @@ -1205,7 +1206,7 @@ void Item::UpdatePlayedTime(Player* owner) // Get current played time uint32 current_playtime = GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME); // Calculate time elapsed since last played time update - time_t curtime = time(nullptr); + time_t curtime = GameTime::GetGameTime().count(); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); uint32 new_playtime = current_playtime + elapsed; // Check if the refund timer has expired yet @@ -1226,7 +1227,7 @@ void Item::UpdatePlayedTime(Player* owner) uint32 Item::GetPlayedTime() { - time_t curtime = time(nullptr); + time_t curtime = GameTime::GetGameTime().count(); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); return GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + elapsed; } diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index efc8f34cf5..e074e5272a 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -23,6 +23,7 @@ #include "Creature.h" #include "DynamicVisibility.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Log.h" #include "MapMgr.h" @@ -1079,7 +1080,7 @@ void MovementInfo::OutDebug() LOG_INFO("movement", "guid %s", guid.ToString().c_str()); LOG_INFO("movement", "flags %u", flags); LOG_INFO("movement", "flags2 %u", flags2); - LOG_INFO("movement", "time %u current time " UI64FMTD "", flags2, uint64(::time(nullptr))); + LOG_INFO("movement", "time %u current time " UI64FMTD "", flags2, uint64(::GameTime::GetGameTime().count())); LOG_INFO("movement", "position: `%s`", pos.ToString().c_str()); if (flags & MOVEMENTFLAG_ONTRANSPORT) @@ -3065,13 +3066,13 @@ void WorldObject::AddToNotify(uint16 f) { uint32 EVENT_VISIBILITY_DELAY = u->FindMap() ? DynamicVisibilityMgr::GetVisibilityNotifyDelay(u->FindMap()->GetEntry()->map_type) : 1000; - uint32 diff = getMSTimeDiff(u->m_last_notify_mstime, World::GetGameTimeMS()); + uint32 diff = getMSTimeDiff(u->m_last_notify_mstime, GameTime::GetGameTimeMS().count()); if (diff >= EVENT_VISIBILITY_DELAY / 2) EVENT_VISIBILITY_DELAY /= 2; else EVENT_VISIBILITY_DELAY -= diff; u->m_delayed_unit_relocation_timer = EVENT_VISIBILITY_DELAY; - u->m_last_notify_mstime = World::GetGameTimeMS() + EVENT_VISIBILITY_DELAY - 1; + u->m_last_notify_mstime = GameTime::GetGameTimeMS().count() + EVENT_VISIBILITY_DELAY - 1; } else if (f & NOTIFY_AI_RELOCATION) { diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index 743a62f143..34108af910 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -20,6 +20,7 @@ #include "Common.h" #include "CreatureAI.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Group.h" #include "InstanceScript.h" #include "Log.h" @@ -320,7 +321,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c break; } - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped here + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(GameTime::GetGameTime().count())); // cast can't be helped here SetCreatorGUID(owner->GetGUID()); InitStatsForLevel(petlevel); @@ -420,7 +421,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c InitTalentForLevel(); // set original talents points before spell loading - uint32 timediff = uint32(time(nullptr) - lastSaveTime); + uint32 timediff = uint32(GameTime::GetGameTime().count() - lastSaveTime); _LoadAuras(holder.GetPreparedResult(PetLoadQueryHolder::AURAS), timediff); // load action bar, if data broken will fill later by default spells. @@ -570,7 +571,7 @@ void Pet::SavePetToDB(PetSaveMode mode) stmt->setUInt32(12, curhealth); stmt->setUInt32(13, curmana); stmt->setUInt32(14, GetPower(POWER_HAPPINESS)); - stmt->setUInt32(15, time(nullptr)); + stmt->setUInt32(15, GameTime::GetGameTime().count()); stmt->setString(16, actionBar); trans->Append(stmt); @@ -651,7 +652,7 @@ void Pet::Update(uint32 diff) { case CORPSE: { - if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(nullptr)) + if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= GameTime::GetGameTime().count()) { Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER! return; @@ -1421,7 +1422,7 @@ void Pet::_LoadSpellCooldowns(PreparedQueryResult result) if (result) { - time_t curTime = time(nullptr); + time_t curTime = GameTime::GetGameTime().count(); PacketCooldowns cooldowns; WorldPacket data; @@ -1465,8 +1466,8 @@ void Pet::_SaveSpellCooldowns(CharacterDatabaseTransaction trans) stmt->setUInt32(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); - time_t curTime = time(nullptr); - uint32 curMSTime = World::GetGameTimeMS(); + time_t curTime = GameTime::GetGameTime().count(); + uint32 curMSTime = GameTime::GetGameTimeMS().count(); uint32 infTime = curMSTime + infinityCooldownDelayCheck; // remove oudated and save active @@ -2418,7 +2419,7 @@ void Pet::FillPetInfo(PetStable::PetInfo* petInfo) const petInfo->Mana = GetPower(POWER_MANA); petInfo->Happiness = GetPower(POWER_HAPPINESS); petInfo->ActionBar = GenerateActionBarData(); - petInfo->LastSaveTime = time(nullptr); + petInfo->LastSaveTime = GameTime::GetGameTime().count(); petInfo->CreatedBySpellId = GetUInt32Value(UNIT_CREATED_BY_SPELL); petInfo->Type = getPetType(); } diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 12051a89a8..1acb2197bf 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -43,6 +43,7 @@ #include "GameEventMgr.h" #include "GameGraveyard.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GossipDef.h" #include "GridNotifiers.h" #include "Group.h" @@ -247,7 +248,7 @@ Player::Player(WorldSession* session): Unit(true), m_mover(this) for (uint8 j = 0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j) m_bgBattlegroundQueueID[j] = BATTLEGROUND_QUEUE_NONE; - m_logintime = time(nullptr); + m_logintime = GameTime::GetGameTime().count(); m_Last_tick = m_logintime; m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; @@ -318,7 +319,7 @@ Player::Player(WorldSession* session): Unit(true), m_mover(this) m_spellPenetrationItemMod = 0; // Honor System - m_lastHonorUpdateTime = time(nullptr); + m_lastHonorUpdateTime = GameTime::GetGameTime().count(); m_IsBGRandomWinner = false; @@ -577,7 +578,7 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo SetArenaPoints(sWorld->getIntConfig(CONFIG_START_ARENA_POINTS)); // Played time - m_Last_tick = time(nullptr); + m_Last_tick = GameTime::GetGameTime().count(); m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; @@ -1074,7 +1075,7 @@ void Player::setDeathState(DeathState s, bool /*despawn = false*/) void Player::SetRestState(uint32 triggerId) { _innTriggerId = triggerId; - _restTime = time(nullptr); + _restTime = GameTime::GetGameTime().count(); SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); } @@ -1432,7 +1433,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if (MustDelayTeleport()) { SetHasDelayedTeleport(true); - SetSemaphoreTeleportNear(time(nullptr)); + SetSemaphoreTeleportNear(GameTime::GetGameTime().count()); //lets save teleport destination for player teleportStore_dest = WorldLocation(mapid, x, y, z, orientation); teleportStore_options = options; @@ -1454,11 +1455,11 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // this will be used instead of the current location in SaveToDB teleportStore_dest = WorldLocation(mapid, x, y, z, orientation); - SetFallInformation(time(nullptr), z); + SetFallInformation(GameTime::GetGameTime().count(), z); // code for finish transfer called in WorldSession::HandleMovementOpcodes() // at client packet MSG_MOVE_TELEPORT_ACK - SetSemaphoreTeleportNear(time(nullptr)); + SetSemaphoreTeleportNear(GameTime::GetGameTime().count()); // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing if (!GetSession()->PlayerLogout()) { @@ -1493,7 +1494,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if (MustDelayTeleport()) { SetHasDelayedTeleport(true); - SetSemaphoreTeleportFar(time(nullptr)); + SetSemaphoreTeleportFar(GameTime::GetGameTime().count()); //lets save teleport destination for player teleportStore_dest = WorldLocation(mapid, x, y, z, orientation); teleportStore_options = options; @@ -1558,7 +1559,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati } teleportStore_dest = WorldLocation(mapid, x, y, z, orientation); - SetFallInformation(time(nullptr), z); + SetFallInformation(GameTime::GetGameTime().count(), z); // if the player is saved before worldportack (at logout for example) // this will be used instead of the current location in SaveToDB @@ -1577,7 +1578,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // move packet sent by client always after far teleport // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet - SetSemaphoreTeleportFar(time(nullptr)); + SetSemaphoreTeleportFar(GameTime::GetGameTime().count()); } } return true; @@ -2683,8 +2684,8 @@ void Player::InitStatsForLevel(bool reapplyMods) void Player::SendInitialSpells() { - uint32 curTime = World::GetGameTimeMS(); - uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; + uint32 curTime = GameTime::GetGameTimeMS().count(); + uint32 infTime = GameTime::GetGameTimeMS().count() + infinityCooldownDelayCheck; uint16 spellCount = 0; @@ -2816,7 +2817,7 @@ void Player::SendNewMail() void Player::AddNewMailDeliverTime(time_t deliver_time) { - if (deliver_time <= time(nullptr)) // ready now + if (deliver_time <= GameTime::GetGameTime().count()) // ready now { ++unReadMails; SendNewMail(); @@ -3459,7 +3460,7 @@ void Player::RemoveCategoryCooldown(uint32 cat) void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) { // remove cooldowns on spells that have < 10 min CD - uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; + uint32 infTime = GameTime::GetGameTimeMS().count() + infinityCooldownDelayCheck; SpellCooldowns::iterator itr, next; for (itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); itr = next) { @@ -3493,7 +3494,7 @@ void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) void Player::RemoveAllSpellCooldown() { - uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; + uint32 infTime = GameTime::GetGameTimeMS().count() + infinityCooldownDelayCheck; if (!m_spellCooldowns.empty()) { for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr) @@ -3512,7 +3513,7 @@ void Player::_LoadSpellCooldowns(PreparedQueryResult result) if (result) { - time_t curTime = time(nullptr); + time_t curTime = GameTime::GetGameTime().count(); do { @@ -3546,8 +3547,8 @@ void Player::_SaveSpellCooldowns(CharacterDatabaseTransaction trans, bool logout stmt->setUInt32(0, GetGUID().GetCounter()); trans->Append(stmt); - time_t curTime = time(nullptr); - uint32 curMSTime = World::GetGameTimeMS(); + time_t curTime = GameTime::GetGameTime().count(); + uint32 curMSTime = GameTime::GetGameTimeMS().count(); uint32 infTime = curMSTime + infinityCooldownDelayCheck; bool first_round = true; @@ -3601,7 +3602,7 @@ uint32 Player::resetTalentsCost() const return 10 * GOLD; else { - uint64 months = (sWorld->GetGameTime() - m_resetTalentsTime) / MONTH; + uint64 months = (GameTime::GetGameTime().count() - m_resetTalentsTime) / MONTH; if (months > 0) { // This cost will be reduced by a rate of 5 gold per month @@ -3710,7 +3711,7 @@ bool Player::resetTalents(bool noResetCost) UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1); m_resetTalentsCost = resetCost; - m_resetTalentsTime = time(nullptr); + m_resetTalentsTime = GameTime::GetGameTime().count(); } return true; @@ -4252,7 +4253,7 @@ void Player::DeleteOldCharacters(uint32 keepDays) LOG_INFO("server.loading", " "); CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS); - stmt->setUInt32(0, uint32(time(nullptr) - time_t(keepDays * DAY))); + stmt->setUInt32(0, uint32(GameTime::GetGameTime().count() - time_t(keepDays * DAY))); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (result) @@ -7627,7 +7628,7 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) // Xinef: loot was generated and respawntime has passed since then, allow to recreate loot // Xinef: to avoid bugs, this rule covers spawned gameobjects only - if (go->isSpawnedByDefault() && go->getLootState() == GO_ACTIVATED && !go->loot.isLooted() && go->GetLootGenerationTime() + go->GetRespawnDelay() < time(nullptr)) + if (go->isSpawnedByDefault() && go->getLootState() == GO_ACTIVATED && !go->loot.isLooted() && go->GetLootGenerationTime() + go->GetRespawnDelay() < GameTime::GetGameTime().count()) go->SetLootState(GO_READY); if (go->getLootState() == GO_READY) @@ -8661,7 +8662,7 @@ void Player::SendBattlefieldWorldStates() SendUpdateWorldState(BATTLEFIELD_WG_WORLD_STATE_SHOW_WORLDSTATE, wg->IsWarTime() ? 1 : 0); for (uint32 i = 0; i < 2; ++i) - SendUpdateWorldState(ClockWorldState[i], uint32(time(nullptr) + (wg->GetTimer() / 1000))); + SendUpdateWorldState(ClockWorldState[i], uint32(GameTime::GetGameTime().count() + (wg->GetTimer() / 1000))); } } } @@ -8808,29 +8809,23 @@ Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetTy SetMinion(pet, true); - switch (petType) + if (petType == SUMMON_PET) { - case SUMMON_PET: + if (pet->GetCreatureTemplate()->type == CREATURE_TYPE_DEMON || pet->GetCreatureTemplate()->type == CREATURE_TYPE_UNDEAD) { - if (pet->GetCreatureTemplate()->type == CREATURE_TYPE_DEMON || pet->GetCreatureTemplate()->type == CREATURE_TYPE_UNDEAD) - { - pet->GetCharmInfo()->SetPetNumber(pet_number, true); // Show pet details tab (Shift+P) only for demons & undead - } - else - { - pet->GetCharmInfo()->SetPetNumber(pet_number, false); - } - - pet->SetUInt32Value(UNIT_FIELD_BYTES_0, 2048); - pet->SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); - pet->SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000); - pet->SetFullHealth(); - pet->SetPower(POWER_MANA, pet->GetMaxPower(POWER_MANA)); - pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped in this case - break; + pet->GetCharmInfo()->SetPetNumber(pet_number, true); // Show pet details tab (Shift+P) only for demons & undead } - default: - break; + else + { + pet->GetCharmInfo()->SetPetNumber(pet_number, false); + } + + pet->SetUInt32Value(UNIT_FIELD_BYTES_0, 2048); + pet->SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); + pet->SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, 1000); + pet->SetFullHealth(); + pet->SetPower(POWER_MANA, pet->GetMaxPower(POWER_MANA)); + pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(GameTime::GetGameTime().count())); // cast can't be helped in this case } map->AddToMap(pet->ToCreature(), true); @@ -9321,8 +9316,8 @@ void Player::PetSpellInitialize() uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size(); data << uint8(cooldownsCount); - uint32 curTime = World::GetGameTimeMS(); - uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; + uint32 curTime = GameTime::GetGameTimeMS().count(); + uint32 infTime = GameTime::GetGameTimeMS().count() + infinityCooldownDelayCheck; for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr) { @@ -9424,8 +9419,8 @@ void Player::VehicleSpellInitialize() // Cooldowns data << uint8(cooldownCount); - uint32 curTime = World::GetGameTimeMS(); - uint32 infTime = World::GetGameTimeMS() + infinityCooldownDelayCheck; + uint32 curTime = GameTime::GetGameTimeMS().count(); + uint32 infTime = GameTime::GetGameTimeMS().count() + infinityCooldownDelayCheck; for (CreatureSpellCooldowns::const_iterator itr = vehicle->m_CreatureSpellCooldowns.begin(); itr != vehicle->m_CreatureSpellCooldowns.end(); ++itr) { @@ -10726,7 +10721,7 @@ void Player::AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 ite void Player::_AddSpellCooldown(uint32 spellid, uint16 categoryId, uint32 itemid, uint32 end_time, bool needSendToClient, bool forceSendToSpectator) { SpellCooldown sc; - sc.end = World::GetGameTimeMS() + end_time; + sc.end = GameTime::GetGameTimeMS().count() + end_time; sc.category = categoryId; sc.itemid = itemid; sc.maxduration = end_time; @@ -11003,7 +10998,7 @@ void Player::LeaveBattleground(Battleground* bg) } // xinef: reset corpse reclaim time - m_deathExpireTime = time(nullptr); + m_deathExpireTime = GameTime::GetGameTime().count(); // pussywizard: clear movement, because after porting player will move to arena cords GetMotionMaster()->MovementExpired(); @@ -11241,7 +11236,7 @@ void Player::SendInitialPacketsBeforeAddToMap() SendEquipmentSetList(); data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4); - data.AppendPackedTime(sWorld->GetGameTime()); + data.AppendPackedTime(GameTime::GetGameTime().count()); data << float(0.01666667f); // game speed data << uint32(0); // added in 3.1.2 GetSession()->SendPacket(&data); @@ -11426,7 +11421,7 @@ void Player::ApplyEquipCooldown(Item* pItem) // Don't replace longer cooldowns by equip cooldown if we have any. SpellCooldowns::iterator itr = m_spellCooldowns.find(spellData.SpellId); - if (itr != m_spellCooldowns.end() && itr->second.itemid == pItem->GetEntry() && itr->second.end > World::GetGameTimeMS() + 30 * IN_MILLISECONDS) + if (itr != m_spellCooldowns.end() && itr->second.itemid == pItem->GetEntry() && itr->second.end > GameTime::GetGameTimeMS().count() + 30 * IN_MILLISECONDS) continue; // xinef: dont apply eqiup cooldown for spells with this attribute @@ -11730,7 +11725,7 @@ void Player::SetDailyQuestStatus(uint32 quest_id) if (!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx)) { SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, quest_id); - m_lastDailyQuestTime = time(nullptr); // last daily quest time + m_lastDailyQuestTime = GameTime::GetGameTime().count(); // last daily quest time m_DailyQuestChanged = true; break; } @@ -11739,7 +11734,7 @@ void Player::SetDailyQuestStatus(uint32 quest_id) else { m_DFQuests.insert(quest_id); - m_lastDailyQuestTime = time(nullptr); + m_lastDailyQuestTime = GameTime::GetGameTime().count(); m_DailyQuestChanged = true; } } @@ -11966,7 +11961,7 @@ void Player::SummonIfPossible(bool agree, ObjectGuid summoner_guid) } // expire and auto declined - if (m_summon_expire < time(nullptr)) + if (m_summon_expire < GameTime::GetGameTime().count()) return; // drop flag at summon @@ -12455,7 +12450,7 @@ uint32 Player::GetCorpseReclaimDelay(bool pvp) const else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)) return 0; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); // 0..2 full period // should be std::ceil(x)-1 but not floor(x) uint64 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now) / DEATH_EXPIRE_STEP : 0; @@ -12490,7 +12485,7 @@ int32 Player::CalculateCorpseReclaimDelay(bool load) } time_t expected_time = corpse->GetGhostTime() + copseReclaimDelay[count]; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (now >= expected_time) return -1; @@ -14207,7 +14202,7 @@ void Player::_SaveCharacter(bool create, CharacterDatabaseTransaction trans) stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]); stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]); stmt->setFloat(index++, finiteAlways(_restBonus)); - stmt->setUInt32(index++, uint32(time(nullptr))); + stmt->setUInt32(index++, uint32(GameTime::GetGameTime().count())); stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0)); //save, far from tavern/city //save, but in tavern/city @@ -14346,7 +14341,7 @@ void Player::_SaveCharacter(bool create, CharacterDatabaseTransaction trans) stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]); stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]); stmt->setFloat(index++, finiteAlways(_restBonus)); - stmt->setUInt32(index++, uint32(time(nullptr))); + stmt->setUInt32(index++, uint32(GameTime::GetGameTime().count())); stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0)); //save, far from tavern/city //save, but in tavern/city @@ -15379,7 +15374,7 @@ bool Player::SetCanFly(bool apply, bool packetOnly /*= false*/) return false; if (!apply) - SetFallInformation(time(nullptr), GetPositionZ()); + SetFallInformation(GameTime::GetGameTime().count(), GetPositionZ()); WorldPacket data(apply ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12); data << GetPackGUID(); @@ -15658,7 +15653,7 @@ void Player::SetRestFlag(RestFlag restFlag, uint32 triggerId /*= 0*/) if (!oldRestMask && _restFlagMask) // only set flag/time on the first rest state { - _restTime = time(nullptr); + _restTime = GameTime::GetGameTime().count(); SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); } @@ -15799,3 +15794,36 @@ std::string Player::GetPlayerName() return "|Hplayer:" + name + "|h" + color + name + "|h|r"; } + +void Player::SetSummonPoint(uint32 mapid, float x, float y, float z, uint32 delay /*= 0*/, bool asSpectator /*= false*/) +{ + m_summon_expire = GameTime::GetGameTime().count() + (delay ? delay : MAX_PLAYER_SUMMON_DELAY); + m_summon_mapid = mapid; + m_summon_x = x; + m_summon_y = y; + m_summon_z = z; + m_summon_asSpectator = asSpectator; +} + +bool Player::IsSummonAsSpectator() const +{ + return m_summon_asSpectator && m_summon_expire >= GameTime::GetGameTime().count(); +} + +bool Player::HasSpellCooldown(uint32 spell_id) const +{ + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return itr != m_spellCooldowns.end() && itr->second.end > getMSTime(); +} + +bool Player::HasSpellItemCooldown(uint32 spell_id, uint32 itemid) const +{ + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return itr != m_spellCooldowns.end() && itr->second.end > getMSTime() && itr->second.itemid == itemid; +} + +uint32 Player::GetSpellCooldownDelay(uint32 spell_id) const +{ + SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); + return uint32(itr != m_spellCooldowns.end() && itr->second.end > getMSTime() ? itr->second.end - getMSTime() : 0); +} diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index b87c4c0589..479633e5b7 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -1066,16 +1066,8 @@ public: } bool TeleportToEntryPoint(); - void SetSummonPoint(uint32 mapid, float x, float y, float z, uint32 delay = 0, bool asSpectator = false) - { - m_summon_expire = time(nullptr) + (delay ? delay : MAX_PLAYER_SUMMON_DELAY); - m_summon_mapid = mapid; - m_summon_x = x; - m_summon_y = y; - m_summon_z = z; - m_summon_asSpectator = asSpectator; - } - [[nodiscard]] bool IsSummonAsSpectator() const { return m_summon_asSpectator && m_summon_expire >= time(nullptr); } + void SetSummonPoint(uint32 mapid, float x, float y, float z, uint32 delay = 0, bool asSpectator = false); + [[nodiscard]] bool IsSummonAsSpectator() const; void SetSummonAsSpectator(bool on) { m_summon_asSpectator = on; } void SummonIfPossible(bool agree, ObjectGuid summoner_guid); [[nodiscard]] time_t GetSummonExpireTimer() const { return m_summon_expire; } @@ -1726,21 +1718,9 @@ public: void DropModCharge(SpellModifier* mod, Spell* spell); void SetSpellModTakingSpell(Spell* spell, bool apply); - [[nodiscard]] bool HasSpellCooldown(uint32 spell_id) const override - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS(); - } - [[nodiscard]] bool HasSpellItemCooldown(uint32 spell_id, uint32 itemid) const override - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() && itr->second.itemid == itemid; - } - [[nodiscard]] uint32 GetSpellCooldownDelay(uint32 spell_id) const - { - SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); - return uint32(itr != m_spellCooldowns.end() && itr->second.end > World::GetGameTimeMS() ? itr->second.end - World::GetGameTimeMS() : 0); - } + [[nodiscard]] bool HasSpellCooldown(uint32 spell_id) const override; + [[nodiscard]] bool HasSpellItemCooldown(uint32 spell_id, uint32 itemid) const override; + [[nodiscard]] uint32 GetSpellCooldownDelay(uint32 spell_id) const; void AddSpellAndCategoryCooldowns(SpellInfo const* spellInfo, uint32 itemId, Spell* spell = nullptr, bool infinityCooldown = false); void AddSpellCooldown(uint32 spell_id, uint32 itemid, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false) override; void _AddSpellCooldown(uint32 spell_id, uint16 categoryId, uint32 itemid, uint32 end_time, bool needSendToClient = false, bool forceSendToSpectator = false); diff --git a/src/server/game/Entities/Player/PlayerMisc.cpp b/src/server/game/Entities/Player/PlayerMisc.cpp index 0c016c2ea9..2d7fc957bb 100644 --- a/src/server/game/Entities/Player/PlayerMisc.cpp +++ b/src/server/game/Entities/Player/PlayerMisc.cpp @@ -16,6 +16,7 @@ */ #include "AccountMgr.h" +#include "GameTime.h" #include "MapMgr.h" #include "Player.h" #include "ScriptMgr.h" @@ -31,7 +32,7 @@ void Player::UpdateSpeakTime(uint32 specialMessageLimit) if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity())) return; - time_t current = time (nullptr); + time_t current = GameTime::GetGameTime().count(); if (m_speakTime > current) { uint32 max_count = specialMessageLimit ? specialMessageLimit : sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT); diff --git a/src/server/game/Entities/Player/PlayerQuest.cpp b/src/server/game/Entities/Player/PlayerQuest.cpp index ead2efd4de..e9d69373b7 100644 --- a/src/server/game/Entities/Player/PlayerQuest.cpp +++ b/src/server/game/Entities/Player/PlayerQuest.cpp @@ -18,6 +18,7 @@ #include "CreatureAI.h" #include "DisableMgr.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GitRevision.h" #include "GossipDef.h" #include "Group.h" @@ -553,7 +554,7 @@ void Player::AddQuest(Quest const* quest, Object* questGiver) AddTimedQuest(quest_id); questStatusData.Timer = timeAllowed * IN_MILLISECONDS; - qtime = static_cast<uint32>(time(nullptr)) + timeAllowed; + qtime = static_cast<uint32>(GameTime::GetGameTime().count()) + timeAllowed; } else questStatusData.Timer = 0; diff --git a/src/server/game/Entities/Player/PlayerStorage.cpp b/src/server/game/Entities/Player/PlayerStorage.cpp index 601d72f317..92b26813a5 100644 --- a/src/server/game/Entities/Player/PlayerStorage.cpp +++ b/src/server/game/Entities/Player/PlayerStorage.cpp @@ -37,6 +37,7 @@ #include "GameEventMgr.h" #include "GameGraveyard.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "GroupMgr.h" @@ -3995,7 +3996,7 @@ void Player::AddItemToBuyBackSlot(Item* pItem) LOG_DEBUG("entities.player.items", "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot); m_items[slot] = pItem; - time_t base = time(nullptr); + time_t base = GameTime::GetGameTime().count(); uint32 etime = uint32(base - m_logintime + (30 * 3600)); uint32 eslot = slot - BUYBACK_SLOT_START; @@ -5336,7 +5337,7 @@ bool Player::LoadFromDB(ObjectGuid playerGuid, CharacterDatabaseQueryHolder cons SaveRecallPosition(); - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); time_t logoutTime = time_t(fields[27].GetUInt32()); // since last logout (in seconds) @@ -5504,7 +5505,7 @@ bool Player::LoadFromDB(ObjectGuid playerGuid, CharacterDatabaseQueryHolder cons SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle); // has to be called after last Relocate() in Player::LoadFromDB - SetFallInformation(time(nullptr), GetPositionZ()); + SetFallInformation(GameTime::GetGameTime().count(), GetPositionZ()); _LoadSpellCooldowns(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS)); @@ -6218,7 +6219,7 @@ void Player::_LoadMail(PreparedQueryResult mailsResult, PreparedQueryResult mail m->state = MAIL_STATE_UNCHANGED; // Do not load expired pending sale mail if there is already delivery auction mail - if (m->auctionId < 0 && m->expire_time <= time(nullptr)) + if (m->auctionId < 0 && m->expire_time <= GameTime::GetGameTime().count()) { uint32 auctionId = std::abs(m->auctionId); if (pendingAuctions.count(auctionId)) @@ -6335,10 +6336,10 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) { AddTimedQuest(quest_id); - if (quest_time <= sWorld->GetGameTime()) + if (quest_time <= GameTime::GetGameTime().count()) questStatusData.Timer = 1; else - questStatusData.Timer = uint32((quest_time - sWorld->GetGameTime()) * IN_MILLISECONDS); + questStatusData.Timer = uint32((quest_time - GameTime::GetGameTime().count()) * IN_MILLISECONDS); } else quest_time = 0; @@ -6595,7 +6596,7 @@ void Player::SendRaidInfo() size_t p_counter = data.wpos(); data << uint32(counter); // placeholder - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { @@ -7535,7 +7536,7 @@ void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans) stmt->setUInt32(index++, statusItr->first); stmt->setUInt8(index++, uint8(statusItr->second.Status)); stmt->setBool(index++, statusItr->second.Explored); - stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS + sWorld->GetGameTime())); + stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS + GameTime::GetGameTime().count())); for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; i++) stmt->setUInt16(index++, statusItr->second.CreatureOrGOCount[i]); diff --git a/src/server/game/Entities/Player/PlayerUpdates.cpp b/src/server/game/Entities/Player/PlayerUpdates.cpp index 9e8bac89dd..36af2f95e2 100644 --- a/src/server/game/Entities/Player/PlayerUpdates.cpp +++ b/src/server/game/Entities/Player/PlayerUpdates.cpp @@ -20,6 +20,7 @@ #include "Channel.h" #include "ChannelMgr.h" #include "Formulas.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "Guild.h" @@ -57,7 +58,7 @@ void Player::Update(uint32 p_time) sScriptMgr->OnBeforePlayerUpdate(this, p_time); // undelivered mail - if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(nullptr)) + if (m_nextMailDelivereTime && m_nextMailDelivereTime <= GameTime::GetGameTime().count()) { SendNewMail(); ++unReadMails; @@ -82,7 +83,7 @@ void Player::Update(uint32 p_time) Unit::Update(p_time); SetMustDelayTeleport(false); - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); UpdatePvPFlag(now); UpdateFFAPvPFlag(now); @@ -239,7 +240,7 @@ void Player::Update(uint32 p_time) { if (now > lastTick && _restTime > 0) // freeze update { - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); time_t timeDiff = currTime - _restTime; if (timeDiff >= 10) // freeze update { @@ -434,7 +435,7 @@ void Player::UpdateMirrorTimers() void Player::UpdateNextMailTimeAndUnreads() { // Update the next delivery time and unread mails - time_t cTime = time(nullptr); + time_t cTime = GameTime::GetGameTime().count(); // Get the next delivery time CharacterDatabasePreparedStatement* stmtNextDeliveryTime = CharacterDatabase.GetPreparedStatement(CHAR_SEL_NEXT_MAIL_DELIVERYTIME); @@ -1126,8 +1127,8 @@ bool Player::UpdatePosition(float x, float y, float z, float orientation, void Player::UpdateHonorFields() { /// called when rewarding honor and at each save - time_t now = time_t(time(nullptr)); - time_t today = time_t(time(nullptr) / DAY) * DAY; + time_t now = time_t(GameTime::GetGameTime().count()); + time_t today = time_t(GameTime::GetGameTime().count() / DAY) * DAY; if (m_lastHonorUpdateTime < today) { @@ -1384,7 +1385,7 @@ void Player::UpdatePvPState() { if (IsPvP() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && pvpInfo.EndTimer == 0) - pvpInfo.EndTimer = time(nullptr); // start toggle-off + pvpInfo.EndTimer = GameTime::GetGameTime().count(); // start toggle-off } } @@ -1450,7 +1451,7 @@ void Player::UpdateFFAPvPState(bool reset /*= true*/) !pvpInfo.FFAPvPEndTimer) { pvpInfo.FFAPvPEndTimer = - sWorld->GetGameTime() + + GameTime::GetGameTime().count() + sWorld->getIntConfig(CONFIG_FFA_PVP_TIMER); } } @@ -1466,7 +1467,7 @@ void Player::UpdatePvP(bool state, bool _override) } else { - pvpInfo.EndTimer = time(nullptr); + pvpInfo.EndTimer = GameTime::GetGameTime().count(); SetPvP(state); } @@ -1958,7 +1959,7 @@ void Player::UpdateCorpseReclaimDelay() (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) return; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (now < m_deathExpireTime) { diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index 3cb459d14d..2e647360bf 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -21,6 +21,7 @@ #include "Common.h" #include "DBCStores.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "MapMgr.h" #include "MapReference.h" #include "ObjectMgr.h" @@ -296,7 +297,7 @@ void MotionTransport::RemovePassenger(WorldObject* passenger, bool withAll) if (Player* plr = passenger->ToPlayer()) { sScriptMgr->OnRemovePassenger(ToTransport(), plr); - plr->SetFallInformation(time(nullptr), plr->GetPositionZ()); + plr->SetFallInformation(GameTime::GetGameTime().count(), plr->GetPositionZ()); } if (withAll) @@ -945,7 +946,7 @@ void StaticTransport::UpdatePassengerPositions() if (passenger->IsInWorld()) { GetMap()->PlayerRelocation(passenger->ToPlayer(), x, y, z, o); - passenger->ToPlayer()->SetFallInformation(time(nullptr), z); + passenger->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), z); } break; case TYPEID_GAMEOBJECT: @@ -991,7 +992,7 @@ void StaticTransport::RemovePassenger(WorldObject* passenger, bool withAll) if (Player* plr = passenger->ToPlayer()) { sScriptMgr->OnRemovePassenger(ToTransport(), plr); - plr->SetFallInformation(time(nullptr), plr->GetPositionZ()); + plr->SetFallInformation(GameTime::GetGameTime().count(), plr->GetPositionZ()); } if (withAll) diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index 9d832c1d0c..b9fba23d44 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -34,6 +34,7 @@ #include "DisableMgr.h" #include "DynamicVisibility.h" #include "Formulas.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceSaveMgr.h" @@ -321,12 +322,12 @@ Unit::Unit(bool isWorldObject) : WorldObject(isWorldObject), bool GlobalCooldownMgr::HasGlobalCooldown(SpellInfo const* spellInfo) const { GlobalCooldownList::const_iterator itr = m_GlobalCooldowns.find(spellInfo->StartRecoveryCategory); - return itr != m_GlobalCooldowns.end() && itr->second.duration && getMSTimeDiff(itr->second.cast_time, World::GetGameTimeMS()) < itr->second.duration; + return itr != m_GlobalCooldowns.end() && itr->second.duration && getMSTimeDiff(itr->second.cast_time, GameTime::GetGameTimeMS().count()) < itr->second.duration; } void GlobalCooldownMgr::AddGlobalCooldown(SpellInfo const* spellInfo, uint32 gcd) { - m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, World::GetGameTimeMS()); + m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, GameTime::GetGameTimeMS().count()); } void GlobalCooldownMgr::CancelGlobalCooldown(SpellInfo const* spellInfo) @@ -499,7 +500,7 @@ void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint32 T data << uint8(0); // new in 3.1 data << GetPositionX() << GetPositionY() << GetPositionZ(); - data << World::GetGameTimeMS(); + data << GameTime::GetGameTimeMS().count(); data << uint8(0); data << uint32(sf); data << TransitTime; // Time in between points @@ -995,7 +996,7 @@ uint32 Unit::DealDamage(Unit* attacker, Unit* victim, uint32 damage, CleanDamage { // Part of Evade mechanics. DoT's and Thorns / Retribution Aura do not contribute to this if (damagetype != DOT && damage > 0 && !victim->GetOwnerGUID().IsPlayer() && (!spellProto || !spellProto->HasAura(SPELL_AURA_DAMAGE_SHIELD))) - victim->ToCreature()->SetLastDamagedTime(sWorld->GetGameTime() + MAX_AGGRO_RESET_TIME); + victim->ToCreature()->SetLastDamagedTime(GameTime::GetGameTime().count() + MAX_AGGRO_RESET_TIME); if (attacker) victim->AddThreat(attacker, float(damage), damageSchoolMask, spellProto); @@ -5358,7 +5359,7 @@ uint32 Unit::GetDiseasesByCaster(ObjectGuid casterGUID, uint8 mode) { Aura* aura = (*i)->GetBase(); if (aura && !aura->IsRemoved() && aura->GetDuration() > 0) - if ((aura->GetApplyTime() + aura->GetMaxDuration() / 1000 + 8) > (time(nullptr) + aura->GetDuration() / 1000)) + if ((aura->GetApplyTime() + aura->GetMaxDuration() / 1000 + 8) > (GameTime::GetGameTime().count() + aura->GetDuration() / 1000)) aura->SetDuration(aura->GetDuration() + 3000); } } @@ -7080,7 +7081,7 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere if (AuraEffect* aurEff = victim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x100000, 0, 0, GetGUID())) if (Aura* aur = aurEff->GetBase()) if (!aur->IsRemoved() && aur->GetDuration() > 0) - if ((aur->GetApplyTime() + aur->GetMaxDuration() / 1000 + 5) > (time(nullptr) + aur->GetDuration() / 1000) ) + if ((aur->GetApplyTime() + aur->GetMaxDuration() / 1000 + 5) > (GameTime::GetGameTime().count() + aur->GetDuration() / 1000) ) { aur->SetDuration(aur->GetDuration() + 2000); return true; @@ -12800,7 +12801,7 @@ void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry) WorldPacket data(SMSG_MOVE_SET_COLLISION_HGT, GetPackGUID().size() + 4 + 4); data << GetPackGUID(); - data << uint32(sWorld->GetGameTime()); // Packet counter + data << uint32(GameTime::GetGameTime().count()); // Packet counter data << player->GetCollisionHeight(); player->GetSession()->SendPacket(&data); } @@ -12820,7 +12821,7 @@ void Unit::Dismount() { WorldPacket data(SMSG_MOVE_SET_COLLISION_HGT, GetPackGUID().size() + 4 + 4); data << GetPackGUID(); - data << uint32(sWorld->GetGameTime()); // Packet counter + data << uint32(GameTime::GetGameTime().count()); // Packet counter data << thisPlayer->GetCollisionHeight(); thisPlayer->GetSession()->SendPacket(&data); } @@ -14246,7 +14247,7 @@ DiminishingLevels Unit::GetDiminishing(DiminishingGroup group) return DIMINISHING_LEVEL_1; // If last spell was casted more than 15 seconds ago - reset the count. - if (i->stack == 0 && getMSTimeDiff(i->hitTime, World::GetGameTimeMS()) > 15000) + if (i->stack == 0 && getMSTimeDiff(i->hitTime, GameTime::GetGameTimeMS().count()) > 15000) { i->hitCount = DIMINISHING_LEVEL_1; return DIMINISHING_LEVEL_1; @@ -14269,7 +14270,7 @@ void Unit::IncrDiminishing(DiminishingGroup group) i->hitCount += 1; return; } - m_Diminishing.push_back(DiminishingReturn(group, World::GetGameTimeMS(), DIMINISHING_LEVEL_2)); + m_Diminishing.push_back(DiminishingReturn(group, GameTime::GetGameTimeMS().count(), DIMINISHING_LEVEL_2)); } float Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32& duration, Unit* caster, DiminishingLevels Level, int32 limitduration) @@ -14366,7 +14367,7 @@ void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) i->stack -= 1; // Remember time after last aura from group removed if (i->stack == 0) - i->hitTime = World::GetGameTimeMS(); + i->hitTime = GameTime::GetGameTimeMS().count(); } break; } @@ -16634,7 +16635,7 @@ float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) bool Unit::IsUnderLastManaUseEffect() const { - return getMSTimeDiff(m_lastManaUse, World::GetGameTimeMS()) < 5000; + return getMSTimeDiff(m_lastManaUse, GameTime::GetGameTimeMS().count()) < 5000; } void Unit::SetContestedPvP(Player* attackedPlayer, bool lookForNearContestedGuards) @@ -17862,7 +17863,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true); // if charmed two demons the same session, the 2nd gets the 1st one's name - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(GameTime::GetGameTime().count())); // cast can't be helped } } GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, GetFollowAngle()); @@ -19099,7 +19100,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) if (player) { - player->SetFallInformation(time(nullptr), GetPositionZ()); + player->SetFallInformation(GameTime::GetGameTime().count(), GetPositionZ()); sScriptMgr->AnticheatSetUnderACKmount(player); sScriptMgr->AnticheatSetSkipOnePacketForASH(player, true); @@ -19181,7 +19182,7 @@ void Unit::BuildMovementPacket(ByteBuffer* data) const { *data << uint32(GetUnitMovementFlags()); // movement flags *data << uint16(GetExtraUnitMovementFlags()); // 2.3.0 - *data << uint32(World::GetGameTimeMS()); // time / counter + *data << uint32(GameTime::GetGameTimeMS().count()); // time / counter *data << GetPositionX(); *data << GetPositionY(); *data << GetPositionZ(); diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index d5b363a77e..ec31e266f0 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -19,6 +19,7 @@ #include "BattlegroundMgr.h" #include "DisableMgr.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GossipDef.h" #include "Language.h" #include "Log.h" @@ -47,7 +48,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const default: case GAMEEVENT_NORMAL: { - time_t currenttime = time(nullptr); + time_t currenttime = GameTime::GetGameTime().count(); // Get the event information return mGameEvent[entry].start < currenttime && currenttime < mGameEvent[entry].end @@ -64,7 +65,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const // if inactive world event, check the prerequisite events case GAMEEVENT_WORLD_INACTIVE: { - time_t currenttime = time(nullptr); + time_t currenttime = GameTime::GetGameTime().count(); for (std::set<uint16>::const_iterator itr = mGameEvent[entry].prerequisite_events.begin(); itr != mGameEvent[entry].prerequisite_events.end(); ++itr) { if ((mGameEvent[*itr].state != GAMEEVENT_WORLD_NEXTPHASE && mGameEvent[*itr].state != GAMEEVENT_WORLD_FINISHED) || // if prereq not in nextphase or finished state, then can't start this one @@ -80,7 +81,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const uint32 GameEventMgr::NextCheck(uint16 entry) const { - time_t currenttime = time(nullptr); + time_t currenttime = GameTime::GetGameTime().count(); // for NEXTPHASE state world events, return the delay to start the next event, so the followup event will be checked correctly if ((mGameEvent[entry].state == GAMEEVENT_WORLD_NEXTPHASE || mGameEvent[entry].state == GAMEEVENT_WORLD_FINISHED) && mGameEvent[entry].nextstart >= currenttime) @@ -145,7 +146,7 @@ bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) ApplyNewEvent(event_id); if (overwrite) { - mGameEvent[event_id].start = time(nullptr); + mGameEvent[event_id].start = GameTime::GetGameTime().count(); if (data.end <= data.start) data.end = data.start + data.length; } @@ -157,7 +158,7 @@ bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) auto itr = _gameEventSeasonalQuestsMap.find(event_id); if (itr != _gameEventSeasonalQuestsMap.end() && !itr->second.empty()) { - sWorld->setWorldState(event_id, sWorld->GetGameTime()); + sWorld->setWorldState(event_id, GameTime::GetGameTime().count()); } return false; @@ -203,7 +204,7 @@ void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) if (overwrite && !serverwide_evt) { - data.start = time(nullptr) - data.length * MINUTE; + data.start = GameTime::GetGameTime().count() - data.length * MINUTE; if (data.end <= data.start) data.end = data.start + data.length; } @@ -268,7 +269,7 @@ void GameEventMgr::LoadFromDB() pGameEvent.start = time_t(starttime); uint64 endtime = fields[2].GetUInt64(); if (fields[2].IsNull()) - endtime = time(nullptr) + 63072000; // add 2 years to current date + endtime = GameTime::GetGameTime().count() + 63072000; // add 2 years to current date pGameEvent.end = time_t(endtime); pGameEvent.occurence = fields[3].GetUInt64(); pGameEvent.length = fields[4].GetUInt64(); @@ -1126,7 +1127,7 @@ void GameEventMgr::StartArenaSeason() uint32 GameEventMgr::Update() // return the next event delay in ms { - time_t currenttime = time(nullptr); + time_t currenttime = GameTime::GetGameTime().count(); uint32 nextEventDelay = max_ge_check_delay; // 1 day uint32 calcDelay; std::set<uint16> activate, deactivate; @@ -1720,7 +1721,7 @@ bool GameEventMgr::CheckOneGameEventConditions(uint16 event_id) // set the followup events' start time if (!mGameEvent[event_id].nextstart) { - time_t currenttime = time(nullptr); + time_t currenttime = GameTime::GetGameTime().count(); mGameEvent[event_id].nextstart = currenttime + mGameEvent[event_id].length * 60; } return true; @@ -1840,7 +1841,7 @@ void GameEventMgr::SetHolidayEventTime(GameEventData& event) bool singleDate = ((holiday->Date[0] >> 24) & 0x1F) == 31; // Events with fixed date within year have - 1 - time_t curTime = time(nullptr); + time_t curTime = GameTime::GetGameTime().count(); for (uint8 i = 0; i < MAX_HOLIDAY_DATES && holiday->Date[i]; ++i) { @@ -1890,7 +1891,7 @@ void GameEventMgr::SetHolidayEventTime(GameEventData& event) uint32 GameEventMgr::GetHolidayEventId(uint32 holidayId) const { - auto const events = sGameEventMgr->GetEventMap(); + auto const& events = sGameEventMgr->GetEventMap(); for (auto const& eventEntry : events) { diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index 63c92c1377..41b7e31cd6 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -25,6 +25,7 @@ #include "DatabaseEnv.h" #include "DisableMgr.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "GossipDef.h" #include "GroupMgr.h" #include "GuildMgr.h" @@ -5923,7 +5924,7 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) { uint32 oldMSTime = getMSTime(); - time_t curTime = time(nullptr); + time_t curTime = GameTime::GetGameTime().count(); CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_EXPIRED_MAIL); stmt->setUInt32(0, uint32(curTime)); diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index 3049b4c199..f075ee5870 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -19,6 +19,7 @@ #include "Battleground.h" #include "BattlegroundMgr.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "GroupMgr.h" #include "InstanceSaveMgr.h" #include "LFG.h" @@ -2410,3 +2411,14 @@ void Group::ToggleGroupMemberFlag(member_witerator slot, uint8 flag, bool apply) else slot->flags &= ~flag; } + +uint32 Group::GetDifficultyChangePreventionTime() const +{ + return _difficultyChangePreventionTime > GameTime::GetGameTime().count() ? _difficultyChangePreventionTime - GameTime::GetGameTime().count() : 0; +} + +void Group::SetDifficultyChangePrevention(DifficultyPreventionChangeType type) +{ + _difficultyChangePreventionTime = GameTime::GetGameTime().count() + MINUTE; + _difficultyChangePreventionType = type; +} diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index 37f827852a..9028b69143 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -309,13 +309,9 @@ public: bool IsLfgHeroic() const { return isLFGGroup() && (m_lfgGroupFlags & GROUP_LFG_FLAG_IS_HEROIC); } // Difficulty Change - uint32 GetDifficultyChangePreventionTime() const { return _difficultyChangePreventionTime > time(nullptr) ? _difficultyChangePreventionTime - time(nullptr) : 0; } + uint32 GetDifficultyChangePreventionTime() const; DifficultyPreventionChangeType GetDifficultyChangePreventionReason() const { return _difficultyChangePreventionType; } - void SetDifficultyChangePrevention(DifficultyPreventionChangeType type) - { - _difficultyChangePreventionTime = time(nullptr) + MINUTE; - _difficultyChangePreventionType = type; - } + void SetDifficultyChangePrevention(DifficultyPreventionChangeType type); protected: void _homebindIfInstance(Player* player); diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index fd0e718ff2..45913fdc2b 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -23,6 +23,7 @@ #include "Chat.h" #include "Config.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "GuildMgr.h" #include "GuildPackets.h" #include "Language.h" @@ -172,6 +173,9 @@ inline uint32 Guild::LogHolder<Entry>::GetNextGUID() return m_nextGUID; } +Guild::LogEntry::LogEntry(uint32 guildId, ObjectGuid::LowType guid) : + m_guildId(guildId), m_guid(guid), m_timestamp(GameTime::GetGameTime().count()) { } + // EventLogEntry void Guild::EventLogEntry::SaveToDB(CharacterDatabaseTransaction trans) const { @@ -201,7 +205,7 @@ void Guild::EventLogEntry::WritePacket(WorldPackets::Guild::GuildEventLogQueryRe eventEntry.PlayerGUID = playerGUID; eventEntry.OtherGUID = otherGUID; eventEntry.TransactionType = uint8(m_eventType); - eventEntry.TransactionDate = uint32(::time(nullptr) - m_timestamp); + eventEntry.TransactionDate = uint32(GameTime::GetGameTime().count() - m_timestamp); eventEntry.RankID = uint8(m_newRank); packet.Entry.push_back(eventEntry); } @@ -235,7 +239,7 @@ void Guild::BankEventLogEntry::WritePacket(WorldPackets::Guild::GuildBankLogQuer { WorldPackets::Guild::GuildBankLogEntry bankLogEntry; bankLogEntry.PlayerGUID = ObjectGuid::Create<HighGuid::Player>(m_playerGuid.GetCounter()); - bankLogEntry.TimeOffset = int32(::time(nullptr) - m_timestamp); + bankLogEntry.TimeOffset = int32(GameTime::GetGameTime().count() - m_timestamp); bankLogEntry.EntryType = int8(m_eventType); switch(m_eventType) @@ -576,6 +580,11 @@ void Guild::Member::ChangeRank(uint8 newRank) CharacterDatabase.Execute(stmt); } +void Guild::Member::UpdateLogoutTime() +{ + m_logoutTime = GameTime::GetGameTime().count(); +} + void Guild::Member::SaveToDB(CharacterDatabaseTransaction trans) const { CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER); @@ -1050,7 +1059,7 @@ bool Guild::Create(Player* pLeader, std::string_view name) m_info = ""; m_motd = "No message set."; m_bankMoney = 0; - m_createdDate = sWorld->GetGameTime(); + m_createdDate = GameTime::GetGameTime().count(); LOG_DEBUG("guild", "GUILD: creating guild [%s] for leader %s (%s)", m_name.c_str(), pLeader->GetName().c_str(), m_leaderGuid.ToString().c_str()); @@ -1198,7 +1207,7 @@ void Guild::HandleRoster(WorldSession* session) memberData.Guid = member.GetGUID(); memberData.RankID = int32(member.GetRankId()); memberData.AreaID = int32(member.GetZoneId()); - memberData.LastSave = float(float(::time(nullptr) - member.GetLogoutTime()) / DAY); + memberData.LastSave = float(float(GameTime::GetGameTime().count() - member.GetLogoutTime()) / DAY); memberData.Status = member.GetFlags(); memberData.Level = member.GetLevel(); diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 2d40407dda..1c89b7bd47 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -305,7 +305,6 @@ public: // pussywizard: public class Member m_level(0), m_class(0), m_flags(GUILDMEMBER_STATUS_NONE), - m_logoutTime(::time(nullptr)), m_accountId(0), m_rankId(rankId) { @@ -343,7 +342,7 @@ public: // pussywizard: public class Member void ChangeRank(uint8 newRank); - inline void UpdateLogoutTime() { m_logoutTime = ::time(nullptr); } + void UpdateLogoutTime(); inline bool IsRank(uint8 rankId) const { return m_rankId == rankId; } inline bool IsRankNotLower(uint8 rankId) const { return m_rankId <= rankId; } inline bool IsSamePlayer(ObjectGuid guid) const { return m_guid == guid; } @@ -399,7 +398,7 @@ private: class LogEntry { public: - LogEntry(uint32 guildId, ObjectGuid::LowType guid) : m_guildId(guildId), m_guid(guid), m_timestamp(::time(nullptr)) { } + LogEntry(uint32 guildId, ObjectGuid::LowType guid); LogEntry(uint32 guildId, ObjectGuid::LowType guid, time_t timestamp) : m_guildId(guildId), m_guid(guid), m_timestamp(timestamp) { } virtual ~LogEntry() { } diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index dd06418101..c9bb6cbae0 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -18,6 +18,7 @@ #include "AsyncAuctionListing.h" #include "AuctionHouseMgr.h" #include "Chat.h" +#include "GameTime.h" #include "Language.h" #include "Log.h" #include "ObjectMgr.h" @@ -299,7 +300,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = ObjectGuid::Empty; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(nullptr) + auctionTime; + AH->expire_time = GameTime::GetGameTime().count() + auctionTime; AH->deposit = deposit; AH->auctionHouseEntry = auctionHouseEntry; @@ -340,7 +341,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = ObjectGuid::Empty; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(nullptr) + auctionTime; + AH->expire_time = GameTime::GetGameTime().count() + auctionTime; AH->deposit = deposit; AH->auctionHouseEntry = auctionHouseEntry; @@ -661,7 +662,7 @@ void WorldSession::HandleAuctionListOwnerItems(WorldPacket& recvData) // pussywizard: const uint32 delay = 4500; - const uint32 now = World::GetGameTimeMS(); + const uint32 now = GameTime::GetGameTimeMS().count(); if (_lastAuctionListOwnerItemsMSTime > now) // list is pending return; uint32 diff = getMSTimeDiff(_lastAuctionListOwnerItemsMSTime, now); @@ -676,7 +677,7 @@ void WorldSession::HandleAuctionListOwnerItemsEvent(ObjectGuid creatureGuid) { LOG_DEBUG("network", "WORLD: Received CMSG_AUCTION_LIST_OWNER_ITEMS"); - _lastAuctionListOwnerItemsMSTime = World::GetGameTimeMS(); // pussywizard + _lastAuctionListOwnerItemsMSTime = GameTime::GetGameTimeMS().count(); // pussywizard Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(creatureGuid, UNIT_NPC_FLAG_AUCTIONEER); if (!creature) @@ -750,7 +751,7 @@ void WorldSession::HandleAuctionListItems(WorldPacket& recvData) // pussywizard: const uint32 delay = 2000; - const uint32 now = World::GetGameTimeMS(); + const uint32 now = GameTime::GetGameTimeMS().count(); uint32 diff = getMSTimeDiff(_lastAuctionListItemsMSTime, now); if (diff > delay) { diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index a0ddff9667..172d86c732 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -21,6 +21,7 @@ #include "BattlegroundMgr.h" #include "Chat.h" #include "DisableMgr.h" +#include "GameTime.h" #include "Group.h" #include "Language.h" #include "ObjectAccessor.h" @@ -548,7 +549,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket& /*recvData*/) if (!bg) continue; - uint32 remainingTime = (World::GetGameTimeMS() < ginfo.RemoveInviteTime ? getMSTimeDiff(World::GetGameTimeMS(), ginfo.RemoveInviteTime) : 1); + uint32 remainingTime = (GameTime::GetGameTimeMS().count() < ginfo.RemoveInviteTime ? getMSTimeDiff(GameTime::GetGameTimeMS().count(), ginfo.RemoveInviteTime) : 1); sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, i, STATUS_WAIT_JOIN, remainingTime, 0, ginfo.ArenaType, TEAM_NEUTRAL, bg->isRated(), ginfo.BgTypeId); SendPacket(&data); } @@ -565,7 +566,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket& /*recvData*/) continue; uint32 avgWaitTime = bgQueue.GetAverageQueueWaitTime(&ginfo); - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bgt, i, STATUS_WAIT_QUEUE, avgWaitTime, getMSTimeDiff(ginfo.JoinTime, World::GetGameTimeMS()), ginfo.ArenaType, TEAM_NEUTRAL, ginfo.IsRated); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bgt, i, STATUS_WAIT_QUEUE, avgWaitTime, getMSTimeDiff(ginfo.JoinTime, GameTime::GetGameTimeMS().count()), ginfo.ArenaType, TEAM_NEUTRAL, ginfo.IsRated); SendPacket(&data); } } diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index 95f444ff47..c1bf6142cb 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -38,6 +38,7 @@ Copied events should probably have a new owner #include "DatabaseEnv.h" #include "DisableMgr.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "GuildMgr.h" #include "InstanceSaveMgr.h" #include "Log.h" @@ -46,14 +47,14 @@ Copied events should probably have a new owner #include "Player.h" #include "SocialMgr.h" #include "WorldSession.h" -#include "utf8.h" +#include <utf8.h> void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recvData*/) { ObjectGuid guid = _player->GetGUID(); LOG_DEBUG("network", "CMSG_CALENDAR_GET_CALENDAR [%s]", guid.ToString().c_str()); - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); WorldPacket data(SMSG_CALENDAR_SEND_CALENDAR, 1000); // Average size if no instance @@ -260,7 +261,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) + if (time_t(eventPackedTime) < (GameTime::GetGameTime().count() - time_t(86400L))) { recvData.rfinish(); sCalendarMgr->SendCalendarCommandResult(guid, CALENDAR_ERROR_EVENT_PASSED); @@ -298,13 +299,13 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) } } - if (GetCalendarEventCreationCooldown() > time(nullptr)) + if (GetCalendarEventCreationCooldown() > GameTime::GetGameTime().count()) { recvData.rfinish(); sCalendarMgr->SendCalendarCommandResult(guid, CALENDAR_ERROR_INTERNAL); return; } - SetCalendarEventCreationCooldown(time(nullptr) + CALENDAR_CREATE_EVENT_COOLDOWN); + SetCalendarEventCreationCooldown(GameTime::GetGameTime().count() + CALENDAR_CREATE_EVENT_COOLDOWN); CalendarEvent* calendarEvent = new CalendarEvent(sCalendarMgr->GetFreeEventId(), guid, 0, CalendarEventType(type), dungeonId, time_t(eventPackedTime), flags, time_t(unkPackedTime), title, description); @@ -392,7 +393,7 @@ void WorldSession::HandleCalendarUpdateEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) + if (time_t(eventPackedTime) < (GameTime::GetGameTime().count() - time_t(86400L))) { recvData.rfinish(); return; @@ -449,7 +450,7 @@ void WorldSession::HandleCalendarCopyEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventTime) < (time(nullptr) - time_t(86400L))) + if (time_t(eventTime) < (GameTime::GetGameTime().count() - time_t(86400L))) { recvData.rfinish(); sCalendarMgr->SendCalendarCommandResult(guid, CALENDAR_ERROR_EVENT_PASSED); @@ -494,12 +495,12 @@ void WorldSession::HandleCalendarCopyEvent(WorldPacket& recvData) } } - if (GetCalendarEventCreationCooldown() > time(nullptr)) + if (GetCalendarEventCreationCooldown() > GameTime::GetGameTime().count()) { sCalendarMgr->SendCalendarCommandResult(guid, CALENDAR_ERROR_INTERNAL); return; } - SetCalendarEventCreationCooldown(time(nullptr) + CALENDAR_CREATE_EVENT_COOLDOWN); + SetCalendarEventCreationCooldown(GameTime::GetGameTime().count() + CALENDAR_CREATE_EVENT_COOLDOWN); CalendarEvent* newEvent = new CalendarEvent(*oldEvent, sCalendarMgr->GetFreeEventId()); newEvent->SetEventTime(time_t(eventTime)); @@ -633,7 +634,7 @@ void WorldSession::HandleCalendarEventSignup(WorldPacket& recvData) } CalendarInviteStatus status = tentative ? CALENDAR_STATUS_TENTATIVE : CALENDAR_STATUS_SIGNED_UP; - CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, time(nullptr), status, CALENDAR_RANK_PLAYER, ""); + CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, GameTime::GetGameTime().count(), status, CALENDAR_RANK_PLAYER, ""); sCalendarMgr->AddInvite(calendarEvent, invite); sCalendarMgr->SendCalendarClearPendingAction(guid); } @@ -665,7 +666,7 @@ void WorldSession::HandleCalendarEventRsvp(WorldPacket& recvData) if (CalendarInvite* invite = sCalendarMgr->GetInvite(inviteId)) { invite->SetStatus(CalendarInviteStatus(status)); - invite->SetStatusTime(time(nullptr)); + invite->SetStatusTime(GameTime::GetGameTime().count()); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -725,7 +726,7 @@ void WorldSession::HandleCalendarEventStatus(WorldPacket& recvData) if (CalendarInvite* invite = sCalendarMgr->GetInvite(inviteId)) { invite->SetStatus((CalendarInviteStatus)status); - invite->SetStatusTime(time(nullptr)); + invite->SetStatusTime(GameTime::GetGameTime().count()); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -824,7 +825,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) void WorldSession::SendCalendarRaidLockout(InstanceSave const* save, bool add) { LOG_DEBUG("network", "%s", add ? "SMSG_CALENDAR_RAID_LOCKOUT_ADDED" : "SMSG_CALENDAR_RAID_LOCKOUT_REMOVED"); - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_REMOVED, (add ? 4 : 0) + 4 + 4 + 4 + 8); if (add) @@ -842,7 +843,7 @@ void WorldSession::SendCalendarRaidLockout(InstanceSave const* save, bool add) void WorldSession::SendCalendarRaidLockoutUpdated(InstanceSave const* save, bool isExtended) { - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); time_t resetTime = isExtended ? save->GetExtendedResetTime() : save->GetResetTime(); time_t resetTimeOp = isExtended ? save->GetResetTime() : save->GetExtendedResetTime(); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_UPDATED, 4 + 4 + 4 + 4 + 8); diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index c6d98c3e5f..6c98a4bcc9 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -25,6 +25,7 @@ #include "Chat.h" #include "Common.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "GitRevision.h" #include "Group.h" #include "Guild.h" @@ -124,7 +125,7 @@ bool LoginQueryHolder::Initialize() stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL); stmt->setUInt32(0, lowGuid); - stmt->setUInt32(1, uint32(time(nullptr))); + stmt->setUInt32(1, uint32(GameTime::GetGameTime().count())); res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAILS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS); @@ -914,7 +915,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder const& holder) loginStmt->setUInt32(1, GetAccountId()); LoginDatabase.Execute(loginStmt); - pCurrChar->SetInGameTime(World::GetGameTimeMS()); + pCurrChar->SetInGameTime(GameTime::GetGameTimeMS().count()); // announce group about member online (must be after add to player list to receive announce to self) if (Group* group = pCurrChar->GetGroup()) @@ -928,7 +929,7 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder const& holder) if (mapDiff->resetTime) if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(pCurrChar->GetMap()->GetId(), pCurrChar->GetMap()->GetDifficulty())) { - uint32 timeleft = uint32(timeReset - time(nullptr)); + uint32 timeleft = uint32(timeReset - GameTime::GetGameTime().count()); pCurrChar->SendInstanceResetWarning(pCurrChar->GetMap()->GetId(), pCurrChar->GetMap()->GetDifficulty(), timeleft, true); } @@ -1179,7 +1180,7 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) uint32 currZone, currArea; pCurrChar->GetZoneAndAreaId(currZone, currArea); pCurrChar->SendInitWorldStates(currZone, currArea); - pCurrChar->SetInGameTime(World::GetGameTimeMS()); + pCurrChar->SetInGameTime(GameTime::GetGameTimeMS().count()); // Xinef: we need to resend all spell mods for (uint16 Opcode = SMSG_SET_FLAT_SPELL_MODIFIER; Opcode <= SMSG_SET_PCT_SPELL_MODIFIER; ++Opcode) // PCT = FLAT+1 @@ -1224,7 +1225,7 @@ void WorldSession::HandlePlayerLoginToCharInWorld(Player* pCurrChar) if (mapDiff->resetTime) if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(pCurrChar->GetMap()->GetId(), pCurrChar->GetMap()->GetDifficulty())) { - uint32 timeleft = uint32(timeReset - time(nullptr)); + uint32 timeleft = uint32(timeReset - GameTime::GetGameTime().count()); GetPlayer()->SendInstanceResetWarning(pCurrChar->GetMap()->GetId(), pCurrChar->GetMap()->GetDifficulty(), timeleft, true); } diff --git a/src/server/game/Handlers/ChatHandler.cpp b/src/server/game/Handlers/ChatHandler.cpp index b1b2bc6c87..00ea787d44 100644 --- a/src/server/game/Handlers/ChatHandler.cpp +++ b/src/server/game/Handlers/ChatHandler.cpp @@ -21,6 +21,7 @@ #include "Chat.h" #include "ChatPackets.h" #include "Common.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "Guild.h" @@ -297,7 +298,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) if (!_player->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); + std::string timeStr = secsToTimeString(m_muteTime - GameTime::GetGameTime().count()); SendNotification(GetAcoreString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); return; } @@ -729,7 +730,7 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData) if (!GetPlayer()->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); + std::string timeStr = secsToTimeString(m_muteTime - GameTime::GetGameTime().count()); SendNotification(GetAcoreString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); return; } diff --git a/src/server/game/Handlers/DuelHandler.cpp b/src/server/game/Handlers/DuelHandler.cpp index 3d55e79e7d..71555f8652 100644 --- a/src/server/game/Handlers/DuelHandler.cpp +++ b/src/server/game/Handlers/DuelHandler.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Log.h" #include "Opcodes.h" #include "Player.h" @@ -38,7 +39,7 @@ void WorldSession::HandleDuelAcceptedOpcode(WorldPacket& recvPacket) LOG_DEBUG("network.opcode", "Player 1 is: %s (%s)", player->GetGUID().ToString().c_str(), player->GetName().c_str()); LOG_DEBUG("network.opcode", "Player 2 is: %s (%s)", target->GetGUID().ToString().c_str(), target->GetName().c_str()); - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); player->duel->StartTime = now + 3; target->duel->StartTime = now + 3; diff --git a/src/server/game/Handlers/LFGHandler.cpp b/src/server/game/Handlers/LFGHandler.cpp index 12b9c0b1f7..c78c880b21 100644 --- a/src/server/game/Handlers/LFGHandler.cpp +++ b/src/server/game/Handlers/LFGHandler.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Group.h" #include "LFGMgr.h" #include "ObjectMgr.h" @@ -524,7 +525,7 @@ void WorldSession::SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot) lfg::LfgAnswer playerVote = boot.votes.find(guid)->second; uint8 votesNum = 0; uint8 agreeNum = 0; - uint32 secsleft = boot.cancelTime - time(nullptr); + uint32 secsleft = boot.cancelTime - GameTime::GetGameTime().count(); for (lfg::LfgAnswerContainer::const_iterator it = boot.votes.begin(); it != boot.votes.end(); ++it) { if (it->second != lfg::LFG_ANSWER_PENDING) diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index a1e51c86b3..7b3a394959 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -19,6 +19,7 @@ #include "CharacterCache.h" #include "DBCStores.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Item.h" #include "Language.h" #include "Log.h" @@ -401,7 +402,7 @@ void WorldSession::HandleMailReturnToSender(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > GameTime::GetGameTime().count()) { player->SendMailResult(mailId, MAIL_RETURNED_TO_SENDER, MAIL_ERR_INTERNAL_ERROR); return; @@ -465,7 +466,7 @@ void WorldSession::HandleMailTakeItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > GameTime::GetGameTime().count()) { player->SendMailResult(mailId, MAIL_ITEM_TAKEN, MAIL_ERR_INTERNAL_ERROR); return; @@ -571,7 +572,7 @@ void WorldSession::HandleMailTakeMoney(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > GameTime::GetGameTime().count()) { player->SendMailResult(mailId, MAIL_MONEY_TAKEN, MAIL_ERR_INTERNAL_ERROR); return; @@ -613,7 +614,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) WorldPacket data(SMSG_MAIL_LIST_RESULT, (200)); // guess size data << uint32(0); // real mail's count data << uint8(0); // mail's count - time_t cur_time = time(nullptr); + time_t cur_time = GameTime::GetGameTime().count(); for (Mail const* mail : player->GetMails()) { @@ -675,7 +676,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) data << uint32(mail->stationery); // stationery (Stationery.dbc) data << uint32(mail->money); // Gold data << uint32(mail->checked); // flags - data << float(float(mail->expire_time - time(nullptr)) / DAY); // Time + data << float(float(mail->expire_time - GameTime::GetGameTime().count()) / DAY); // Time data << uint32(mail->mailTemplateId); // mail template (MailTemplate.dbc) data << subject; // Subject string - once 00, when mail type = 3, max 256 data << body; // message? max 8000 @@ -739,7 +740,7 @@ void WorldSession::HandleMailCreateTextItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr) || (m->checked & MAIL_CHECK_MASK_COPIED)) + if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > GameTime::GetGameTime().count() || (m->checked & MAIL_CHECK_MASK_COPIED)) { player->SendMailResult(mailId, MAIL_MADE_PERMANENT, MAIL_ERR_INTERNAL_ERROR); return; @@ -802,7 +803,7 @@ void WorldSession::HandleQueryNextMailTime(WorldPacket& /*recvData*/) data << uint32(0); // count uint32 count = 0; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); std::set<uint32> sentSenders; for (Mail const* mail : _player->GetMails()) { diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 2af164a836..3cf4ec18db 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -26,6 +26,7 @@ #include "DBCEnums.h" #include "DatabaseEnv.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GossipDef.h" #include "Group.h" #include "GuildMgr.h" @@ -464,7 +465,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPackets::Character::LogoutRequ GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } - SetLogoutStartTime(time(nullptr)); + SetLogoutStartTime(GameTime::GetGameTime().count()); } void WorldSession::HandlePlayerLogoutOpcode(WorldPackets::Character::PlayerLogout& /*playerLogout*/) @@ -651,7 +652,7 @@ void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recv_data) return; // prevent resurrect before 30-sec delay after body release not finished - if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(time(nullptr))) + if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(GameTime::GetGameTime().count())) return; if (!corpse->IsWithinDistInMap(_player, CORPSE_RECLAIM_RADIUS, true)) @@ -1570,7 +1571,7 @@ void WorldSession::HandleWorldStateUITimerUpdate(WorldPacket& /*recv_data*/) LOG_DEBUG("network", "WORLD: CMSG_WORLD_STATE_UI_TIMER_UPDATE"); WorldPacket data(SMSG_WORLD_STATE_UI_TIMER_UPDATE, 4); - data << uint32(time(nullptr)); + data << uint32(GameTime::GetGameTime().count()); SendPacket(&data); } diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 7426c40ad9..b9fbf1500b 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -22,6 +22,7 @@ #include "Chat.h" #include "Corpse.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "InstanceSaveMgr.h" #include "Log.h" #include "MapMgr.h" @@ -216,7 +217,7 @@ void WorldSession::HandleMoveWorldportAck() if (mapDiff->resetTime) if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(mEntry->MapID, diff)) { - uint32 timeleft = uint32(timeReset - time(nullptr)); + uint32 timeleft = uint32(timeReset - GameTime::GetGameTime().count()); GetPlayer()->SendInstanceResetWarning(mEntry->MapID, diff, timeleft, true); } allowMount = mInstance->AllowMount; diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index 671333b885..b7682d6208 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -18,6 +18,7 @@ #include "Common.h" #include "CreatureAI.h" #include "DisableMgr.h" +#include "GameTime.h" #include "Group.h" #include "Log.h" #include "ObjectAccessor.h" @@ -923,7 +924,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) CharacterDatabase.CommitTransaction(trans); - pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped + pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(GameTime::GetGameTime().count())); // cast can't be helped } void WorldSession::HandlePetAbandon(WorldPacket& recvData) diff --git a/src/server/game/Handlers/QueryHandler.cpp b/src/server/game/Handlers/QueryHandler.cpp index e32c923b08..7d973b1c5f 100644 --- a/src/server/game/Handlers/QueryHandler.cpp +++ b/src/server/game/Handlers/QueryHandler.cpp @@ -16,6 +16,7 @@ */ #include "Common.h" +#include "GameTime.h" #include "Log.h" #include "MapMgr.h" #include "NPCHandler.h" @@ -81,9 +82,11 @@ void WorldSession::HandleQueryTimeOpcode(WorldPacket& /*recvData*/) void WorldSession::SendQueryTimeResponse() { + auto timeResponse = sWorld->GetNextDailyQuestsResetTime() - GameTime::GetGameTime(); + WorldPacket data(SMSG_QUERY_TIME_RESPONSE, 4 + 4); - data << uint32(time(nullptr)); - data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(nullptr)); + data << uint32(GameTime::GetGameTime().count()); + data << uint32(timeResponse.count()); SendPacket(&data); } diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index b7485443a8..acc3528c1e 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -16,6 +16,7 @@ */ #include "Chat.h" +#include "GameTime.h" #include "Language.h" #include "Opcodes.h" #include "Player.h" @@ -24,7 +25,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "zlib.h" +#include <zlib.h> void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recvData) { @@ -272,7 +273,7 @@ void WorldSession::HandleReportLag(WorldPacket& recv_data) stmt->setFloat (4, y); stmt->setFloat (5, z); stmt->setUInt32(6, GetLatency()); - stmt->setUInt32(7, time(nullptr)); + stmt->setUInt32(7, GameTime::GetGameTime().count()); CharacterDatabase.Execute(stmt); } diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index 717b2a0d52..2b71465b1a 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -18,6 +18,7 @@ #include "InstanceSaveMgr.h" #include "Common.h" #include "Config.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" @@ -93,7 +94,7 @@ InstanceSave* InstanceSaveMgr::AddInstanceSave(uint32 mapId, uint32 instanceId, } else { - resetTime = time(nullptr) + 3 * DAY; // normals expire after 3 days even if someone is still bound to them, cleared on startup + resetTime = GameTime::GetGameTime().count() + 3 * DAY; // normals expire after 3 days even if someone is still bound to them, cleared on startup extendedResetTime = 0; } InstanceSave* save = new InstanceSave(mapId, instanceId, difficulty, resetTime, extendedResetTime); @@ -260,7 +261,7 @@ void InstanceSaveMgr::LoadInstances() void InstanceSaveMgr::LoadResetTimes() { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); time_t today = (now / DAY) * DAY; // load the global respawn times for raid/heroic instances @@ -423,7 +424,7 @@ void InstanceSaveMgr::ScheduleReset(time_t time, InstResetEvent event) void InstanceSaveMgr::Update() { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); time_t t; bool resetOccurred = false; @@ -522,7 +523,7 @@ void InstanceSaveMgr::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool if (!mapEntry->Instanceable()) return; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (!warn) { diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index 0ea6008a21..9d8f9f62da 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -21,6 +21,7 @@ #include "CalendarMgr.h" #include "CharacterCache.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Item.h" #include "Log.h" #include "ObjectMgr.h" @@ -206,7 +207,7 @@ void MailDraft::SendMailTo(CharacterDatabaseTransaction trans, MailReceiver cons uint32 mailId = sObjectMgr->GenerateMailID(); - time_t deliver_time = time(nullptr) + deliver_delay; + time_t deliver_time = GameTime::GetGameTime().count() + deliver_delay; //expire time if COD 3 days, if no COD 30 days, if auction sale pending 1 hour uint32 expire_delay; diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index 188aa22405..a4f2e74a31 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -21,6 +21,7 @@ #include "Chat.h" #include "DisableMgr.h" #include "DynamicTree.h" +#include "GameTime.h" #include "Geometry.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" @@ -2946,7 +2947,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) // increase current instances (hourly limit) // xinef: specific instances are still limited if (!group || !group->isLFGGroup() || !group->IsLfgRandomInstance()) - player->AddInstanceEnterTime(GetInstanceId(), time(nullptr)); + player->AddInstanceEnterTime(GetInstanceId(), GameTime::GetGameTime().count()); if (!playerBind->perm && !mapSave->CanReset() && group && !group->isLFGGroup() && !group->IsLfgRandomInstance()) { @@ -3297,7 +3298,7 @@ void Map::SaveCreatureRespawnTime(ObjectGuid::LowType spawnId, time_t& respawnTi return; } - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (GetInstanceResetPeriod() > 0 && respawnTime - now + 5 >= GetInstanceResetPeriod()) respawnTime = now + YEAR; @@ -3331,7 +3332,7 @@ void Map::SaveGORespawnTime(ObjectGuid::LowType spawnId, time_t& respawnTime) return; } - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (GetInstanceResetPeriod() > 0 && respawnTime - now + 5 >= GetInstanceResetPeriod()) respawnTime = now + YEAR; @@ -3622,7 +3623,7 @@ Corpse* Map::ConvertCorpseToBones(ObjectGuid const ownerGuid, bool insignia /*= void Map::RemoveOldCorpses() { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); std::vector<ObjectGuid> corpses; corpses.reserve(_corpsesByPlayer.size()); diff --git a/src/server/game/Maps/MapMgr.cpp b/src/server/game/Maps/MapMgr.cpp index dd2956fc3b..51b09800f0 100644 --- a/src/server/game/Maps/MapMgr.cpp +++ b/src/server/game/Maps/MapMgr.cpp @@ -16,7 +16,6 @@ */ #include "MapMgr.h" -#include "AvgDiffTracker.h" #include "Chat.h" #include "DatabaseEnv.h" #include "GridDefines.h" @@ -252,13 +251,12 @@ void MapMgr::Update(uint32 diff) //if (mapUpdateStep == 0) { if (m_updater.activated()) + { m_updater.schedule_lfg_update(diff); + } else { - uint32 startTime = getMSTime(); sLFGMgr->Update(diff, 1); - uint32 totalTime = getMSTimeDiff(startTime, getMSTime()); - lfgDiffTracker.Update(10000 + totalTime); // +10k to mark it was NOT multithreaded } } diff --git a/src/server/game/Maps/MapUpdater.cpp b/src/server/game/Maps/MapUpdater.cpp index 9156ec5d87..0c1fde4ae9 100644 --- a/src/server/game/Maps/MapUpdater.cpp +++ b/src/server/game/Maps/MapUpdater.cpp @@ -16,7 +16,6 @@ */ #include "MapUpdater.h" -#include "AvgDiffTracker.h" #include "LFGMgr.h" #include "Map.h" #include "Metric.h" @@ -59,10 +58,7 @@ public: void call() override { - uint32 startTime = getMSTime(); sLFGMgr->Update(m_diff, 1); - uint32 totalTime = getMSTimeDiff(startTime, getMSTime()); - lfgDiffTracker.Update(totalTime); m_updater.update_finished(); } private: diff --git a/src/server/game/Misc/AvgDiffTracker.h b/src/server/game/Misc/AvgDiffTracker.h deleted file mode 100644 index 8fa0c250c5..0000000000 --- a/src/server/game/Misc/AvgDiffTracker.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * This file is part of the AzerothCore 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 Affero General Public License as published by the - * Free Software Foundation; either version 3 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 Affero 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 __AVGDIFFTRACKER_H -#define __AVGDIFFTRACKER_H - -#include "Common.h" -#include <cstring> - -#define AVG_DIFF_COUNT 500 - -class AvgDiffTracker -{ -public: - AvgDiffTracker() : total(0), index(0), average(0) { memset(&tab, 0, sizeof(tab)); max[0] = 0; max[1] = 0; } - - uint32 getAverage() - { - return average; - } - - uint32 getTimeWeightedAverage() - { - if (tab[AVG_DIFF_COUNT - 1] == 0) - return 0; - - uint32 sum = 0, weightsum = 0; - for (uint32 i = 0; i < AVG_DIFF_COUNT; ++i) - { - sum += tab[i] * tab[i]; - weightsum += tab[i]; - } - return sum / weightsum; - } - - uint32 getMax() - { - return max[0] > max[1] ? max[0] : max[1]; - } - - void Update(uint32 diff) - { - if (diff < 1) - diff = 1; - total -= tab[index]; - total += diff; - tab[index] = diff; - if (diff > max[0]) - max[0] = diff; - if (++index >= AVG_DIFF_COUNT) - { - index = 0; - max[1] = max[0]; - max[0] = 0; - } - - if (tab[AVG_DIFF_COUNT - 1]) - average = total / AVG_DIFF_COUNT; - else if (index) - average = total / index; - else - average = 0; - } - -private: - uint32 tab[AVG_DIFF_COUNT]; - uint32 total; - uint32 index; - uint32 max[2]; - uint32 average; -}; - -extern AvgDiffTracker avgDiffTracker; -extern AvgDiffTracker lfgDiffTracker; -extern AvgDiffTracker devDiffTracker; - -#endif diff --git a/src/server/game/Misc/BanMgr.cpp b/src/server/game/Misc/BanMgr.cpp index 8d1f979c19..7ebb215279 100644 --- a/src/server/game/Misc/BanMgr.cpp +++ b/src/server/game/Misc/BanMgr.cpp @@ -18,6 +18,7 @@ #include "BanMgr.h" #include "AccountMgr.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Language.h" #include "ObjectAccessor.h" #include "Player.h" @@ -51,7 +52,7 @@ BanReturn BanMgr::BanAccount(std::string const& AccountName, std::string const& stmtAccountBanned->setUInt32(0, AccountID); PreparedQueryResult banresult = LoginDatabase.Query(stmtAccountBanned); - if (banresult && ((*banresult)[0].GetUInt32() == (*banresult)[1].GetUInt32() || ((*banresult)[1].GetUInt32() > time(nullptr) + DurationSecs && DurationSecs))) + if (banresult && ((*banresult)[0].GetUInt32() == (*banresult)[1].GetUInt32() || ((*banresult)[1].GetUInt32() > GameTime::GetGameTime().count() + DurationSecs && DurationSecs))) return BAN_LONGER_EXISTS; // make sure there is only one active ban @@ -113,7 +114,7 @@ BanReturn BanMgr::BanAccountByPlayerName(std::string const& CharacterName, std:: stmtAccountBanned->setUInt32(0, AccountID); PreparedQueryResult banresult = LoginDatabase.Query(stmtAccountBanned); - if (banresult && ((*banresult)[0].GetUInt32() == (*banresult)[1].GetUInt32() || ((*banresult)[1].GetUInt32() > time(nullptr) + DurationSecs && DurationSecs))) + if (banresult && ((*banresult)[0].GetUInt32() == (*banresult)[1].GetUInt32() || ((*banresult)[1].GetUInt32() > GameTime::GetGameTime().count() + DurationSecs && DurationSecs))) return BAN_LONGER_EXISTS; // make sure there is only one active ban diff --git a/src/server/game/Movement/MotionMaster.cpp b/src/server/game/Movement/MotionMaster.cpp index 5663d399b3..844874e19e 100644 --- a/src/server/game/Movement/MotionMaster.cpp +++ b/src/server/game/Movement/MotionMaster.cpp @@ -21,6 +21,7 @@ #include "CreatureAISelector.h" #include "EscortMovementGenerator.h" #include "FleeingMovementGenerator.h" +#include "GameTime.h" #include "HomeMovementGenerator.h" #include "IdleMovementGenerator.h" #include "Log.h" @@ -568,7 +569,7 @@ void MotionMaster::MoveFall(uint32 id /*=0*/, bool addFlagForNPC) { _owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING); _owner->m_movementInfo.SetFallTime(0); - _owner->ToPlayer()->SetFallInformation(time(nullptr), _owner->GetPositionZ()); + _owner->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), _owner->GetPositionZ()); } else if (_owner->GetTypeId() == TYPEID_UNIT && addFlagForNPC) // pussywizard { diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index 2abefcd255..6eab59208b 100644 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -19,6 +19,7 @@ #include "Creature.h" #include "CreatureAI.h" #include "CreatureGroups.h" +#include "GameTime.h" #include "MapMgr.h" #include "MoveSpline.h" #include "MoveSplineInit.h" @@ -316,7 +317,7 @@ void FlightPathMovementGenerator::DoFinalize(Player* player) // this prevent cheating with landing point at lags // when client side flight end early in comparison server side player->StopMoving(); - player->SetFallInformation(time(nullptr), player->GetPositionZ()); + player->SetFallInformation(GameTime::GetGameTime().count(), player->GetPositionZ()); } player->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_TAXI_BENCHMARK); @@ -409,7 +410,7 @@ bool FlightPathMovementGenerator::DoUpdate(Player* player, uint32 /*diff*/) if (i_currentNode >= i_path.size() - 1) { player->CleanupAfterTaxiFlight(); - player->SetFallInformation(time(nullptr), player->GetPositionZ()); + player->SetFallInformation(GameTime::GetGameTime().count(), player->GetPositionZ()); if (player->pvpInfo.IsHostile) player->CastSpell(player, 2479, true); diff --git a/src/server/game/Movement/Spline/MoveSpline.cpp b/src/server/game/Movement/Spline/MoveSpline.cpp index 30b8315784..59ec1aebab 100644 --- a/src/server/game/Movement/Spline/MoveSpline.cpp +++ b/src/server/game/Movement/Spline/MoveSpline.cpp @@ -107,14 +107,16 @@ namespace Movement struct CommonInitializer { - CommonInitializer(float _velocity) : velocityInv(1000.f / _velocity), time(minimal_duration) {} - float velocityInv; - int32 time; + CommonInitializer(float _velocity) : velocityInv(1000.f / _velocity), _time(minimal_duration) {} + inline int32 operator()(Spline<int32>& s, int32 i) { - time += (s.SegLength(i) * velocityInv); - return time; + _time += (s.SegLength(i) * velocityInv); + return _time; } + + float velocityInv; + int32 _time; }; void MoveSpline::init_spline(const MoveSplineInitArgs& args) diff --git a/src/server/game/Scripting/MapScripts.cpp b/src/server/game/Scripting/MapScripts.cpp index 97d9ce5b69..54d8f78a03 100644 --- a/src/server/game/Scripting/MapScripts.cpp +++ b/src/server/game/Scripting/MapScripts.cpp @@ -16,6 +16,7 @@ */ #include "CellImpl.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Map.h" @@ -53,7 +54,7 @@ void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, O sa.ownerGUID = ownerGUID; sa.script = &iter->second; - m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld->GetGameTime() + iter->first), sa)); + m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(GameTime::GetGameTime().count() + iter->first), sa)); if (iter->first == 0) immedScript = true; @@ -83,7 +84,7 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* sou sa.ownerGUID = ownerGUID; sa.script = &script; - m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld->GetGameTime() + delay), sa)); + m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(GameTime::GetGameTime().count() + delay), sa)); sScriptMgr->IncreaseScheduledScriptsCount(); @@ -284,7 +285,7 @@ void Map::ScriptsProcess() ///- Process overdue queued scripts ScriptScheduleMap::iterator iter = m_scriptSchedule.begin(); // ok as multimap is a *sorted* associative container - while (!m_scriptSchedule.empty() && (iter->first <= sWorld->GetGameTime())) + while (!m_scriptSchedule.empty() && (iter->first <= GameTime::GetGameTime().count())) { ScriptAction const& step = iter->second; diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index 07689bcdff..4dd381abf5 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -1741,7 +1741,7 @@ public: [[nodiscard]] virtual bool IsCompletedCriteria(AchievementMgr* /*mgr*/, AchievementCriteriaEntry const* /*achievementCriteria*/, AchievementEntry const* /*achievement*/, CriteriaProgress const* /*progress*/) { return true; } - [[nodiscard]] virtual bool IsRealmCompleted(AchievementGlobalMgr const* /*globalmgr*/, AchievementEntry const* /*achievement*/, std::chrono::system_clock::time_point /*completionTime*/) { return true; } + [[nodiscard]] virtual bool IsRealmCompleted(AchievementGlobalMgr const* /*globalmgr*/, AchievementEntry const* /*achievement*/, SystemTimePoint /*completionTime*/) { return true; } virtual void OnBeforeCheckCriteria(AchievementMgr* /*mgr*/, AchievementCriteriaEntryList const* /*achievementCriteriaList*/) { } diff --git a/src/server/game/Server/Protocol/PacketLog.cpp b/src/server/game/Server/Protocol/PacketLog.cpp index 8479c8616d..2047bf84b9 100644 --- a/src/server/game/Server/Protocol/PacketLog.cpp +++ b/src/server/game/Server/Protocol/PacketLog.cpp @@ -17,6 +17,7 @@ #include "PacketLog.h" #include "Config.h" +#include "GameTime.h" #include "IpAddress.h" #include "Timer.h" #include "WorldPacket.h" @@ -99,7 +100,7 @@ void PacketLog::Initialize() header.Build = 12340; header.Locale[0] = 'e'; header.Locale[1] = 'n'; header.Locale[2] = 'U'; header.Locale[3] = 'S'; std::memset(header.SessionKey, 0, sizeof(header.SessionKey)); - header.SniffStartUnixtime = time(nullptr); + header.SniffStartUnixtime = GameTime::GetGameTime().count(); header.SniffStartTicks = getMSTime(); header.OptionalDataSize = 0; diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index d1e8b41cca..1a0d647392 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -25,6 +25,7 @@ #include "CharacterPackets.h" #include "Common.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Group.h" #include "Guild.h" #include "GuildMgr.h" @@ -219,13 +220,13 @@ void WorldSession::SendPacket(WorldPacket const* packet) static uint64 sendPacketCount = 0; static uint64 sendPacketBytes = 0; - static time_t firstTime = time(nullptr); + static time_t firstTime = GameTime::GetGameTime().count(); static time_t lastTime = firstTime; // next 60 secs start time static uint64 sendLastPacketCount = 0; static uint64 sendLastPacketBytes = 0; - time_t cur_time = time(nullptr); + time_t cur_time = GameTime::GetGameTime().count(); if ((cur_time - lastTime) < 60) { @@ -306,7 +307,7 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) bool deletePacket = true; std::vector<WorldPacket*> requeuePackets; uint32 processedPackets = 0; - time_t currentTime = time(nullptr); + time_t currentTime = GameTime::GetGameTime().count(); while (m_Socket && _recvQueue.next(packet, updater)) { @@ -510,7 +511,7 @@ void WorldSession::HandleTeleportTimeout(bool updateInSessions) // pussywizard: handle teleport ack timeout if (m_Socket && m_Socket->IsOpen() && GetPlayer() && GetPlayer()->IsBeingTeleported()) { - time_t currTime = time(nullptr); + time_t currTime = GameTime::GetGameTime().count(); if (updateInSessions) // session update from World::UpdateSessions { if (GetPlayer()->IsBeingTeleportedFar() && GetPlayer()->GetSemaphoreTeleportFar() + sWorld->getIntConfig(CONFIG_TELEPORT_TIMEOUT_FAR) < currTime) @@ -897,7 +898,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string c void WorldSession::SendAccountDataTimes(uint32 mask) { WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + 8 * 4); // changed in WotLK - data << uint32(time(nullptr)); // unix time of something + data << uint32(GameTime::GetGameTime().count()); // unix time of something data << uint8(1); data << uint32(mask); // type mask for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index 17761099ab..2f2c918e0b 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -21,6 +21,7 @@ #include "CryptoHash.h" #include "CryptoRandom.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "IPLocation.h" #include "Opcodes.h" #include "PacketLog.h" @@ -357,7 +358,7 @@ WorldSocket::ReadDataHandlerResult WorldSocket::ReadDataHandler() _worldSession->ResetTimeOutTime(true); return ReadDataHandlerResult::Ok; case CMSG_TIME_SYNC_RESP: - packetToQueue = new WorldPacket(std::move(packet), std::chrono::steady_clock::now()); + packetToQueue = new WorldPacket(std::move(packet), GameTime::Now()); break; default: packetToQueue = new WorldPacket(std::move(packet)); @@ -556,7 +557,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<AuthSession> authSes //! Negative mutetime indicates amount of minutes to be muted effective on next login - which is now. if (account.MuteTime < 0) { - account.MuteTime = time(nullptr) + llabs(account.MuteTime); + account.MuteTime = GameTime::GetGameTime().count() + llabs(account.MuteTime); auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); stmt->setInt64(0, account.MuteTime); diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 4436a7f89f..07c90ed132 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -20,6 +20,7 @@ #include "Battleground.h" #include "CellImpl.h" #include "Common.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "InstanceScript.h" #include "Log.h" @@ -2944,7 +2945,7 @@ void AuraEffect::HandleAuraFeatherFall(AuraApplication const* aurApp, uint8 mode // start fall from current height if (!apply && target->GetTypeId() == TYPEID_PLAYER) - target->ToPlayer()->SetFallInformation(time(nullptr), target->GetPositionZ()); + target->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), target->GetPositionZ()); } void AuraEffect::HandleAuraHover(AuraApplication const* aurApp, uint8 mode, bool apply) const diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index 2c389ed952..3105474ddd 100644 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -18,6 +18,7 @@ #include "ArenaSpectator.h" #include "CellImpl.h" #include "Common.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Log.h" #include "ObjectAccessor.h" @@ -407,7 +408,7 @@ Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owne Aura::Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, ObjectGuid casterGUID, ObjectGuid itemGUID /*= ObjectGuid::Empty*/) : m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), - m_castItemGuid(itemGUID ? itemGUID : castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_castItemEntry(castItem ? castItem->GetEntry() : 0), m_applyTime(time(nullptr)), + m_castItemGuid(itemGUID ? itemGUID : castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_castItemEntry(castItem ? castItem->GetEntry() : 0), m_applyTime(GameTime::GetGameTime().count()), m_owner(owner), m_timeCla(0), m_updateTargetMapInterval(0), m_casterLevel(caster ? caster->getLevel() : m_spellInfo->SpellLevel), m_procCharges(0), m_stackAmount(1), m_isRemoved(false), m_isSingleTarget(false), m_isUsingCharges(false), m_triggeredByAuraSpellInfo(nullptr) @@ -2134,7 +2135,7 @@ bool Aura::IsProcOnCooldown() const { /*if (m_procCooldown) { - if (m_procCooldown > time(nullptr)) + if (m_procCooldown > GameTime::GetGameTime().count()) return true; }*/ return false; @@ -2142,7 +2143,7 @@ bool Aura::IsProcOnCooldown() const void Aura::AddProcCooldown(uint32 /*msec*/) { - //m_procCooldown = time(nullptr) + msec; + //m_procCooldown = GameTime::GetGameTime().count() + msec; } void Aura::PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo) diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 3d5d9f29f6..1473a2586b 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -26,6 +26,7 @@ #include "DisableMgr.h" #include "DynamicObject.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" @@ -2440,7 +2441,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // Xinef: absorb delayed projectiles for 500ms if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsTargetingArea() && !m_spellInfo->IsPositive() && - (World::GetGameTimeMS() - target->timeDelay) <= effectUnit->m_lastSanctuaryTime && World::GetGameTimeMS() < (effectUnit->m_lastSanctuaryTime + 500) && + (GameTime::GetGameTimeMS().count() - target->timeDelay) <= effectUnit->m_lastSanctuaryTime && GameTime::GetGameTimeMS().count() < (effectUnit->m_lastSanctuaryTime + 500) && effectUnit->FindMap() && !effectUnit->FindMap()->IsDungeon() ) return; // No missinfo in that case @@ -4461,7 +4462,7 @@ void Spell::SendSpellGo() data << uint8(m_cast_count); // pending spell cast? data << uint32(m_spellInfo->Id); // spellId data << uint32(castFlags); // cast flags - data << uint32(World::GetGameTimeMS()); // timestamp + data << uint32(GameTime::GetGameTimeMS().count()); // timestamp WriteSpellGoTargets(&data); @@ -4961,7 +4962,7 @@ void Spell::TakePower() // Set the five second timer if (PowerType == POWER_MANA && m_powerCost > 0) - m_caster->SetLastManaUse(World::GetGameTimeMS()); + m_caster->SetLastManaUse(GameTime::GetGameTimeMS().count()); } void Spell::TakeAmmo() @@ -6030,7 +6031,7 @@ SpellCastResult Spell::CheckCast(bool strict) return SPELL_FAILED_BAD_TARGETS; // Xinef: Implement summon pending error - if (target->GetSummonExpireTimer() > time(nullptr)) + if (target->GetSummonExpireTimer() > GameTime::GetGameTime().count()) return SPELL_FAILED_SUMMON_PENDING; // check if our map is dungeon @@ -6070,7 +6071,7 @@ SpellCastResult Spell::CheckCast(bool strict) return SPELL_FAILED_BAD_TARGETS; // Xinef: Implement summon pending error - if (target->GetSummonExpireTimer() > time(nullptr)) + if (target->GetSummonExpireTimer() > GameTime::GetGameTime().count()) return SPELL_FAILED_SUMMON_PENDING; break; diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index f9f38c4bcf..b1b8409422 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -28,6 +28,7 @@ #include "Formulas.h" #include "GameObject.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GossipDef.h" #include "GridNotifiers.h" #include "Group.h" @@ -686,7 +687,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) case 17731: case 69294: { - if( !gameObjTarget || gameObjTarget->GetRespawnTime() > time(nullptr) ) + if( !gameObjTarget || gameObjTarget->GetRespawnTime() > GameTime::GetGameTime().count() ) return; gameObjTarget->SetRespawnTime(10); @@ -4305,7 +4306,7 @@ void Spell::EffectSanctuary(SpellEffIndex /*effIndex*/) } // Xinef: Set last sanctuary time - unitTarget->m_lastSanctuaryTime = World::GetGameTimeMS(); + unitTarget->m_lastSanctuaryTime = GameTime::GetGameTimeMS().count(); // Vanish allows to remove all threat and cast regular stealth so other spells can be used if (m_caster->GetTypeId() == TYPEID_PLAYER @@ -5079,7 +5080,7 @@ void Spell::EffectCharge(SpellEffIndex /*effIndex*/) // charge changes fall time if( m_caster->GetTypeId() == TYPEID_PLAYER ) - m_caster->ToPlayer()->SetFallInformation(time(nullptr), m_caster->GetPositionZ()); + m_caster->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), m_caster->GetPositionZ()); ObjectGuid targetGUID = ObjectGuid::Empty; if (!m_spellInfo->IsPositive() && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->GetTarget() == unitTarget->GetGUID()) @@ -5224,7 +5225,7 @@ void Spell::EffectLeapBack(SpellEffIndex effIndex) // xinef: changes fall time if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->SetFallInformation(time(nullptr), m_caster->GetPositionZ()); + m_caster->ToPlayer()->SetFallInformation(GameTime::GetGameTime().count(), m_caster->GetPositionZ()); } void Spell::EffectQuestClear(SpellEffIndex effIndex) diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index e25706da3f..352da72e1a 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -20,6 +20,7 @@ #include "Chat.h" #include "Common.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "Language.h" #include "Log.h" #include "Opcodes.h" @@ -28,14 +29,14 @@ #include "WorldPacket.h" #include "WorldSession.h" -inline float GetAge(uint64 t) { return float(time(nullptr) - t) / DAY; } +inline float GetAge(uint64 t) { return float(GameTime::GetGameTime().count() - t) / DAY; } /////////////////////////////////////////////////////////////////////////////////////////////////// // GM ticket GmTicket::GmTicket() : _id(0), _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(0), _lastModifiedTime(0), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needResponse(false), _needMoreHelp(false) { } -GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _createTime(time(nullptr)), _lastModifiedTime(time(nullptr)), +GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _createTime(GameTime::GetGameTime().count()), _lastModifiedTime(GameTime::GetGameTime().count()), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needMoreHelp(false) { _id = sTicketMgr->GenerateTicketId(); @@ -159,7 +160,7 @@ void GmTicket::SendResponse(WorldSession* session) const std::string GmTicket::FormatMessageString(ChatHandler& handler, bool detailed) const { - time_t curTime = time(nullptr); + time_t curTime = GameTime::GetGameTime().count(); std::stringstream ss; ss << handler.PGetParseString(LANG_COMMAND_TICKETLISTGUID, _id); @@ -252,9 +253,15 @@ void GmTicket::SetChatLog(std::list<uint32> time, std::string const& log) _chatLog = newss.str(); } +void GmTicket::SetMessage(std::string const& message) +{ + _message = message; + _lastModifiedTime = uint64(GameTime::GetGameTime().count()); +} + /////////////////////////////////////////////////////////////////////////////////////////////////// // Ticket manager -TicketMgr::TicketMgr() : _status(true), _lastTicketId(0), _lastSurveyId(0), _openTicketCount(0), _lastChange(time(nullptr)) { } +TicketMgr::TicketMgr() : _status(true), _lastTicketId(0), _lastSurveyId(0), _openTicketCount(0), _lastChange(GameTime::GetGameTime().count()) { } TicketMgr::~TicketMgr() { @@ -430,3 +437,8 @@ void TicketMgr::SendTicket(WorldSession* session, GmTicket* ticket) const session->SendPacket(&data); } + +void TicketMgr::UpdateLastChange() +{ + _lastChange = GameTime::GetGameTime().count(); +} diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index 3e1b2a9a1f..c5538489ab 100644 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -130,11 +130,7 @@ public: void SetClosedBy(ObjectGuid value) { _closedBy = value; _type = TICKET_TYPE_CLOSED; } void SetResolvedBy(ObjectGuid value) { _resolvedBy = value; } void SetCompleted() { _completed = true; } - void SetMessage(std::string const& message) - { - _message = message; - _lastModifiedTime = uint64(time(nullptr)); - } + void SetMessage(std::string const& message); void SetComment(std::string const& comment) { _comment = comment; } void SetViewed() { _viewed = true; } void SetUnassigned(); @@ -232,7 +228,7 @@ public: void SetStatus(bool status) { _status = status; } uint64 GetLastChange() const { return _lastChange; } - void UpdateLastChange() { _lastChange = uint64(time(nullptr)); } + void UpdateLastChange(); uint32 GenerateTicketId() { return ++_lastTicketId; } uint32 GetOpenTicketCount() const { return _openTicketCount; } diff --git a/src/server/game/Time/GameTime.cpp b/src/server/game/Time/GameTime.cpp new file mode 100644 index 0000000000..3dbcbc0f25 --- /dev/null +++ b/src/server/game/Time/GameTime.cpp @@ -0,0 +1,70 @@ +/* + * This file is part of the AzerothCore 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 Affero General Public License as published by the + * Free Software Foundation; either version 3 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 Affero 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 "GameTime.h" +#include "Timer.h" + +namespace GameTime +{ + using namespace std::chrono; + + Seconds const StartTime = GetEpochTime(); + + Seconds GameTime = GetEpochTime(); + Milliseconds GameMSTime = 0ms; + + SystemTimePoint GameTimeSystemPoint = SystemTimePoint::min(); + TimePoint GameTimeSteadyPoint = TimePoint::min(); + + Seconds GetStartTime() + { + return StartTime; + } + + Seconds GetGameTime() + { + return GameTime; + } + + Milliseconds GetGameTimeMS() + { + return GameMSTime; + } + + SystemTimePoint GetSystemTime() + { + return GameTimeSystemPoint; + } + + TimePoint Now() + { + return GameTimeSteadyPoint; + } + + Seconds GetUptime() + { + return GameTime - StartTime; + } + + void UpdateGameTimers() + { + GameTime = GetEpochTime(); + GameMSTime = GetTimeMS(); + GameTimeSystemPoint = system_clock::now(); + GameTimeSteadyPoint = steady_clock::now(); + } +} diff --git a/src/server/game/Misc/AvgDiffTracker.cpp b/src/server/game/Time/GameTime.h index b59db17862..3350a14d40 100644 --- a/src/server/game/Misc/AvgDiffTracker.cpp +++ b/src/server/game/Time/GameTime.h @@ -15,8 +15,34 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "AvgDiffTracker.h" +#ifndef __GAMETIME_H +#define __GAMETIME_H -AvgDiffTracker avgDiffTracker; -AvgDiffTracker lfgDiffTracker; -AvgDiffTracker devDiffTracker; +#include "Define.h" +#include "Duration.h" + +namespace GameTime +{ + // Server start time + AC_GAME_API Seconds GetStartTime(); + + // Current server time (unix) + AC_GAME_API Seconds GetGameTime(); + + // Milliseconds since server start + AC_GAME_API Milliseconds GetGameTimeMS(); + + /// Current chrono system_clock time point + AC_GAME_API SystemTimePoint GetSystemTime(); + + /// Current chrono steady_clock time point + AC_GAME_API TimePoint Now(); + + /// Uptime + AC_GAME_API Seconds GetUptime(); + + /// Update all timers + void UpdateGameTimers(); +} + +#endif diff --git a/src/server/game/Time/UpdateTime.cpp b/src/server/game/Time/UpdateTime.cpp new file mode 100644 index 0000000000..535a9ed981 --- /dev/null +++ b/src/server/game/Time/UpdateTime.cpp @@ -0,0 +1,124 @@ +/* + * This file is part of the AzerothCore 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 Affero General Public License as published by the + * Free Software Foundation; either version 3 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 Affero 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 "UpdateTime.h" +#include "Config.h" +#include "Log.h" +#include "Timer.h" + +// create instance +WorldUpdateTime sWorldUpdateTime; + +UpdateTime::UpdateTime() +{ + _averageUpdateTime = 0; + _totalUpdateTime = 0; + _updateTimeTableIndex = 0; + _maxUpdateTime = 0; + _maxUpdateTimeOfLastTable = 0; + _maxUpdateTimeOfCurrentTable = 0; + + _updateTimeDataTable = { }; +} + +uint32 UpdateTime::GetAverageUpdateTime() const +{ + return _averageUpdateTime; +} + +uint32 UpdateTime::GetTimeWeightedAverageUpdateTime() const +{ + uint32 sum = 0, weightsum = 0; + + for (uint32 diff : _updateTimeDataTable) + { + sum += diff * diff; + weightsum += diff; + } + + if (weightsum == 0) + return 0; + + return sum / weightsum; +} + +uint32 UpdateTime::GetMaxUpdateTime() const +{ + return _maxUpdateTime; +} + +uint32 UpdateTime::GetMaxUpdateTimeOfCurrentTable() const +{ + return std::max(_maxUpdateTimeOfCurrentTable, _maxUpdateTimeOfLastTable); +} + +uint32 UpdateTime::GetLastUpdateTime() const +{ + return _updateTimeDataTable[_updateTimeTableIndex != 0 ? _updateTimeTableIndex - 1 : _updateTimeDataTable.size() - 1]; +} + +void UpdateTime::UpdateWithDiff(uint32 diff) +{ + _totalUpdateTime = _totalUpdateTime - _updateTimeDataTable[_updateTimeTableIndex] + diff; + _updateTimeDataTable[_updateTimeTableIndex] = diff; + + if (diff > _maxUpdateTime) + _maxUpdateTime = diff; + + if (diff > _maxUpdateTimeOfCurrentTable) + _maxUpdateTimeOfCurrentTable = diff; + + if (++_updateTimeTableIndex >= _updateTimeDataTable.size()) + { + _updateTimeTableIndex = 0; + _maxUpdateTimeOfLastTable = _maxUpdateTimeOfCurrentTable; + _maxUpdateTimeOfCurrentTable = 0; + } + + if (_updateTimeDataTable[_updateTimeDataTable.size() - 1]) + _averageUpdateTime = _totalUpdateTime / _updateTimeDataTable.size(); + else if (_updateTimeTableIndex) + _averageUpdateTime = _totalUpdateTime / _updateTimeTableIndex; +} + +void UpdateTime::RecordUpdateTimeReset() +{ + _recordedTime = GetTimeMS(); +} + +void WorldUpdateTime::LoadFromConfig() +{ + _recordUpdateTimeInverval = Milliseconds(sConfigMgr->GetOption<uint32>("RecordUpdateTimeDiffInterval", 60000)); + _recordUpdateTimeMin = Milliseconds(sConfigMgr->GetOption<uint32>("MinRecordUpdateTimeDiff", 100)); +} + +void WorldUpdateTime::SetRecordUpdateTimeInterval(Milliseconds t) +{ + _recordUpdateTimeInverval = t; +} + +void WorldUpdateTime::RecordUpdateTime(Milliseconds gameTimeMs, uint32 diff, uint32 sessionCount) +{ + if (_recordUpdateTimeInverval > 0s && diff > _recordUpdateTimeMin.count()) + { + if (GetMSTimeDiff(_lastRecordTime, gameTimeMs) > _recordUpdateTimeInverval) + { + FMT_LOG_INFO("time.update", "Update time diff: {}. Players online: {}.", GetAverageUpdateTime(), sessionCount); + _lastRecordTime = gameTimeMs; + } + } +} diff --git a/src/server/game/Time/UpdateTime.h b/src/server/game/Time/UpdateTime.h new file mode 100644 index 0000000000..b95f74060d --- /dev/null +++ b/src/server/game/Time/UpdateTime.h @@ -0,0 +1,75 @@ +/* + * This file is part of the AzerothCore 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 Affero General Public License as published by the + * Free Software Foundation; either version 3 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 Affero 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 __UPDATETIME_H +#define __UPDATETIME_H + +#include "Define.h" +#include "Duration.h" +#include <array> +#include <string> + +constexpr auto AVG_DIFF_COUNT = 500; + +class AC_GAME_API UpdateTime +{ +using DiffTableArray = std::array<uint32, AVG_DIFF_COUNT>; + +public: + uint32 GetAverageUpdateTime() const; + uint32 GetTimeWeightedAverageUpdateTime() const; + uint32 GetMaxUpdateTime() const; + uint32 GetMaxUpdateTimeOfCurrentTable() const; + uint32 GetLastUpdateTime() const; + + void UpdateWithDiff(uint32 diff); + + void RecordUpdateTimeReset(); + +protected: + UpdateTime(); + +private: + DiffTableArray _updateTimeDataTable; + uint32 _averageUpdateTime; + uint32 _totalUpdateTime; + uint32 _updateTimeTableIndex; + uint32 _maxUpdateTime; + uint32 _maxUpdateTimeOfLastTable; + uint32 _maxUpdateTimeOfCurrentTable; + + Milliseconds _recordedTime; +}; + +class AC_GAME_API WorldUpdateTime : public UpdateTime +{ +public: + WorldUpdateTime() : UpdateTime(), _recordUpdateTimeInverval(0), _recordUpdateTimeMin(0), _lastRecordTime(0) { } + void LoadFromConfig(); + void SetRecordUpdateTimeInterval(Milliseconds t); + void RecordUpdateTime(Milliseconds gameTimeMs, uint32 diff, uint32 sessionCount); + void RecordUpdateTimeDuration(std::string const& text); + +private: + Milliseconds _recordUpdateTimeInverval; + Milliseconds _recordUpdateTimeMin; + Milliseconds _lastRecordTime; +}; + +AC_GAME_API extern WorldUpdateTime sWorldUpdateTime; + +#endif diff --git a/src/server/game/Warden/WardenWin.cpp b/src/server/game/Warden/WardenWin.cpp index a5f2308411..7deaf7bde0 100644 --- a/src/server/game/Warden/WardenWin.cpp +++ b/src/server/game/Warden/WardenWin.cpp @@ -19,6 +19,7 @@ #include "ByteBuffer.h" #include "Common.h" #include "CryptoRandom.h" +#include "GameTime.h" #include "HMAC.h" #include "Log.h" #include "Opcodes.h" @@ -255,7 +256,7 @@ void WardenWin::RequestChecks() _ChecksTodo[i].assign(sWardenCheckMgr->CheckIdPool[i].begin(), sWardenCheckMgr->CheckIdPool[i].end()); } - _serverTicks = World::GetGameTimeMS(); + _serverTicks = GameTime::GetGameTimeMS().count(); _CurrentChecks.clear(); // No pending checks @@ -493,7 +494,7 @@ void WardenWin::HandleData(ByteBuffer& buff) uint32 newClientTicks; buff >> newClientTicks; - uint32 ticksNow = World::GetGameTimeMS(); + uint32 ticksNow = GameTime::GetGameTimeMS().count(); uint32 ourTicks = newClientTicks + (ticksNow - _serverTicks); LOG_DEBUG("warden", "ServerTicks %u", ticksNow); // Now diff --git a/src/server/game/World/IWorld.h b/src/server/game/World/IWorld.h index 2bfb3fb696..c736e1c69a 100644 --- a/src/server/game/World/IWorld.h +++ b/src/server/game/World/IWorld.h @@ -20,10 +20,10 @@ #include "AsyncCallbackProcessor.h" #include "Common.h" +#include "Duration.h" #include "ObjectGuid.h" #include "QueryResult.h" #include "SharedDefines.h" -#include "Timer.h" #include <atomic> #include <list> #include <map> @@ -314,8 +314,6 @@ enum WorldIntConfigs CONFIG_PVP_TOKEN_MAP_TYPE, CONFIG_PVP_TOKEN_ID, CONFIG_PVP_TOKEN_COUNT, - CONFIG_INTERVAL_LOG_UPDATE, - CONFIG_MIN_LOG_UPDATE, CONFIG_ENABLE_SINFO_LOGIN, CONFIG_PLAYER_ALLOW_COMMANDS, CONFIG_NUMTHREADS, @@ -528,14 +526,9 @@ public: [[nodiscard]] virtual std::string const& GetNewCharString() const = 0; [[nodiscard]] virtual LocaleConstant GetDefaultDbcLocale() const = 0; [[nodiscard]] virtual std::string const& GetDataPath() const = 0; - [[nodiscard]] virtual time_t const& GetStartTime() const = 0; - [[nodiscard]] virtual time_t const& GetGameTime() const = 0; - [[nodiscard]] virtual uint32 GetUptime() const = 0; - [[nodiscard]] virtual uint32 GetUpdateTime() const = 0; - virtual void SetRecordDiffInterval(int32 t) = 0; - [[nodiscard]] virtual time_t GetNextDailyQuestsResetTime() const = 0; - [[nodiscard]] virtual time_t GetNextWeeklyQuestsResetTime() const = 0; - [[nodiscard]] virtual time_t GetNextRandomBGResetTime() const = 0; + [[nodiscard]] virtual Seconds GetNextDailyQuestsResetTime() const = 0; + [[nodiscard]] virtual Seconds GetNextWeeklyQuestsResetTime() const = 0; + [[nodiscard]] virtual Seconds GetNextRandomBGResetTime() const = 0; [[nodiscard]] virtual uint16 GetConfigMaxSkillValue() const = 0; virtual void SetInitialWorldSettings() = 0; virtual void LoadConfigSettings(bool reload = false) = 0; diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 6133e53f9c..a7bf0170b8 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -26,7 +26,6 @@ #include "ArenaTeamMgr.h" #include "AsyncAuctionListing.h" #include "AuctionHouseMgr.h" -#include "AvgDiffTracker.h" #include "BattlefieldMgr.h" #include "BattlegroundMgr.h" #include "CalendarMgr.h" @@ -47,6 +46,7 @@ #include "DynamicVisibility.h" #include "GameEventMgr.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "GitRevision.h" #include "GridNotifiersImpl.h" #include "GroupMgr.h" @@ -79,6 +79,7 @@ #include "TicketMgr.h" #include "Transport.h" #include "TransportMgr.h" +#include "UpdateTime.h" #include "Util.h" #include "VMapFactory.h" #include "VMapMgr2.h" @@ -101,7 +102,6 @@ namespace std::atomic_long World::m_stopEvent = false; uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE; uint32 World::m_worldLoopCounter = 0; -uint32 World::m_gameMSTime = 0; float World::m_MaxVisibleDistanceOnContinents = DEFAULT_VISIBILITY_DISTANCE; float World::m_MaxVisibleDistanceInInstances = DEFAULT_VISIBILITY_INSTANCE; @@ -117,28 +117,19 @@ World::World() m_allowMovement = true; m_ShutdownMask = 0; m_ShutdownTimer = 0; - m_gameTime = time(nullptr); - m_gameMSTime = getMSTime(); - m_startTime = m_gameTime; m_maxActiveSessionCount = 0; m_maxQueuedSessionCount = 0; m_PlayerCount = 0; m_MaxPlayerCount = 0; - m_NextDailyQuestReset = 0; - m_NextWeeklyQuestReset = 0; - m_NextMonthlyQuestReset = 0; - m_NextRandomBGReset = 0; - m_NextCalendarOldEventsDeletionTime = 0; - m_NextGuildReset = 0; - + m_NextDailyQuestReset = 0s; + m_NextWeeklyQuestReset = 0s; + m_NextMonthlyQuestReset = 0s; + m_NextRandomBGReset = 0s; + m_NextCalendarOldEventsDeletionTime = 0s; + m_NextGuildReset = 0s; m_defaultDbcLocale = LOCALE_enUS; - - mail_expire_check_timer = 0; - m_updateTime = 0; - m_updateTimeSum = 0; - + mail_expire_check_timer = 0s; m_isClosed = false; - m_CleaningFlags = 0; memset(rate_values, 0, sizeof(rate_values)); @@ -286,7 +277,7 @@ void World::AddSession_(WorldSession* s) WorldSession* oldSession = old->second; if (!RemoveQueuedPlayer(oldSession) && getIntConfig(CONFIG_INTERVAL_DISCONNECT_TOLERANCE)) - m_disconnects[s->GetAccountId()] = time(nullptr); + m_disconnects[s->GetAccountId()] = GameTime::GetGameTime().count(); // pussywizard: if (oldSession->HandleSocketClosed()) @@ -300,7 +291,7 @@ void World::AddSession_(WorldSession* s) tmp->SetShouldSetOfflineInDB(false); delete tmp; } - oldSession->SetOfflineTime(time(nullptr)); + oldSession->SetOfflineTime(GameTime::GetGameTime().count()); m_offlineSessions[oldSession->GetAccountId()] = oldSession; } else @@ -341,7 +332,7 @@ bool World::HasRecentlyDisconnected(WorldSession* session) { for (DisconnectMap::iterator i = m_disconnects.begin(); i != m_disconnects.end();) { - if ((time(nullptr) - i->second) < tolerance) + if ((GameTime::GetGameTime().count() - i->second) < tolerance) { if (i->first == session->GetAccountId()) return true; @@ -448,6 +439,9 @@ void World::LoadConfigSettings(bool reload) sScriptMgr->OnBeforeConfigLoad(reload); + // load update time related configs + sWorldUpdateTime.LoadFromConfig(); + ///- Read the player limit and the Message of the day from the config file if (!reload) { @@ -1303,8 +1297,6 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_SHOW_KICK_IN_WORLD] = sConfigMgr->GetOption<bool>("ShowKickInWorld", false); m_bool_configs[CONFIG_SHOW_MUTE_IN_WORLD] = sConfigMgr->GetOption<bool>("ShowMuteInWorld", false); m_bool_configs[CONFIG_SHOW_BAN_IN_WORLD] = sConfigMgr->GetOption<bool>("ShowBanInWorld", false); - m_int_configs[CONFIG_INTERVAL_LOG_UPDATE] = sConfigMgr->GetOption<int32>("RecordUpdateTimeDiffInterval", 300000); - m_int_configs[CONFIG_MIN_LOG_UPDATE] = sConfigMgr->GetOption<int32>("MinRecordUpdateTimeDiff", 100); m_int_configs[CONFIG_NUMTHREADS] = sConfigMgr->GetOption<int32>("MapUpdate.Threads", 1); m_int_configs[CONFIG_MAX_RESULTS_LOOKUP_COMMANDS] = sConfigMgr->GetOption<int32>("Command.LookupMaxResults", 0); @@ -1448,7 +1440,7 @@ void World::SetInitialWorldSettings() uint32 startupBegin = getMSTime(); ///- Initialize the random number generator - srand((unsigned int)time(nullptr)); + srand((unsigned int)GameTime::GetGameTime().count()); ///- Initialize detour memory management dtAllocSetCustom(dtCustomAlloc, dtCustomFree); @@ -1967,11 +1959,9 @@ void World::SetInitialWorldSettings() ///- Initialize game time and timers LOG_INFO("server.loading", "Initialize game time and timers"); LOG_INFO("server.loading", " "); - m_gameTime = time(nullptr); - m_startTime = m_gameTime; - LoginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, uptime, revision) VALUES(%u, %u, 0, '%s')", - realm.Id.Realm, uint32(m_startTime), GitRevision::GetFullVersion()); // One-time query + LoginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, uptime, revision) VALUES (%u, %u, 0, '%s')", + realm.Id.Realm, uint32(GameTime::GetStartTime().count()), GitRevision::GetFullVersion()); // One-time query m_timers[WUPDATE_WEATHERS].SetInterval(1 * IN_MILLISECONDS); m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE * IN_MILLISECONDS); @@ -1992,7 +1982,7 @@ void World::SetInitialWorldSettings() m_timers[WUPDATE_WHO_LIST].SetInterval(5 * IN_MILLISECONDS); // update who list cache every 5 seconds - mail_expire_check_timer = time(nullptr) + 6 * 3600; + mail_expire_check_timer = GameTime::GetGameTime() + 6h; ///- Initilize static helper structures AIRegistry::Initialize(); @@ -2204,17 +2194,14 @@ void World::Update(uint32 diff) { METRIC_TIMER("world_update_time_total"); - m_updateTime = diff; + ///- Update the game time and check for shutdown time + _UpdateGameTime(); + Seconds currentGameTime = GameTime::GetGameTime(); - if (m_int_configs[CONFIG_INTERVAL_LOG_UPDATE]) - { - m_updateTimeSum += diff; - if (m_updateTimeSum > m_int_configs[CONFIG_INTERVAL_LOG_UPDATE]) - { - LOG_INFO("diff", "Average update time diff: %u. Players online: %u.", avgDiffTracker.getAverage(), (uint32)GetActiveSessionCount()); - m_updateTimeSum = 0; - } - } + sWorldUpdateTime.UpdateWithDiff(diff); + + // Record update if recording set in log and diff is greater then minimum set in log + sWorldUpdateTime.RecordUpdateTime(GameTime::GetGameTimeMS(), diff, GetActiveSessionCount()); DynamicVisibilityMgr::Update(GetActiveSessionCount()); @@ -2237,9 +2224,6 @@ void World::Update(uint32 diff) CharacterDatabase.Execute(stmt); } - ///- Update the game time and check for shutdown time - _UpdateGameTime(); - ///- Update Who List Cache if (m_timers[WUPDATE_WHO_LIST].Passed()) { @@ -2252,37 +2236,37 @@ void World::Update(uint32 diff) METRIC_TIMER("world_update_time", METRIC_TAG("type", "Check quest reset times")); /// Handle daily quests reset time - if (m_gameTime > m_NextDailyQuestReset) + if (currentGameTime > m_NextDailyQuestReset) { ResetDailyQuests(); } /// Handle weekly quests reset time - if (m_gameTime > m_NextWeeklyQuestReset) + if (currentGameTime > m_NextWeeklyQuestReset) { ResetWeeklyQuests(); } /// Handle monthly quests reset time - if (m_gameTime > m_NextMonthlyQuestReset) + if (currentGameTime > m_NextMonthlyQuestReset) { ResetMonthlyQuests(); } } - if (m_gameTime > m_NextRandomBGReset) + if (currentGameTime > m_NextRandomBGReset) { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Reset random BG")); ResetRandomBG(); } - if (m_gameTime > m_NextCalendarOldEventsDeletionTime) + if (currentGameTime > m_NextCalendarOldEventsDeletionTime) { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Delete old calendar events")); CalendarDeleteOldEvents(); } - if (m_gameTime > m_NextGuildReset) + if (currentGameTime > m_NextGuildReset) { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Reset guild cap")); ResetGuildCap(); @@ -2308,10 +2292,10 @@ void World::Update(uint32 diff) AsyncAuctionListingMgr::Update(diff); - if (m_gameTime > mail_expire_check_timer) + if (currentGameTime > mail_expire_check_timer) { sObjectMgr->ReturnOrDeleteOldMails(true); - mail_expire_check_timer = m_gameTime + 6 * 3600; + mail_expire_check_timer = currentGameTime + 6h; } { @@ -2341,10 +2325,8 @@ void World::Update(uint32 diff) m_timers[WUPDATE_CLEANDB].Reset(); LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_OLD_LOGS); - stmt->setUInt32(0, sWorld->getIntConfig(CONFIG_LOGDB_CLEARTIME)); - stmt->setUInt32(1, uint32(time(0))); - + stmt->setUInt32(1, uint32(currentGameTime.count())); LoginDatabase.Execute(stmt); } } @@ -2354,8 +2336,8 @@ void World::Update(uint32 diff) sLFGMgr->Update(diff, 0); // pussywizard: remove obsolete stuff before finding compatibility during map update } - ///- Update objects when the timer has passed (maps, transport, creatures, ...) { + ///- Update objects when the timer has passed (maps, transport, creatures, ...) METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update maps")); sMapMgr->Update(diff); } @@ -2401,18 +2383,13 @@ void World::Update(uint32 diff) { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update uptime")); - uint32 tmpDiff = uint32(m_gameTime - m_startTime); - uint32 maxOnlinePlayers = GetMaxPlayerCount(); - m_timers[WUPDATE_UPTIME].Reset(); LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_UPTIME_PLAYERS); - - stmt->setUInt32(0, tmpDiff); - stmt->setUInt16(1, uint16(maxOnlinePlayers)); + stmt->setUInt32(0, uint32(GameTime::GetUptime().count())); + stmt->setUInt16(1, uint16(GetMaxPlayerCount())); stmt->setUInt32(2, realm.Id.Realm); - stmt->setUInt32(3, uint32(m_startTime)); - + stmt->setUInt32(3, uint32(GameTime::GetStartTime().count())); LoginDatabase.Execute(stmt); } @@ -2421,6 +2398,7 @@ void World::Update(uint32 diff) { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Remove old corpses")); m_timers[WUPDATE_CORPSES].Reset(); + sMapMgr->DoForAllMaps([](Map* map) { map->RemoveOldCorpses(); @@ -2710,16 +2688,16 @@ void World::KickAllLess(AccountTypes sec) void World::_UpdateGameTime() { ///- update the time - time_t thisTime = time(nullptr); - uint32 elapsed = uint32(thisTime - m_gameTime); - m_gameTime = thisTime; - m_gameMSTime = getMSTime(); + Seconds lastGameTime = GameTime::GetGameTime(); + GameTime::UpdateGameTimers(); + + Seconds elapsed = GameTime::GetGameTime() - lastGameTime; ///- if there is a shutdown timer - if (!IsStopped() && m_ShutdownTimer > 0 && elapsed > 0) + if (!IsStopped() && m_ShutdownTimer > 0 && elapsed > 0s) { ///- ... and it is overdue, stop the world (set m_stopEvent) - if (m_ShutdownTimer <= elapsed) + if (m_ShutdownTimer <= elapsed.count()) { if (!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount() == 0) m_stopEvent = true; // exist code already set @@ -2729,7 +2707,7 @@ void World::_UpdateGameTime() ///- ... else decrease it and if necessary display a shutdown countdown to the users else { - m_ShutdownTimer -= elapsed; + m_ShutdownTimer -= elapsed.count(); ShutdownMsg(); } @@ -2882,7 +2860,7 @@ void World::UpdateSessions(uint32 diff) if (pSession->HandleSocketClosed()) { if (!RemoveQueuedPlayer(pSession) && getIntConfig(CONFIG_INTERVAL_DISCONNECT_TOLERANCE)) - m_disconnects[pSession->GetAccountId()] = time(nullptr); + m_disconnects[pSession->GetAccountId()] = GameTime::GetGameTime().count(); m_sessions.erase(itr); // there should be no offline session if current one is logged onto a character SessionMap::iterator iter; @@ -2893,7 +2871,7 @@ void World::UpdateSessions(uint32 diff) tmp->SetShouldSetOfflineInDB(false); delete tmp; } - pSession->SetOfflineTime(time(nullptr)); + pSession->SetOfflineTime(GameTime::GetGameTime().count()); m_offlineSessions[pSession->GetAccountId()] = pSession; continue; } @@ -2904,7 +2882,7 @@ void World::UpdateSessions(uint32 diff) if (!pSession->Update(diff, updater)) { if (!RemoveQueuedPlayer(pSession) && getIntConfig(CONFIG_INTERVAL_DISCONNECT_TOLERANCE)) - m_disconnects[pSession->GetAccountId()] = time(nullptr); + m_disconnects[pSession->GetAccountId()] = GameTime::GetGameTime().count(); m_sessions.erase(itr); if (m_offlineSessions.find(pSession->GetAccountId()) != m_offlineSessions.end()) // pussywizard: don't set offline in db because offline session for that acc is present (character is in world) pSession->SetShouldSetOfflineInDB(false); @@ -2915,7 +2893,7 @@ void World::UpdateSessions(uint32 diff) // pussywizard: if (m_offlineSessions.empty()) return; - uint32 currTime = time(nullptr); + uint32 currTime = GameTime::GetGameTime().count(); for (SessionMap::iterator itr = m_offlineSessions.begin(), next; itr != m_offlineSessions.end(); itr = next) { next = itr; @@ -3046,59 +3024,79 @@ void World::_UpdateRealmCharCount(PreparedQueryResult resultCharCount) void World::InitWeeklyQuestResetTime() { - time_t wstime = time_t(sWorld->getWorldState(WS_WEEKLY_QUEST_RESET_TIME)); - m_NextWeeklyQuestReset = wstime ? wstime : Acore::Time::GetNextTimeWithDayAndHour(4, 6); - if (!wstime) - sWorld->setWorldState(WS_WEEKLY_QUEST_RESET_TIME, uint64(m_NextWeeklyQuestReset)); + Seconds wstime = Seconds(sWorld->getWorldState(WS_WEEKLY_QUEST_RESET_TIME)); + m_NextWeeklyQuestReset = wstime > 0s ? wstime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(4, 6)); + + if (wstime == 0s) + { + sWorld->setWorldState(WS_WEEKLY_QUEST_RESET_TIME, m_NextWeeklyQuestReset.count()); + } } void World::InitDailyQuestResetTime() { - time_t wstime = time_t(sWorld->getWorldState(WS_DAILY_QUEST_RESET_TIME)); - m_NextDailyQuestReset = wstime ? wstime : Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - if (!wstime) - sWorld->setWorldState(WS_DAILY_QUEST_RESET_TIME, uint64(m_NextDailyQuestReset)); + Seconds wstime = Seconds(sWorld->getWorldState(WS_DAILY_QUEST_RESET_TIME)); + m_NextDailyQuestReset = wstime > 0s ? wstime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + + if (wstime == 0s) + { + sWorld->setWorldState(WS_DAILY_QUEST_RESET_TIME, m_NextDailyQuestReset.count()); + } } void World::InitMonthlyQuestResetTime() { - time_t wstime = time_t(sWorld->getWorldState(WS_MONTHLY_QUEST_RESET_TIME)); - m_NextMonthlyQuestReset = wstime ? wstime : Acore::Time::GetNextTimeWithMonthAndHour(-1, 6); - if (!wstime) - sWorld->setWorldState(WS_MONTHLY_QUEST_RESET_TIME, uint64(m_NextMonthlyQuestReset)); + Seconds wstime = Seconds(sWorld->getWorldState(WS_MONTHLY_QUEST_RESET_TIME)); + m_NextMonthlyQuestReset = wstime > 0s ? wstime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + + if (wstime == 0s) + { + sWorld->setWorldState(WS_MONTHLY_QUEST_RESET_TIME, m_NextMonthlyQuestReset.count()); + } } void World::InitRandomBGResetTime() { - time_t wstime = time_t(sWorld->getWorldState(WS_BG_DAILY_RESET_TIME)); - m_NextRandomBGReset = wstime ? wstime : Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - if (!wstime) - sWorld->setWorldState(WS_BG_DAILY_RESET_TIME, uint64(m_NextRandomBGReset)); + Seconds wstime = Seconds(sWorld->getWorldState(WS_BG_DAILY_RESET_TIME)); + m_NextRandomBGReset = wstime > 0s ? wstime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + + if (wstime == 0s) + { + sWorld->setWorldState(WS_BG_DAILY_RESET_TIME, m_NextRandomBGReset.count()); + } } void World::InitCalendarOldEventsDeletionTime() { - time_t now = time(nullptr); - time_t currentDeletionTime = getWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME); - time_t nextDeletionTime = currentDeletionTime ? currentDeletionTime : Acore::Time::GetNextTimeWithDayAndHour(-1, getIntConfig(CONFIG_CALENDAR_DELETE_OLD_EVENTS_HOUR)); + Seconds currentDeletionTime = Seconds(getWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME)); + Seconds nextDeletionTime = currentDeletionTime > 0s ? currentDeletionTime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, getIntConfig(CONFIG_CALENDAR_DELETE_OLD_EVENTS_HOUR))); // If the reset time saved in the worldstate is before now it means the server was offline when the reset was supposed to occur. // In this case we set the reset time in the past and next world update will do the reset and schedule next one in the future. - if (currentDeletionTime < now) - m_NextCalendarOldEventsDeletionTime = nextDeletionTime - DAY; + if (currentDeletionTime < GameTime::GetGameTime()) + { + m_NextCalendarOldEventsDeletionTime = nextDeletionTime - 1_days; + } else + { m_NextCalendarOldEventsDeletionTime = nextDeletionTime; + } - if (!currentDeletionTime) - sWorld->setWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME, uint64(m_NextCalendarOldEventsDeletionTime)); + if (currentDeletionTime == 0s) + { + sWorld->setWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME, m_NextCalendarOldEventsDeletionTime.count()); + } } void World::InitGuildResetTime() { - time_t wstime = time_t(getWorldState(WS_GUILD_DAILY_RESET_TIME)); - m_NextGuildReset = wstime ? wstime : Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - if (!wstime) - sWorld->setWorldState(WS_GUILD_DAILY_RESET_TIME, uint64(m_NextGuildReset)); + Seconds wstime = Seconds(getWorldState(WS_GUILD_DAILY_RESET_TIME)); + m_NextGuildReset = wstime > 0s ? wstime : Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + + if (wstime == 0s) + { + sWorld->setWorldState(WS_GUILD_DAILY_RESET_TIME, m_NextGuildReset.count()); + } } void World::ResetDailyQuests() @@ -3110,8 +3108,8 @@ void World::ResetDailyQuests() if (itr->second->GetPlayer()) itr->second->GetPlayer()->ResetDailyQuestStatus(); - m_NextDailyQuestReset = Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - sWorld->setWorldState(WS_DAILY_QUEST_RESET_TIME, uint64(m_NextDailyQuestReset)); + m_NextDailyQuestReset = Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + sWorld->setWorldState(WS_DAILY_QUEST_RESET_TIME, m_NextDailyQuestReset.count()); // change available dailies sPoolMgr->ChangeDailyQuests(); @@ -3145,8 +3143,8 @@ void World::ResetWeeklyQuests() if (itr->second->GetPlayer()) itr->second->GetPlayer()->ResetWeeklyQuestStatus(); - m_NextWeeklyQuestReset = Acore::Time::GetNextTimeWithDayAndHour(4, 6); - sWorld->setWorldState(WS_WEEKLY_QUEST_RESET_TIME, uint64(m_NextWeeklyQuestReset)); + m_NextWeeklyQuestReset = Seconds(Acore::Time::GetNextTimeWithDayAndHour(4, 6)); + sWorld->setWorldState(WS_WEEKLY_QUEST_RESET_TIME, m_NextWeeklyQuestReset.count()); // change available weeklies sPoolMgr->ChangeWeeklyQuests(); @@ -3163,8 +3161,8 @@ void World::ResetMonthlyQuests() if (itr->second->GetPlayer()) itr->second->GetPlayer()->ResetMonthlyQuestStatus(); - m_NextMonthlyQuestReset = Acore::Time::GetNextTimeWithMonthAndHour(-1, 6); - sWorld->setWorldState(WS_MONTHLY_QUEST_RESET_TIME, uint64(m_NextMonthlyQuestReset)); + m_NextMonthlyQuestReset = Seconds(Acore::Time::GetNextTimeWithMonthAndHour(-1, 6)); + sWorld->setWorldState(WS_MONTHLY_QUEST_RESET_TIME, m_NextMonthlyQuestReset.count()); } void World::ResetEventSeasonalQuests(uint16 event_id) @@ -3189,16 +3187,16 @@ void World::ResetRandomBG() if (itr->second->GetPlayer()) itr->second->GetPlayer()->SetRandomWinner(false); - m_NextRandomBGReset = Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - sWorld->setWorldState(WS_BG_DAILY_RESET_TIME, uint64(m_NextRandomBGReset)); + m_NextRandomBGReset = Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + sWorld->setWorldState(WS_BG_DAILY_RESET_TIME, m_NextRandomBGReset.count()); } void World::CalendarDeleteOldEvents() { LOG_INFO("server.worldserver", "Calendar deletion of old events."); - m_NextCalendarOldEventsDeletionTime = time_t(m_NextCalendarOldEventsDeletionTime + DAY); - sWorld->setWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME, uint64(m_NextCalendarOldEventsDeletionTime)); + m_NextCalendarOldEventsDeletionTime += 1_days; + sWorld->setWorldState(WS_DAILY_CALENDAR_DELETION_OLD_EVENTS_TIME, m_NextCalendarOldEventsDeletionTime.count()); sCalendarMgr->DeleteOldEvents(); } @@ -3206,8 +3204,8 @@ void World::ResetGuildCap() { LOG_INFO("server.worldserver", "Guild Daily Cap reset."); - m_NextGuildReset = Acore::Time::GetNextTimeWithDayAndHour(-1, 6); - sWorld->setWorldState(WS_GUILD_DAILY_RESET_TIME, uint64(m_NextGuildReset)); + m_NextGuildReset = Seconds(Acore::Time::GetNextTimeWithDayAndHour(-1, 6)); + sWorld->setWorldState(WS_GUILD_DAILY_RESET_TIME, m_NextGuildReset.count()); sGuildMgr->ResetTimes(); } @@ -3225,7 +3223,7 @@ void World::LoadDBVersion() { Field* fields = result->Fetch(); - m_DBVersion = fields[0].GetString(); + m_DBVersion = fields[0].GetString(); // will be overwrite by config values if different and non-0 m_int_configs[CONFIG_CLIENTCACHE_VERSION] = fields[1].GetUInt32(); @@ -3298,48 +3296,42 @@ void World::LoadWorldStates() return; } - uint32 count = 0; - do { Field* fields = result->Fetch(); m_worldstates[fields[0].GetUInt32()] = fields[1].GetUInt32(); - ++count; } while (result->NextRow()); - LOG_INFO("server.loading", ">> Loaded %u world states in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + FMT_LOG_INFO("server.loading", ">> Loaded {} world states in %u ms", m_worldstates.size(), GetMSTimeDiffToNow(oldMSTime)); LOG_INFO("server.loading", " "); } // Setting a worldstate will save it to DB -void World::setWorldState(uint32 index, uint64 value) +void World::setWorldState(uint32 index, uint64 timeValue) { - WorldStatesMap::const_iterator it = m_worldstates.find(index); + auto const& it = m_worldstates.find(index); if (it != m_worldstates.end()) { CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_WORLDSTATE); - - stmt->setUInt32(0, uint32(value)); + stmt->setUInt32(0, uint32(timeValue)); stmt->setUInt32(1, index); - CharacterDatabase.Execute(stmt); } else { CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_WORLDSTATE); - stmt->setUInt32(0, index); - stmt->setUInt32(1, uint32(value)); - + stmt->setUInt32(1, uint32(timeValue)); CharacterDatabase.Execute(stmt); } - m_worldstates[index] = value; + + m_worldstates[index] = timeValue; } uint64 World::getWorldState(uint32 index) const { - WorldStatesMap::const_iterator it = m_worldstates.find(index); - return it != m_worldstates.end() ? it->second : 0; + auto const& itr = m_worldstates.find(index); + return itr != m_worldstates.end() ? itr->second : 0; } void World::ProcessQueryCallbacks() diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index 9b2d91ab2a..423bba6691 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -226,22 +226,10 @@ public: /// Get the path where data (dbc, maps) are stored on disk [[nodiscard]] std::string const& GetDataPath() const override { return m_dataPath; } - /// When server started? - [[nodiscard]] time_t const& GetStartTime() const override { return m_startTime; } - /// What time is it? - [[nodiscard]] time_t const& GetGameTime() const override { return m_gameTime; } - /// What time is it? in ms - static uint32 GetGameTimeMS() { return m_gameMSTime; } - /// Uptime (in secs) - [[nodiscard]] uint32 GetUptime() const override { return uint32(m_gameTime - m_startTime); } - /// Update time - [[nodiscard]] uint32 GetUpdateTime() const override { return m_updateTime; } - void SetRecordDiffInterval(int32 t) override { if (t >= 0) m_int_configs[CONFIG_INTERVAL_LOG_UPDATE] = (uint32)t; } - /// Next daily quests and random bg reset time - [[nodiscard]] time_t GetNextDailyQuestsResetTime() const override { return m_NextDailyQuestReset; } - [[nodiscard]] time_t GetNextWeeklyQuestsResetTime() const override { return m_NextWeeklyQuestReset; } - [[nodiscard]] time_t GetNextRandomBGResetTime() const override { return m_NextRandomBGReset; } + [[nodiscard]] Seconds GetNextDailyQuestsResetTime() const override { return m_NextDailyQuestReset; } + [[nodiscard]] Seconds GetNextWeeklyQuestsResetTime() const override { return m_NextWeeklyQuestReset; } + [[nodiscard]] Seconds GetNextRandomBGResetTime() const override { return m_NextRandomBGReset; } /// Get the maximum skill level a player can reach [[nodiscard]] uint16 GetConfigMaxSkillValue() const override @@ -397,12 +385,8 @@ private: bool m_isClosed; - time_t m_startTime; - time_t m_gameTime; IntervalTimer m_timers[WUPDATE_COUNT]; - time_t mail_expire_check_timer; - uint32 m_updateTime, m_updateTimeSum; - static uint32 m_gameMSTime; + Seconds mail_expire_check_timer; SessionMap m_sessions; SessionMap m_offlineSessions; @@ -440,12 +424,12 @@ private: LockedQueue<CliCommandHolder*> cliCmdQueue; // next daily quests and random bg reset time - time_t m_NextDailyQuestReset; - time_t m_NextWeeklyQuestReset; - time_t m_NextMonthlyQuestReset; - time_t m_NextRandomBGReset; - time_t m_NextCalendarOldEventsDeletionTime; - time_t m_NextGuildReset; + Seconds m_NextDailyQuestReset; + Seconds m_NextWeeklyQuestReset; + Seconds m_NextMonthlyQuestReset; + Seconds m_NextRandomBGReset; + Seconds m_NextCalendarOldEventsDeletionTime; + Seconds m_NextGuildReset; //Player Queue Queue m_QueuedPlayer; diff --git a/src/server/scripts/Commands/cs_ban.cpp b/src/server/scripts/Commands/cs_ban.cpp index 849287da11..a34e0aa672 100644 --- a/src/server/scripts/Commands/cs_ban.cpp +++ b/src/server/scripts/Commands/cs_ban.cpp @@ -26,6 +26,7 @@ EndScriptData */ #include "BanMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "GameTime.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" @@ -305,7 +306,7 @@ public: time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(nullptr))) + if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= GameTime::GetGameTime().count())) active = true; bool permanent = (fields[1].GetUInt64() == uint64(0)); std::string banTime = permanent ? handler->GetAcoreString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); @@ -353,7 +354,7 @@ public: Field* fields = result->Fetch(); time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(nullptr))) + if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= GameTime::GetGameTime().count())) active = true; bool permanent = (fields[1].GetUInt32() == uint32(0)); std::string banTime = permanent ? handler->GetAcoreString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); diff --git a/src/server/scripts/Commands/cs_event.cpp b/src/server/scripts/Commands/cs_event.cpp index 4dc64ce1a7..f1c1da6b7d 100644 --- a/src/server/scripts/Commands/cs_event.cpp +++ b/src/server/scripts/Commands/cs_event.cpp @@ -24,6 +24,7 @@ #include "Chat.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "Language.h" #include "Player.h" #include "ScriptMgr.h" @@ -116,8 +117,8 @@ public: std::string endTimeStr = Acore::Time::TimeToTimestampStr(Seconds(eventData.end)); uint32 delay = sGameEventMgr->NextCheck(eventId); - time_t nextTime = time(nullptr) + delay; - std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? Acore::Time::TimeToTimestampStr(Seconds(time(nullptr) + delay)) : "-"; + time_t nextTime = GameTime::GetGameTime().count() + delay; + std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? Acore::Time::TimeToTimestampStr(Seconds(nextTime)) : "-"; std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE, true); std::string lengthStr = secsToTimeString(eventData.length * MINUTE, true); diff --git a/src/server/scripts/Commands/cs_gobject.cpp b/src/server/scripts/Commands/cs_gobject.cpp index 9e7f925ab7..4cad8ed71b 100644 --- a/src/server/scripts/Commands/cs_gobject.cpp +++ b/src/server/scripts/Commands/cs_gobject.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "Chat.h" #include "GameEventMgr.h" #include "GameObject.h" +#include "GameTime.h" #include "Language.h" #include "MapMgr.h" #include "ObjectMgr.h" @@ -280,7 +281,7 @@ public: if (target) { - int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - time(nullptr)); + int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - GameTime::GetGameTime().count()); if (curRespawnDelay < 0) curRespawnDelay = 0; diff --git a/src/server/scripts/Commands/cs_instance.cpp b/src/server/scripts/Commands/cs_instance.cpp index a1de1ebef1..d9170ad6cd 100644 --- a/src/server/scripts/Commands/cs_instance.cpp +++ b/src/server/scripts/Commands/cs_instance.cpp @@ -23,6 +23,7 @@ EndScriptData */ #include "Chat.h" +#include "GameTime.h" #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" @@ -73,7 +74,7 @@ public: { InstanceSave const* save = bind.save; uint32 resetTime = bind.extended ? save->GetExtendedResetTime() : save->GetResetTime(); - uint32 ttr = (resetTime >= time(nullptr) ? resetTime - time(nullptr) : 0); + uint32 ttr = (resetTime >= GameTime::GetGameTime().count() ? resetTime - GameTime::GetGameTime().count() : 0); std::string timeleft = secsToTimeString(ttr); handler->PSendSysMessage("map: %d, inst: %d, perm: %s, diff: %d, canReset: %s, TTR: %s%s", mapId, save->GetInstanceId(), bind.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str(), (bind.extended ? " (extended)" : "")); @@ -111,7 +112,7 @@ public: if (itr->first != player->GetMapId() && (!mapId || mapId == itr->first) && (!difficultyArg || difficultyArg == save->GetDifficulty())) { uint32 resetTime = itr->second.extended ? save->GetExtendedResetTime() : save->GetResetTime(); - uint32 ttr = (resetTime >= time(nullptr) ? resetTime - time(nullptr) : 0); + uint32 ttr = (resetTime >= GameTime::GetGameTime().count() ? resetTime - GameTime::GetGameTime().count() : 0); std::string timeleft = secsToTimeString(ttr); handler->PSendSysMessage("unbinding map: %d, inst: %d, perm: %s, diff: %d, canReset: %s, TTR: %s%s", itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str(), (itr->second.extended ? " (extended)" : "")); sInstanceSaveMgr->PlayerUnbindInstance(player->GetGUID(), itr->first, Difficulty(i), true, player); diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index de1722e075..5f35e58d2c 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -22,6 +22,7 @@ #include "CharacterCache.h" #include "Chat.h" #include "GameGraveyard.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "GuildMgr.h" @@ -2131,13 +2132,13 @@ public: // Output III. LANG_PINFO_BANNED if ban exists and is applied if (banTime >= 0) { - handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - time(nullptr), true).c_str() : handler->GetAcoreString(LANG_PERMANENTLY), bannedBy.c_str()); + handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - GameTime::GetGameTime().count(), true).c_str() : handler->GetAcoreString(LANG_PERMANENTLY), bannedBy.c_str()); } // Output IV. LANG_PINFO_MUTED if mute is applied if (muteTime > 0) { - handler->PSendSysMessage(LANG_PINFO_MUTED, muteReason.c_str(), secsToTimeString(muteTime - time(nullptr), true).c_str(), muteBy.c_str()); + handler->PSendSysMessage(LANG_PINFO_MUTED, muteReason.c_str(), secsToTimeString(muteTime - GameTime::GetGameTime().count(), true).c_str(), muteBy.c_str()); } // Output V. LANG_PINFO_ACC_ACCOUNT @@ -2409,7 +2410,7 @@ public: if (target) { // Target is online, mute will be in effect right away. - int64 muteTime = time(nullptr) + notSpeakTime * MINUTE; + int64 muteTime = GameTime::GetGameTime().count() + notSpeakTime * MINUTE; target->GetSession()->m_muteTime = muteTime; stmt->setInt64(0, muteTime); std::string nameLink = handler->playerLink(player->GetName()); diff --git a/src/server/scripts/Commands/cs_npc.cpp b/src/server/scripts/Commands/cs_npc.cpp index 3b8347e311..92689e8667 100644 --- a/src/server/scripts/Commands/cs_npc.cpp +++ b/src/server/scripts/Commands/cs_npc.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "Chat.h" #include "CreatureAI.h" #include "CreatureGroups.h" +#include "GameTime.h" #include "Language.h" #include "ObjectMgr.h" #include "Pet.h" @@ -605,7 +606,7 @@ public: id3 = cData->id3; } - int64 curRespawnDelay = target->GetRespawnTimeEx() - time(nullptr); + int64 curRespawnDelay = target->GetRespawnTimeEx() - GameTime::GetGameTime().count(); if (curRespawnDelay < 0) curRespawnDelay = 0; std::string curRespawnDelayStr = secsToTimeString(uint64(curRespawnDelay), true); diff --git a/src/server/scripts/Commands/cs_quest.cpp b/src/server/scripts/Commands/cs_quest.cpp index 6cb46ed49b..18f3257265 100644 --- a/src/server/scripts/Commands/cs_quest.cpp +++ b/src/server/scripts/Commands/cs_quest.cpp @@ -23,6 +23,7 @@ Category: commandscripts EndScriptData */ #include "Chat.h" +#include "GameTime.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" @@ -379,7 +380,7 @@ public: // fill mail MailDraft draft(quest->GetTitle(), std::string()); - for (auto itr : questItems) + for (auto const& itr : questItems) { if (Item* item = Item::CreateItem(itr.first, itr.second)) { @@ -615,7 +616,7 @@ public: // fill mail MailDraft draft(quest->GetTitle(), "This quest has been manually rewarded to you. This mail contains your quest rewards."); - for (auto itr : questRewardItems) + for (auto const& itr : questRewardItems) { if (!itr.first || !itr.second) { @@ -652,7 +653,7 @@ public: stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS); stmt->setUInt32(0, guid); stmt->setUInt32(1, entry); - stmt->setUInt64(2, time(nullptr)); + stmt->setUInt64(2, GameTime::GetGameTime().count()); trans->Append(stmt); } else if (quest->IsWeekly()) diff --git a/src/server/scripts/Commands/cs_server.cpp b/src/server/scripts/Commands/cs_server.cpp index 7ccd4d2305..53ab969717 100644 --- a/src/server/scripts/Commands/cs_server.cpp +++ b/src/server/scripts/Commands/cs_server.cpp @@ -22,9 +22,9 @@ Category: commandscripts EndScriptData */ -#include "AvgDiffTracker.h" #include "Chat.h" #include "Config.h" +#include "GameTime.h" #include "GitRevision.h" #include "Language.h" #include "ModuleMgr.h" @@ -34,6 +34,7 @@ #include "ScriptMgr.h" #include "ServerMotd.h" #include "StringConvert.h" +#include "UpdateTime.h" #include "VMapFactory.h" #include "VMapMgr2.h" #include <boost/version.hpp> @@ -77,7 +78,6 @@ public: static ChatCommandTable serverSetCommandTable = { - { "difftime", HandleServerSetDiffTimeCommand, SEC_CONSOLE, Console::Yes }, { "loglevel", HandleServerSetLogLevelCommand, SEC_CONSOLE, Console::Yes }, { "motd", HandleServerSetMotdCommand, SEC_ADMINISTRATOR, Console::Yes }, { "closed", HandleServerSetClosedCommand, SEC_CONSOLE, Console::Yes }, @@ -238,23 +238,16 @@ public: uint32 activeSessionCount = sWorld->GetActiveSessionCount(); uint32 queuedSessionCount = sWorld->GetQueuedSessionCount(); uint32 connPeak = sWorld->GetMaxActiveSessionCount(); - std::string uptime = secsToTimeString(sWorld->GetUptime()).append("."); - uint32 updateTime = sWorld->GetUpdateTime(); - uint32 avgUpdateTime = avgDiffTracker.getAverage(); handler->PSendSysMessage("%s", GitRevision::GetFullVersion()); if (!queuedSessionCount) handler->PSendSysMessage("Connected players: %u. Characters in world: %u.", activeSessionCount, playerCount); else handler->PSendSysMessage("Connected players: %u. Characters in world: %u. Queue: %u.", activeSessionCount, playerCount, queuedSessionCount); - handler->PSendSysMessage("Connection peak: %u.", connPeak); - handler->PSendSysMessage(LANG_UPTIME, uptime.c_str()); - handler->PSendSysMessage("Update time diff: %ums, average: %ums.", updateTime, avgUpdateTime); - if (handler->GetSession()) - if (Player* p = handler->GetSession()->GetPlayer()) - if (p->IsDeveloper()) - handler->PSendSysMessage("DEV wavg: %ums, nsmax: %ums, nsavg: %ums. LFG avg: %ums, max: %ums.", avgDiffTracker.getTimeWeightedAverage(), devDiffTracker.getMax(), devDiffTracker.getAverage(), lfgDiffTracker.getAverage(), lfgDiffTracker.getMax()); + handler->PSendSysMessage("Connection peak: %u.", connPeak); + handler->PSendSysMessage(LANG_UPTIME, secsToTimeString(GameTime::GetUptime().count()).c_str()); + handler->PSendSysMessage("Update time diff: %ums, average: %ums.", sWorldUpdateTime.GetLastUpdateTime(), sWorldUpdateTime.GetAverageUpdateTime()); //! Can't use sWorld->ShutdownMsg here in case of console command if (sWorld->IsShuttingDown()) @@ -439,18 +432,6 @@ public: sLog->SetLogLevel(name, level, isLogger); return true; } - - // set diff time record interval - static bool HandleServerSetDiffTimeCommand(ChatHandler* /*handler*/, int32 newTime) - { - if (newTime < 0) - return false; - - sWorld->SetRecordDiffInterval(newTime); - printf("Record diff every %u ms\n", newTime); - - return true; - } }; void AddSC_server_commandscript() diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp index 6786a0a708..bd04b5b1d0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp @@ -16,6 +16,7 @@ */ #include "blackrock_depths.h" +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -154,7 +155,7 @@ public: { if (InstanceScript* instance = player->GetInstanceScript()) { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (instance->GetData(TYPE_RING_OF_LAW) == IN_PROGRESS || instance->GetData(TYPE_RING_OF_LAW) == DONE) { return false; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp index b6055df4a4..d4bd921f92 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp @@ -15,12 +15,13 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "InstanceScript.h" #include "Player.h" #include "ScriptMgr.h" #include "blackrock_depths.h" -#define MAX_ENCOUNTER 6 +constexpr auto MAX_ENCOUNTER = 6; enum Timers { @@ -462,7 +463,7 @@ public: { TempSummonGrimstone->RemoveFromWorld(); TempSummonGrimstone = nullptr; - timeRingFail = time(nullptr); + timeRingFail = GameTime::GetGameTime().count(); } SetData(TYPE_RING_OF_LAW, NOT_STARTED); break; diff --git a/src/server/scripts/Events/brewfest.cpp b/src/server/scripts/Events/brewfest.cpp index 55b46485e4..5996eed010 100644 --- a/src/server/scripts/Events/brewfest.cpp +++ b/src/server/scripts/Events/brewfest.cpp @@ -18,6 +18,7 @@ #include "CellImpl.h" #include "GameEventMgr.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "LFGMgr.h" @@ -99,7 +100,7 @@ struct npc_brewfest_keg_reciver : public ScriptedAI { if (Aura* aur = player->GetAura(SPELL_RAM_AURA)) { - int32 diff = aur->GetApplyTime() - (time(nullptr) - (HOUR * 18) + spellCooldown); + int32 diff = aur->GetApplyTime() - (GameTime::GetGameTime().count() - (HOUR * 18) + spellCooldown); if (diff > 10) // aura applied later return; diff --git a/src/server/scripts/Events/midsummer.cpp b/src/server/scripts/Events/midsummer.cpp index 1b769815fe..99cbf09005 100644 --- a/src/server/scripts/Events/midsummer.cpp +++ b/src/server/scripts/Events/midsummer.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -198,7 +199,7 @@ public: Position pos; pos.Relocate(posVec.at(num)); me->m_last_notify_position.Relocate(0.0f, 0.0f, 0.0f); - me->m_last_notify_mstime = World::GetGameTimeMS() + 10000; + me->m_last_notify_mstime = GameTime::GetGameTimeMS().count() + 10000; me->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } @@ -310,7 +311,7 @@ public: } // Achievement - if ((time(nullptr) - GetApplyTime()) > 60 && target->GetTypeId() == TYPEID_PLAYER) + if ((GameTime::GetGameTime().count() - GetApplyTime()) > 60 && target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 58934, 0, target); } } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp index 74cc7eb41c..e5463f1f92 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Group.h" #include "Player.h" #include "ScriptMgr.h" @@ -348,7 +349,7 @@ public: c->DespawnOrUnsummon(10000); if( Creature* c = instance->GetCreature(NPC_DreadscaleGUID) ) c->DespawnOrUnsummon(10000); - if( AchievementTimer + 10 >= time(nullptr) ) + if( AchievementTimer + 10 >= GameTime::GetGameTime().count() ) DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_JORMUNGAR_ACHIEV); AchievementTimer = 0; @@ -365,7 +366,7 @@ public: } else // first one died, start timer for achievement { - AchievementTimer = time(nullptr); + AchievementTimer = GameTime::GetGameTime().count(); } } else @@ -447,14 +448,14 @@ public: HandleGameObject(GO_EnterGateGUID, true); - if( AchievementTimer + 60 >= time(nullptr) ) + if( AchievementTimer + 60 >= GameTime::GetGameTime().count() ) DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_RESILIENCE_WILL_FIX_IT_CREDIT); AchievementTimer = 0; SaveToDB(); } else if( Counter == 1 ) - AchievementTimer = time(nullptr); + AchievementTimer = GameTime::GetGameTime().count(); } break; case TYPE_FACTION_CHAMPIONS_START: diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp index 3c0afa64cb..f427a448d1 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp @@ -16,6 +16,7 @@ */ #include "CreatureTextMgr.h" +#include "GameTime.h" #include "MoveSpline.h" #include "MoveSplineInit.h" #include "ScriptMgr.h" @@ -424,7 +425,7 @@ public: return false; bool summoned = false; - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); for (int32 i = first; i <= last; ++i) { if (_respawnCooldowns[i] > now) @@ -460,7 +461,7 @@ public: void ClearSlot(PassengerSlots slot) { _controlledSlots[slot].Clear(); - _respawnCooldowns[slot] = time(nullptr) + _slotInfo[slot].Cooldown; + _respawnCooldowns[slot] = GameTime::GetGameTime().count() + _slotInfo[slot].Cooldown; } private: @@ -749,7 +750,7 @@ public: _controller.ResetSlots(TEAM_HORDE, creature->GetTransport()->ToMotionTransport()); me->SetRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(nullptr) + 45; + _firstMageCooldown = GameTime::GetGameTime().count() + 45; _axethrowersYellCooldown = time_t(0); _rocketeersYellCooldown = time_t(0); checkTimer = 1000; @@ -814,7 +815,7 @@ public: } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -989,10 +990,10 @@ public: case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(me, SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_axethrowersYellCooldown < time(nullptr)) + if (_axethrowersYellCooldown < GameTime::GetGameTime().count()) { Talk(SAY_SAURFANG_AXETHROWERS); - _axethrowersYellCooldown = time(nullptr) + 5; + _axethrowersYellCooldown = GameTime::GetGameTime().count() + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1500); @@ -1000,10 +1001,10 @@ public: case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(me, SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_rocketeersYellCooldown < time(nullptr)) + if (_rocketeersYellCooldown < GameTime::GetGameTime().count()) { Talk(SAY_SAURFANG_ROCKETEERS); - _rocketeersYellCooldown = time(nullptr) + 5; + _rocketeersYellCooldown = GameTime::GetGameTime().count() + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1500); @@ -1084,7 +1085,7 @@ public: _controller.ResetSlots(TEAM_ALLIANCE, creature->GetTransport()->ToMotionTransport()); me->SetRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(nullptr) + 45; + _firstMageCooldown = GameTime::GetGameTime().count() + 45; _riflemanYellCooldown = time_t(0); _mortarYellCooldown = time_t(0); checkTimer = 1000; @@ -1150,7 +1151,7 @@ public: } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(nullptr); + time_t now = GameTime::GetGameTime().count(); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -1328,10 +1329,10 @@ public: case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(me, SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_riflemanYellCooldown < time(nullptr)) + if (_riflemanYellCooldown < GameTime::GetGameTime().count()) { Talk(SAY_MURADIN_RIFLEMAN); - _riflemanYellCooldown = time(nullptr) + 5; + _riflemanYellCooldown = GameTime::GetGameTime().count() + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1500); @@ -1339,10 +1340,10 @@ public: case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(me, SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_mortarYellCooldown < time(nullptr)) + if (_mortarYellCooldown < GameTime::GetGameTime().count()) { Talk(SAY_MURADIN_MORTAR); - _mortarYellCooldown = time(nullptr) + 5; + _mortarYellCooldown = GameTime::GetGameTime().count() + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1500); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp index 8dff5e2a34..e0f7bf2bd1 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "GridNotifiers.h" #include "ObjectMgr.h" #include "Player.h" @@ -950,7 +951,7 @@ public: if (!spellInfo) return false; - uint32 currMSTime = World::GetGameTimeMS(); + uint32 currMSTime = GameTime::GetGameTimeMS().count(); std::map<uint32, uint32>::iterator itr = _lastMSTimeForSpell.find(spellInfo->Id); if (itr != _lastMSTimeForSpell.end()) { diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp index b6d1548dcb..42b6cbc683 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp @@ -18,6 +18,7 @@ #include "Cell.h" #include "CellImpl.h" #include "CreatureTextMgr.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "ObjectMgr.h" @@ -720,9 +721,9 @@ public: void KilledUnit(Unit* victim) override { - if (victim->GetTypeId() == TYPEID_PLAYER && !me->IsInEvadeMode() && _phase != PHASE_OUTRO && _lastTalkTimeKill + 5 < time(nullptr)) + if (victim->GetTypeId() == TYPEID_PLAYER && !me->IsInEvadeMode() && _phase != PHASE_OUTRO && _lastTalkTimeKill + 5 < GameTime::GetGameTime().count()) { - _lastTalkTimeKill = time(nullptr); + _lastTalkTimeKill = GameTime::GetGameTime().count(); Talk(SAY_LK_KILL); } } @@ -751,7 +752,7 @@ public: events.RescheduleEvent(EVENT_START_ATTACK, 1000); EntryCheckPredicate pred(NPC_STRANGULATE_VEHICLE); summons.DoAction(ACTION_TELEPORT_BACK, pred); - if (!IsHeroic() && _phase != PHASE_OUTRO && me->IsInCombat() && _lastTalkTimeBuff + 5 <= time(nullptr)) + if (!IsHeroic() && _phase != PHASE_OUTRO && me->IsInCombat() && _lastTalkTimeBuff + 5 <= GameTime::GetGameTime().count()) Talk(SAY_LK_FROSTMOURNE_ESCAPE); } break; @@ -906,9 +907,9 @@ public: void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { - if (spell->Id == HARVESTED_SOUL_BUFF && me->IsInCombat() && !IsHeroic() && _phase != PHASE_OUTRO && _lastTalkTimeBuff + 5 <= time(nullptr)) + if (spell->Id == HARVESTED_SOUL_BUFF && me->IsInCombat() && !IsHeroic() && _phase != PHASE_OUTRO && _lastTalkTimeBuff + 5 <= GameTime::GetGameTime().count()) { - _lastTalkTimeBuff = time(nullptr); + _lastTalkTimeBuff = GameTime::GetGameTime().count(); Talk(SAY_LK_FROSTMOURNE_KILL); } } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp index 5fac2ebc4b..6aa0a1fb87 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -276,10 +277,10 @@ public: if (id == 1337) { if (lastShatterMSTime) - if (getMSTimeDiff(lastShatterMSTime, World::GetGameTimeMS()) <= 5000) + if (getMSTimeDiff(lastShatterMSTime, GameTime::GetGameTimeMS().count()) <= 5000) bShattered = true; - lastShatterMSTime = World::GetGameTimeMS(); + lastShatterMSTime = GameTime::GetGameTimeMS().count(); } } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp index d9a50a68fa..ee3c75bb32 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "MapMgr.h" #include "PassiveAI.h" #include "Player.h" @@ -455,7 +456,7 @@ public: case EVENT_SPAWN_FLAMES_INITIAL: { if (changeAllowedFlameSpreadTime) - allowedFlameSpreadTime = time(nullptr); + allowedFlameSpreadTime = GameTime::GetGameTime().count(); std::vector<Player*> pg; Map::PlayerList const& pl = me->GetMap()->GetPlayers(); @@ -2204,7 +2205,7 @@ public: bool Load() override { - lastMSTime = World::GetGameTimeMS(); + lastMSTime = GameTime::GetGameTimeMS().count(); lastOrientation = -1.0f; return true; } @@ -2215,14 +2216,14 @@ public: { if (c->GetTypeId() != TYPEID_UNIT) return; - uint32 diff = getMSTimeDiff(lastMSTime, World::GetGameTimeMS()); + uint32 diff = getMSTimeDiff(lastMSTime, GameTime::GetGameTimeMS().count()); if (lastOrientation == -1.0f) { lastOrientation = (c->ToCreature()->AI()->GetData(0) * 2 * M_PI) / 100.0f; diff = 0; } float new_o = Position::NormalizeOrientation(lastOrientation - (M_PI / 60) * (diff / 250.0f)); - lastMSTime = World::GetGameTimeMS(); + lastMSTime = GameTime::GetGameTimeMS().count(); lastOrientation = new_o; c->SetFacingTo(new_o); @@ -2283,7 +2284,7 @@ public: { npc_ulduar_flames_initialAI(Creature* pCreature) : NullCreatureAI(pCreature) { - CreateTime = time(nullptr); + CreateTime = GameTime::GetGameTime().count(); events.Reset(); events.ScheduleEvent(EVENT_FLAMES_SPREAD, 5750); if( Creature* flame = me->SummonCreature(NPC_FLAMES_SPREAD, me->GetPositionX(), me->GetPositionY(), 364.32f, 0.0f) ) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp index ced3d0467a..27188aa3db 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -1013,10 +1014,10 @@ public: } else if (unit->GetTypeId() == TYPEID_UNIT && unit->GetAreaId() == 4656 /*Conservatory of Life*/) { - if (time(nullptr) > (m_conspeedatoryAttempt + DAY)) + if (GameTime::GetGameTime().count() > (m_conspeedatoryAttempt + DAY)) { DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, 21597 /*CON-SPEED-ATORY_TIMED_CRITERIA*/); - m_conspeedatoryAttempt = time(nullptr); + m_conspeedatoryAttempt = GameTime::GetGameTime().count(); SaveToDB(); } } diff --git a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp index 7f81b6c0c3..ee6c391a69 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp @@ -17,6 +17,7 @@ #include "Battlefield.h" #include "BattlefieldMgr.h" +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -190,13 +191,13 @@ public: switch (type) { case EVENT_ARCHAVON: - ArchavonDeath = time(nullptr); + ArchavonDeath = GameTime::GetGameTime().count(); break; case EVENT_EMALON: - EmalonDeath = time(nullptr); + EmalonDeath = GameTime::GetGameTime().count(); break; case EVENT_KORALON: - KoralonDeath = time(nullptr); + KoralonDeath = GameTime::GetGameTime().count(); break; default: return; diff --git a/src/server/scripts/Northrend/zone_wintergrasp.cpp b/src/server/scripts/Northrend/zone_wintergrasp.cpp index 683591a04f..f602368bc4 100644 --- a/src/server/scripts/Northrend/zone_wintergrasp.cpp +++ b/src/server/scripts/Northrend/zone_wintergrasp.cpp @@ -21,6 +21,7 @@ #include "CombatAI.h" #include "GameGraveyard.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "ObjectMgr.h" #include "Player.h" #include "PoolMgr.h" @@ -294,7 +295,7 @@ public: else { uint32 timer = wintergrasp->GetTimer() / 1000; - player->SendUpdateWorldState(4354, time(nullptr) + timer); + player->SendUpdateWorldState(4354, GameTime::GetGameTime().count() + timer); if (timer < 15 * MINUTE) { AddGossipItemFor(player, GOSSIP_ICON_CHAT, "Queue for Wintergrasp.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); diff --git a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp index 9c5a096dec..bacbe7cfdc 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp @@ -15,6 +15,7 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ +#include "GameTime.h" #include "InstanceScript.h" #include "ScriptMgr.h" #include "the_botanica.h" @@ -163,7 +164,7 @@ public: { if (SpellInfo const* spellInfo = eventInfo.GetSpellInfo()) { - if ((spellInfo->GetSchoolMask() & _lastSchool) && _swapTime > time(nullptr)) + if ((spellInfo->GetSchoolMask() & _lastSchool) && _swapTime > GameTime::GetGameTime().count()) return false; uint32 form = 0; @@ -187,7 +188,7 @@ public: if (form) { - _swapTime = time(nullptr) + 6; + _swapTime = GameTime::GetGameTime().count() + 6; _lastSchool = spellInfo->GetSchoolMask(); GetUnitOwner()->RemoveAurasDueToSpell(_lastForm); _lastForm = form; diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index 13c5adc895..dc9429f6ce 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -29,6 +29,7 @@ #include "Cell.h" #include "CellImpl.h" #include "Chat.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "Group.h" #include "InstanceScript.h" @@ -2250,12 +2251,12 @@ class spell_gen_turkey_marker : public AuraScript { if (GetStackAmount() > stackAmount) { - _applyTimes.push_back(World::GetGameTimeMS()); + _applyTimes.push_back(GameTime::GetGameTimeMS().count()); stackAmount++; } // pop stack if it expired for us - if (_applyTimes.front() + GetMaxDuration() < World::GetGameTimeMS()) + if (_applyTimes.front() + GetMaxDuration() < GameTime::GetGameTimeMS().count()) { stackAmount--; ModStackAmount(-1, AURA_REMOVE_BY_EXPIRE); diff --git a/src/server/scripts/Spells/spell_item.cpp b/src/server/scripts/Spells/spell_item.cpp index 8b0ed7ec0e..8d1140e54f 100644 --- a/src/server/scripts/Spells/spell_item.cpp +++ b/src/server/scripts/Spells/spell_item.cpp @@ -22,6 +22,7 @@ */ #include "Battleground.h" +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -2716,11 +2717,13 @@ class spell_item_crystal_prison_dummy_dnd : public SpellScript void HandleDummy(SpellEffIndex /* effIndex */) { if (Creature* target = GetHitCreature()) + { if (target->isDead() && !target->IsPet()) { - GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0, 0, 0, 0, uint32(target->GetRespawnTime() - time(nullptr))); + GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0, 0, 0, 0, uint32(target->GetRespawnTime() - GameTime::GetGameTime().count())); target->DespawnOrUnsummon(); } + } } void Register() override diff --git a/src/server/scripts/World/areatrigger_scripts.cpp b/src/server/scripts/World/areatrigger_scripts.cpp index d60a4180d1..3de188d331 100644 --- a/src/server/scripts/World/areatrigger_scripts.cpp +++ b/src/server/scripts/World/areatrigger_scripts.cpp @@ -34,6 +34,7 @@ at_brewfest at_area_52_entrance EndContentData */ +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -384,7 +385,7 @@ public: { uint32 triggerId = trigger->entry; // Second trigger happened too early after first, skip for now - if (sWorld->GetGameTime() - _triggerTimes[triggerId] < AREATRIGGER_TALK_COOLDOWN) + if (GameTime::GetGameTime().count() - _triggerTimes[triggerId] < AREATRIGGER_TALK_COOLDOWN) return false; switch (triggerId) @@ -401,7 +402,7 @@ public: break; } - _triggerTimes[triggerId] = sWorld->GetGameTime(); + _triggerTimes[triggerId] = GameTime::GetGameTime().count(); return false; } @@ -441,7 +442,7 @@ public: return false; uint32 triggerId = trigger->entry; - if (sWorld->GetGameTime() - _triggerTimes[trigger->entry] < SUMMON_COOLDOWN) + if (GameTime::GetGameTime().count() - _triggerTimes[trigger->entry] < SUMMON_COOLDOWN) return false; switch (triggerId) @@ -470,7 +471,7 @@ public: player->SummonCreature(NPC_SPOTLIGHT, x, y, z, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 5000); player->AddAura(SPELL_A52_NEURALYZER, player); - _triggerTimes[trigger->entry] = sWorld->GetGameTime(); + _triggerTimes[trigger->entry] = GameTime::GetGameTime().count(); return false; } diff --git a/src/server/scripts/World/go_scripts.cpp b/src/server/scripts/World/go_scripts.cpp index 95a7c806da..4c05c2a390 100644 --- a/src/server/scripts/World/go_scripts.cpp +++ b/src/server/scripts/World/go_scripts.cpp @@ -43,6 +43,7 @@ EndContentData */ #include "CellImpl.h" #include "GameObjectAI.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Player.h" #include "ScriptMgr.h" @@ -1414,7 +1415,7 @@ class go_inconspicuous_landmark : public GameObjectScript public: go_inconspicuous_landmark() : GameObjectScript("go_inconspicuous_landmark") { - _lastUsedTime = time(nullptr); + _lastUsedTime = GameTime::GetGameTime().count(); } bool OnGossipHello(Player* player, GameObject* /*go*/) override @@ -1422,10 +1423,10 @@ public: if (player->HasItemCount(ITEM_CUERGOS_KEY)) return true; - if (_lastUsedTime > time(nullptr)) + if (_lastUsedTime > GameTime::GetGameTime().count()) return true; - _lastUsedTime = time(nullptr) + MINUTE; + _lastUsedTime = GameTime::GetGameTime().count() + MINUTE; player->CastSpell(player, SPELL_SUMMON_PIRATES_TREASURE_AND_TRIGGER_MOB, true); return true; } diff --git a/src/server/scripts/World/npc_stave_of_ancients.cpp b/src/server/scripts/World/npc_stave_of_ancients.cpp index 0e52049fea..3d781258c7 100644 --- a/src/server/scripts/World/npc_stave_of_ancients.cpp +++ b/src/server/scripts/World/npc_stave_of_ancients.cpp @@ -17,6 +17,7 @@ #include "npc_stave_of_ancients.h" #include "CreatureGroups.h" +#include "GameTime.h" #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -602,7 +603,7 @@ public: if (Precious()->isDead()) { // Make it so that Precious respawns after Simone - uint32 respawnTime = me->GetRespawnTime() - time(nullptr); + uint32 respawnTime = me->GetRespawnTime() - GameTime::GetGameTime().count(); Precious()->SetRespawnTime(respawnTime); return; } diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 5b71ad17b4..0a0da2de2a 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -42,6 +42,7 @@ EndContentData */ #include "CreatureTextMgr.h" #include "DBCStructure.h" #include "GameEventMgr.h" +#include "GameTime.h" #include "GridNotifiers.h" #include "ObjectMgr.h" #include "PassiveAI.h" diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index 29b73b509a..dc69d8c028 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -23,7 +23,6 @@ #include "AppenderDB.h" #include "AsyncAcceptor.h" #include "AsyncAuctionListing.h" -#include "AvgDiffTracker.h" #include "Banner.h" #include "BattlegroundMgr.h" #include "BigNumber.h" @@ -590,8 +589,6 @@ void WorldUpdateLoop() realPrevTime = realCurrTime; uint32 executionTimeDiff = getMSTimeDiff(realCurrTime, getMSTime()); - devDiffTracker.Update(executionTimeDiff); - avgDiffTracker.Update(executionTimeDiff > WORLD_SLEEP_CONST ? executionTimeDiff : WORLD_SLEEP_CONST); // we know exactly how long it took to update the world, if the update took less than WORLD_SLEEP_CONST, sleep for WORLD_SLEEP_CONST - world update time if (executionTimeDiff < WORLD_SLEEP_CONST) diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist index e5c46f7d05..8e7e7b3e78 100644 --- a/src/server/worldserver/worldserver.conf.dist +++ b/src/server/worldserver/worldserver.conf.dist @@ -3724,6 +3724,7 @@ Logger.scripts.hotswap=4,Console Server Logger.server=4,Console Server Logger.sql.sql=2,Console DBErrors Logger.sql=4,Console Server +Logger.time.update=4,Console Server #Logger.achievement=4,Console Server #Logger.addon=4,Console Server diff --git a/src/test/mocks/WorldMock.h b/src/test/mocks/WorldMock.h index f95e15e9b0..832d4917a4 100644 --- a/src/test/mocks/WorldMock.h +++ b/src/test/mocks/WorldMock.h @@ -20,6 +20,7 @@ #include "ArenaSpectator.h" #include "IWorld.h" +#include "Duration.h" #include "gmock/gmock.h" #pragma GCC diagnostic push @@ -27,9 +28,10 @@ void AddScripts() {} -class WorldMock: public IWorld { +class WorldMock: public IWorld +{ public: - ~WorldMock() override {} + ~WorldMock() override { } MOCK_METHOD(WorldSession*, FindSession, (uint32 id), (const)); MOCK_METHOD(WorldSession*, FindOfflineSession, (uint32 id), (const)); MOCK_METHOD(WorldSession*, FindOfflineSessionForCharacterGUID, (ObjectGuid::LowType guidLow),(const)); @@ -65,14 +67,9 @@ public: MOCK_METHOD(std::string const&, GetNewCharString, (), (const)); MOCK_METHOD(LocaleConstant, GetDefaultDbcLocale, (), (const)); MOCK_METHOD(std::string const&, GetDataPath, (), (const)); - MOCK_METHOD(time_t const&, GetStartTime, (), (const)); - MOCK_METHOD(time_t const&, GetGameTime, (), (const)); - MOCK_METHOD(uint32, GetUptime, (), (const)); - MOCK_METHOD(uint32, GetUpdateTime, (), (const)); - MOCK_METHOD(void, SetRecordDiffInterval, (int32 t)); - MOCK_METHOD(time_t, GetNextDailyQuestsResetTime, (), (const)); - MOCK_METHOD(time_t, GetNextWeeklyQuestsResetTime, (), (const)); - MOCK_METHOD(time_t, GetNextRandomBGResetTime, (), (const)); + MOCK_METHOD(Seconds, GetNextDailyQuestsResetTime, (), (const)); + MOCK_METHOD(Seconds, GetNextWeeklyQuestsResetTime, (), (const)); + MOCK_METHOD(Seconds, GetNextRandomBGResetTime, (), (const)); MOCK_METHOD(uint16, GetConfigMaxSkillValue, (), (const)); MOCK_METHOD(void, SetInitialWorldSettings, ()); MOCK_METHOD(void, LoadConfigSettings, (bool reload), ()); |