diff options
Diffstat (limited to 'src/common')
22 files changed, 150 insertions, 199 deletions
diff --git a/src/common/Banner.cpp b/src/common/Banner.cpp index 640b4b248a9..7d96504eabe 100644 --- a/src/common/Banner.cpp +++ b/src/common/Banner.cpp @@ -21,17 +21,17 @@ void Trinity::Banner::Show(char const* applicationName, void(*log)(char const* text), void(*logExtraInfo)()) { - log(Trinity::StringFormat("%s (%s)", GitRevision::GetFullVersion(), applicationName).c_str()); - log("<Ctrl-C> to stop.\n"); - log(" ______ __"); - log("/\\__ _\\ __ __/\\ \\__"); - log("\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); - log(" \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); - log(" \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); - log(" \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); - log(" \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); - log(" C O R E /\\___/"); - log("http://TrinityCore.org \\/__/\n"); + log(Trinity::StringFormat("{} ({})", GitRevision::GetFullVersion(), applicationName).c_str()); + log(R"(<Ctrl-C> to stop.)" "\n"); + log(R"( ______ __)"); + log(R"(/\__ _\ __ __/\ \__)"); + log(R"(\/_/\ \/ _ __ /\_\ ___ /\_\ \, _\ __ __)"); + log(R"( \ \ \/\`'__\/\ \ /' _ `\/\ \ \ \/ /\ \/\ \)"); + log(R"( \ \ \ \ \/ \ \ \/\ \/\ \ \ \ \ \_\ \ \_\ \)"); + log(R"( \ \_\ \_\ \ \_\ \_\ \_\ \_\ \__\\/`____ \)"); + log(R"( \/_/\/_/ \/_/\/_/\/_/\/_/\/__/ `/___/> \)"); + log(R"( C O R E /\___/)"); + log(R"(http://TrinityCore.org \/__/)" "\n"); if (logExtraInfo) logExtraInfo(); diff --git a/src/common/Collision/DynamicTree.cpp b/src/common/Collision/DynamicTree.cpp index 012011eb053..34c38d98fa7 100644 --- a/src/common/Collision/DynamicTree.cpp +++ b/src/common/Collision/DynamicTree.cpp @@ -18,10 +18,8 @@ #include "DynamicTree.h" #include "BoundingIntervalHierarchyWrapper.h" #include "GameObjectModel.h" -#include "Log.h" #include "MapTree.h" #include "ModelIgnoreFlags.h" -#include "ModelInstance.h" #include "RegularGrid.h" #include "Timer.h" #include "VMapFactory.h" @@ -152,28 +150,6 @@ struct DynamicTreeIntersectionCallback bool didHit() const { return did_hit;} }; -struct DynamicTreeIntersectionCallback_WithLogger -{ - bool did_hit; - uint32 phase_mask; - DynamicTreeIntersectionCallback_WithLogger(uint32 phasemask) : did_hit(false), phase_mask(phasemask) - { - TC_LOG_DEBUG("maps", "Dynamic Intersection log"); - } - bool operator()(G3D::Ray const& r, GameObjectModel const& obj, float& distance) - { - TC_LOG_DEBUG("maps", "testing intersection with %s", obj.name.c_str()); - bool hit = obj.intersectRay(r, distance, true, phase_mask, VMAP::ModelIgnoreFlags::Nothing); - if (hit) - { - did_hit = true; - TC_LOG_DEBUG("maps", "result: intersects"); - } - return hit; - } - bool didHit() const { return did_hit;} -}; - struct DynamicTreeAreaInfoCallback { DynamicTreeAreaInfoCallback(uint32 phaseMask) : _phaseMask(phaseMask) {} diff --git a/src/common/Collision/Management/MMapManager.cpp b/src/common/Collision/Management/MMapManager.cpp index 31019e2b5c7..5ed38644fce 100644 --- a/src/common/Collision/Management/MMapManager.cpp +++ b/src/common/Collision/Management/MMapManager.cpp @@ -23,8 +23,8 @@ namespace MMAP { - static char const* const MAP_FILE_NAME_FORMAT = "%s/mmaps/%03i.mmap"; - static char const* const TILE_FILE_NAME_FORMAT = "%s/mmaps/%03i%02i%02i.mmtile"; + constexpr char MAP_FILE_NAME_FORMAT[] = "{}/mmaps/{:03}.mmap"; + constexpr char TILE_FILE_NAME_FORMAT[] = "{}/mmaps/{:03}{:02}{:02}.mmtile"; // ######################## MMapManager ######################## MMapManager::~MMapManager() @@ -73,11 +73,11 @@ namespace MMAP } // load and init dtNavMesh - read parameters from file - std::string fileName = Trinity::StringFormat(MAP_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", ".").c_str(), mapId); + std::string fileName = Trinity::StringFormat(MAP_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", "."), mapId); FILE* file = fopen(fileName.c_str(), "rb"); if (!file) { - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not open mmap file '%s'", fileName.c_str()); + TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not open mmap file '{}'", fileName); return false; } @@ -86,7 +86,7 @@ namespace MMAP fclose(file); if (count != 1) { - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not read params from file '%s'", fileName.c_str()); + TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not read params from file '{}'", fileName); return false; } @@ -95,11 +95,11 @@ namespace MMAP if (dtStatusFailed(mesh->init(¶ms))) { dtFreeNavMesh(mesh); - TC_LOG_ERROR("maps", "MMAP:loadMapData: Failed to initialize dtNavMesh for mmap %03u from file %s", mapId, fileName.c_str()); + TC_LOG_ERROR("maps", "MMAP:loadMapData: Failed to initialize dtNavMesh for mmap {:03} from file {}", mapId, fileName); return false; } - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Loaded %03i.mmap", mapId); + TC_LOG_DEBUG("maps", "MMAP:loadMapData: Loaded {:03}.mmap", mapId); // store inside our map list MMapData* mmap_data = new MMapData(mesh); @@ -129,11 +129,11 @@ namespace MMAP return false; // load this tile :: mmaps/MMMXXYY.mmtile - std::string fileName = Trinity::StringFormat(TILE_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", ".").c_str(), mapId, x, y); + std::string fileName = Trinity::StringFormat(TILE_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", "."), mapId, x, y); FILE* file = fopen(fileName.c_str(), "rb"); if (!file) { - TC_LOG_DEBUG("maps", "MMAP:loadMap: Could not open mmtile file '%s'", fileName.c_str()); + TC_LOG_DEBUG("maps", "MMAP:loadMap: Could not open mmtile file '{}'", fileName); return false; } @@ -141,14 +141,14 @@ namespace MMAP MmapTileHeader fileHeader; if (fread(&fileHeader, sizeof(MmapTileHeader), 1, file) != 1 || fileHeader.mmapMagic != MMAP_MAGIC) { - TC_LOG_ERROR("maps", "MMAP:loadMap: Bad header in mmap %03u%02i%02i.mmtile", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:loadMap: Bad header in mmap {:03}{:02}{:02}.mmtile", mapId, x, y); fclose(file); return false; } if (fileHeader.mmapVersion != MMAP_VERSION) { - TC_LOG_ERROR("maps", "MMAP:loadMap: %03u%02i%02i.mmtile was built with generator v%i, expected v%i", + TC_LOG_ERROR("maps", "MMAP:loadMap: {:03}{:02}{:02}.mmtile was built with generator v{}, expected v{}", mapId, x, y, fileHeader.mmapVersion, MMAP_VERSION); fclose(file); return false; @@ -158,7 +158,7 @@ namespace MMAP fseek(file, 0, SEEK_END); if (pos < 0 || static_cast<int32>(fileHeader.size) > ftell(file) - pos) { - TC_LOG_ERROR("maps", "MMAP:loadMap: %03u%02i%02i.mmtile has corrupted data size", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:loadMap: {:03}{:02}{:02}.mmtile has corrupted data size", mapId, x, y); fclose(file); return false; } @@ -171,7 +171,7 @@ namespace MMAP size_t result = fread(data, fileHeader.size, 1, file); if (!result) { - TC_LOG_ERROR("maps", "MMAP:loadMap: Bad header or data in mmap %03u%02i%02i.mmtile", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:loadMap: Bad header or data in mmap {:03}{:02}{:02}.mmtile", mapId, x, y); fclose(file); return false; } @@ -186,12 +186,12 @@ namespace MMAP { mmap->loadedTileRefs.insert(std::pair<uint32, dtTileRef>(packedGridPos, tileRef)); ++loadedTiles; - TC_LOG_DEBUG("maps", "MMAP:loadMap: Loaded mmtile %03i[%02i, %02i] into %03i[%02i, %02i]", mapId, x, y, mapId, header->x, header->y); + TC_LOG_DEBUG("maps", "MMAP:loadMap: Loaded mmtile {:03}[{:02}, {:02}] into {:03}[{:02}, {:02}]", mapId, x, y, mapId, header->x, header->y); return true; } else { - TC_LOG_ERROR("maps", "MMAP:loadMap: Could not load %03u%02i%02i.mmtile into navmesh", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:loadMap: Could not load {:03}{:02}{:02}.mmtile into navmesh", mapId, x, y); dtFree(data); return false; } @@ -204,7 +204,7 @@ namespace MMAP if (itr == loadedMMaps.end()) { // file may not exist, therefore not loaded - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh map. %03u%02i%02i.mmtile", mapId, x, y); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh map. {:03}{:02}{:02}.mmtile", mapId, x, y); return false; } @@ -215,7 +215,7 @@ namespace MMAP if (mmap->loadedTileRefs.find(packedGridPos) == mmap->loadedTileRefs.end()) { // file may not exist, therefore not loaded - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh tile. %03u%02i%02i.mmtile", mapId, x, y); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh tile. {:03}{:02}{:02}.mmtile", mapId, x, y); return false; } @@ -227,14 +227,14 @@ namespace MMAP // this is technically a memory leak // if the grid is later reloaded, dtNavMesh::addTile will return error but no extra memory is used // we cannot recover from this error - assert out - TC_LOG_ERROR("maps", "MMAP:unloadMap: Could not unload %03u%02i%02i.mmtile from navmesh", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:unloadMap: Could not unload {:03}{:02}{:02}.mmtile from navmesh", mapId, x, y); ABORT(); } else { mmap->loadedTileRefs.erase(packedGridPos); --loadedTiles; - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded mmtile %03i[%02i, %02i] from %03i", mapId, x, y, mapId); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded mmtile {:03}[{:02}, {:02}] from {:03}", mapId, x, y, mapId); return true; } @@ -247,7 +247,7 @@ namespace MMAP if (itr == loadedMMaps.end() || !itr->second) { // file may not exist, therefore not loaded - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh map %03u", mapId); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Asked to unload not loaded navmesh map {:03}", mapId); return false; } @@ -258,17 +258,17 @@ namespace MMAP uint32 x = (i->first >> 16); uint32 y = (i->first & 0x0000FFFF); if (dtStatusFailed(mmap->navMesh->removeTile(i->second, nullptr, nullptr))) - TC_LOG_ERROR("maps", "MMAP:unloadMap: Could not unload %03u%02i%02i.mmtile from navmesh", mapId, x, y); + TC_LOG_ERROR("maps", "MMAP:unloadMap: Could not unload {:03}{:02}{:02}.mmtile from navmesh", mapId, x, y); else { --loadedTiles; - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded mmtile %03i[%02i, %02i] from %03i", mapId, x, y, mapId); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded mmtile {:03}[{:02}, {:02}] from {:03}", mapId, x, y, mapId); } } delete mmap; itr->second = nullptr; - TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded %03i.mmap", mapId); + TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded {:03}.mmap", mapId); return true; } @@ -280,14 +280,14 @@ namespace MMAP if (itr == loadedMMaps.end()) { // file may not exist, therefore not loaded - TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded navmesh map %03u", mapId); + TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded navmesh map {:03}", mapId); return false; } MMapData* mmap = itr->second; if (mmap->navMeshQueries.find(instanceId) == mmap->navMeshQueries.end()) { - TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded dtNavMeshQuery mapId %03u instanceId %u", mapId, instanceId); + TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded dtNavMeshQuery mapId {:03} instanceId {}", mapId, instanceId); return false; } @@ -295,7 +295,7 @@ namespace MMAP dtFreeNavMeshQuery(query); mmap->navMeshQueries.erase(instanceId); - TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Unloaded mapId %03u instanceId %u", mapId, instanceId); + TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Unloaded mapId {:03} instanceId {}", mapId, instanceId); return true; } @@ -324,11 +324,11 @@ namespace MMAP if (dtStatusFailed(query->init(mmap->navMesh, 1024))) { dtFreeNavMeshQuery(query); - TC_LOG_ERROR("maps", "MMAP:GetNavMeshQuery: Failed to initialize dtNavMeshQuery for mapId %03u instanceId %u", mapId, instanceId); + TC_LOG_ERROR("maps", "MMAP:GetNavMeshQuery: Failed to initialize dtNavMeshQuery for mapId {:03} instanceId {}", mapId, instanceId); return nullptr; } - TC_LOG_DEBUG("maps", "MMAP:GetNavMeshQuery: created dtNavMeshQuery for mapId %03u instanceId %u", mapId, instanceId); + TC_LOG_DEBUG("maps", "MMAP:GetNavMeshQuery: created dtNavMeshQuery for mapId {:03} instanceId {}", mapId, instanceId); mmap->navMeshQueries.insert(std::pair<uint32, dtNavMeshQuery*>(instanceId, query)); } diff --git a/src/common/Collision/Management/VMapManager2.cpp b/src/common/Collision/Management/VMapManager2.cpp index 04b0900a6b3..df4ac1b4859 100644 --- a/src/common/Collision/Management/VMapManager2.cpp +++ b/src/common/Collision/Management/VMapManager2.cpp @@ -323,11 +323,11 @@ namespace VMAP WorldModel* worldmodel = new WorldModel(); if (!worldmodel->readFile(basepath + filename + ".vmo")) { - VMAP_ERROR_LOG("misc", "VMapManager2: could not load '%s%s.vmo'", basepath.c_str(), filename.c_str()); + TC_LOG_ERROR("misc", "VMapManager2: could not load '%s%s.vmo'", basepath.c_str(), filename.c_str()); delete worldmodel; return nullptr; } - VMAP_DEBUG_LOG("maps", "VMapManager2: loading file '%s%s'", basepath.c_str(), filename.c_str()); + TC_LOG_DEBUG("maps", "VMapManager2: loading file '%s%s'", basepath.c_str(), filename.c_str()); worldmodel->Flags = flags; @@ -346,12 +346,12 @@ namespace VMAP ModelFileMap::iterator model = iLoadedModelFiles.find(filename); if (model == iLoadedModelFiles.end()) { - VMAP_ERROR_LOG("misc", "VMapManager2: trying to unload non-loaded file '%s'", filename.c_str()); + TC_LOG_ERROR("misc", "VMapManager2: trying to unload non-loaded file '%s'", filename.c_str()); return; } if (model->second.decRefCount() == 0) { - VMAP_DEBUG_LOG("maps", "VMapManager2: unloading file '%s'", filename.c_str()); + TC_LOG_DEBUG("maps", "VMapManager2: unloading file '%s'", filename.c_str()); delete model->second.getModel(); iLoadedModelFiles.erase(model); } diff --git a/src/common/Collision/Maps/MapTree.cpp b/src/common/Collision/Maps/MapTree.cpp index 2e952e74d80..e0166a9de1a 100644 --- a/src/common/Collision/Maps/MapTree.cpp +++ b/src/common/Collision/Maps/MapTree.cpp @@ -57,7 +57,7 @@ namespace VMAP void operator()(Vector3 const& point, uint32 entry) { #ifdef VMAP_DEBUG - TC_LOG_DEBUG("maps", "AreaInfoCallback: trying to intersect '%s'", prims[entry].name.c_str()); + TC_LOG_DEBUG("maps", "AreaInfoCallback: trying to intersect '{}'", prims[entry].name); #endif prims[entry].intersectPoint(point, aInfo); } @@ -73,7 +73,7 @@ namespace VMAP void operator()(Vector3 const& point, uint32 entry) { #ifdef VMAP_DEBUG - TC_LOG_DEBUG("maps", "LocationInfoCallback: trying to intersect '%s'", prims[entry].name.c_str()); + TC_LOG_DEBUG("maps", "LocationInfoCallback: trying to intersect '{}'", prims[entry].name); #endif if (prims[entry].GetLocationInfo(point, locInfo)) result = true; @@ -277,7 +277,7 @@ namespace VMAP bool StaticMapTree::InitMap(const std::string &fname, VMapManager2* vm) { - VMAP_DEBUG_LOG("maps", "StaticMapTree::InitMap() : initializing StaticMapTree '%s'", fname.c_str()); + TC_LOG_DEBUG("maps", "StaticMapTree::InitMap() : initializing StaticMapTree '%s'", fname.c_str()); bool success = false; std::string fullname = iBasePath + fname; FILE* rf = fopen(fullname.c_str(), "rb"); @@ -301,12 +301,12 @@ namespace VMAP // only non-tiled maps have them, and if so exactly one (so far at least...) ModelSpawn spawn; #ifdef VMAP_DEBUG - TC_LOG_DEBUG("maps", "StaticMapTree::InitMap() : map isTiled: %u", static_cast<uint32>(iIsTiled)); + TC_LOG_DEBUG("maps", "StaticMapTree::InitMap() : map isTiled: {}", static_cast<uint32>(iIsTiled)); #endif if (!iIsTiled && ModelSpawn::readFromFile(rf, spawn)) { WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name, spawn.flags); - VMAP_DEBUG_LOG("maps", "StaticMapTree::InitMap() : loading %s", spawn.name.c_str()); + TC_LOG_DEBUG("maps", "StaticMapTree::InitMap() : loading %s", spawn.name.c_str()); if (model) { // assume that global model always is the first and only tree value (could be improved...) @@ -316,7 +316,7 @@ namespace VMAP else { success = false; - VMAP_ERROR_LOG("misc", "StaticMapTree::InitMap() : could not acquire WorldModel pointer for '%s'", spawn.name.c_str()); + TC_LOG_ERROR("misc", "StaticMapTree::InitMap() : could not acquire WorldModel pointer for '%s'", spawn.name.c_str()); } } @@ -351,7 +351,7 @@ namespace VMAP } if (!iTreeValues) { - VMAP_ERROR_LOG("misc", "StaticMapTree::LoadMapTile() : tree has not been initialized [%u, %u]", tileX, tileY); + TC_LOG_ERROR("misc", "StaticMapTree::LoadMapTile() : tree has not been initialized [%u, %u]", tileX, tileY); return false; } bool result = true; @@ -377,7 +377,7 @@ namespace VMAP // acquire model instance WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name, spawn.flags); if (!model) - VMAP_ERROR_LOG("misc", "StaticMapTree::LoadMapTile() : could not acquire WorldModel pointer [%u, %u]", tileX, tileY); + TC_LOG_ERROR("misc", "StaticMapTree::LoadMapTile() : could not acquire WorldModel pointer [%u, %u]", tileX, tileY); // update tree uint32 referencedVal; @@ -388,7 +388,7 @@ namespace VMAP { if (referencedVal > iNTreeValues) { - VMAP_ERROR_LOG("maps", "StaticMapTree::LoadMapTile() : invalid tree element (%u/%u) referenced in tile %s", referencedVal, iNTreeValues, tilefile.c_str()); + TC_LOG_ERROR("maps", "StaticMapTree::LoadMapTile() : invalid tree element (%u/%u) referenced in tile %s", referencedVal, iNTreeValues, tilefile.c_str()); continue; } @@ -402,7 +402,7 @@ namespace VMAP if (iTreeValues[referencedVal].ID != spawn.ID) TC_LOG_DEBUG("maps", "StaticMapTree::LoadMapTile() : trying to load wrong spawn in node"); else if (iTreeValues[referencedVal].name != spawn.name) - TC_LOG_DEBUG("maps", "StaticMapTree::LoadMapTile() : name collision on GUID=%u", spawn.ID); + TC_LOG_DEBUG("maps", "StaticMapTree::LoadMapTile() : name collision on GUID={}", spawn.ID); #endif } } @@ -428,7 +428,7 @@ namespace VMAP loadedTileMap::iterator tile = iLoadedTiles.find(tileID); if (tile == iLoadedTiles.end()) { - VMAP_ERROR_LOG("misc", "StaticMapTree::UnloadMapTile() : trying to unload non-loaded tile - Map:%u X:%u Y:%u", iMapID, tileX, tileY); + TC_LOG_ERROR("misc", "StaticMapTree::UnloadMapTile() : trying to unload non-loaded tile - Map:%u X:%u Y:%u", iMapID, tileX, tileY); return; } if (tile->second) // file associated with tile @@ -462,7 +462,7 @@ namespace VMAP else { if (!iLoadedSpawns.count(referencedNode)) - VMAP_ERROR_LOG("misc", "StaticMapTree::UnloadMapTile() : trying to unload non-referenced model '%s' (ID:%u)", spawn.name.c_str(), spawn.ID); + TC_LOG_ERROR("misc", "StaticMapTree::UnloadMapTile() : trying to unload non-referenced model '%s' (ID:%u)", spawn.name.c_str(), spawn.ID); else if (--iLoadedSpawns[referencedNode] == 0) { iTreeValues[referencedNode].setUnloaded(); diff --git a/src/common/Collision/Models/GameObjectModel.cpp b/src/common/Collision/Models/GameObjectModel.cpp index 599a8025f60..23735f2d8e5 100644 --- a/src/common/Collision/Models/GameObjectModel.cpp +++ b/src/common/Collision/Models/GameObjectModel.cpp @@ -43,14 +43,12 @@ ModelList model_list; void LoadGameObjectModelList(std::string const& dataPath) { -#ifndef NO_CORE_FUNCS uint32 oldMSTime = getMSTime(); -#endif FILE* model_list_file = fopen((dataPath + "vmaps/" + VMAP::GAMEOBJECT_MODELS).c_str(), "rb"); if (!model_list_file) { - VMAP_ERROR_LOG("misc", "Unable to open '%s' file.", VMAP::GAMEOBJECT_MODELS); + TC_LOG_ERROR("misc", "Unable to open '{}' file.", VMAP::GAMEOBJECT_MODELS); return; } @@ -58,7 +56,7 @@ void LoadGameObjectModelList(std::string const& dataPath) if (fread(magic, 1, 8, model_list_file) != 8 || memcmp(magic, VMAP::VMAP_MAGIC, 8) != 0) { - TC_LOG_ERROR("misc", "File '%s' has wrong header, expected %s.", VMAP::GAMEOBJECT_MODELS, VMAP::VMAP_MAGIC); + TC_LOG_ERROR("misc", "File '{}' has wrong header, expected {}.", VMAP::GAMEOBJECT_MODELS, VMAP::VMAP_MAGIC); fclose(model_list_file); return; } @@ -80,13 +78,13 @@ void LoadGameObjectModelList(std::string const& dataPath) || fread(&v1, sizeof(Vector3), 1, model_list_file) != 1 || fread(&v2, sizeof(Vector3), 1, model_list_file) != 1) { - VMAP_ERROR_LOG("misc", "File '%s' seems to be corrupted!", VMAP::GAMEOBJECT_MODELS); + TC_LOG_ERROR("misc", "File '{}' seems to be corrupted!", VMAP::GAMEOBJECT_MODELS); break; } if (v1.isNaN() || v2.isNaN()) { - VMAP_ERROR_LOG("misc", "File '%s' Model '%s' has invalid v1%s v2%s values!", VMAP::GAMEOBJECT_MODELS, std::string(buff, name_length).c_str(), v1.toString().c_str(), v2.toString().c_str()); + TC_LOG_ERROR("misc", "File '{}' Model '{}' has invalid v1{} v2{} values!", VMAP::GAMEOBJECT_MODELS, std::string(buff, name_length), v1.toString(), v2.toString()); continue; } @@ -94,7 +92,7 @@ void LoadGameObjectModelList(std::string const& dataPath) } fclose(model_list_file); - VMAP_INFO_LOG("server.loading", ">> Loaded %u GameObject models in %u ms", uint32(model_list.size()), GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded {} GameObject models in {} ms", uint32(model_list.size()), GetMSTimeDiffToNow(oldMSTime)); } GameObjectModel::~GameObjectModel() @@ -113,7 +111,7 @@ bool GameObjectModel::initialize(std::unique_ptr<GameObjectModelOwnerBase> model // ignore models with no bounds if (mdl_box == G3D::AABox::zero()) { - VMAP_ERROR_LOG("misc", "GameObject model %s has zero bounds, loading skipped", it->second.name.c_str()); + TC_LOG_ERROR("misc", "GameObject model {} has zero bounds, loading skipped", it->second.name); return false; } @@ -261,7 +259,7 @@ bool GameObjectModel::UpdatePosition() // ignore models with no bounds if (mdl_box == G3D::AABox::zero()) { - VMAP_ERROR_LOG("misc", "GameObject model %s has zero bounds, loading skipped", it->second.name.c_str()); + TC_LOG_ERROR("misc", "GameObject model {} has zero bounds, loading skipped", it->second.name); return false; } diff --git a/src/common/Collision/VMapDefinitions.h b/src/common/Collision/VMapDefinitions.h index a2702b32609..bce315d7ac2 100644 --- a/src/common/Collision/VMapDefinitions.h +++ b/src/common/Collision/VMapDefinitions.h @@ -17,7 +17,7 @@ #ifndef _VMAPDEFINITIONS_H #define _VMAPDEFINITIONS_H -#include <cstring> + #include <cstdio> #define LIQUID_TILE_SIZE (533.333f / 128.f) @@ -32,15 +32,4 @@ namespace VMAP bool readChunk(FILE* rf, char *dest, const char *compare, uint32 len); } -// Set of helper macros for extractors (VMAP and MMAP) -#ifndef NO_CORE_FUNCS -#define VMAP_ERROR_LOG(FILTER, ...) TC_LOG_ERROR(FILTER, __VA_ARGS__) -#define VMAP_DEBUG_LOG(FILTER, ...) TC_LOG_DEBUG(FILTER, __VA_ARGS__) -#define VMAP_INFO_LOG(FILTER, ...) TC_LOG_INFO(FILTER, __VA_ARGS__) -#else -#define VMAP_ERROR_LOG(FILTER, ...) (void)sizeof(FILTER) -#define VMAP_DEBUG_LOG(FILTER, ...) (void)sizeof(FILTER) -#define VMAP_INFO_LOG(FILTER, ...) (void)sizeof(FILTER) -#endif - #endif diff --git a/src/common/Configuration/Config.cpp b/src/common/Configuration/Config.cpp index 3471c568491..baf5d5bf11c 100644 --- a/src/common/Configuration/Config.cpp +++ b/src/common/Configuration/Config.cpp @@ -227,25 +227,25 @@ T ConfigMgr::GetValueDefault(std::string const& name, T def, bool quiet) const Optional<T> castedVar = Trinity::StringTo<T>(*envVar); if (!castedVar) { - TC_LOG_ERROR("server.loading", "Bad value defined for name %s in environment variables, going to use default instead", name.c_str()); + TC_LOG_ERROR("server.loading", "Bad value defined for name {} in environment variables, going to use default instead", name); return def; } if (!quiet) - TC_LOG_WARN("server.loading", "Missing name %s in config file %s, recovered with environment '%s' value.", name.c_str(), _filename.c_str(), envVar->c_str()); + TC_LOG_WARN("server.loading", "Missing name {} in config file {}, recovered with environment '{}' value.", name, _filename, envVar->c_str()); return *castedVar; } else if (!quiet) { - TC_LOG_WARN("server.loading", "Missing name %s in config file %s, add \"%s = %s\" to this file", - name.c_str(), _filename.c_str(), name.c_str(), std::to_string(def).c_str()); + TC_LOG_WARN("server.loading", "Missing name {} in config file {}, add \"{} = {}\" to this file", + name, _filename, name, def); } } catch (bpt::ptree_bad_data const&) { - TC_LOG_ERROR("server.loading", "Bad value defined for name %s in config file %s, going to use %s instead", - name.c_str(), _filename.c_str(), std::to_string(def).c_str()); + TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use {} instead", + name, _filename, def); } return def; @@ -264,20 +264,20 @@ std::string ConfigMgr::GetValueDefault<std::string>(std::string const& name, std if (envVar) { if (!quiet) - TC_LOG_WARN("server.loading", "Missing name %s in config file %s, recovered with environment '%s' value.", name.c_str(), _filename.c_str(), envVar->c_str()); + TC_LOG_WARN("server.loading", "Missing name {} in config file {}, recovered with environment '{}' value.", name, _filename, envVar->c_str()); return *envVar; } else if (!quiet) { - TC_LOG_WARN("server.loading", "Missing name %s in config file %s, add \"%s = %s\" to this file", - name.c_str(), _filename.c_str(), name.c_str(), def.c_str()); + TC_LOG_WARN("server.loading", "Missing name {} in config file {}, add \"{} = {}\" to this file", + name, _filename, name, def); } } catch (bpt::ptree_bad_data const&) { - TC_LOG_ERROR("server.loading", "Bad value defined for name %s in config file %s, going to use %s instead", - name.c_str(), _filename.c_str(), def.c_str()); + TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use {} instead", + name, _filename, def); } return def; @@ -299,8 +299,8 @@ bool ConfigMgr::GetBoolDefault(std::string const& name, bool def, bool quiet) co return *boolVal; else { - TC_LOG_ERROR("server.loading", "Bad value defined for name %s in config file %s, going to use '%s' instead", - name.c_str(), _filename.c_str(), def ? "true" : "false"); + TC_LOG_ERROR("server.loading", "Bad value defined for name {} in config file {}, going to use '{}' instead", + name, _filename, def ? "true" : "false"); return def; } } diff --git a/src/common/Debugging/Errors.cpp b/src/common/Debugging/Errors.cpp index 295e61faee4..aa08ff1ab14 100644 --- a/src/common/Debugging/Errors.cpp +++ b/src/common/Debugging/Errors.cpp @@ -70,7 +70,7 @@ namespace Trinity void Assert(char const* file, int line, char const* function, std::string debugInfo, char const* message) { - std::string formattedMessage = StringFormat("\n%s:%i in %s ASSERTION FAILED:\n %s\n", file, line, function, message) + debugInfo + '\n'; + std::string formattedMessage = StringFormat("\n{}:{} in {} ASSERTION FAILED:\n {}\n", file, line, function, message) + debugInfo + '\n'; fprintf(stderr, "%s", formattedMessage.c_str()); fflush(stderr); Crash(formattedMessage.c_str()); @@ -81,7 +81,7 @@ void Assert(char const* file, int line, char const* function, std::string debugI va_list args; va_start(args, format); - std::string formattedMessage = StringFormat("\n%s:%i in %s ASSERTION FAILED:\n %s\n", file, line, function, message) + FormatAssertionMessage(format, args) + '\n' + debugInfo + '\n'; + std::string formattedMessage = StringFormat("\n{}:{} in {} ASSERTION FAILED:\n {}\n", file, line, function, message) + FormatAssertionMessage(format, args) + '\n' + debugInfo + '\n'; va_end(args); fprintf(stderr, "%s", formattedMessage.c_str()); @@ -95,7 +95,7 @@ void Fatal(char const* file, int line, char const* function, char const* message va_list args; va_start(args, message); - std::string formattedMessage = StringFormat("\n%s:%i in %s FATAL ERROR:\n", file, line, function) + FormatAssertionMessage(message, args) + '\n'; + std::string formattedMessage = StringFormat("\n{}:{} in {} FATAL ERROR:\n", file, line, function) + FormatAssertionMessage(message, args) + '\n'; va_end(args); fprintf(stderr, "%s", formattedMessage.c_str()); @@ -107,7 +107,7 @@ void Fatal(char const* file, int line, char const* function, char const* message void Error(char const* file, int line, char const* function, char const* message) { - std::string formattedMessage = StringFormat("\n%s:%i in %s ERROR:\n %s\n", file, line, function, message); + std::string formattedMessage = StringFormat("\n{}:{} in {} ERROR:\n {}\n", file, line, function, message); fprintf(stderr, "%s", formattedMessage.c_str()); fflush(stderr); Crash(formattedMessage.c_str()); @@ -121,7 +121,7 @@ void Warning(char const* file, int line, char const* function, char const* messa void Abort(char const* file, int line, char const* function) { - std::string formattedMessage = StringFormat("\n%s:%i in %s ABORTED.\n", file, line, function); + std::string formattedMessage = StringFormat("\n{}:{} in {} ABORTED.\n", file, line, function); fprintf(stderr, "%s", formattedMessage.c_str()); fflush(stderr); Crash(formattedMessage.c_str()); @@ -132,7 +132,7 @@ void Abort(char const* file, int line, char const* function, char const* message va_list args; va_start(args, message); - std::string formattedMessage = StringFormat("\n%s:%i in %s ABORTED:\n", file, line, function) + FormatAssertionMessage(message, args) + '\n'; + std::string formattedMessage = StringFormat("\n{}:{} in {} ABORTED:\n", file, line, function) + FormatAssertionMessage(message, args) + '\n'; va_end(args); fprintf(stderr, "%s", formattedMessage.c_str()); @@ -144,7 +144,7 @@ void Abort(char const* file, int line, char const* function, char const* message void AbortHandler(int sigval) { // nothing useful to log here, no way to pass args - std::string formattedMessage = StringFormat("Caught signal %i\n", sigval); + std::string formattedMessage = StringFormat("Caught signal {}\n", sigval); fprintf(stderr, "%s", formattedMessage.c_str()); fflush(stderr); Crash(formattedMessage.c_str()); diff --git a/src/common/IPLocation/IPLocation.cpp b/src/common/IPLocation/IPLocation.cpp index b11182e4b08..a1717420eb4 100644 --- a/src/common/IPLocation/IPLocation.cpp +++ b/src/common/IPLocation/IPLocation.cpp @@ -45,13 +45,13 @@ void IpLocationStore::Load() std::ifstream databaseFile(databaseFilePath); if (!databaseFile) { - TC_LOG_ERROR("server.loading", "IPLocation: No ip database file exists (%s).", databaseFilePath.c_str()); + TC_LOG_ERROR("server.loading", "IPLocation: No ip database file exists ({}).", databaseFilePath); return; } if (!databaseFile.is_open()) { - TC_LOG_ERROR("server.loading", "IPLocation: Ip database file (%s) can not be opened.", databaseFilePath.c_str()); + TC_LOG_ERROR("server.loading", "IPLocation: Ip database file ({}) can not be opened.", databaseFilePath); return; } @@ -94,7 +94,7 @@ void IpLocationStore::Load() databaseFile.close(); - TC_LOG_INFO("server.loading", ">> Loaded " SZFMTD " ip location entries.", _ipLocationStore.size()); + TC_LOG_INFO("server.loading", ">> Loaded {} ip location entries.", _ipLocationStore.size()); } IpLocationRecord const* IpLocationStore::GetLocationRecord(std::string const& ipAddress) const diff --git a/src/common/Logging/Appender.cpp b/src/common/Logging/Appender.cpp index 607af852a42..ca5f56157d4 100644 --- a/src/common/Logging/Appender.cpp +++ b/src/common/Logging/Appender.cpp @@ -62,7 +62,7 @@ void Appender::write(LogMessage* message) ss << message->getTimeStr() << ' '; if (flags & APPENDER_FLAGS_PREFIX_LOGLEVEL) - ss << Trinity::StringFormat("%-5s ", Appender::getLogLevelString(message->level)); + ss << Trinity::StringFormat("{:<5} ", Appender::getLogLevelString(message->level)); if (flags & APPENDER_FLAGS_PREFIX_LOGFILTERTYPE) ss << '[' << message->type << "] "; diff --git a/src/common/Logging/AppenderConsole.cpp b/src/common/Logging/AppenderConsole.cpp index eb02f5f3ccf..43d663c7ce3 100644 --- a/src/common/Logging/AppenderConsole.cpp +++ b/src/common/Logging/AppenderConsole.cpp @@ -48,8 +48,8 @@ void AppenderConsole::InitColors(std::string const& name, std::string_view str) std::vector<std::string_view> colorStrs = Trinity::Tokenize(str, ' ', false); if (colorStrs.size() != NUM_ENABLED_LOG_LEVELS) { - throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid color data '%s' for console appender %s (expected %u entries, got %zu)", - std::string(str).c_str(), name.c_str(), NUM_ENABLED_LOG_LEVELS, colorStrs.size())); + throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid color data '{}' for console appender {} (expected {} entries, got {})", + str, name, NUM_ENABLED_LOG_LEVELS, colorStrs.size())); } for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) @@ -58,8 +58,8 @@ void AppenderConsole::InitColors(std::string const& name, std::string_view str) _colors[i] = static_cast<ColorTypes>(*color); else { - throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid color '%s' for log level %s on console appender %s", - std::string(colorStrs[i]).c_str(), EnumUtils::ToTitle(static_cast<LogLevel>(i)), name.c_str())); + throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid color '{}' for log level {} on console appender {}", + colorStrs[i], EnumUtils::ToTitle(static_cast<LogLevel>(i)), name)); } } diff --git a/src/common/Logging/AppenderFile.cpp b/src/common/Logging/AppenderFile.cpp index bb38cade4e4..421a70b06b4 100644 --- a/src/common/Logging/AppenderFile.cpp +++ b/src/common/Logging/AppenderFile.cpp @@ -30,7 +30,7 @@ AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, Ap _fileSize(0) { if (args.size() < 4) - throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Missing file name for appender %s", name.c_str())); + throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Missing file name for appender {}", name)); _fileName.assign(args[3]); @@ -52,7 +52,7 @@ AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, Ap if (Optional<uint32> size = Trinity::StringTo<uint32>(args[5])) _maxFileSize = *size; else - throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid size '%s' for appender %s", std::string(args[5]).c_str(), name.c_str())); + throw InvalidAppenderArgsException(Trinity::StringFormat("Log::CreateAppenderFromConfig: Invalid size '{}' for appender {}", args[5], name)); } _dynamicName = std::string::npos != _fileName.find("%s"); diff --git a/src/common/Logging/Log.cpp b/src/common/Logging/Log.cpp index 96dadcb82c5..2e7e39e62ec 100644 --- a/src/common/Logging/Log.cpp +++ b/src/common/Logging/Log.cpp @@ -214,12 +214,12 @@ void Log::RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn) appenderFactory[index] = appenderCreateFn; } -void Log::outMessage(std::string const& filter, LogLevel level, std::string&& message) +void Log::OutMessageImpl(std::string_view filter, LogLevel level, std::string&& message) { - write(std::make_unique<LogMessage>(level, filter, std::move(message))); + write(std::make_unique<LogMessage>(level, std::string(filter), std::move(message))); } -void Log::outCommand(std::string&& message, std::string&& param1) +void Log::OutCommandImpl(std::string&& message, std::string&& param1) { write(std::make_unique<LogMessage>(LOG_LEVEL_INFO, "commands.gm", std::move(message), std::move(param1))); } @@ -267,7 +267,7 @@ std::string Log::GetTimestampStr() // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) - return Trinity::StringFormat("%04d-%02d-%02d_%02d-%02d-%02d", + return Trinity::StringFormat("{:04}-{:02}-{:02}_{:02}-{:02}-{:02}", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); } @@ -304,7 +304,7 @@ bool Log::SetLogLevel(std::string const& name, int32 newLeveli, bool isLogger /* return true; } -void Log::outCharDump(char const* str, uint32 accountId, uint64 guid, char const* name) +void Log::OutCharDump(char const* str, uint32 accountId, uint64 guid, char const* name) { if (!str || !ShouldLog("entities.player.dump", LOG_LEVEL_INFO)) return; diff --git a/src/common/Logging/Log.h b/src/common/Logging/Log.h index 7a84d1120d3..17ba5682ceb 100644 --- a/src/common/Logging/Log.h +++ b/src/common/Logging/Log.h @@ -71,29 +71,29 @@ class TC_COMMON_API Log bool ShouldLog(std::string const& type, LogLevel level) const; bool SetLogLevel(std::string const& name, int32 level, bool isLogger = true); - template<typename Format, typename... Args> - inline void outMessage(std::string const& filter, LogLevel const level, Format&& fmt, Args&&... args) + template<typename... Args> + void OutMessage(std::string_view filter, LogLevel const level, Trinity::FormatString<Args...> fmt, Args&&... args) { - outMessage(filter, level, Trinity::StringFormat(std::forward<Format>(fmt), std::forward<Args>(args)...)); + this->OutMessageImpl(filter, level, Trinity::StringFormat(fmt, std::forward<Args>(args)...)); } - template<typename Format, typename... Args> - void outCommand(uint32 account, Format&& fmt, Args&&... args) + template<typename... Args> + void OutCommand(uint32 account, Trinity::FormatString<Args...> fmt, Args&&... args) { if (!ShouldLog("commands.gm", LOG_LEVEL_INFO)) return; - outCommand(Trinity::StringFormat(std::forward<Format>(fmt), std::forward<Args>(args)...), std::to_string(account)); + this->OutCommandImpl(Trinity::StringFormat(fmt, std::forward<Args>(args)...), std::to_string(account)); } - void outCharDump(char const* str, uint32 account_id, uint64 guid, char const* name); + void OutCharDump(char const* str, uint32 account_id, uint64 guid, char const* name); void SetRealmId(uint32 id); template<class AppenderImpl> void RegisterAppender() { - RegisterAppender(AppenderImpl::type, &CreateAppender<AppenderImpl>); + this->RegisterAppender(AppenderImpl::type, &CreateAppender<AppenderImpl>); } std::string const& GetLogsDir() const { return m_logsDir; } @@ -111,8 +111,8 @@ class TC_COMMON_API Log void ReadAppendersFromConfig(); void ReadLoggersFromConfig(); void RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn); - void outMessage(std::string const& filter, LogLevel level, std::string&& message); - void outCommand(std::string&& message, std::string&& param1); + void OutMessageImpl(std::string_view filter, LogLevel level, std::string&& message); + void OutCommandImpl(std::string&& message, std::string&& param1); std::unordered_map<uint8, AppenderCreatorFn> appenderFactory; std::unordered_map<uint8, std::unique_ptr<Appender>> appenders; @@ -129,35 +129,15 @@ class TC_COMMON_API Log #define sLog Log::instance() -#define LOG_EXCEPTION_FREE(filterType__, level__, ...) \ - { \ - try \ - { \ - sLog->outMessage(filterType__, level__, __VA_ARGS__); \ - } \ - catch (std::exception& e) \ - { \ - sLog->outMessage("server", LOG_LEVEL_ERROR, "Wrong format occurred (%s) at %s:%u.", \ - e.what(), __FILE__, __LINE__); \ - } \ - } - #ifdef PERFORMANCE_PROFILING #define TC_LOG_MESSAGE_BODY(filterType__, level__, ...) ((void)0) #elif TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS -void check_args(char const*, ...) ATTR_PRINTF(1, 2); -void check_args(std::string const&, ...); // This will catch format errors on build time #define TC_LOG_MESSAGE_BODY(filterType__, level__, ...) \ do { \ if (sLog->ShouldLog(filterType__, level__)) \ - { \ - if (false) \ - check_args(__VA_ARGS__); \ - \ - LOG_EXCEPTION_FREE(filterType__, level__, __VA_ARGS__); \ - } \ + sLog->OutMessage(filterType__, level__, __VA_ARGS__); \ } while (0) #else #define TC_LOG_MESSAGE_BODY(filterType__, level__, ...) \ @@ -165,7 +145,7 @@ void check_args(std::string const&, ...); __pragma(warning(disable:4127)) \ do { \ if (sLog->ShouldLog(filterType__, level__)) \ - LOG_EXCEPTION_FREE(filterType__, level__, __VA_ARGS__); \ + sLog->OutMessage(filterType__, level__, __VA_ARGS__); \ } while (0) \ __pragma(warning(pop)) #endif diff --git a/src/common/Logging/LogMessage.cpp b/src/common/Logging/LogMessage.cpp index 5f10087d1f0..a9a99312db1 100644 --- a/src/common/Logging/LogMessage.cpp +++ b/src/common/Logging/LogMessage.cpp @@ -33,7 +33,7 @@ std::string LogMessage::getTimeStr(time_t time) { tm aTm; localtime_r(&time, &aTm); - return Trinity::StringFormat("%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); + return Trinity::StringFormat("{:04}-{:02}-{:02}_{:02}:{:02}:{:02}", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); } std::string LogMessage::getTimeStr() const diff --git a/src/common/Metric/Metric.cpp b/src/common/Metric/Metric.cpp index 843f4c16f56..06c084a3c2c 100644 --- a/src/common/Metric/Metric.cpp +++ b/src/common/Metric/Metric.cpp @@ -42,8 +42,8 @@ bool Metric::Connect() auto error = stream.error(); if (error) { - TC_LOG_ERROR("metric", "Error connecting to '%s:%s', disabling Metric. Error message : %s", - _hostname.c_str(), _port.c_str(), error.message().c_str()); + TC_LOG_ERROR("metric", "Error connecting to '{}:{}', disabling Metric. Error message : {}", + _hostname, _port, error.message()); _enabled = false; return false; } @@ -58,14 +58,14 @@ void Metric::LoadFromConfigs() _updateInterval = sConfigMgr->GetIntDefault("Metric.Interval", 1); if (_updateInterval < 1) { - TC_LOG_ERROR("metric", "'Metric.Interval' config set to %d, overriding to 1.", _updateInterval); + TC_LOG_ERROR("metric", "'Metric.Interval' config set to {}, overriding to 1.", _updateInterval); _updateInterval = 1; } _overallStatusTimerInterval = sConfigMgr->GetIntDefault("Metric.OverallStatusInterval", 1); if (_overallStatusTimerInterval < 1) { - TC_LOG_ERROR("metric", "'Metric.OverallStatusInterval' config set to %d, overriding to 1.", _overallStatusTimerInterval); + TC_LOG_ERROR("metric", "'Metric.OverallStatusInterval' config set to {}, overriding to 1.", _overallStatusTimerInterval); _overallStatusTimerInterval = 1; } @@ -201,7 +201,7 @@ void Metric::SendBatch() GetDataStream() >> status_code; if (status_code != 204) { - TC_LOG_ERROR("metric", "Error sending data, returned HTTP code: %u", status_code); + TC_LOG_ERROR("metric", "Error sending data, returned HTTP code: {}", status_code); } // Read and ignore the status description diff --git a/src/common/Platform/ServiceWin32.cpp b/src/common/Platform/ServiceWin32.cpp index 162632551f0..87381090dbc 100644 --- a/src/common/Platform/ServiceWin32.cpp +++ b/src/common/Platform/ServiceWin32.cpp @@ -254,7 +254,7 @@ bool WinServiceRun() if (!StartServiceCtrlDispatcher(serviceTable)) { - TC_LOG_ERROR("server.worldserver", "StartService Failed. Error [%u]", uint32(::GetLastError())); + TC_LOG_ERROR("server.worldserver", "StartService Failed. Error [{}]", uint32(::GetLastError())); return false; } return true; diff --git a/src/common/Threading/ProcessPriority.cpp b/src/common/Threading/ProcessPriority.cpp index 3428a56258c..5c0077c0cc5 100644 --- a/src/common/Threading/ProcessPriority.cpp +++ b/src/common/Threading/ProcessPriority.cpp @@ -43,11 +43,11 @@ void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool hig ULONG_PTR currentAffinity = affinity & appAff; if (!currentAffinity) - TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) %x are not accessible. Accessible processors bitmask (hex): %x", affinity, appAff); + TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) {:x} are not accessible. Accessible processors bitmask (hex): {:x}", affinity, appAff); else if (SetProcessAffinityMask(hProcess, currentAffinity)) - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %x", currentAffinity); + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): {:x}", currentAffinity); else - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x", currentAffinity); + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): {:x}", currentAffinity); } } @@ -71,21 +71,21 @@ void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool hig CPU_SET(i, &mask); if (sched_setaffinity(0, sizeof(mask), &mask)) - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): {:x}, error: {}", affinity, strerror(errno)); else { CPU_ZERO(&mask); sched_getaffinity(0, sizeof(mask), &mask); - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): {:x}", *(__cpu_mask*)(&mask)); } } if (highPriority) { if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) - TC_LOG_ERROR(logChannel, "Can't set process priority class, error: %s", strerror(errno)); + TC_LOG_ERROR(logChannel, "Can't set process priority class, error: {}", strerror(errno)); else - TC_LOG_INFO(logChannel, "Process priority class set to %i", getpriority(PRIO_PROCESS, 0)); + TC_LOG_INFO(logChannel, "Process priority class set to {}", getpriority(PRIO_PROCESS, 0)); } #else diff --git a/src/common/Utilities/StartProcess.cpp b/src/common/Utilities/StartProcess.cpp index 00e5bc0bfe7..dc4fc4e7646 100644 --- a/src/common/Utilities/StartProcess.cpp +++ b/src/common/Utilities/StartProcess.cpp @@ -87,8 +87,8 @@ static int CreateChildProcess(T waiter, std::string const& executable, if (!secure) { - TC_LOG_TRACE(logger, "Starting process \"%s\" with arguments: \"%s\".", - executable.c_str(), boost::algorithm::join(argsVector, " ").c_str()); + TC_LOG_TRACE(logger, "Starting process \"{}\" with arguments: \"{}\".", + executable, boost::algorithm::join(argsVector, " ")); } // prepare file with only read permission (boost process opens with read_write) @@ -129,12 +129,12 @@ static int CreateChildProcess(T waiter, std::string const& executable, auto outInfo = MakeTCLogSink([&](std::string_view msg) { - TC_LOG_INFO(logger, STRING_VIEW_FMT, STRING_VIEW_FMT_ARG(msg)); + TC_LOG_INFO(logger, "{}", msg); }); auto outError = MakeTCLogSink([&](std::string_view msg) { - TC_LOG_ERROR(logger, STRING_VIEW_FMT, STRING_VIEW_FMT_ARG(msg)); + TC_LOG_ERROR(logger, "{}", msg); }); copy(outStream, outInfo); @@ -146,8 +146,8 @@ static int CreateChildProcess(T waiter, std::string const& executable, if (!secure) { - TC_LOG_TRACE(logger, ">> Process \"%s\" finished with return value %i.", - executable.c_str(), result); + TC_LOG_TRACE(logger, ">> Process \"{}\" finished with return value {}.", + executable, result); } return result; diff --git a/src/common/Utilities/StringFormat.h b/src/common/Utilities/StringFormat.h index da1615575a4..b4d4d9e5743 100644 --- a/src/common/Utilities/StringFormat.h +++ b/src/common/Utilities/StringFormat.h @@ -18,22 +18,24 @@ #ifndef TRINITYCORE_STRING_FORMAT_H #define TRINITYCORE_STRING_FORMAT_H -#include "fmt/printf.h" +#include "fmt/core.h" namespace Trinity { + template<typename... Args> + using FormatString = std::string_view; + /// Default TC string format function. - template<typename Format, typename... Args> - inline std::string StringFormat(Format&& fmt, Args&&... args) + template<typename... Args> + inline std::string StringFormat(FormatString<Args...> fmt, Args&&... args) { try { - return fmt::sprintf(std::forward<Format>(fmt), std::forward<Args>(args)...); + return fmt::format(fmt, std::forward<Args>(args)...); } - catch (const fmt::format_error& formatError) + catch (std::exception const& formatError) { - std::string error = "An error occurred formatting string \"" + std::string(fmt) + "\" : " + std::string(formatError.what()); - return error; + return fmt::format("An error occurred formatting string \"{}\" : {}", fmt, formatError.what()); } } @@ -48,6 +50,12 @@ namespace Trinity { return fmt.empty(); } + + /// Returns true if the given std::string is empty. + inline constexpr bool IsFormatEmptyOrNull(std::string_view fmt) + { + return fmt.empty(); + } } #endif diff --git a/src/common/Utilities/Util.cpp b/src/common/Utilities/Util.cpp index 4693bd9eb08..6763685ba70 100644 --- a/src/common/Utilities/Util.cpp +++ b/src/common/Utilities/Util.cpp @@ -106,13 +106,13 @@ std::string secsToTimeString(uint64 timeInSecs, TimeFormat timeFormat, bool hour if (timeFormat == TimeFormat::Numeric) { if (days) - return Trinity::StringFormat("%u:%02u:%02u:%02u", days, hours, minutes, secs); + return Trinity::StringFormat("{}:{:02}:{:02}:{:02}", days, hours, minutes, secs); else if (hours) - return Trinity::StringFormat("%u:%02u:%02u", hours, minutes, secs); + return Trinity::StringFormat("{}:{:02}:{:02}", hours, minutes, secs); else if (minutes) - return Trinity::StringFormat("%u:%02u", minutes, secs); + return Trinity::StringFormat("{}:{:02}", minutes, secs); else - return Trinity::StringFormat("0:%02u", secs); + return Trinity::StringFormat("0:{:02}", secs); } std::ostringstream ss; @@ -281,7 +281,7 @@ std::string TimeToTimestampStr(time_t t) // HH hour (2 digits 00-23) // MM minutes (2 digits 00-59) // SS seconds (2 digits 00-59) - return Trinity::StringFormat("%04d-%02d-%02d_%02d-%02d-%02d", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); + return Trinity::StringFormat("{:04}-{:02}-{:02}_{:02}-{:02}-{:02}", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); } std::string TimeToHumanReadable(time_t t) |